1 <?php
2 // +----------------------------------------------------------------------
3 // | 方维购物分享网站系统 (Build on ThinkPHP)
4 // +----------------------------------------------------------------------
5 // | Copyright (c) 2011 http://fanwe.com All rights reserved.
6 // +----------------------------------------------------------------------
7
8 /**
9 * global.func
10 *
11 * 公共函数
12 *
13 * @package function
14 * @author awfigq <awfigq@qq.com>
15 */
16 function getPhpSelf()
17 {
18 $php_self = '';
19 $script_name = basename($_SERVER['SCRIPT_FILENAME']);
20 if(basename($_SERVER['SCRIPT_NAME']) === $script_name)
21 $php_self = $_SERVER['SCRIPT_NAME'];
22 else if(basename($_SERVER['PHP_SELF']) === $script_name)
23 $php_self = $_SERVER['PHP_SELF'];
24 else if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $script_name)
25 $php_self = $_SERVER['ORIG_SCRIPT_NAME'];
26 else if(($pos = strpos($_SERVER['PHP_SELF'],'/'.$script_name)) !== false)
27 $php_self = substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$script_name;
28 else if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT']) === 0)
29 $php_self = str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
30 else
31 return false;
32 return $php_self;
33 }
34
35 /**
36 * 获取引用文件路径
37 * @param string $file_name 文件名称
38 * @param string $folder 所在目录(默认为空)
39 * @return string
40 */
41 function fimport($file_name, $folder = '')
42 {
43 global $_FANWE;
44 static $sufix = array(
45 'module'=>'.module',
46 'service'=>'.service',
47 'class'=>'.class',
48 'function' => '.func',
49 'include' => '.inc',
50 'language' => '.lang',
51 'cache' => '.cache',
52 'dynamic'=>'.dynamic',
53 );
54
55 $file_name = strtolower($file_name);
56 $file_path = FANWE_ROOT.'./core';
57 if(strstr($file_name, '/'))
58 {
59 list($pre, $name) = explode('/', $file_name);
60
61 $insert = '';
62 if($pre == 'language')
63 $insert = $_FANWE['config']['default_lang'].'/';
64
65 return "{$file_path}/{$pre}/".$insert.(empty($folder) ? "" : $folder . "/")."{$name}".$sufix[$pre].".php";
66 }
67 else
68 {
69 return "{$file_path}/".(empty($folder) ? "" : $folder . "/")."{$file_name}.php";
70 }
71 }
72
73 /**
74 * 获取页面显示操作类
75 * @param string $module 类名
76 * @return object
77 */
78 function FM($module)
79 {
80 static $modules = array();
81 if($modules[$module] === NULL)
82 {
83 require fimport("module/".strtolower($module));
84 $m = ucfirst($module)."Module";
85 $modules[$module] = new $m();
86 unset($m);
87 }
88 return $modules[$module];
89 }
90
91 /**
92 * 获取服务类
93 * @param string $service 类名
94 * @return object
95 */
96 function FS($service)
97 {
98 static $services = array();
99 if($services[$service] === NULL)
100 {
101 require_once fimport("service/".strtolower($service));
102 $s = ucfirst($service)."Service";
103 $services[$service] = new $s();
104 unset($s);
105 }
106
107 return $services[$service];
108 }
109
110 /**
111 * 页面路径处理
112 * @param string $type 页面
113 * @param array $args 参数
114 * @return string
115 */
116 function FU($type,$args = array(),$is_full = false)
117 {
118 global $_FANWE;
119 static $is_rewrite = NULL,$site_url = NULL,$url_lists = array(),$url_flists = array(),$seo_modules = NULL;
120
121 if ($is_rewrite === NULL)
122 $is_rewrite = intval($_FANWE['setting']['url_model']);
123
124 if ($site_url === NULL)
125 $site_url = $_FANWE['site_root'];
126
127 if ($seo_modules === NULL)
128 {
129 if(!isset($_FANWE['cache']['seos']))
130 Cache::getInstance()->loadCache('seos');
131
132 $seo_modules = $_FANWE['cache']['seos'];
133 }
134
135 $depr = '/';
136
137 $url = $site_url;
138 if($is_full)
139 {
140 $url = $_FANWE['site_url'];
141 $site_url = $_FANWE['site_url'];
142 }
143
144 $apps = explode('/',$type);
145 $module = $apps[0];
146 $action = isset($apps[1]) ? $apps[1] : 'index';
147 $type = $module.'/'.$action;
148
149 $url_key = $type.'_'.md5(http_build_query($args));
150 if($is_full)
151 {
152 if(isset($url_flists[$url_key]))
153 return $url_flists[$url_key];
154 }
155 else
156 {
157 if(isset($url_lists[$url_key]))
158 return $url_lists[$url_key];
159 }
160
161 $query = '';
162 if($is_rewrite == 0 || $module == 'search')
163 {
164 $query = http_build_query($args);
165 if(!empty($query))
166 $query = '&'.$query;
167 }
168
169 $is_url_app = true;
170 if($is_rewrite == 0 || $module == 'search')
171 {
172 $url .= $module.'.php?action='.$action.$query;
173 }
174 else
175 {
176 $params = array();
177 switch($module)
178 {
179 case 'index':
180 $is_url_app = false;
181 $url = $site_url;
182 break;
183
184 case 'book':
185 $params = array('cate' => '','gid' => '','sid' => '','price'=>'','color'=>'','sort'=>'','tag' => '','page' => 0);
186 $search = array('cate/','gid/','sid/','price/','color/','sort/','tag/','page/');
187 $replace = array('','g','s','p','c','','','');
188 if($action == 'shopping')
189 $action = $seo_modules[$module][$action]['action'];
190
191 $module = $seo_modules[$module]['module'];
192 break;
193
194 case 'note':
195 $is_url_app = false;
196 $module = $seo_modules[$module]['module'];
197 if($action == 'index')
198 $url = $site_url.$module.$depr.$args['sid'];
199 else
200 $url = $site_url.$module.$depr.$args['sid'].$depr.$action.$depr.$args['id'];
201
202 if(isset($args['page']) && $args['page'] != '0')
203 $url.= $depr.$args['page'];
204 break;
205
206 case 'album':
207 switch($action)
208 {
209 case 'index':
210 $params = array('sort'=>'','page' => 0);
211 $search = array('/index','sort/','page/');
212 $replace = array('','','');
213 break;
214
215 case 'category':
216 $action = $seo_modules[$module][$action]['action'];
217 $params = array('id'=>0,'sort'=>'','page' => 0);
218 $search = array('id/','sort/','page/');
219 $replace = array('c','','');
220 break;
221
222 case 'show':
223 $action = $seo_modules[$module][$action]['action'];
224 $args['aid'] = $args['id'];
225 unset($args['id']);
226 $params = array('aid'=>0,'sid'=>0,'type' => 0,'page' => 0);
227 $search = array('aid/','sid/','type/','page/');
228 $replace = array('a','s','t','');
229 break;
230
231 case 'edit':
232 $params = array('id'=>0);
233 $search = array('id/');
234 $replace = array('');
235 break;
236 }
237 $module = $seo_modules[$module]['module'];
238 break;
239
240 case 'look':
241 case 'dapei':
242 $params = array('type' => '','sort' => '','page' => 0);
243 $search = array('/index','/type','/sort','/page');
244 $replace = array('','','','');
245 $module = $seo_modules[$module]['module'];
246 break;
247
248 case 'group':
249 switch($action)
250 {
251 case 'index':
252 $search = array('/index');
253 $replace = array('');
254 break;
255
256 case 'detail':
257 $params = array('type' => '','fid' => 0,'sort' => '','page' => 0);
258 $search = array('detail/','type/','fid/','sort/','page/');
259 $replace = array('','','','','');
260 break;
261
262 case 'users':
263 case 'apply':
264 $params = array('fid' => 0,'page' => 0);
265 $search = array('fid/','page/');
266 $replace = array('','');
267 break;
268
269 case "edit":
270 $params = array('fid' => 0);
271 $search = array('fid/');
272 $replace = array('');
273 break;
274 }
275 $module = $seo_modules[$module]['module'];
276 break;
277
278 case 'daren':
279 switch($action)
280 {
281 case 'index':
282 $search = array('/index');
283 $replace = array('');
284 break;
285
286 case 'cate':
287 $params = array('id' => 0,'page' => 0);
288 $search = array('cate/','id/','page/');
289 $replace = array('','','');
290 break;
291 }
292 $module = $seo_modules[$module]['module'];
293 break;
294
295 case 'shop':
296 switch($action)
297 {
298 case 'index':
299 if(empty($args['cid']))
300 {
301 unset($args['cid']);
302 $search = array('/index','/page');
303 $replace = array('','');
304 }
305 else
306 {
307 $params = array('cid' => 0,'page' => 0);
308 $search = array('index/','cid/','page/');
309 $replace = array('','c','');
310 }
311 break;
312
313 case 'show':
314 $params = array('id' => 0,'page' => 0);
315 $search = array('id/','page/');
316 $replace = array('s','');
317 $action = $seo_modules[$module][$action]['action'];
318 break;
319 }
320 $module = $seo_modules[$module]['module'];
321
322 break;
323
324
325 case 'topic':
326 switch($action)
327 {
328 case 'detail':
329 $params = array('tid' => 0,'page' => 0);
330 $search = array('tid/','page/');
331 $replace = array('','');
332 $action = $seo_modules[$module][$action]['action'];
333 break;
334
335 case 'create':
336 $params = array('fid' => 0);
337 $search = array('fid/');
338 $replace = array('');
339 break;
340
341 case 'edit':
342 $params = array('tid' => 0);
343 $search = array('tid/');
344 $replace = array('');
345 break;
346 }
347 $module = $seo_modules[$module]['module'];
348 break;
349
350 case 'activity':
351 switch($action)
352 {
353 case 'detail':
354 $params = array('id' => 0,'page' => 0);
355 $search = array('id/','page/');
356 $replace = array('','');
357 break;
358
359 case 'edit':
360 $params = array('id' => 0);
361 $search = array('id/');
362 $replace = array('');
363 break;
364
365 case 'manage':
366 $params = array('id' => 0);
367 $search = array('id/');
368 $replace = array('');
369 break;
370 }
371 break;
372
373 case 'vote':
374 switch($action)
375 {
376 case 'detail':
377 $params = array('id' => 0,'page' => 0);
378 $search = array('id/','page/');
379 $replace = array('','');
380 break;
381
382 case 'edit':
383 $params = array('id' => 0);
384 $search = array('id/');
385 $replace = array('');
386 break;
387 }
388 break;
389
390 case 'exchange':
391 switch($action)
392 {
393 case 'index':
394 $search = array('/index','/page');
395 $replace = array('','');
396 break;
397
398 case 'info':
399 $params = array('id' => 0,'page' => 0);
400 $search = array('id/','page/');
401 $replace = array('','');
402 $action = $seo_modules[$module][$action]['action'];
403 break;
404 }
405 $module = $seo_modules[$module]['module'];
406
407 break;
408
409 case 'mailrss':
410 switch($action)
411 {
412 case 'index':
413 $search = array('/index',);
414 $replace = array('','');
415 break;
416
417 case 'show':
418 $params = array('id' => 0);
419 $search = array('id/');
420 $replace = array('');
421 break;
422 }
423 break;
424
425 case 'u':
426 $is_url_app = false;
427
428 if(!isset($args['uid']))
429 $args['uid'] = $_FANWE['uid'];
430
431 if($action == 'all')
432 $url = $site_url.$module.$depr.$action;
433 elseif($action == 'msgview')
434 {
435 $url = $site_url.$module.$depr.$action;
436 if($args['lid'] > 0)
437 $url .= $depr.'lid'.$depr.$args['lid'];
438
439 if($args['mid'] > 0)
440 $url .= $depr.'mid'.$depr.$args['mid'];
441
442 if($args['page'] != '' || $args['page'] > 0 )
443 $url .= $depr.$args['page'];
444 }
445 else
446 {
447 if($action == 'index')
448 {
449 if($args['uid'] == $_FANWE['uid'])
450 $url = $site_url.'me';
451 else
452 $url = $site_url.$module.$depr.$args['uid'];
453 }
454 elseif($action == 'me')
455 $url = $site_url.$module.'/me';
456 else
457 $url = $site_url.$module.$depr.$args['uid'].$depr.$action;
458
459 if($action == 'album')
460 {
461 if(isset($args['type']) && $args['type'] != '')
462 {
463 $url.= $depr.'t'.$args['type'];
464 }
465 }
466 elseif($action == 'exchange')
467 {
468 if(isset($args['status']) && $args['status'] != '')
469 $url.= $depr.'s'.$args['status'];
470 }
471 elseif($action == 'commission')
472 {
473 if(isset($args['type']) && $args['type'] != '')
474 $url.= $depr.'t'.$args['type'];
475 }
476 elseif($action == 'group')
477 {
478 if(isset($args['sort']) && $args['sort'] != '')
479 $url.= $depr.'s'.$args['sort'];
480 }
481 else
482 {
483 if(isset($args['type']) && $args['type'] != '')
484 $url.= $depr.$args['type'];
485
486 if(isset($args['sort']) && $args['sort'] != '')
487 $url.= $depr.$args['sort'];
488 }
489
490 if(isset($args['page']) && $args['page'] != '0')
491 $url.= $depr.$args['page'];
492 }
493 break;
494
495 default:
496 switch($type)
497 {
498 case 'event/index':
499 case 'invite/index':
500 $search = array('/index');
501 $replace = array('');
502 break;
503
504 case 'link/index':
505 $module = "links";
506 $search = array('/index');
507 $replace = array('');
508 break;
509
510 case 'event/detail':
511 $params = array('detail'=>'','id'=>'','page' => 0);
512 $search = array('/detail','/id','/page');
513 $replace = array('','','');
514 break;
515
516 case 'event/list':
517 $params = array('type'=>'','order'=>'','page' => 0);
518 $search = array('/type','/order','/page');
519 $replace = array('','','');
520 break;
521
522 case 'adv/show':
523 $params = array('id'=>'');
524 $search = array('/show','/id');
525 $replace = array('','');
526 break;
527 }
528 break;
529 }
530
531 if(!empty($params))
532 $args = array_merge($params, $args);
533
534 foreach($args as $var=>$val)
535 {
536 if($var == 'page' && $val == '0')
537 $val = '';
538
539 if($val !== '')
540 $query .= $depr.$var.$depr.$val;
541 }
542
543 if($is_url_app)
544 $url .= $module.(empty($action) ? '' : $depr.$action).$query;
545
546 if(!empty($search))
547 $url = str_replace($search,$replace,$url);
548 }
549
550 if($type == 'tgo/index')
551 {
552 $url = $site_url.'tgo.php?url='.base64_encode($args['url']);
553 $tk = array();
554 if(isset($args['uid']) && (int)$args['uid'] > 0)
555 $tk['uid'] = (int)$args['uid'];
556
557 if(isset($args['sid']) && (int)$args['sid'] > 0)
558 $tk['sid'] = (int)$args['sid'];
559
560 if(isset($args['gid']) && (int)$args['gid'] > 0)
561 $tk['gid'] = (int)$args['gid'];
562
563 if(isset($args['kid']))
564 $tk['kid'] = $args['kid'];
565
566 if(count($tk) > 0)
567 $url .= '&args='.base64_encode(serialize($tk));
568 }
569
570 if($is_full)
571 $url_flists[$url_key] = $url;
572 else
573 $url_lists[$url_key] = $url;
574 return $url;
575 }
576
577 /**
578 * 页面重写参数处理
579 * @param array $keys 键值对
580 * @return void
581 */
582 function getRewriteArgs($keys)
583 {
584 global $_FANWE;
585 $args = trim($_FANWE['request']['args']);
586 foreach($keys as $key)
587 {
588 preg_match("/$key-(.+?)(?:$|-)/is",$args,$value);
589 if(count($value) > 1)
590 {
591 $_FANWE['request'][$key] = $value[1];
592 if($key == 'page')
593 $_FANWE['page'] = $value[1];
594 }
595 }
596 unset($_FANWE['request']['args']);
597 }
598
599 /**
600 * 分页处理
601 * @param string $type 所在页面
602 * @param array $args 参数
603 * @param int $total_count 总数
604 * @param int $page 当前页
605 * @param int $page_size 分页大小
606 * @param string $url 自定义路径
607 * @param int $offset 偏移量
608 * @return array
609 */
610 function buildPage($type,$args,$total_count,$page = 1,$page_size = 0,$url='',$offset = 5)
611 {
612 global $_FANWE;
613
614 $pager['total_count'] = intval($total_count);
615 $pager['page'] = $page;
616 $pager['page_size'] = ($page_size == 0) ? ($_FANWE['setting']['page_listrows'] > 0 ? $_FANWE['setting']['page_listrows'] : 20) : $page_size;
617 /* page 总数 */
618 $pager['page_count'] = ($pager['total_count'] > 0) ? ceil($pager['total_count'] / $pager['page_size']) : 1;
619
620 /* 边界处理 */
621 if ($pager['page'] > $pager['page_count'])
622 $pager['page'] = $pager['page_count'];
623
624 $pager['limit'] = ($pager['page'] - 1) * $pager['page_size'] . "," . $pager['page_size'];
625
626 $page_prev = ($pager['page'] > 1) ? $pager['page'] - 1 : 1;
627 $page_next = ($pager['page'] < $pager['page_count']) ? $pager['page'] + 1 : $pager['page_count'];
628 $pager['prev_page'] = $page_prev;
629 $pager['next_page'] = $page_next;
630
631 if (!empty($url))
632 {
633 $pager['page_first'] = $url . 1;
634 $pager['page_prev'] = $url . $page_prev;
635 $pager['page_next'] = $url . $page_next;
636 $pager['page_last'] = $url . $pager['page_count'];
637 }
638 else
639 {
640 $args['page'] = '_page_';
641 if(!empty($type))
642 $page_url = FU($type,$args);
643 else
644 $page_url = 'javascript:;';
645
646 $pager['page_first'] = str_replace('_page_',1,$page_url);
647 $pager['page_prev'] = str_replace('_page_',$page_prev,$page_url);
648 $pager['page_next'] = str_replace('_page_',$page_next,$page_url);
649 $pager['page_last'] = str_replace('_page_',$pager['page_count'],$page_url);
650 }
651
652 $pager['page_nums'] = array();
653
654 if($pager['page_count'] <= $offset * 2)
655 {
656 for ($i=1; $i <= $pager['page_count']; $i++)
657 {
658 $pager['page_nums'][] = array('name' => $i,'url' => empty($url) ? str_replace('_page_',$i,$page_url) : $url . $i);
659 }
660 }
661 else
662 {
663 if($pager['page'] - $offset < 2)
664 {
665 $temp = $offset * 2;
666
667 for ($i=1; $i<=$temp; $i++)
668 {
669 $pager['page_nums'][] = array('name' => $i,'url' => empty($url) ? str_replace('_page_',$i,$page_url) : $url . $i);
670 }
671
672 $pager['page_nums'][] = array('name'=>'...');
673 $pager['page_nums'][] = array('name' => $pager['page_count'],'url' => empty($url) ? str_replace('_page_',$pager['page_count'],$page_url) : $url . $pager['page_count']);
674 }
675 else
676 {
677 $pager['page_nums'][] = array('name' => 1,'url' => empty($url) ? str_replace('_page_',1,$page_url) : $url . 1);
678 $pager['page_nums'][] = array('name'=>'...');
679 $start = $pager['page'] - $offset + 1;
680 $end = $pager['page'] + $offset - 1;
681
682 if($pager['page_count'] - $end > 1)
683 {
684 for ($i=$start;$i<=$end;$i++)
685 {
686 $pager['page_nums'][] = array('name' => $i,'url' => empty($url) ? str_replace('_page_',$i,$page_url) : $url . $i);
687 }
688
689 $pager['page_nums'][] = array('name'=>'...');
690 $pager['page_nums'][] = array('name' => $pager['page_count'],'url' => empty($url) ? str_replace('_page_',$pager['page_count'],$page_url) : $url . $pager['page_count']);
691 }
692 else
693 {
694 $start = $pager['page_count'] - $offset * 2 + 1;
695 $end = $pager['page_count'];
696 for ($i=$start;$i<=$end;$i++)
697 {
698 $pager['page_nums'][] = array('name' => $i,'url' => empty($url) ? str_replace('_page_',$i,$page_url) : $url . $i);
699 }
700 }
701 }
702 }
703
704 return $pager;
705 }
706
707 /**
708 * 分页处理
709 * @param int $total_count 总数
710 * @param int $page 当前页
711 * @param int $page_size 分页大小
712 * @return array
713 */
714 function buildPageMini($total_count,$page = 1,$page_size = 0)
715 {
716 $pager['total_count'] = intval($total_count);
717 $pager['page'] = $page;
718 $pager['page_size'] = ($page_size == 0) ? ($_FANWE['setting']['page_listrows'] > 0 ? $_FANWE['setting']['page_listrows'] : 20) : $page_size;
719 /* page 总数 */
720 $pager['page_count'] = ($pager['total_count'] > 0) ? ceil($pager['total_count'] / $pager['page_size']) : 1;
721
722 /* 边界处理 */
723 if ($pager['page'] > $pager['page_count'])
724 $pager['page'] = $pager['page_count'];
725
726 $pager['limit'] = ($pager['page'] - 1) * $pager['page_size'] . "," . $pager['page_size'];
727
728 $page_prev = ($pager['page'] > 1) ? $pager['page'] - 1 : 1;
729 $page_next = ($pager['page'] < $pager['page_count']) ? $pager['page'] + 1 : $pager['page_count'];
730 $pager['prev_page'] = $page_prev;
731 $pager['next_page'] = $page_next;
732 return $pager;
733 }
734
735 /**
736 * 用于检测当前用户IP的可操作性,time_span为验证的时间间隔 秒
737 *
738 * @param string $ip_str IP地址
739 * @param string $module 操作的模块 *
740 * @param integer $time_span 间隔
741 * @param integer $id 操作的数据
742 *
743 * @return boolean
744 */
745 function checkIpOperation($module,$time_span = 0,$id = 0)
746 {
747 global $_FANWE;
748 @session_start();
749 $key = $_FANWE['client_ip'].'_'.$_FANWE['uid'].'_check_'.$module.($id > 0 ? '_'.$id : '');
750
751 if(!isset($_SESSION[$key]))
752 {
753 $_SESSION[$key] = TIME_UTC;
754 return true;
755 }
756 else
757 {
758 $time = (int)$_SESSION[$key];
759 if(TIME_UTC - $time < $time_span)
760 {
761 return false;
762 }
763 else
764 {
765 $_SESSION[$key] = TIME_UTC;
766 return true;
767 }
768 }
769 }
770
771 /**
772 * 字符串截断处理
773 * @param string $string 要处理的字符串
774 * @param int $length 指定长度
775 * @param string $dot 超出指定长度时显示
776 * @return array
777 */
778 function cutStr($string, $length, $dot = '...')
779 {
780 if(getStrLen($string) <= $length)
781 return $string;
782
783 $pre = '{%';
784 $end = '%}';
785 $string = str_replace(array('&', '"', '<', '>'), array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), $string);
786
787 $strcut = '';
788 if(strtolower(CHARSET) == 'utf-8')
789 {
790 $n = $tn = $noc = 0;
791 while($n < strlen($string))
792 {
793 $t = ord($string[$n]);
794 if($t == 9 || $t == 10 || (32 <= $t && $t <= 126))
795 {
796 $tn = 1; $n++; $noc++;
797 }
798 elseif(194 <= $t && $t <= 223)
799 {
800 $tn = 2; $n += 2; $noc += 2;
801 }
802 elseif(224 <= $t && $t <= 239)
803 {
804 $tn = 3; $n += 3; $noc += 2;
805 }
806 elseif(240 <= $t && $t <= 247)
807 {
808 $tn = 4; $n += 4; $noc += 2;
809 }
810 elseif(248 <= $t && $t <= 251)
811 {
812 $tn = 5; $n += 5; $noc += 2;
813 }
814 elseif($t == 252 || $t == 253)
815 {
816 $tn = 6; $n += 6; $noc += 2;
817 }
818 else
819 {
820 $n++;
821 }
822
823 if($noc >= $length)
824 break;
825 }
826
827 if($noc > $length)
828 $n -= $tn;
829
830 $strcut = substr($string,0,$n);
831 }
832 else
833 {
834 for($i = 0; $i < $length; $i++)
835 {
836 $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
837 }
838 }
839
840 $strcut = str_replace(array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), array('&', '"', '<', '>'), $strcut);
841
842 return $strcut.$dot;
843 }
844
845 /**
846 * 获取字符串长度
847 * @param string $str 要获取长度的字符串
848 * @return int
849 */
850 function getStrLen($str)
851 {
852 $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));
853
854 if ($length)
855 {
856 return strlen($str) - $length + intval($length / 3) * 2;
857 }
858 else
859 {
860 return strlen($str);
861 }
862 }
863
864 /**
865 * 获取字节数
866 * @param string $val 要获取字节数的字符串
867 * @return int
868 */
869 function getBytes($val)
870 {
871 $val = trim($val);
872 $last = strtolower($val{strlen($val)-1});
873 switch($last)
874 {
875 case 'g': $val *= 1024;
876 case 'm': $val *= 1024;
877 case 'k': $val *= 1024;
878 }
879
880 return $val;
881 }
882
883 /**
884 * 错误处理
885 * @param string $message 错误信息
886 * @param bool $show 是否显示
887 * @param bool $save 是否保存
888 * @param bool $halt 是否停止
889 * @return void
890 */
891 function systemError($message, $show = true, $save = true, $halt = true)
892 {
893 require_once fimport('class/error');
894 FanweError::systemError($message, $show, $save, $halt);
895 }
896
897 /**
898 * 显示成功信息
899 * @param string $title 标题
900 * @param string $message 成功信息
901 * @param string $jump_url 跳转地址
902 * @param int $wait 等待时间
903 * @return void
904 */
905 function showSuccess($title, $message,$jump_url,$wait = 3)
906 {
907 global $_FANWE;
908 include template('page/success');
909 display();
910 exit;
911 }
912
913 /**
914 * 显示错误信息
915 * @param string $title 标题
916 * @param string $message 错误信息
917 * @param string $jump_url 跳转地址
918 * @param int $wait 等待时间
919 * @param bool $is_close 是否显示网站关闭
920 * @return void
921 */
922 function showError($title, $message,$jump_url,$wait = 3,$is_close = false)
923 {
924 global $_FANWE;
925
926 if($is_close)
927 include template('page/close');
928 else
929 include template('page/error');
930
931 display();
932 exit;
933 }
934
935 /**
936 * 查询字符串是否存在
937 * @param string $string
938 * @param string $find
939 * @return bool
940 */
941 function strExists($string, $find)
942 {
943 return !(strpos($string, $find) === FALSE);
944 }
945
946 /**
947 * 获取是否为搜索引擎爬虫
948 * @param string $userAgent 用户信息
949 * @return bool
950 */
951 function checkRobot($userAgent = '')
952 {
953 static $kwSpiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
954 static $kwBrowsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
955
956 $userAgent = empty($userAgent) ? $_SERVER['HTTP_USER_AGENT'] : $userAgent;
957
958 if(!strExists($userAgent, 'http://') && preg_match("/($kwBrowsers)/i", $userAgent))
959 return false;
960 elseif(preg_match("/($kwSpiders)/i", $userAgent))
961 return true;
962 else
963 return false;
964 }
965
966 /**
967 * 获取链接格式是否正确
968 * @param string $url 链接
969 * @return bool
970 */
971 function parseUrl($url)
972 {
973 $parse_url = parse_url($url);
974 return (!empty($parse_url['scheme']) && !empty($parse_url['host']));
975 }
976
977
978 /**
979 * 获取客户端IP
980 * @return string
981 */
982 function getFClientIp()
983 {
984 $ip = $_SERVER['REMOTE_ADDR'];
985 if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP']))
986 {
987 $ip = $_SERVER['HTTP_CLIENT_IP'];
988 }
989 elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches))
990 {
991 foreach ($matches[0] AS $xip)
992 {
993 if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip))
994 {
995 $ip = $xip;
996 break;
997 }
998 }
999 }
1000 return $ip;
1001 }
1002
1003 /**
1004 * 字符转义
1005 * @return string
1006 */
1007 function fAddslashes($string)
1008 {
1009 if(empty($string))
1010 return $string;
1011
1012 if(is_array($string))
1013 {
1014 $keys = array_keys($string);
1015 foreach($keys as $key)
1016 {
1017 $val = $string[$key];
1018 unset($string[$key]);
1019 $string[addslashes($key)] = fAddslashes($val);
1020 }
1021 }
1022 else
1023 {
1024 $string = addslashes($string);
1025 }
1026 return $string;
1027 }
1028
1029 /**
1030 * 字符转义
1031 * @return string
1032 */
1033 function fStripslashes($string)
1034 {
1035 if(empty($string))
1036 return $string;
1037
1038 if(is_array($string))
1039 {
1040 foreach($string as $key => $val)
1041 {
1042 $string[$key] = fStripslashes($val);
1043 }
1044 }
1045 else
1046 {
1047 $string = stripslashes($string);
1048 }
1049 return $string;
1050 }
1051
1052 /**
1053 * 生成随机数
1054 * @param int $length 随机数长度
1055 * @param int $numeric 是否只生成数字
1056 * @return string
1057 */
1058 function random($length, $numeric = 0)
1059 {
1060 $seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
1061 $seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
1062 $hash = '';
1063 $max = strlen($seed) - 1;
1064 for($i = 0; $i < $length; $i++)
1065 {
1066 $hash .= $seed{mt_rand(0, $max)};
1067 }
1068 return $hash;
1069 }
1070
1071 /**
1072 * 生成cookie
1073 * @param string $var 键名
1074 * @param string $value 值
1075 * @param int $life 过期时间
1076 * @param bool $prefix 是否加入前缘
1077 * @param bool $http_only
1078 * @return void
1079 */
1080 function fSetCookie($var, $value = '', $life = 0, $prefix = true, $http_only = false)
1081 {
1082 global $_FANWE;
1083 $config = $_FANWE['config']['cookie'];
1084 $_FANWE['cookie'][$var] = $value;
1085 $var = ($prefix ? $config['cookie_pre'] : '').$var;
1086 $_COOKIE[$var] = $value;
1087
1088 if($value == '' || $life < 0)
1089 {
1090 $value = '';
1091 $life = -1;
1092 }
1093
1094 $life = $life > 0 ? TIME_UTC + $life : ($life < 0 ? TIME_UTC - 31536000 : 0);
1095 $path = $http_only && PHP_VERSION < '5.2.0' ? $config['cookie_path'].'; HttpOnly' : $config['cookie_path'];
1096
1097 $secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
1098 if(PHP_VERSION < '5.2.0')
1099 {
1100 setcookie($var, $value, $life, $path, $config['cookie_domain'], $secure);
1101 }
1102 else
1103 {
1104 setcookie($var, $value, $life, $path, $config['cookie_domain'], $secure, $http_only);
1105 }
1106 }
1107
1108 /**
1109 * 更新session
1110 * @param bool $force 强制更新
1111 * @return bool
1112 */
1113 function updateSession($force = false) {
1114
1115 global $_FANWE;
1116 static $updated = false;
1117
1118 if(!$updated)
1119 {
1120 $fanwe = & FanweService::instance();
1121 foreach($fanwe->session->var as $k => $v)
1122 {
1123 if(isset($_FANWE['user'][$k]) && $k != 'last_activity')
1124 $fanwe->session->set($k, $_FANWE['user'][$k]);
1125 }
1126
1127 $fanwe->session->update();
1128
1129 $updated = true;
1130 }
1131
1132 return $updated;
1133 }
1134
1135 /**
1136 * 获取cookie
1137 * @param string $key 键名
1138 * @return bool
1139 */
1140 function getCookie($key)
1141 {
1142 global $_FANWE;
1143 return isset($_FANWE['cookie'][$key]) ? $_FANWE['cookie'][$key] : '';
1144 }
1145
1146 /**
1147 * 生成表单随机数
1148 * @param string $specialadd 增加文本
1149 * @return string
1150 */
1151 function formHash($specialadd = '')
1152 {
1153 global $_FANWE;
1154 return substr(md5(substr(TIME_UTC, 0, -7).$_FANWE['user_name'].$_FANWE['uid'].$_FANWE['authkey'].$specialadd), 8, 8);
1155 }
1156
1157 /**
1158 * 安全代码处理
1159 * @param string $string 要处理的文本
1160 * @param string $operation 处理方式(DECODE:解码,ENCODE:编码)
1161 * @param string $key 密匙
1162 * @param int $expiry 过期时间
1163 * @return string
1164 */
1165 function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
1166 {
1167 global $_FANWE;
1168 $ckey_length = 4;
1169 $key = md5($key != '' ? $key : $_FANWE['authkey']);
1170 $keya = md5(substr($key, 0, 16));
1171 $keyb = md5(substr($key, 16, 16));
1172 $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
1173
1174 $cryptkey = $keya.md5($keya.$keyc);
1175 $key_length = strlen($cryptkey);
1176
1177 $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
1178 $string_length = strlen($string);
1179
1180 $result = '';
1181 $box = range(0, 255);
1182
1183 $rndkey = array();
1184 for($i = 0; $i <= 255; $i++)
1185 {
1186 $rndkey[$i] = ord($cryptkey[$i % $key_length]);
1187 }
1188
1189 for($j = $i = 0; $i < 256; $i++)
1190 {
1191 $j = ($j + $box[$i] + $rndkey[$i]) % 256;
1192 $tmp = $box[$i];
1193 $box[$i] = $box[$j];
1194 $box[$j] = $tmp;
1195 }
1196
1197 for($a = $j = $i = 0; $i < $string_length; $i++)
1198 {
1199 $a = ($a + 1) % 256;
1200 $j = ($j + $box[$a]) % 256;
1201 $tmp = $box[$a];
1202 $box[$a] = $box[$j];
1203 $box[$j] = $tmp;
1204 $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
1205 }
1206
1207 if($operation == 'DECODE')
1208 {
1209 if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16))
1210 {
1211 return substr($result, 26);
1212 } else {
1213 return '';
1214 }
1215 }
1216 else
1217 {
1218 return $keyc.str_replace('=', '', base64_encode($result));
1219 }
1220
1221 }
1222
1223 /**
1224 * 获取语言文本
1225 * @param string $file 所在文件
1226 * @param string $var 键
1227 * @param string $default 默认值
1228 * @return mixed
1229 */
1230 function lang($file, $var = NULL, $default = NULL)
1231 {
1232 global $_FANWE;
1233
1234 $key = $file."_lang";
1235
1236 if(!isset($_FANWE['lang'][$key]))
1237 {
1238 include fimport("language/$file");
1239 $_FANWE['lang'][$key] = $lang;
1240 }
1241
1242 $return = $var !== NULL ? (isset($_FANWE['lang'][$key][$var]) ? $_FANWE['lang'][$key][$var] : NULL) : $_FANWE['lang'][$key];
1243
1244 $return = $return === NULL ? ($default !== NULL ? $default : $var) : $return;
1245
1246 return $return;
1247 }
1248
1249 /**
1250 * 获取IP列表中是否存在指定的IP
1251 * @param string $ip ip
1252 * @param string $access_list ip列表
1253 * @return bool
1254 */
1255 function ipAccess($ip, $access_list)
1256 {
1257 return preg_match("/^(".str_replace(array("\r\n", ' '), array('|', ''), preg_quote($access_list, '/')).")/", $ip);
1258 }
1259
1260 /**
1261 * 获取IP是否充许访问
1262 * @param string $ip ip
1263 * @return bool
1264 */
1265 function ipBanned($ip)
1266 {
1267 global $_FANWE;
1268
1269 if($_FANWE['setting']['ip_access'] && !ipAccess($ip, $_FANWE['setting']['ip_access']))
1270 {
1271 return true;
1272 }
1273
1274 FanweService::instance()->cache->loadCache('ipbanned');
1275
1276 if(empty($_FANWE['cache']['ipbanned']))
1277 return false;
1278 else
1279 {
1280 if($_FANWE['cache']['ipbanned']['expiration'] < TIME_UTC)
1281 {
1282 FanweService::instance()->cache->updateCache('ipbanned');
1283 }
1284
1285 return preg_match("/^(".$_FANWE['cache']['ipbanned']['regexp'].")$/", $ip);
1286 }
1287 }
1288
1289 /**
1290 * 获取模板cache文件路径
1291 * @param string $file 模板文件
1292 * @param array $args 参数
1293 * @param int $is_dynamic 是否为动态缓存(动态缓存页面在清空缓存,不删除)
1294 * @param string $dir 缓存目录
1295 * @return string
1296 */
1297 function getTplCache($file, $args = array(), $is_dynamic = 0,$dir = '')
1298 {
1299 global $_FANWE;
1300 $tpl_dir = './tpl/'.$_FANWE['setting']['site_tmpl'];
1301 $tpl_file = $tpl_dir.'/'.$file.'.htm';
1302
1303 if(!empty($dir))
1304 $dir .= '/';
1305
1306 switch($is_dynamic)
1307 {
1308 case 1:
1309 $dir = 'dynamic/'.$dir;
1310 break;
1311
1312 case 2:
1313 $dir = 'page/'.$dir;
1314 break;
1315
1316 default:
1317 $dir = 'static/'.$dir;
1318 break;
1319 }
1320
1321 if(!empty($args))
1322 {
1323 $tpl_file .= http_build_query($args);
1324 }
1325 $filename = md5($tpl_file);
1326 return PUBLIC_ROOT.'./data/tpl/caches/'.$dir.str_replace('/', '_', $file).'/'.substr($filename,0,2)."/".substr($filename,2,2)."/".$filename.".htm";
1327 }
1328
1329 /**
1330 * 检测模板是否需要更新
1331 * @param string $main_tpl
1332 * @param string $sub_tpl
1333 * @param int $time_compare
1334 * @param string $cache_file
1335 * @param string $tpl_dir
1336 * @param string $file
1337 * @return bool
1338 */
1339 function checkTplRefresh($main_tpl, $sub_tpl, $time_compare, $cache_file, $tpl_dir, $file)
1340 {
1341 global $_FANWE;
1342 static $tpl_refresh = NULL;
1343 if($tpl_refresh === NULL)
1344 {
1345 $tpl_refresh = $_FANWE['config']['output']['tpl_refresh'];
1346 }
1347
1348 if(empty($time_compare) || $tpl_refresh == 1 || ($tpl_refresh > 1 && !(TIMESTAMP % $tpl_refresh)))
1349 {
1350 if(empty($time_compare) || @filemtime(FANWE_ROOT.$sub_tpl) > $time_compare)
1351 {
1352 require_once fimport('class/template');
1353 $template = new Template();
1354 $template->parseTemplate($main_tpl, $tpl_dir, $file, $cache_file);
1355 return TRUE;
1356 }
1357 }
1358 return FALSE;
1359 }
1360
1361 /**
1362 * 模板处理
1363 * @param string $file
1364 * @param string $tpl_dir
1365 * @param bool $get_tpl_file
1366 * @return string
1367 */
1368 function template($file, $tpl_dir = '', $get_tpl_file = 0)
1369 {
1370 global $_FANWE;
1371
1372 $tpl_dir = $tpl_dir ? $tpl_dir : './tpl/'.$_FANWE['setting']['site_tmpl'];
1373 $tpl_file = $tpl_dir.'/'.$file.'.htm';
1374 $cache_file = './data/tpl/compiled/'.str_replace('/', '_', $file).'.tpl.php';
1375
1376 if($get_tpl_file)
1377 return $tpl_file;
1378
1379 checkTplRefresh($tpl_file, $tpl_file, @filemtime(PUBLIC_ROOT.$cache_file), $cache_file, $tpl_dir, $file);
1380 return PUBLIC_ROOT.$cache_file;
1381 }
1382
1383 /**
1384 * 获取模板编译后内容
1385 * @param string $file
1386 * @param array $args
1387 * @param string $tpl_dir
1388 * @return string
1389 */
1390 function tplFetch($file,&$args = array(), $tpl_dir = '',$cache_file = '')
1391 {
1392 global $_FANWE;
1393
1394 if(!empty($args))
1395 {
1396 foreach($args as $key=>$val)
1397 {
1398 $$key = &$args[$key];
1399 }
1400 }
1401
1402 ob_start();
1403 if(!empty($cache_file) && file_exists($cache_file))
1404 include $cache_file;
1405 else
1406 include template($file,$tpl_dir);
1407 $content = ob_get_contents();
1408 ob_end_clean();
1409
1410 if(empty($cache_file))
1411 express($content);
1412
1413
1414 if(!empty($cache_file) && !file_exists($cache_file))
1415 {
1416 express($content);
1417 $dynamic_php = '';
1418 if(isset($_FANWE['tpl_image_formats']))
1419 $dynamic_php .= "<?php\n".' setTplFormats(\'tpl_image_formats\','.var_export($_FANWE['tpl_image_formats'], true).");\n?>";
1420
1421 if(makeDir(preg_replace("/^(.*)\/.*?\.htm$/is", "\\1", $cache_file)))
1422 writeFile($cache_file,$dynamic_php.$content);
1423 }
1424
1425 require_once fimport('dynamic/common');
1426 $module_dynamic = '';
1427 if(defined('MODULE_NAME') && MODULE_NAME != '')
1428 $module_dynamic = fimport('dynamic/'.MODULE_NAME);
1429
1430 if(!empty($module_dynamic) && file_exists($module_dynamic))
1431 require_once $module_dynamic;
1432
1433 $content = preg_replace('/<!--dynamic\s+(.+?)(?:|\sargs=(.*?))-->/ies', "\\1('\\2');", $content);
1434
1435 //格式化会员关注
1436 formatUserFollowTags($content);
1437 formatImageTags($content);
1438 contentParse($content);
1439
1440 return $content;
1441 }
1442
1443 /**
1444 * 处理模板字符串,并返回编译后内容
1445 * @param string $string
1446 * @param string $cache_key
1447 * @param array $args
1448 * @return string
1449 */
1450 function tplString($string,$cache_key,&$args = array())
1451 {
1452 global $_FANWE;
1453
1454 if(!empty($args))
1455 {
1456 foreach($args as $key=>$val)
1457 {
1458 $$key = &$args[$key];
1459 }
1460 }
1461
1462 if(empty($cache_key))
1463 $cache_key = md5($string);
1464
1465 $cache_file = PUBLIC_ROOT.'./data/tpl/caches/'.$cache_key.'.htm';
1466
1467 if(!file_exists($cache_file))
1468 {
1469 if(makeDir(preg_replace("/^(.*)\/.*?\.htm$/is", "\\1", $cache_file)))
1470 {
1471 require_once fimport('class/template');
1472 $template = new Template();
1473 $string = $template->parseString($string);
1474 writeFile($cache_file,$string);
1475 }
1476 }
1477
1478 ob_start();
1479 include $cache_file;
1480 $content = ob_get_contents();
1481 ob_end_clean();
1482
1483 require_once fimport('dynamic/common');
1484 $module_dynamic = '';
1485 if(defined('MODULE_NAME') && MODULE_NAME != '')
1486 $module_dynamic = fimport('dynamic/'.MODULE_NAME);
1487
1488 if(!empty($module_dynamic) && file_exists($module_dynamic))
1489 require_once $module_dynamic;
1490
1491 $content = preg_replace('/<!--dynamic\s+(.+?)(?:|\sargs=(.*?))-->/ies', "\\1('\\2');", $content);
1492 //格式化会员关注
1493 express($content);
1494 formatUserFollowTags($content);
1495 formatImageTags($content);
1496 contentParse($content);
1497 return $content;
1498 }
1499
1500 /**
1501 * 显示页面
1502 * @param string $cache_file 缓存路径
1503 * @param bool $is_session 是否更新session
1504 * @param bool $is_return 是否返回页面内容
1505 * @return mixed
1506 */
1507 function display($cache_file = '',$is_session = true,$is_return = false)
1508 {
1509 global $_FANWE;
1510 $content = NULL;
1511 if(!empty($cache_file) && !file_exists($cache_file))
1512 {
1513 if(makeDir(preg_replace("/^(.*)\/.*?\.htm$/is", "\\1", $cache_file)))
1514 {
1515 $dynamic_php = '';
1516 if(isset($_FANWE['page_parses']))
1517 $dynamic_php = "<?php\n".' $_FANWE[\'CACHE_CSS_SCRIPT_PHP\']'." = ".var_export($_FANWE['page_parses'], true).";\n?>";
1518
1519 $content = ob_get_contents();
1520 express($content);
1521
1522 if(isset($_FANWE['tpl_image_formats']))
1523 $dynamic_php .= "<?php\n".' setTplFormats(\'tpl_image_formats\','.var_export($_FANWE['tpl_image_formats'], true).");\n?>";
1524
1525 writeFile($cache_file,$dynamic_php.$content);
1526 }
1527 }
1528
1529 require_once fimport('dynamic/common');
1530 $module_dynamic = '';
1531 if(defined('MODULE_NAME') && MODULE_NAME != '')
1532 $module_dynamic = fimport('dynamic/'.MODULE_NAME);
1533
1534 if(!empty($module_dynamic) && file_exists($module_dynamic))
1535 require_once $module_dynamic;
1536
1537 if($content === NULL)
1538 {
1539 $content = ob_get_contents();
1540 express($content);
1541 }
1542 ob_end_clean();
1543
1544 $content = preg_replace('/<!--dynamic\s+(.+?)(?:|\sargs=(.*?))-->/ies', "\\1('\\2');", $content);
1545
1546 if(isset($_FANWE['CACHE_CSS_SCRIPT_PHP']))
1547 {
1548 if(isset($_FANWE['CACHE_CSS_SCRIPT_PHP']['css']))
1549 {
1550 foreach($_FANWE['CACHE_CSS_SCRIPT_PHP']['css'] as $url)
1551 {
1552 cssParse($url);
1553 }
1554 }
1555
1556 if(isset($_FANWE['CACHE_CSS_SCRIPT_PHP']['script']))
1557 {
1558 foreach($_FANWE['CACHE_CSS_SCRIPT_PHP']['script'] as $url)
1559 {
1560 scriptParse($url);
1561 }
1562 }
1563 }
1564
1565 //格式化会员关注
1566 formatUserFollowTags($content);
1567 formatImageTags($content);
1568 contentParse($content);
1569
1570 if($is_session)
1571 updateSession();
1572
1573 if($is_return)
1574 return $content;
1575
1576 $_FANWE['config']['gzip_compress'] ? ob_start('ob_gzhandler') : ob_start();
1577 echo $content;
1578 }
1579
1580 function contentParse(&$content)
1581 {
1582 global $_FANWE;
1583 $patterns = array (
1584 "/\.\/public\/js\//i",
1585 "/\.\/public\/upload\//i",
1586 "/\.\/public\//i",
1587 //"/\.\/tpl\/(.*?)\/css\//i",
1588 //"/\.\/tpl\/(.*?)\/js\//i",
1589 //"/\.\/tpl\/(.*?)\/images\//i",
1590 "/\.\/tpl\/css\//i",
1591 "/\.\/tpl\/images\//i",
1592 "/\.\/tpl\/js\//i",
1593 "/\.\/tpl\/(.*?)\//i",
1594 );
1595
1596 $image_url = !empty($_FANWE['config']['cdn']['image']) ? $_FANWE['config']['cdn']['image'] : $_FANWE['site_root'];
1597 $css_url = !empty($_FANWE['config']['cdn']['css']) ? $_FANWE['config']['cdn']['css'] : $_FANWE['site_root'];
1598 $js_url = !empty($_FANWE['config']['cdn']['js']) ? $_FANWE['config']['cdn']['js'] : $_FANWE['site_root'];
1599
1600 $replace = array (
1601 $js_url.'public/js/',
1602 $image_url.'public/upload/',
1603 $_FANWE['site_root'].'public/',
1604 //$css_url.'tpl/\\1/css/',
1605 //$js_url.'tpl/\\1/js/',
1606 //$image_url.'tpl/\\1/images/',
1607 $_FANWE['site_root'].'public/data/tpl/css/',
1608 $_FANWE['site_root'].'tpl/'.TMPL.'/images/',
1609 $_FANWE['site_root'].'tpl/'.TMPL.'/js/',
1610 $_FANWE['site_root'].'tpl/\\1/',
1611 );
1612
1613 if(FS('Image')->getIsServer())
1614 {
1615 if(!isset($_FANWE['cache']['image_servers']))
1616 FanweService::instance()->cache->loadCache('image_servers');
1617 foreach($_FANWE['cache']['image_servers']['all'] as $server)
1618 {
1619 $patterns[] = "/\.\/".$server['code']."\//i";
1620 $replace[] = $server['url'];
1621 }
1622 }
1623
1624 if(isset($_FANWE['UPYUN_SETTING']))
1625 {
1626 $patterns[] = "/\.\/upyun\//i";
1627 $replace[] = $_FANWE['UPYUN_SETTING']['url'].'/';
1628 }
1629
1630 $content = preg_replace($patterns,$replace, $content);
1631 }
1632
1633 function clearExpress($content)
1634 {
1635 return preg_replace("/\[[^\]]+\]/i",'',$content);
1636 }
1637
1638 function express(&$content)
1639 {
1640 global $_FANWE;
1641
1642 $express = getCache('emotion_express_cache'); //缓存过的表情hash
1643 if(!$express)
1644 {
1645 $express_rs = FDB::fetchAll("select `emotion`,concat('".$_FANWE['site_root']."public/expression/',`type`,'/',`filename`) as fname from ".FDB::table('expression'));
1646 foreach($express_rs as $k=>$row)
1647 {
1648 $express[0][] = $row['emotion'];
1649 $express[1][] = "<img src='".$row['fname']."' title='".preg_replace("/[\[\]]/",'',$row['emotion'])."' />";
1650 }
1651 setCache('emotion_express_cache',$express);
1652 }
1653
1654 preg_match("/(<html.*?>.*?<\/head>)/s",$content,$data);
1655 $head_html = $data[1];
1656 $content = str_replace($head_html,'<!--TAG_HEADER-->',$content);
1657
1658 preg_match_all("/(<textarea.*?>.*?<\/textarea>)/s",$content,$data);
1659 $textareas = $data[1];
1660 if(count($textareas) > 0)
1661 {
1662 foreach($textareas as $key => $textarea)
1663 {
1664 $content = str_replace($textarea,'<!--TAG_TEXTAREA_'.$key.'-->',$content);
1665 }
1666 }
1667
1668 preg_match_all("/#([^\f\n\r\t\v]{1,80}?)#/",$content,$events);
1669 if(!empty($events[1]))
1670 {
1671 $patterns = array();
1672 $replace = array();
1673 $events = array_unique($events[1]);
1674 $arr = array();
1675 foreach($events as $event)
1676 {
1677 if(!empty($event))
1678 {
1679 if(substr($event,0,3) != '35;' && substr($event,0,3) != '64;')
1680 $arr[] = addslashes($event);
1681 }
1682 }
1683
1684 $res = FDB::query('SELECT id,title
1685 FROM '.FDB::table('event').'
1686 WHERE title '.FDB::createIN($arr));
1687 while($data = FDB::fetch($res))
1688 {
1689 $patterns[] = '#'.$data['title'].'#';
1690 $replace[] = '<a href="'.FU("event/detail",array("id"=>$data['id'])).'" target="_blank">#'.str_replace('@','@',$data['title']).'#</a>';
1691 }
1692
1693 $content = str_replace($patterns,$replace,$content);
1694 }
1695
1696 preg_match_all("/@([^\f\n\r\t\v@<> ]{2,20}?)(?:\:| )/",$content,$users);
1697 if(!empty($users[1]))
1698 {
1699 $patterns = array();
1700 $replace = array();
1701 $users = array_unique($users[1]);
1702 $arr = array();
1703 foreach($users as $user)
1704 {
1705 if(!empty($user))
1706 {
1707 $arr[] = addslashes($user);
1708 }
1709 }
1710
1711 $res = FDB::query('SELECT uid,user_name
1712 FROM '.FDB::table('user').'
1713 WHERE user_name '.FDB::createIN($arr));
1714 while($data = FDB::fetch($res))
1715 {
1716 $patterns[] = '/@'.preg_quote($data['user_name']).'(\:| )/';
1717 $replace[] = '<a class="u_name GUID" uid="'.$data['uid'].'" href="'.FU('u/index',array('uid'=>$data['uid'])).'">@'.$data['user_name']."</a>\$1";
1718 }
1719
1720 $content = preg_replace($patterns,$replace,$content);
1721 }
1722
1723 if(count($_FANWE['tpl_user_formats']) > 0)
1724 {
1725 $patterns = array();
1726 $replace = array();
1727
1728 $user_ids = array_keys($_FANWE['tpl_user_formats']);
1729 $user_ids = implode(',',$user_ids);
1730 $user_ids = str_replace(',,',',',$user_ids);
1731 if(!empty($user_ids))
1732 {
1733 $res = FDB::query("SELECT u.uid,u.gid,u.user_name,u.avatar,u.reg_time,u.credits,u.is_daren,u.is_buyer,uc.* FROM ".FDB::table('user').' AS u
1734 INNER JOIN '.FDB::table('user_count').' AS uc USING(uid)
1735 WHERE u.uid IN ('.$user_ids.')');
1736 while($user = FDB::fetch($res))
1737 {
1738 $uid = $user['uid'];
1739 $user['url'] = FU('u/index',array('uid'=>$uid));
1740 foreach($_FANWE['tpl_user_formats'][$uid] as $tuf_key => $tuf_val)
1741 {
1742 $patterns[] = "<!--USER_".$uid."_".$tuf_key."-->";
1743 $replace[] = getUserFormatHtml($user,$tuf_val);
1744 }
1745 unset($_FANWE['tpl_user_formats'][$uid]);
1746 }
1747 $content = str_replace($patterns,$replace,$content);
1748 }
1749 }
1750
1751 $content = str_replace($express[0],$express[1],$content);
1752 $content = str_replace('<!--TAG_HEADER-->',$head_html,$content);
1753
1754 if(count($textareas) > 0)
1755 {
1756 foreach($textareas as $key => $textarea)
1757 {
1758 $content = str_replace('<!--TAG_TEXTAREA_'.$key.'-->',$textarea,$content);
1759 }
1760 }
1761 return $content;
1762 }
1763
1764 function setTplFormats($format_key,$format_list)
1765 {
1766 global $_FANWE;
1767 foreach($format_list as $rkey => $rformats)
1768 {
1769 if(is_array($rformats))
1770 {
1771 foreach($rformats as $ckey => $cformats)
1772 {
1773 if(!isset($_FANWE[$format_key][$rkey][$ckey]))
1774 $_FANWE[$format_key][$rkey][$ckey] = $cformats;
1775 }
1776 }
1777 }
1778 }
1779
1780 //加入会员格式化
1781 function setTplUserFormat($uid,$type,$is_mark,$img_type,$img_size,$link_class,$img_class,$tpl)
1782 {
1783 global $_FANWE;
1784 $uid = (int)$uid;
1785 $key = md5($type.'_'.$is_mark.'_'.$img_type.'_'.$img_size.'_'.$link_class.'_'.$img_class.'_'.$tpl);
1786 $_FANWE['tpl_user_formats'][$uid][$key] = array(
1787 'type' => $type,
1788 'is_mark'=>$is_mark,
1789 'img_type' => $img_type,
1790 'img_size' => $img_size,
1791 'link_class' => $link_class,
1792 'img_class' => $img_class,
1793 'tpl' => $tpl
1794 );
1795 return "<!--USER_".$uid."_".$key."-->";
1796 }
1797
1798 //获取会员格式化html
1799 function getUserFormatHtml($user,$format)
1800 {
1801 global $_FANWE;
1802 static $templates = array(),$daren_name = NULL;
1803 $html = '';
1804 $mark_html = '';
1805 if($format['is_mark'] == 1)
1806 {
1807 $group = $_FANWE['cache']['user_group'][$user['gid']];
1808 if(!empty($group['icon']))
1809 {
1810 $mark_html .= '<img alt="'.$group['name'].'" src="./public/icons/'.$group['icon'].'" class="v">';
1811 }
1812 elseif($user['is_daren'] == 1)
1813 {
1814 if($daren_name === NULL)
1815 $daren_name = sprintf(lang('user','daren_alt'),$_FANWE['setting']['site_name']);
1816 $mark_html .= '<a href="'.FU('daren/apply').'" class="v" target="_blank"><img title="'.$daren_name.'" src="./tpl/images/daren_icon.png" class="v"></a>';
1817 }
1818 elseif($user['is_buyer'] == 1)
1819 $mark_html .= '<a href="'.FU('settings/buyerverifier').'" class="v" target="_blank"><img title="'.lang('user','buyer_alt').'" src="./tpl/images/buyer_icon.png" class="v"></a>';
1820 }
1821
1822 if(!empty($format['tpl']))
1823 {
1824 if(!isset($templates[$format['tpl']]))
1825 $templates[$format['tpl']] = template($format['tpl']);
1826
1827 if($templates[$format['tpl']])
1828 {
1829 ob_start();
1830 include $templates[$format['tpl']];
1831 $html = ob_get_contents();
1832 ob_end_clean();
1833 }
1834 }
1835 else
1836 {
1837 $uid = $user['uid'];
1838 $user_name = htmlspecialchars($user['user_name']);
1839 if($format['type'] == 0)
1840 $html = '<a class="GUID '.$format['link_class'].'" uid="'.$uid.'" title="'.$user_name.'" href="'.$user['url'].'" target="_blank">'.$user_name.'</a>';
1841 elseif($format['type'] == 2)
1842 {
1843 $html = '<a href="javascript:;" onclick="$.AtMe_Share(this);" class="home_at_ta bc" toname="'.$user_name.'" >@'.$user_name.'</a>';
1844 }
1845 else
1846 {
1847 $width = '';
1848 if($format['img_size'] > 0)
1849 $width = 'width="'.$format['img_size'].'" ';
1850
1851 $is_lazyload = FALSE;
1852 $img_class = $format['img_class'];
1853 if(!empty($img_class))
1854 $is_lazyload = strpos($img_class,'lazyload');
1855
1856 $link_class = '';
1857 if(!empty($format['link_class']))
1858 $link_class = 'class="'.$format['link_class'].'" ';
1859
1860 if($format['type'] == 3)
1861 {
1862 if($is_lazyload === FALSE)
1863 $html = '<img class="'.$img_class.'" src="'.setTplAvatarFormat($user['avatar'],$format['img_type']).'" '.$width.' />';
1864 else
1865 $html = '<img class="'.$img_class.'" original="'.setTplAvatarFormat($user['avatar'],$format['img_type']).'" src="./tpl/images/lazyload.gif" '.$width.'/>';
1866 }
1867 elseif($format['type'] == 4)
1868 {
1869 $html = '<a '.$link_class.'title="'.$user_name.'" href="'.$user['url'].'" target="_blank">@'.$user_name.'</a>';
1870 }
1871 else
1872 {
1873 if($is_lazyload === FALSE)
1874 $html = '<a '.$link_class.'title="'.$user_name.'" href="'.$user['url'].'" target="_blank"><img class="GUID '.$img_class.'" uid="'.$uid.'" src="'.setTplAvatarFormat($user['avatar'],$format['img_type']).'" '.$width.' alt="'.$user_name.'"/></a>';
1875 else
1876 $html = '<a '.$link_class.'title="'.$user_name.'" href="'.$user['url'].'" target="_blank"><img class="GUID '.$img_class.'" uid="'.$uid.'" original="'.setTplAvatarFormat($user['avatar'],$format['img_type']).'" src="./tpl/images/lazyload.gif" '.$width.' alt="'.$user_name.'"/></a>';
1877 }
1878 }
1879 $html .= $mark_html;
1880 }
1881 return $html;
1882 }
1883
1884 function formatUserFollowTags(&$content)
1885 {
1886 global $_FANWE;
1887
1888 preg_match_all("/<!--getfollow\s(\d+?)\s(.+?)-->/",$content,$follows);
1889 if(!empty($follows[1]))
1890 {
1891 $patterns = array();
1892 $replace = array();
1893 $user_ids = array();
1894
1895 foreach($follows[1] as $key => $uid)
1896 {
1897 $uid = (int)$uid;
1898 $tpl = $follows[2][$key];
1899 if($_FANWE['uid'] == $uid)
1900 {
1901 if(!isset($user_ids[$uid][$tpl]))
1902 {
1903 $patterns[] = "<!--getfollow ".$uid." ".$tpl."-->";
1904 $replace[] = getUserFollowFormatHtml($uid,-1,$tpl);
1905 $user_ids[$uid][$tpl] = -1;
1906 }
1907 }
1908 else
1909 {
1910 $user_ids[$uid]['is_follow'] = 0;
1911 $user_ids[$uid]['tpls'][$tpl] = 0;
1912 }
1913 }
1914 unset($user_ids[$_FANWE['uid']]);
1915
1916 if($_FANWE['uid'] > 0)
1917 {
1918 $follow_ids = array_keys($user_ids);
1919 if(count($follow_ids) > 0)
1920 {
1921 $follow_ids = implode(',',$follow_ids);
1922 $follow_ids = str_replace(',,',',',$follow_ids);
1923 if(!empty($follow_ids))
1924 {
1925 $res = FDB::query("SELECT uid FROM ".FDB::table('user_follow').'
1926 WHERE f_uid = '.$_FANWE['uid'].' AND uid IN ('.$follow_ids.')');
1927 while($item = FDB::fetch($res))
1928 {
1929 $user_ids[$item['uid']]['is_follow'] = 1;
1930 }
1931 }
1932 }
1933 }
1934
1935 foreach($user_ids as $uid => $user)
1936 {
1937 $is_follow = $user['is_follow'];
1938 foreach($user['tpls'] as $tpl => $temp)
1939 {
1940 $patterns[] = "<!--getfollow ".$uid." ".$tpl."-->";
1941 $replace[] = getUserFollowFormatHtml($uid,$is_follow,$tpl);
1942 }
1943 }
1944
1945 $content = str_replace($patterns,$replace,$content);
1946 }
1947 }
1948
1949 //获取会员关注格式化html
1950 function getUserFollowFormatHtml($uid,$is_follow,$tpl)
1951 {
1952 static $templates = array();
1953 $html = '';
1954
1955 if(!isset($templates[$tpl]))
1956 $templates[$tpl] = template($tpl);
1957
1958 if($templates[$tpl])
1959 {
1960 ob_start();
1961 include $templates[$tpl];
1962 $html = ob_get_contents();
1963 ob_end_clean();
1964 }
1965
1966 return $html;
1967 }
1968
1969 //加入图片格式化
1970 function setTplImageFormat($id,$width,$height,$gen,$is_full)
1971 {
1972 global $_FANWE;
1973 $id = (int)$id;
1974 $width = (int)$width;
1975 $height = (int)$height;
1976 $gen = (int)$gen;
1977 $is_full = (int)$is_full;
1978
1979 $key = md5($width.'_'.$height.'_'.$gen.'_'.$is_full);
1980 $_FANWE['tpl_image_formats'][$id][$key] = array(
1981 'width' => $width,
1982 'height'=>$height,
1983 'gen' => $gen,
1984 'is_full' => $is_full
1985 );
1986 return "<!--IMAGE_".$id."_".$key."-->";
1987 }
1988
1989 function setTplAvatarFormat($id,$type)
1990 {
1991 global $_FANWE;
1992 $id = (int)$id;
1993 $type = trim($type);
1994
1995 if($id == 0)
1996 {
1997 switch($type)
1998 {
1999 case 'm':
2000 return './public/upload/avatar/noavatar_middle.jpg';
2001 break;
2002 case 'b':
2003 return './public/upload/avatar/noavatar_big.jpg';
2004 break;
2005 default:
2006 return './public/upload/avatar/noavatar_small.jpg';
2007 break;
2008 }
2009 }
2010
2011 static $types = NULL;
2012 if($types === NULL)
2013 {
2014 FS("Image")->getImageArgs($types,'avatar');
2015 $types = $types['types'];
2016 }
2017
2018 $size = $types['s'];
2019 if(array_key_exists($type,$types))
2020 $size = $types[$type];
2021
2022 return setTplImageFormat($id,$size,$size,1,0);
2023 }
2024
2025 function formatImageTags(&$content)
2026 {
2027 global $_FANWE;
2028 if(isset($_FANWE['tpl_image_formats']) && count($_FANWE['tpl_image_formats']) > 0)
2029 {
2030 $patterns = array();
2031 $replace = array();
2032
2033 $img_ids = array_keys($_FANWE['tpl_image_formats']);
2034 $img_list = FS('Image')->getImageListByIds($img_ids);
2035 if(count($img_list) > 0)
2036 {
2037 foreach($img_list as $img_id => $img)
2038 {
2039 foreach($_FANWE['tpl_image_formats'][$img_id] as $img_key => $img_val)
2040 {
2041 $patterns[] = "<!--IMAGE_".$img_id."_".$img_key."-->";
2042 $replace[] = formatImage($img,$img_val['width'],$img_val['height'],$img_val['gen'],$img_val['is_full']);
2043 }
2044 }
2045 $content = str_replace($patterns,$replace,$content);
2046 }
2047 }
2048 }
2049
2050 /**
2051 * 清除缓存目录
2052 * @param string $file 缓存模板目录
2053 * @param int $is_dynamic 是否为动态缓存
2054 * @param string $dir 缓存目录
2055 * @return void
2056 */
2057 function clearTplCache($file,$is_dynamic = 0,$dir='')
2058 {
2059 if(!empty($dir))
2060 $dir .= '/';
2061 $dir = ($is_dynamic == 1 ? 'dynamic/' : 'static/').$dir;
2062 clearDir(PUBLIC_ROOT.'./data/tpl/caches/'.$dir.str_replace('/', '_', $file));
2063 }
2064
2065 /**
2066 * 检测缓存文件是否需要更新
2067 * @param string $cache_file 缓存文件路径
2068 * @param int $time_out 缓存时间(秒)
2069 * @param int $is_clear 清除缓存
2070 * @return bool 需要更新返回 true
2071 */
2072 function getCacheIsUpdate($cache_file,$time_out,$is_clear = 0)
2073 {
2074 if (!file_exists($cache_file))
2075 return true;
2076
2077 $time_clear = 0;
2078 if($is_clear == 1)
2079 {
2080 $clear_path = FANWE_ROOT.'./public/data/is_clear.lock';
2081 if(file_exists($clear_path))
2082 $time_clear = (int)@file_get_contents($clear_path);
2083 }
2084
2085 $mtime = filemtime($cache_file);
2086 if($time_clear > 0 && $mtime < $time_clear)
2087 {
2088 removeFile($cache_file);
2089 return true;
2090 }
2091 elseif(TIMESTAMP - $mtime > $time_out)
2092 {
2093 removeFile($cache_file);
2094 return true;
2095 }
2096 else
2097 return false;
2098 }
2099
2100 /**
2101 * 输出json信息
2102 * @param mixed $result 要输出的信息
2103 * @return void
2104 */
2105 function outputJson($result,$is_die = true)
2106 {
2107 static $json = NULL;
2108 if($json === NULL)
2109 {
2110 require fimport('class/json');
2111 $json = new Json();
2112 }
2113
2114 if($is_die)
2115 die($json->encode($result));
2116 else
2117 return $json->encode($result);
2118 }
2119
2120 /**
2121 * 返回json信息
2122 * @param mixed $result
2123 * @return string
2124 */
2125 function getJson($result)
2126 {
2127 static $json = NULL;
2128 if($json === NULL)
2129 {
2130 require fimport('class/json');
2131 $json = new Json();
2132 }
2133 return $json->encode($result);
2134 }
2135
2136 /**
2137 * 清除指定目录下的文件
2138 * @param string $dir 目录路径
2139 * @return void
2140 */
2141 function clearDir($dir,$is_del_dir = false)
2142 {
2143 if(!file_exists($dir))
2144 return;
2145
2146 $directory = dir($dir);
2147
2148 while($entry = $directory->read())
2149 {
2150 if($entry != '.' && $entry != '..')
2151 {
2152 $filename = $dir.'/'.$entry;
2153 if(is_dir($filename))
2154 clearDir($filename,$is_del_dir);
2155
2156 if(is_file($filename))
2157 removeFile($filename);
2158 }
2159 }
2160
2161 $directory->close();
2162 if($is_del_dir)
2163 @rmdir($dir);
2164 }
2165
2166 /**
2167 * 检查目标文件夹是否存在,如果不存在则自动创建该目录
2168 *
2169 * @access public
2170 * @param string folder 目录路径。不能使用相对于网站根目录的URL
2171 *
2172 * @return bool
2173 */
2174 function makeDir($folder)
2175 {
2176 $reval = false;
2177 if (!file_exists($folder))
2178 {
2179 $folder = str_replace(FANWE_ROOT,'',$folder);
2180 /* 如果目录不存在则尝试创建该目录 */
2181 @umask(0);
2182 /* 将目录路径拆分成数组 */
2183 preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);
2184 /* 如果第一个字符为/则当作物理路径处理 */
2185 $base = FANWE_ROOT.(($atmp[0][0] == '/') ? '/' : '');
2186
2187 /* 遍历包含路径信息的数组 */
2188 foreach ($atmp[1] AS $val)
2189 {
2190 if ('' != $val)
2191 {
2192 $base .= $val;
2193 if ('..' == $val || '.' == $val)
2194 {
2195 /* 如果目录为.或者..则直接补/继续下一个循环 */
2196 $base .= '/';
2197 continue;
2198 }
2199 }
2200 else
2201 {
2202 continue;
2203 }
2204 $base .= '/';
2205
2206 if (!file_exists($base))
2207 {
2208 /* 尝试创建目录,如果创建失败则继续循环 */
2209 if (@mkdir(rtrim($base, '/'), 0777))
2210 {
2211 @chmod($base, 0777);
2212 $reval = true;
2213 }
2214 }
2215 }
2216 }
2217 else
2218 {
2219 /* 路径已经存在。返回该路径是不是一个目录 */
2220 $reval = is_dir($folder);
2221 }
2222
2223 clearstatcache();
2224 return $reval;
2225 }
2226
2227 /**
2228 * utf8字符串转为GBK字符串
2229 * @param string $str 要转换的字符串
2230 * @return void
2231 */
2232 function utf8ToGB($str)
2233 {
2234 static $chinese = NULL;
2235 if($chinese === NULL)
2236 {
2237 require_once fimport('class/chinese');
2238 $chinese = new Chinese('UTF-8','GBK');
2239 }
2240 return $chinese->convert($str);
2241 }
2242
2243 /**
2244 * GBK字符串转utf8为字符串
2245 * @param string $str 要转换的字符串
2246 * @return void
2247 */
2248 function gbToUTF8($str)
2249 {
2250 static $chinese = NULL;
2251 if($chinese === NULL)
2252 {
2253 require_once fimport('class/chinese');
2254 $chinese = new Chinese('GBK','UTF-8');
2255 }
2256 return $chinese->convert($str);
2257 }
2258
2259 /**
2260 * utf8字符转Unicode字符
2261 * @param string $char 要转换的单字符
2262 * @return void
2263 */
2264 function utf8ToUnicode($char)
2265 {
2266 switch(strlen($char))
2267 {
2268 case 1:
2269 return ord($char);
2270 case 2:
2271 $n = (ord($char[0]) & 0x3f) << 6;
2272 $n += ord($char[1]) & 0x3f;
2273 return $n;
2274 case 3:
2275 $n = (ord($char[0]) & 0x1f) << 12;
2276 $n += (ord($char[1]) & 0x3f) << 6;
2277 $n += ord($char[2]) & 0x3f;
2278 return $n;
2279 case 4:
2280 $n = (ord($char[0]) & 0x0f) << 18;
2281 $n += (ord($char[1]) & 0x3f) << 12;
2282 $n += (ord($char[2]) & 0x3f) << 6;
2283 $n += ord($char[3]) & 0x3f;
2284 return $n;
2285 }
2286 }
2287
2288 /**
2289 * utf8字符串分隔为unicode字符串
2290 * @param string $str 要转换的字符串
2291 * @param string $pre
2292 * @return string
2293 */
2294 function segmentToUnicode($str,$pre = '')
2295 {
2296 $arr = array();
2297 $str_len = mb_strlen($str,'UTF-8');
2298 for($i = 0;$i < $str_len;$i++)
2299 {
2300 $s = mb_substr($str,$i,1,'UTF-8');
2301 if($s != ' ' && $s != ' ')
2302 {
2303 $arr[] = $pre.'ux'.utf8ToUnicode($s);
2304 }
2305 }
2306
2307 $arr = array_unique($arr);
2308
2309 return implode(' ',$arr);
2310 }
2311
2312 /**
2313 * 将标签数组转换为unicode字符串
2314 * @param array $tags 要转换的标签
2315 * @param string $pre
2316 * @return string
2317 */
2318 function tagToUnicode($tags,$pre = '')
2319 {
2320 $tags = array_unique($tags);
2321
2322 $arr = array();
2323 foreach($tags as $tag)
2324 {
2325 $tmp = '';
2326 $str_len = mb_strlen($tag,'UTF-8');
2327 for($i = 0;$i < $str_len;$i++)
2328 {
2329 $s = mb_substr($tag,$i,1,'UTF-8');
2330 if($s != ' ' && $s != ' ')
2331 {
2332 $tmp.= 'ux'.utf8ToUnicode($s);
2333 }
2334 }
2335
2336 if($tmp != '')
2337 $arr[] = $pre.$tmp;
2338 }
2339
2340 $arr = array_unique($arr);
2341 return implode(' ',$arr);
2342 }
2343
2344 /**
2345 * 清除符号
2346 * @param string $str 要清除符号的字符串
2347 * @return string
2348 */
2349 function clearSymbol($str)
2350 {
2351 static $symbols = NULL;
2352 if($symbols === NULL)
2353 {
2354 $symbols = file_get_contents(PUBLIC_ROOT.'./table/symbol.table');
2355 $symbols = explode("\r\n",$symbols);
2356 }
2357
2358 return str_replace($symbols,"",$str);
2359 }
2360
2361 /**
2362 * 对 MYSQL LIKE 的内容进行转义
2363 *
2364 * @access public
2365 * @param string string 内容
2366 * @return string
2367 */
2368 function fMysqlLikeQuote($str)
2369 {
2370 return strtr($str, array("\\\\" => "\\\\\\\\", '_' => '\_', '%' => '\%', "\'" => "\\\\\'"));
2371 }
2372
2373 /**
2374 * 页面跳转
2375 * @param string $string
2376 * @param bool $replace
2377 * @param int $http_response_code
2378 * @return void
2379 */
2380 function fHeader($string, $replace = true, $http_response_code = 0)
2381 {
2382 global $_FANWE;
2383
2384 $string = str_replace(array("\r", "\n"), array('', ''), $string);
2385 $reg = '/location:\s?'.preg_quote($_FANWE['site_root'], '/').'/i';
2386 $string = preg_replace($reg,'Location: '.$_FANWE['site_url'], $string);
2387
2388 if(strpos($string,$_FANWE['site_url']))
2389 {
2390 fSetCookie('from_heade',authcode(TIME_UTC,'ENCODE'));
2391 }
2392
2393 if(empty($http_response_code) || PHP_VERSION < '4.3' )
2394 {
2395 @header($string, $replace);
2396 }
2397 else
2398 {
2399 @header($string, $replace, $http_response_code);
2400 }
2401
2402 if(preg_match('/^\s*location:/is', $string))
2403 {
2404 exit();
2405 }
2406 }
2407
2408 /**
2409 * 显示指定名称的广告位布局
2410 * @param string $id 布局编号
2411 * @param int $count 显示数量
2412 * @param string $target 关键字
2413 * @return array
2414 */
2415 function getAdvLayout($id,$count = '',$target='')
2416 {
2417 global $_FANWE;
2418 $layout = FDB::fetchFirst('SELECT rec_id AS pid,item_limit AS acount,target_id AS target FROM '.FDB::table('layout')." WHERE layout_id ='$id' AND tmpl = '".$_FANWE['setting']['site_tmpl']."' AND rec_module = 'AdvPosition'");
2419
2420 if(!$layout)
2421 return '';
2422
2423 if($count != '')
2424 $layout['acount'] = intval($count);
2425
2426 if($target != '')
2427 $layout['target'] = explode(',',$target);
2428
2429 return getAdvPosition($layout['pid'],$layout['acount'],$layout['target']);
2430 }
2431
2432 /**
2433 * 显示指定ID的广告位ID
2434 * @param string $id 广告位
2435 * @param int $count 显示数量
2436 * @param string $target 关键字
2437 * @return array
2438 */
2439 function getAdvPosition($id,$count = '',$target='')
2440 {
2441 global $_FANWE;
2442
2443 if(is_numeric($id))
2444 $ap = FDB::fetchFirst('SELECT * FROM '.FDB::table('adv_position').' WHERE id ='.$id);
2445 else
2446 $ap = FDB::fetchFirst('SELECT * FROM '.FDB::table('adv_position')." WHERE code ='".$id."'");
2447
2448 if(!$ap)
2449 return '';
2450
2451 if($target != '')
2452 $target = explode(',',$target);
2453
2454 $where = "status = 1 AND position_id = '".$ap['id']."'";
2455 if($target != '')
2456 $where .= ' AND target_key'.FDB::createIN($target);
2457
2458 $sql = 'SELECT * FROM '.FDB::table('adv').' WHERE '.$where.' ORDER BY sort ASC,id DESC';
2459
2460 if($count > 0)
2461 $sql .= ' LIMIT 0,'.$count;
2462
2463 $adv_res = FDB::query($sql);
2464
2465 $adv_list = array();
2466
2467 while($adv = FDB::fetch($adv_res))
2468 {
2469 $adv['html'] = getAdvHTML($adv,$ap);
2470 $adv['durl'] = FU("adv/show",array("id"=>$adv['id']));
2471 $adv['turl'] = $adv['url'];
2472 $adv['url'] = urlencode(FU("adv/show",array("id"=>$adv['id'])));
2473 $adv_list[] = $adv;
2474 }
2475
2476 $ap['adv_list'] = $adv_list;
2477 return $ap;
2478 }
2479
2480 /**
2481 * 获取广告的html代码
2482 * @param array $adv 广告
2483 * @param array $ap 广告位
2484 * @return string
2485 */
2486 function getAdvHTML($adv,$ap)
2487 {
2488 if($ap['width'] == 0)
2489 $ap['width']="";
2490 else
2491 $ap['width']=" width='".$ap['width']."'";
2492
2493 if($ap['height'] == 0)
2494 $ap['height']="";
2495 else
2496 $ap['height']=" height='".$ap['height']."'";
2497
2498 switch($adv['type'])
2499 {
2500 case '1':
2501 if($adv['url']=='')
2502 $adv_str = "<img src='".$adv['code']."'".$ap['width'].$ap['height']."/>";
2503 else
2504 $adv_str = "<a href='".FU("adv/show",array("id"=>$adv['id']))."' target='_blank'><img src='".$adv['code']."'".$ap['width'].$ap['height']."/></a>";
2505 break;
2506 case '2':
2507 $adv_str = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0'".$ap['width'].$ap['height'].">".
2508 "<param name='movie' value='".$adv['code']."' />".
2509 "<param name='quality' value='high' />".
2510 "<param name='menu' value='false' />".
2511 "<embed src='".$adv['code']."' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash'".$ap['width'].$ap['height']."></embed>".
2512 "</object>";
2513 break;
2514 case '3':
2515 $adv_str = $adv['code'];
2516 break;
2517 }
2518
2519 return $adv_str;
2520 }
2521
2522 /**
2523 * 写入文件内容
2524 * @param string $filepat 文件路径
2525 * @param string $content 写入内容
2526 * @param string $type 写入方式 w:将文件指针指向文件头并将文件大小截为零 a:将文件指针指向文件末尾
2527 * @return string
2528 */
2529 function writeFile($filepath,$content,$type='w')
2530 {
2531 $is_success = false;
2532
2533 if($fp = fopen($filepath,$type))
2534 {
2535 /*$start_time = microtime();
2536 do
2537 {
2538 $is_write = flock($fp, LOCK_EX);
2539 if(!$is_write)
2540 usleep(round(rand(0,100) * 1000));
2541 }
2542 while(!$is_write && ((microtime() - $start_time) < 10000));
2543
2544 if ($is_write && fwrite($fp, $content))
2545 $is_success = true;*/
2546 @flock($fp, LOCK_EX);
2547 if (fwrite($fp, $content))
2548 $is_success = true;
2549 @flock($fp,LOCK_UN);
2550 @fclose($fp);
2551 @chmod($filepath, 0777);
2552 }
2553
2554 return $is_success;
2555 }
2556
2557 /**
2558 * 删除文件
2559 * @param string $filepat 文件路径
2560 * @return bool
2561 */
2562 function removeFile($filepath)
2563 {
2564 $is_success = false;
2565 /*do
2566 {
2567 @unlink($filepath);
2568 $is_exists = file_exists($filepath);
2569 if($is_exists)
2570 usleep(round(rand(0,100) * 1000));
2571 else
2572 $is_success = true;
2573 }
2574 while($is_exists && ((microtime() - $start_time) < 10000));*/
2575 @unlink($filepath);
2576 if(!file_exists($filepath))
2577 $is_success = true;
2578 return $is_success;
2579 }
2580
2581 /**
2582 * 获取缓存的数据
2583 * @param string $key 缓存键名 如果有目录 格式为 目录1/目录2/.../键名
2584 * @return mixed
2585 */
2586 function getCache($key)
2587 {
2588 static $caches = array();
2589 if(!isset($caches[$key]))
2590 {
2591 if(!file_exists(PUBLIC_ROOT.'./data/caches/custom/'.$key.'.cache.php'))
2592 return NULL;
2593 else
2594 {
2595 include(PUBLIC_ROOT.'./data/caches/custom/'.$key.'.cache.php');
2596 $list = explode('/',$key);
2597 $key = end($list);
2598 $cache_data = $data[$key];
2599
2600 if((int)$cache_data['expired_time'] > 0 && TIMESTAMP > (int)$cache_data['expired_time'])
2601 return NULL;
2602
2603 $time_clear = 0;
2604 $clear_path = FANWE_ROOT.'./public/data/is_clear.lock';
2605 if(file_exists($clear_path))
2606 $time_clear = (int)@file_get_contents($clear_path);
2607
2608 if(($time_clear > 0 && $cache_data['time'] < $time_clear))
2609 return NULL;
2610
2611 $caches[$key] = $cache_data['data'];
2612 }
2613 }
2614 return $caches[$key];
2615 }
2616
2617 /**
2618 * 设置缓存数据
2619 * @param string $key 缓存键名 可设置所在目录 格式为 目录1/目录2/.../键名
2620 * @param string $data 缓存的数据
2621 * @param string $expired_time 有效时长(秒),0 为不过期
2622 * @return bool
2623 */
2624 function setCache($key,$data,$expired_time = 0)
2625 {
2626 $cache_path = PUBLIC_ROOT.'./data/caches/custom/'.$key.'.cache.php';
2627 $phth = dirname($cache_path);
2628 makeDir($phth);
2629 $list = explode('/',$key);
2630 $key = end($list);
2631
2632 $cache_data = array();
2633 $cache_data['time'] = TIMESTAMP;
2634 $cache_data['expired_time'] = 0;
2635 if($expired_time > 0)
2636 $cache_data['expired_time'] = TIMESTAMP + $expired_time;
2637 $cache_data['data'] = $data;
2638
2639 $cache_content = var_export($cache_data, true);
2640 if(strpos($cache_content,'SimpleXMLElement') !== FALSE)
2641 return;
2642
2643 $cache_data = "<?php\n".'$data[\''.$key."'] = ".$cache_content.";\n\n?>";
2644 return writeFile($cache_path,$cache_data);
2645 }
2646
2647 /**
2648 * 生成临时缓存 (2小时后清除)
2649 */
2650 function setTempCache($key,$data)
2651 {
2652 $dir = './public/upload/temp/'.fToDate(NULL,'Y/m/d/H');
2653 if(empty($key))
2654 $key = md5(microtime(true)).random('6');
2655 $file_name = $key.'.cache.php';
2656 makeDir(FANWE_ROOT.$dir);
2657 $cache_path = FANWE_ROOT.$dir."/".$file_name;
2658 $cache_content = var_export($data, true);
2659 $cache_data = "<?php\n".'return'." ".$cache_content.";\n?>";
2660 writeFile($cache_path,$cache_data);
2661 return $dir."/".$file_name;
2662 }
2663
2664 /**
2665 * 获取临时缓存 (当前小时内)
2666 */
2667 function getTempCache($key)
2668 {
2669 $dir = './public/upload/temp/'.fToDate(NULL,'Y/m/d/H');
2670 $cache_path = FANWE_ROOT.$dir."/".$key.'.cache.php';
2671 if(!file_exists($cache_path))
2672 return NULL;
2673
2674 $data = @include $cache_path;
2675 return $data;
2676 }
2677
2678 /**
2679 * 删除缓存
2680 * @param string $key 缓存键名 如果有目录 格式为 目录1/目录2/.../键名
2681 * @return bool
2682 */
2683 function deleteCache($key)
2684 {
2685 return removeFile(PUBLIC_ROOT.'./data/caches/custom/'.$key.'.cache.php');
2686 }
2687
2688 /**
2689 * 清空缓存目录
2690 * @param string $dir 缓存目录
2691 * @return void
2692 */
2693 function clearCacheDir($dir)
2694 {
2695 clearDir(PUBLIC_ROOT.'./data/caches/custom/'.$dir,true);
2696 }
2697
2698 function avatar($img_id, $type = 'm',$is_full = false)
2699 {
2700 $img_id = (int)$img_id;
2701 if($img_id == 0)
2702 {
2703 $src = '';
2704 switch($type)
2705 {
2706 case 'm':
2707 $src = './public/upload/avatar/noavatar_middle.jpg';
2708 break;
2709 case 'b':
2710 $src = './public/upload/avatar/noavatar_big.jpg';
2711 break;
2712 default:
2713 $src = './public/upload/avatar/noavatar_small.jpg';
2714 break;
2715 }
2716
2717 if($is_full)
2718 return FS("Image")->getImageUrl($src,2);
2719 else
2720 return $src;
2721 }
2722
2723 static $avatars = array();
2724 static $types = NULL;
2725 if($types === NULL)
2726 {
2727 FS("Image")->getImageArgs($types,'avatar');
2728 $types = $types['types'];
2729 }
2730
2731 $size = $types['s'];
2732 if(array_key_exists($type,$types))
2733 $size = $types[$type];
2734
2735 return getImgById($img_id,$size,$size,1,$is_full);
2736 }
2737
2738 /**
2739 * 根据图片原图地址。 获取规格图片的地址,如果没有该规则动态生成。
2740 * by fzmatthew
2741 */
2742 function getImgName($img_url,$width=0,$height=0,$gen = 0,$is_full = false)
2743 {
2744 $img['src'] = $img_url;
2745 return formatImage($img,$width,$height,$gen,$is_full);
2746 }
2747
2748 /**
2749 * 根据图片编号。 获取规格图片的地址,如果没有返回动态生成路径。
2750 * by fzmatthew
2751 */
2752 function getImgById($id,$width=0,$height=0,$gen = 0,$is_full = 0)
2753 {
2754 static $imgs = array();
2755 if(!isset($imgs[$id]))
2756 {
2757 $imgs[$id] = FS("Image")->getImageById($id);
2758 }
2759 return formatImage($imgs[$id],$width,$height,$gen,$is_full);
2760 }
2761
2762 function formatImage($img,$width=0,$height=0,$gen = 0,$is_full = 0)
2763 {
2764 if(!$img)
2765 return '';
2766
2767 if(parseUrl($img['src']))
2768 return $img['src'];
2769
2770 global $_FANWE;
2771
2772 if($width == 0 && $height == 0)
2773 {
2774 if($is_full)
2775 $img_url = FS("Image")->getImageUrl($img['src'],2);
2776 else
2777 $img_url = $img['src'];
2778 return $img_url;
2779 }
2780
2781 $img_url_arr[0] = substr($img['src'],0,-4);
2782 $img_url_arr[1] = substr($img['src'],-3,3);
2783 $img_url = $img_url_arr[0]."_".$width."x".$height.".".$img_url_arr[1];
2784 if(strpos($img['src'],'./public/') === FALSE)
2785 {
2786 if(strpos($img['src'],'./upyun/') !== FALSE)
2787 {
2788 $img_url = $img['src'].'!'.$width."x".$height;
2789 if($is_full)
2790 $img_url = str_replace('./upyun/',$_FANWE['UPYUN_SETTING']['url'].'/',$img_url);
2791 }
2792 else
2793 {
2794 $server = FS("Image")->getServerByUrl($img['src']);
2795 if($server['url_rewrite'] == 1)
2796 {
2797 if($is_full)
2798 $img_url = FS("Image")->getImageUrl($img_url,2);
2799 return $img_url;
2800 }
2801
2802 $img_url = $server['url'].'getimg.php?img='.str_replace('./'.$server['code'].'/','',$img_url)."&gen=".$gen;
2803 }
2804 }
2805 else
2806 {
2807 if(!file_exists(FANWE_ROOT.$img_url))
2808 {
2809 $img_url = str_replace('./','',$img_url);
2810 if($is_full)
2811 $img_url = $_FANWE['site_url']."getimg.php?img=".$img_url."&gen=".$gen;
2812 else
2813 $img_url = $_FANWE['site_root']."getimg.php?img=".$img_url."&gen=".$gen;
2814 }
2815 elseif($is_full)
2816 $img_url = FS("Image")->getImageUrl($img_url,2);
2817 }
2818 return $img_url;
2819 }
2820
2821 /**
2822 *
2823 * @param $origin_path 原始物理图片地址
2824 * @param $path 存储的路径
2825 * @param $file_name 保存的文件名
2826 * @param $del_temp 是否删除临时文件
2827 * @param $id 关联编号,将根据编号生成目录
2828 *
2829 * 返回 复制成功的信息,如为false则复制失败
2830 * array(
2831 * 'path' => xxx //物理路径
2832 * 'url' => xxx //相对路径
2833 * );
2834 *
2835 * by fzmatthew
2836 */
2837 function copyFile($origin_path, $path = 'share',$del_temp = true,$id = 0)
2838 {
2839 static $image = NULL;
2840 if($image === NULL)
2841 {
2842 include_once fimport('class/image');
2843 $image = new Image();
2844 }
2845
2846 if($path == 'temp')
2847 $dir = './public/upload/temp/'.fToDate(NULL,'Y/m/d/H');
2848 else
2849 {
2850 if($id > 0)
2851 $dir = './public/upload/'.$path.'/'.getDirsById($id);
2852 else
2853 $dir = './public/upload/'.$path.'/'.fToDate(NULL,'Y/m/d');
2854 }
2855
2856 $file_name = md5(microtime(true)).random('6').'.jpg';
2857 makeDir(FANWE_ROOT.$dir);
2858 $file_path = FANWE_ROOT.$dir."/".$file_name;
2859
2860 if(file_exists($origin_path) && @copy($origin_path,$file_path))
2861 {
2862 if($del_temp)
2863 @unlink($origin_path);
2864 }
2865 else
2866 {
2867 $data = getUrlContent($origin_path);
2868 if(!empty($data) && @file_put_contents($file_path,$data) > 0)
2869 {
2870 if($del_temp)
2871 @unlink($origin_path);
2872 }
2873 else
2874 return false;
2875 }
2876
2877 $info = $image->getImageInfo($file_path);
2878 if($info['type'] != 'jpg' && $info['type'] != 'jpeg')
2879 {
2880 $file_name = md5(microtime(true)).random('6').'.jpg';
2881 $file_path1 = FANWE_ROOT.$dir."/".$file_name;
2882
2883 if(!$image->convertType($file_path,$file_path1))
2884 return false;
2885 else
2886 {
2887 @unlink($file_path);
2888 $file_path = $file_path1;
2889 }
2890 }
2891
2892 return array(
2893 'path' => $file_path,
2894 'url' => $dir."/".$file_name,
2895 'width' => $info[0],
2896 'height' => $info[1],
2897 );
2898 }
2899
2900 /**
2901 *
2902 * @param $origin_path 原始物理图片地址
2903 * @param array $sizes 缩略图大小信息 为空则取后台设置
2904 可生成多个缩略图
2905 数组 参数1 为宽度,
2906 参数2为高度,
2907 参数3为处理方式:0(缩放,默认),1(剪裁),
2908 参数4为是否水印 默认为 0(不生成水印)
2909 array(
2910 array(300,300,0,0),
2911 array(100,100,0,0),
2912 ...
2913 ),
2914 * @param $path 存储的路径
2915 * @param $file_name 保存的文件名
2916 * @param $del_temp 是否删除临时文件
2917 * @param $id 关联编号,将根据编号生成目录
2918 *
2919 * 返回 复制成功的信息,如为false则复制失败
2920 * array(
2921 * 'path' => xxx //物理路径
2922 * 'url' => xxx //相对路径
2923 * );
2924 *
2925 * by fzmatthew
2926 */
2927 function copyImage($origin_path,$sizes = array(),$path = 'photos', $del_temp = true,$id = 0)
2928 {
2929 global $_FANWE;
2930 static $size_setting = NULL,$image = NULL;
2931 if($image === NULL)
2932 {
2933 include_once fimport('class/image');
2934 $image = new Image();
2935 }
2936
2937 if($path == 'temp')
2938 $dir = './public/upload/temp/'.fToDate(NULL,'Y/m/d/H');
2939 else
2940 {
2941 if($id > 0)
2942 $dir = './public/upload/'.$path.'/'.getDirsById($id);
2943 else
2944 $dir = './public/upload/'.$path.'/'.fToDate(NULL,'Y/m/d');
2945 }
2946
2947 makeDir(FANWE_ROOT.$dir);
2948
2949 $file_name = md5(microtime(true)).random('6').'.jpg';
2950 $file_path = FANWE_ROOT.$dir."/".$file_name;
2951
2952 $bln = false;
2953 if(file_exists($origin_path) && @copy($origin_path,$file_path))
2954 $bln = true;
2955 else
2956 {
2957 $data = getUrlContent($origin_path);
2958 if(!empty($data) && @file_put_contents($file_path,$data) > 0)
2959 $bln = true;
2960 }
2961
2962 if($bln)
2963 {
2964 $info = $image->getImageInfo($file_path);
2965 if($info['type'] != 'jpg' && $info['type'] != 'jpeg')
2966 {
2967 $file_name = md5(microtime(true)).random('6').'.jpg';
2968 $file_path1 = FANWE_ROOT.$dir."/".$file_name;
2969
2970 if(!$image->convertType($file_path,$file_path1))
2971 return false;
2972 else
2973 {
2974 @unlink($file_path);
2975 $file_path = $file_path1;
2976 }
2977 }
2978
2979 $water_image = $_FANWE['setting']['water_image'];
2980 if(!empty($water_image))
2981 $water_image = FANWE_ROOT.$water_image;
2982
2983 $water_mark = intval($_FANWE['setting']['water_mark']);
2984 $alpha = intval($_FANWE['setting']['water_alpha']);
2985 $place = intval($_FANWE['setting']['water_position']);
2986
2987 if($sizes !== false && empty($sizes))
2988 {
2989 if($size_setting === NULL)
2990 {
2991 if(!isset($_FANWE['cache']['image_sizes']))
2992 FanweService::instance()->cache->loadCache('image_sizes');
2993 $size_setting = $_FANWE['cache']['image_sizes'];
2994 }
2995
2996 $sizes = $size_setting;
2997 }
2998
2999 if($sizes === false)
3000 $sizes = array();
3001
3002 foreach($sizes as $size)
3003 {
3004 if($size[0] > 0 || $size[1] > 0)
3005 {
3006 $thumb_bln = false;
3007 $thumb_type = isset($size[2]) ? intval($size[2]) : 0;
3008 if($thumb = $image->thumb($file_path,$size[0],$size[1],$thumb_type))
3009 {
3010 if(isset($size[3]) && intval($size[3]) > 0)
3011 $image->water($thumb['path'],$water_image,$alpha, $place);
3012 }
3013 }
3014 }
3015
3016 if($del_temp)
3017 @unlink($origin_path);
3018
3019 return array(
3020 'path' => $file_path,
3021 'url' => $dir."/".$file_name,
3022 'width' => $info[0],
3023 'height' => $info[1],
3024 );
3025 }
3026 else
3027 return false;
3028 }
3029
3030 //获取url的内容
3031 function getUrlContent($url,$is_location = false,$referer = '')
3032 {
3033 $content = '';
3034 if(!parseUrl($url))
3035 {
3036 $content = @file_get_contents($url);
3037 }
3038 else
3039 {
3040 if(function_exists('curl_init'))
3041 {
3042 $ch = curl_init();
3043 curl_setopt($ch, CURLOPT_URL,$url);
3044 curl_setopt($ch, CURLOPT_TIMEOUT,60);
3045 if(!empty($referer))
3046 curl_setopt ($ch, CURLOPT_REFERER,$referer);
3047
3048 curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19");
3049 if($is_location)
3050 {
3051 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
3052 curl_setopt($ch, CURLOPT_MAXREDIRS,11);
3053 }
3054 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
3055 $content = curl_exec($ch);
3056 curl_close($ch);
3057 }
3058 else
3059 {
3060 $content = @file_get_contents($url);
3061 }
3062 }
3063
3064 return $content;
3065 }
3066
3067 //获取图片大小
3068 function getImageLength($url)
3069 {
3070 $size = 0;
3071 if(parseUrl($url))
3072 {
3073 $ch = curl_init($url);
3074 curl_setopt($ch, CURLOPT_TIMEOUT,3);
3075 curl_setopt($ch, CURLOPT_HEADER, 1);
3076 curl_setopt($ch, CURLOPT_NOBODY, 1);
3077 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
3078 $head = curl_exec($ch);
3079 curl_close($ch);
3080 preg_match("/Content-Length:\s*(\d+)\s/m",$head,$size);
3081 if($size)
3082 $size = floatval($size[1]);
3083 }
3084 else
3085 {
3086 if(strpos($url,FANWE_ROOT) === FALSE)
3087 $url = FANWE_ROOT.$url;
3088 $size = floatval(@filesize($url));
3089 }
3090
3091 if($size > 0)
3092 $size = $size / 1024;
3093 return $size;
3094 }
3095
3096 /**
3097 * 搜索Club的分类
3098 *
3099 * @param 父类ID $pid
3100 * @return 数组
3101 */
3102
3103 function getForumClass($pid = 0)
3104 {
3105 global $_FANWE;
3106 FanweService::instance()->cache->loadCache('forums');
3107 $list = $_FANWE['cache']['forums'];
3108 if($pid > 0){
3109 foreach($list as $k => $v)
3110 {
3111 if(intval($pid)==$v['fid'])
3112 return $v;
3113 }
3114 }
3115 else {
3116 return $list;
3117 }
3118 }
3119
3120 function getAskClass($pid = 0)
3121 {
3122 global $_FANWE;
3123 FanweService::instance()->cache->loadCache('asks');
3124 $list = $_FANWE['cache']['asks'];
3125 if($pid > 0){
3126 foreach($list as $k => $v)
3127 {
3128 if(intval($pid)==$v['aid'])
3129 return $v;
3130 }
3131 }
3132 else {
3133 return $list;
3134 }
3135 }
3136 /**
3137 * 获取CDN链接
3138 * @param string $url 链接
3139 * @param string $type (image:图片,css:样式,js:脚本),为空则根据后缀获取
3140 * @return string
3141 */
3142
3143 function getCDNUrl($url,$type='')
3144 {
3145 global $_FANWE;
3146 static $img_exts = array('jpg', 'jpeg', 'png', 'bmp','gif','giff'),
3147 $types = array('image','css','js');
3148
3149 if(empty($type))
3150 {
3151 $ext = fileExt($url);
3152 if(in_array($ext,$img_exts))
3153 $type = 'image';
3154 elseif($ext == 'css')
3155 $type = 'css';
3156 elseif($ext == 'js')
3157 $type = 'js';
3158 }
3159
3160 $url_pre = $_FANWE['site_root'];
3161 if(in_array($type,$types))
3162 {
3163 switch($type)
3164 {
3165 case 'image':
3166 if(!empty($_FANWE['config']['cdn']['image']))
3167 $url_pre = $_FANWE['config']['cdn']['image'];
3168 break;
3169
3170 case 'css':
3171 if(!empty($_FANWE['config']['cdn']['css']))
3172 $url_pre = $_FANWE['config']['cdn']['css'];
3173 break;
3174
3175 case 'js':
3176 if(!empty($_FANWE['config']['cdn']['js']))
3177 $url_pre = $_FANWE['config']['cdn']['js'];
3178 break;
3179 }
3180 }
3181
3182 return $url_pre.$url;
3183 }
3184
3185 /**
3186 * 获取文件扩展名
3187 * @return string
3188 */
3189 function fileExt($file)
3190 {
3191 return addslashes(strtolower(substr(strrchr($file, '.'), 1, 10)));
3192 }
3193
3194 function priceFormat($price)
3195 {
3196 return '¥'.number_format(round($price,2),2);
3197 }
3198
3199 /**
3200 * 根据ID划分目录
3201 * @return string
3202 */
3203 function getDirsById($id)
3204 {
3205 $id = sprintf("%011d", $id);
3206 $dir1 = substr($id, 0, 3);
3207 $dir2 = substr($id, 3, 3);
3208 $dir3 = substr($id, 6, 3);
3209 $dir4 = substr($id, -2);
3210 return $dir1.'/'.$dir2.'/'.$dir3.'/'.$dir4;
3211 }
3212
3213 function cssParse($urls)
3214 {
3215 global $_FANWE;
3216 if(!empty($urls))
3217 $_FANWE['page_parses']['css'][] = $urls;
3218
3219 if(is_array($urls))
3220 {
3221 $url = md5(implode(',',$urls));
3222 $css_url = './public/data/tpl/css/'.$url.'.css';
3223 $url_path = FANWE_ROOT.$css_url;
3224 if(!file_exists($url_path))
3225 {
3226 $css_content = '';
3227 foreach($urls as $url)
3228 {
3229 $url = str_replace('./tpl/css/','./public/data/tpl/css/',$url);
3230 $css_content .= @file_get_contents(FANWE_ROOT.$url);
3231 }
3232 $css_content = preg_replace("/[\r\n]/",'',$css_content);
3233 @file_put_contents($url_path,$css_content);
3234 }
3235
3236 return $css_url;
3237 }
3238 else
3239 {
3240 return $urls;
3241 }
3242 }
3243
3244 function scriptParse($urls)
3245 {
3246 global $_FANWE;
3247 if(!empty($urls))
3248 $_FANWE['page_parses']['script'][] = $urls;
3249
3250 if(is_array($urls))
3251 {
3252 $url = md5(implode(',',$urls));
3253 $js_url = './public/data/tpl/js/'.$url.'.js';
3254 $url_path = FANWE_ROOT.$js_url;
3255 if(!file_exists($url_path))
3256 {
3257 $js_content = '';
3258 foreach($urls as $url)
3259 {
3260 $url = str_replace('./tpl/js/','./tpl/'.TMPL.'/js/',$url);
3261 $js_content .= @file_get_contents(FANWE_ROOT.$url)."\r\n";
3262 }
3263
3264 @file_put_contents($url_path,$js_content);
3265 }
3266
3267 return $js_url;
3268 }
3269 else
3270 {
3271 return $urls;
3272 }
3273 }
3274
3275 /**
3276 * 获取是否显示前台管理
3277 * @return bool
3278 */
3279 function getIsManage($module)
3280 {
3281 global $_FANWE;
3282 if($_FANWE['uid'] == 0)
3283 return false;
3284
3285 $module = strtolower($module);
3286 if(isset($_FANWE['authoritys'][$module]))
3287 return true;
3288 else
3289 return false;
3290 }
3291
3292 /**
3293 * 检测是否具有指定的前台管理权限
3294 * @return bool
3295 */
3296 function checkAuthority($module,$action)
3297 {
3298 global $_FANWE;
3299 if($_FANWE['uid'] == 0)
3300 return false;
3301
3302 $module = strtolower($module);
3303 $action = strtolower($action);
3304
3305 if(isset($_FANWE['authoritys'][$module]) && isset($_FANWE['authoritys'][$module][$action]))
3306 return true;
3307 else
3308 return false;
3309 return true;
3310 }
3311
3312 /**
3313 * 检测所管理的对像是否锁定,已锁定返回锁定数据array,未锁定返回false
3314 如果锁定30分钟以上,还未解锁,将设为未锁定
3315 * @return
3316 */
3317 function checkIsManageLock($module,$id)
3318 {
3319 global $_FANWE;
3320 $module = strtolower($module);
3321 $lock_file = PUBLIC_ROOT.'./manage/'.$module.'/'.$id.'.lock';
3322 if(file_exists($lock_file))
3323 {
3324 include $lock_file;
3325
3326 if(TIME_UTC - $lock['time'] > 1800)
3327 {
3328 removeFile($lock_file);
3329 return false;
3330 }
3331 if($lock['uid'] == $_FANWE['uid'])
3332 return false;
3333 else
3334 return $lock;
3335 }
3336 else
3337 return false;
3338 }
3339
3340 /**
3341 * 获取前台管理锁定
3342 * @return void
3343 */
3344 function getManageLock($module,$id)
3345 {
3346 $module = strtolower($module);
3347 $lock_file = PUBLIC_ROOT.'./manage/'.$module.'/'.$id.'.lock';
3348 if(file_exists($lock_file))
3349 {
3350 include $lock_file;
3351 return $lock;
3352 }
3353 else
3354 return false;
3355 }
3356
3357 /**
3358 * 创建前台管理锁定
3359 * @return void
3360 */
3361 function createManageLock($module,$id)
3362 {
3363 global $_FANWE;
3364 $module = strtolower($module);
3365 $phth = PUBLIC_ROOT.'./manage/'.$module;
3366 makeDir($phth);
3367 $lock_file = $phth.'/'.$id.'.lock';
3368 $data = array(
3369 'uid'=>$_FANWE['uid'],
3370 'user_name'=>$_FANWE['user_name'],
3371 'time'=>TIME_UTC,
3372 );
3373 $data = "<?php\n".'$lock = '.var_export($data, true).";\n?>";
3374 return writeFile($lock_file,$data);
3375 }
3376
3377 /**
3378 * 删除前台管理锁定
3379 * @return void
3380 */
3381 function deleteManageLock($module,$id)
3382 {
3383 $module = strtolower($module);
3384 $lock_file = PUBLIC_ROOT.'./manage/'.$module.'/'.$id.'.lock';
3385 removeFile($lock_file);
3386 }
3387
3388 /**
3389 * 前台管理日志
3390 * @return void
3391 */
3392 function createManageLog($module,$action,$id,$content = '')
3393 {
3394 global $_FANWE;
3395
3396 $log = array(
3397 'rec_id'=>$id,
3398 'module'=>$module,
3399 'action'=>$action,
3400 'uid'=>$_FANWE['uid'],
3401 'user_name'=>$_FANWE['user_name'],
3402 'content'=>$content,
3403 'create_time'=>TIME_UTC
3404 );
3405
3406 FDB::insert('manage_log',$log);
3407 }
3408
3409 /**
3410 * 获取分享链接
3411 * @return string
3412 */
3413 function getSnsLink($types,$title,$url,$content,$pic)
3414 {
3415 global $_FANWE;
3416 $links = array();
3417 $title = urlencode($title);
3418 $content_url = urlencode($content.' '.$url);
3419 $content = urlencode($content);
3420 $url = urlencode($url);
3421 $site_url = urlencode($_FANWE['site_url']);
3422 $pic = empty($pic) ? $pic : urlencode($pic);
3423 foreach($types as $type)
3424 {
3425 switch($type)
3426 {
3427 case 'kaixin':
3428 $links[$type] = "http://www.kaixin001.com/diary/write.php?classid=0&title=$title&content=$content_url";
3429 break;
3430
3431 case 'renren':
3432 $links[$type] = "http://share.renren.com/share/buttonshare.do?link=$url&title=$title";
3433 break;
3434
3435 case 'sina':
3436 $links[$type] = "http://v.t.sina.com.cn/share/share.php?sourceUrl=$site_url&content=utf8&url=$url&title=$content";
3437 if(!empty($pic))
3438 $links[$type] .= "&pic=$pic";
3439 break;
3440
3441 case 'tqq':
3442 $links[$type] = "http://v.t.qq.com/share/share.php?url=$url&title=$content";
3443 if(!empty($pic))
3444 $links[$type] .= "&pic=$pic";
3445 break;
3446
3447 case 'douban':
3448 $links[$type] = "http://www.douban.com/recommend/?url=$url&title=$title";
3449 break;
3450
3451 case 'qzone':
3452 $links[$type] = "http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=$url&title=$title&summary=$content";
3453 if(!empty($pic))
3454 $links[$type] .= "&pics=$pic";
3455 break;
3456
3457 case 'baidu':
3458 $links[$type] = "http://apps.hi.baidu.com/share/?url=$url&title=$title&content=$content";
3459 break;
3460 }
3461 }
3462
3463 return $links;
3464 }
3465
3466 function getLoginModule($class_name)
3467 {
3468 global $_FANWE;
3469 if(!isset($_FANWE['cache']['logins']))
3470 FanweService::instance()->cache->loadCache('logins');
3471
3472 if(file_exists(FANWE_ROOT."login/".$class_name.".php"))
3473 {
3474 require_once FANWE_ROOT."login/".$class_name.".php";
3475 if(class_exists($class_name))
3476 {
3477 $module = new $class_name;
3478 return $module->getInfo();
3479 }
3480 }
3481 else
3482 return false;
3483 }
3484
3485 function getLoginModuleList()
3486 {
3487 global $_FANWE;
3488 if(!isset($_FANWE['cache']['logins']))
3489 FanweService::instance()->cache->loadCache('logins');
3490
3491 $list = array();
3492 foreach($_FANWE['cache']['logins'] as $class_name => $val)
3493 {
3494 if(file_exists(FANWE_ROOT."login/".$class_name.".php"))
3495 {
3496 require_once FANWE_ROOT."login/".$class_name.".php";
3497 if(class_exists($class_name))
3498 {
3499 $module = new $class_name;
3500 $list[$class_name] = $module->getInfo();
3501 }
3502 }
3503 }
3504 return $list;
3505 }
3506
3507 function deleteShareImg($img_path,$server_code = '')
3508 {
3509 if(empty($server_code))
3510 {
3511 $img_path = FANWE_ROOT.str_replace('./','',$img_path);
3512 $paths = pathinfo($img_path);
3513 @unlink($img_path);
3514 $old_img = explode('.',$img_path);
3515 $old_img = $old_img[0];
3516 if($dirhandle = opendir($paths['dirname']))
3517 {
3518 while(($file = readdir($dirhandle)) !== FALSE)
3519 {
3520 if(($file!=".") && ($file!=".."))
3521 {
3522 $filename = $paths['dirname'].'/'.$file;
3523 if(strpos($filename,$old_img) !== FALSE)
3524 {
3525 @unlink($filename);
3526 }
3527 }
3528 }
3529 @closedir($dirhandle);
3530 }
3531 }
3532 else
3533 {
3534 $server = FS("Image")->getServer($server_code);
3535 if($server)
3536 {
3537 $args = array();
3538 $args['img_path'] = $img_path;
3539 $server = FS("Image")->getImageUrlToken($args,$server,1);
3540 FS("Image")->sendRequest($server,'deleteshareimg');
3541 }
3542 }
3543 }
3544
3545 function deleteImg($img_path,$server_code = '')
3546 {
3547 if(empty($server_code))
3548 {
3549 $img_path = FANWE_ROOT.str_replace('./','',$img_path);
3550 @unlink($img_path);
3551 }
3552 else
3553 {
3554 $server = FS("Image")->getServer($server_code);
3555 if($server)
3556 {
3557 $args = array();
3558 $args['img_path'] = $img_path;
3559 $server = FS("Image")->getImageUrlToken($args,$server,1);
3560 FS("Image")->sendRequest($server,'deleteimg');
3561 }
3562 }
3563 }
3564
3565 /**
3566 * 清除当前2小时以前的临时图片
3567 * @param string $dir 目录路径
3568 * @return void
3569 */
3570 function clearTempImage($path = '')
3571 {
3572 global $_FANWE;
3573 if($path == '')
3574 $_FANWE['clear_image_count'] = 0;
3575
3576 $max_time = mktime(date('H')-2,0,0,date('m'),date('d'),date('Y')) - date('Z');
3577 $basepath = FANWE_ROOT.'public/upload/temp/';
3578 $paths = array();
3579 if($path != '')
3580 {
3581 $currentpath = str_replace($basepath,'',$path);
3582 $paths = explode('/',$currentpath);
3583 $year = (int)$paths[0];
3584 $month = isset($paths[1]) ? (int)$paths[1] : 1;
3585 $day = isset($paths[2]) ? (int)$paths[2] : 1;
3586 $hours = isset($paths[3]) ? (int)$paths[3] : 0;
3587 $day_time = mktime($hours,0,0,$month,$day,$year) - date('Z');
3588 if($max_time <= $day_time)
3589 return;
3590
3591 $currentpath .= '/';
3592 }
3593 else
3594 $currentpath = '';
3595
3596 $dir = $basepath.$currentpath;
3597 $directory = @dir($dir);
3598 if(!$directory)
3599 return;
3600
3601 while($entry = @$directory->read())
3602 {
3603 if($_FANWE['clear_image_count'] >= 50)
3604 break;
3605
3606 if($entry != '.' && $entry != '..')
3607 {
3608 $filename = $dir.$entry;
3609 if(is_dir($filename))
3610 {
3611 clearTempImage($filename);
3612 @rmdir($filename);
3613 }
3614
3615 if(is_file($filename))
3616 {
3617 removeFile($filename);
3618 $_FANWE['clear_image_count']++;
3619 }
3620 }
3621 }
3622 $directory->close();
3623 }
3624
3625 function setTimeLimit($time = 0)
3626 {
3627 $time = (int)$time;
3628 @set_time_limit($time);
3629 if(function_exists('ini_set'))
3630 ini_set('max_execution_time',$time);
3631 }
3632
3633 function formatPageSeo()
3634 {
3635 global $_FANWE;
3636 $module = strtolower(MODULE_NAME);
3637 $action = ACTION_NAME;
3638
3639 $seo_title = (empty($_FANWE['nav_title']) ? '' : $_FANWE['nav_title']. '-') . $_FANWE['setting']['site_title'];
3640 $seo_keywords = $_FANWE['seo_keywords'].$_FANWE['setting']['site_keywords'];
3641 $seo_description = $_FANWE['seo_description'].$_FANWE['setting']['site_description'];
3642
3643 if($module == 'note')
3644 $action = 'all';
3645
3646 $seos_cache = $_FANWE['cache']['seos'];
3647
3648 if(isset($seos_cache[$module]) && (isset($seos_cache[$module][$action]) || isset($seos_cache[$module]['all'])))
3649 {
3650 $seos = array();
3651 $seos['GLOBAL_NAME'] = $_FANWE['setting']['site_name'];
3652 $seos['GLOBAL_TITLE'] = $_FANWE['setting']['site_title'];
3653 $seos['GLOBAL_KEYWORDS'] = $_FANWE['setting']['site_keywords'];
3654 $seos['GLOBAL_DESCRIPTION'] = $_FANWE['setting']['site_description'];
3655
3656 if(isset($_FANWE['PAGE_SEO_SELF']))
3657 {
3658 foreach($_FANWE['PAGE_SEO_SELF'] as $name => $val)
3659 {
3660 if(!is_array($val))
3661 $seos[strtoupper($name)] = $val;
3662 }
3663 }
3664 else
3665 {
3666 $_FANWE['PAGE_SEO_SELF'] = array();
3667 }
3668
3669 if(isset($seos_cache[$module]['all']))
3670 $action = 'all';
3671
3672 foreach($seos_cache[$module][$action]['seo']['title'] as $item)
3673 {
3674 $title_rule = $item;
3675 $bln = true;
3676 foreach($item['args'] as $arg)
3677 {
3678 if(!isset($seos[$arg]) || empty($seos[$arg]))
3679 {
3680 $bln = false;
3681 break;
3682 }
3683 }
3684
3685 if($bln)
3686 break;
3687 }
3688 $seo_title = $title_rule['content'];
3689 $search = array();
3690 $replace = array();
3691 foreach($title_rule['args'] as $arg)
3692 {
3693 $search[] = '{'.$arg.'}';
3694 $replace[] = $seos[$arg];
3695 }
3696 $seo_title = str_replace($search,$replace,$seo_title);
3697
3698 foreach($seos_cache[$module][$action]['seo']['keywords'] as $item)
3699 {
3700 $keywords_rule = $item;
3701 $bln = true;
3702 foreach($item['args'] as $arg)
3703 {
3704 if(!isset($seos[$arg]) || empty($seos[$arg]))
3705 {
3706 $bln = false;
3707 break;
3708 }
3709 }
3710
3711 if($bln)
3712 break;
3713 }
3714 $seo_keywords = $keywords_rule['content'];
3715 $search = array();
3716 $replace = array();
3717 foreach($keywords_rule['args'] as $arg)
3718 {
3719 $search[] = '{'.$arg.'}';
3720 $replace[] = $seos[$arg];
3721 }
3722 $seo_keywords = str_replace($search,$replace,$seo_keywords);
3723
3724 foreach($seos_cache[$module][$action]['seo']['description'] as $item)
3725 {
3726 $description_rule = $item;
3727 $bln = true;
3728 foreach($item['args'] as $arg)
3729 {
3730 if(!isset($seos[$arg]) || empty($seos[$arg]))
3731 {
3732 $bln = false;
3733 break;
3734 }
3735 }
3736
3737 if($bln)
3738 break;
3739 }
3740 $seo_description = $description_rule['content'];
3741 $search = array();
3742 $replace = array();
3743 foreach($description_rule['args'] as $arg)
3744 {
3745 $search[] = '{'.$arg.'}';
3746 $replace[] = $seos[$arg];
3747 }
3748 $seo_description = str_replace($search,$replace,$seo_description);
3749 }
3750
3751 return '<title>'.$seo_title.'</title>
3752 <meta name="keywords" content="'.$seo_keywords.'" />
3753 <meta name="description" content="'.$seo_description.'" />';
3754 }
3755
3756 function createAnchorTable()
3757 {
3758 $list = array();
3759 $res = FDB::query('SELECT word,brief,url,target FROM '.FDB::table('anchor').' WHERE status = 1 ORDER BY word ASC');
3760 while($data = FDB::fetch($res))
3761 {
3762 $temp = &$list;
3763 $data['word'] = strtolower($data['word']);
3764 $str_len = mb_strlen($data['word'],'UTF-8');
3765 for ($i = 0; $i < $str_len; $i++)
3766 {
3767 $s = mb_substr($data['word'], $i, 1,'UTF-8');
3768 if($s == ',')
3769 $s = ',';
3770
3771 if(!isset($temp[$s]))
3772 $temp[$s] = array();
3773 $temp = &$temp[$s];
3774 }
3775
3776 if(!isset($temp[',']))
3777 $temp[','] = array('desc'=>$data['brief'],'url'=>$data['url'],'target'=>$data['target']);
3778 }
3779
3780 foreach($list as $item => $val)
3781 {
3782 @file_put_contents(FANWE_ROOT.'public/table/anchor/'.urlencode($item).'.table','<?php '."\nreturn ".(string)var_export($val,true).";\n".'?>');
3783 }
3784 }
3785
3786 function formatAnchorLink($content,$length)
3787 {
3788 if(empty($content))
3789 return '';
3790
3791 $length = (int)$length;
3792 if($length > 0)
3793 $content = cutStr($content,$length);
3794
3795 preg_match_all("/@([^\f\n\r\t\v@<> ]{2,20}?)(?:\:| )/",$content,$users);
3796 if(!empty($users[1]))
3797 {
3798 $patterns = array();
3799 $replace = array();
3800 $users = array_unique($users[1]);
3801 $arr = array();
3802 foreach($users as $user)
3803 {
3804 if(!empty($user))
3805 {
3806 $arr[] = addslashes($user);
3807 }
3808 }
3809
3810 $res = FDB::query('SELECT uid,user_name
3811 FROM '.FDB::table('user').'
3812 WHERE user_name '.FDB::createIN($arr));
3813 while($data = FDB::fetch($res))
3814 {
3815 $patterns[] = '/@'.preg_quote($data['user_name']).'(\:| )/';
3816 $replace[] = '<a class="u_name GUID" uid="'.$data['uid'].'" href="'.FU('u/index',array('uid'=>$data['uid'])).'">@'.$data['user_name']."</a>\$1";
3817 }
3818 $content = preg_replace($patterns,$replace,$content);
3819 }
3820
3821 preg_match_all("/#([^\f\n\r\t\v]{1,80}?)#/",$content,$events);
3822 if(!empty($events[1]))
3823 {
3824 $patterns = array();
3825 $replace = array();
3826 $events = array_unique($events[1]);
3827 $arr = array();
3828 foreach($events as $event)
3829 {
3830 if(!empty($event))
3831 {
3832 if(substr($event,0,3) != '64;')
3833 $arr[] = addslashes($event);
3834 }
3835 }
3836
3837 $res = FDB::query('SELECT id,title
3838 FROM '.FDB::table('event').'
3839 WHERE title '.FDB::createIN($arr));
3840 while($data = FDB::fetch($res))
3841 {
3842 $patterns[] = '#'.$data['title'].'#';
3843 $replace[] = '<a href="'.FU("event/detail",array("id"=>$data['id'])).'" target="_blank">#'.$data['title'].'#</a>';
3844 }
3845
3846 $content = str_replace($patterns,$replace,$content);
3847 }
3848
3849 $patterns = array();
3850 $replace = array();
3851 preg_match_all("/<(.+?)\s.+?>(.+?)<\/\\1>/",$content,$htmls);
3852 if(!empty($htmls[0]))
3853 {
3854 $htmls = array_unique($htmls[0]);
3855 foreach($htmls as $html)
3856 {
3857 $patterns[] = md5($html,true);
3858 $replace[] = $html;
3859 }
3860 }
3861
3862 $content = str_replace(' ',' ',$content);
3863 $content = str_replace($replace,$patterns,$content);
3864 $strlen = mb_strlen($content, 'UTF-8');
3865
3866 $newcontent = '';
3867 $index = 0;
3868 $bln = true;
3869 while($bln)
3870 {
3871 $char = mb_substr($content,$index,1,'UTF-8');
3872 $char1 = strtolower($char);
3873 if($char1 == ',')
3874 $char1 = ',';
3875
3876 if(file_exists(FANWE_ROOT.'public/table/anchor/'.urlencode($char1).'.table'))
3877 {
3878 $charindex = $index + 1;
3879 $words = include FANWE_ROOT.'public/table/anchor/'.urlencode($char1).'.table';
3880 $wbln = true;
3881 $temp = &$words;
3882 $word = $char;
3883 $anchor = NULL;
3884 if(isset($words[',']))
3885 $anchor = $words[','];
3886
3887 while($wbln)
3888 {
3889 $char = mb_substr($content,$charindex,1,'UTF-8');
3890 $char1 = strtolower($char);
3891 if(isset($temp[$char1]))
3892 {
3893 $word .= $char;
3894 if(isset($temp[$char1][',']))
3895 $anchor = $temp[$char1][','];
3896
3897 $temp = &$temp[$char1];
3898 $charindex++;
3899 }
3900 else
3901 $wbln = false;
3902 }
3903
3904 if($anchor !== NULL)
3905 $word = '<a href="'.$anchor['url'].'" title="'.$anchor['desc'].'" target="'.$anchor['target'].'">'.$word.'</a>';
3906
3907 $newcontent .= $word;
3908 $index = $charindex;
3909 }
3910 else
3911 {
3912 $newcontent .= $char;
3913 $index++;
3914 }
3915
3916 if($index >= $strlen)
3917 $bln = false;
3918 }
3919 return str_replace($patterns,$replace,$newcontent);
3920 }
3921 ?>