PageRenderTime 52ms CodeModel.GetById 2ms app.highlight 40ms RepoModel.GetById 1ms app.codeStats 1ms

/code/core/sociax/functions.php

http://thinksns-2.googlecode.com/
PHP | 1068 lines | 757 code | 76 blank | 235 comment | 154 complexity | 8f6579d60e7094a69f485bf7e403f661 MD5 | raw file
   1<?php
   2// +----------------------------------------------------------------------
   3// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
   4// +----------------------------------------------------------------------
   5// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
   6// +----------------------------------------------------------------------
   7// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
   8// +----------------------------------------------------------------------
   9// | Author: liu21st <liu21st@gmail.com>
  10// +----------------------------------------------------------------------
  11// $Id$
  12
  13/**
  14 +------------------------------------------------------------------------------
  15 * Think?????
  16 +------------------------------------------------------------------------------
  17 * @category   Think
  18 * @package  Common
  19 * @author   liu21st <liu21st@gmail.com>
  20 * @version  $Id$
  21 +------------------------------------------------------------------------------
  22 */
  23
  24
  25// URL?? ????????? 2010-2-5 ??
  26function U($url,$params=false,$redirect=false,$suffix=true) {
  27
  28
  29	//????
  30	if(false==strpos($url,'/')){
  31		$url	.='//';
  32	}
  33
  34	//??????
  35	$urls	=	explode('/',$url);
  36	$app	=	($urls[0]) ? $urls[0] : APP_NAME;
  37	$mod	=	($urls[1]) ? $urls[1] : 'Index';
  38	$act	=	($urls[2]) ? $urls[2] : 'index';
  39
  40	//??????
  41	$site_url	=	SITE_URL.'/index.php?'.C('VAR_APP').'='.$app.'&'.C('VAR_MODULE').'='.$mod.'&'.C('VAR_ACTION').'='.$act;
  42
  43	//??????
  44	if($params){
  45		if(is_array($params)){
  46			$params	=	http_build_query($params);
  47			$params	=	urldecode($params);
  48		}
  49		$params		=	str_replace('&amp;','&',$params);
  50		$site_url	.=	'&'.$params;
  51	}
  52
  53	//?????Rewrite
  54	if(C('URL_ROUTER_ON')){
  55
  56		//????
  57		$router_ruler	=	C('router');
  58		$router_key		=	$app.'/'.ucfirst($mod).'/'.$act;
  59
  60		//????
  61		if(isset($router_ruler[$router_key])){
  62
  63			//??????
  64			$site_url	=	SITE_URL.'/'.$router_ruler[$router_key];
  65
  66			//??????
  67			if($params){
  68
  69				//????URL????
  70				parse_str($params,$r);
  71				foreach($r as $k=>$v){
  72					if(strpos($site_url,'['.$k.']')){
  73						$site_url	=	str_replace('['.$k.']',$v,$site_url);
  74					}else{
  75						$lr[$k]	=	$v;
  76					}
  77				}
  78
  79				//??????
  80				if(is_array($lr) && count($lr)>0){
  81					$site_url	.=	'?'.http_build_query($lr);
  82				}
  83
  84			}
  85		}
  86	}
  87
  88	//???????
  89	if($redirect){
  90		redirect($site_url);
  91	}else{
  92		return $site_url;
  93	}
  94}
  95
  96/**
  97 +----------------------------------------------------------
  98 * ?????????
  99 * type
 100 * =0 ?Java?????C???
 101 * =1 ?C?????Java???
 102 +----------------------------------------------------------
 103 * @access protected
 104 +----------------------------------------------------------
 105 * @param string $name ???
 106 * @param integer $type ????
 107 +----------------------------------------------------------
 108 * @return string
 109 +----------------------------------------------------------
 110 */
 111function parse_name($name,$type=0) {
 112    if($type) {
 113        return ucfirst(preg_replace("/_([a-zA-Z])/e", "strtoupper('\\1')", $name));
 114    }else{
 115        $name = preg_replace("/[A-Z]/", "_\\0", $name);
 116        return strtolower(trim($name, "_"));
 117    }
 118}
 119
 120// ????
 121function halt($error) {
 122    if(IS_CLI)   exit ($error);
 123    $e = array();
 124    if(C('APP_DEBUG')){
 125        //???????????
 126        if(!is_array($error)) {
 127            $trace = debug_backtrace();
 128            $e['message'] = $error;
 129            $e['file'] = $trace[0]['file'];
 130            $e['class'] = $trace[0]['class'];
 131            $e['function'] = $trace[0]['function'];
 132            $e['line'] = $trace[0]['line'];
 133            $traceInfo='';
 134            $time = date("y-m-d H:i:m");
 135            foreach($trace as $t)
 136            {
 137                $traceInfo .= '['.$time.'] '.$t['file'].' ('.$t['line'].') ';
 138                $traceInfo .= $t['class'].$t['type'].$t['function'].'(';
 139                $traceInfo .= implode(', ', $t['args']);
 140                $traceInfo .=")<br/>";
 141            }
 142            $e['trace']  = $traceInfo;
 143        }else {
 144            $e = $error;
 145        }
 146        // ????????
 147        include C('TMPL_EXCEPTION_FILE');
 148    }
 149    else
 150    {
 151        //?????????
 152        $error_page =   C('ERROR_PAGE');
 153        if(!empty($error_page)){
 154            redirect($error_page);
 155        }else {
 156            if(C('SHOW_ERROR_MSG'))
 157                $e['message'] =  is_array($error)?$error['message']:$error;
 158            else
 159                $e['message'] = C('ERROR_MESSAGE');
 160            // ????????
 161            include C('TMPL_EXCEPTION_FILE');
 162        }
 163    }
 164    exit;
 165}
 166
 167// URL???
 168function redirect($url,$time=0,$msg='') {
 169    //??URL????
 170    $url = str_replace(array("\n", "\r"), '', $url);
 171    if(empty($msg))
 172        $msg    =   "????{$time}????????{$url}?";
 173    if (!headers_sent()) {
 174        // redirect
 175        if(0===$time) {
 176            header("Location: ".$url);
 177        }else {
 178            header("refresh:{$time};url={$url}");
 179            // ???????????
 180            $str = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 181            $msg = $str . $msg;
 182            echo($msg);
 183        }
 184        exit();
 185    }else {
 186        $str    = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
 187        if($time!=0)
 188            $str   .=   $msg;
 189        exit($str);
 190    }
 191}
 192
 193// ???????
 194function throw_exception($msg,$type='ThinkException',$code=0)
 195{
 196    if(IS_CLI)   exit($msg);
 197    if(class_exists($type,false))
 198        throw new $type($msg,$code,true);
 199    else
 200        halt($msg);        // ????????????????
 201}
 202
 203// ??????
 204function debug_start($label='')
 205{
 206    $GLOBALS[$label]['_beginTime'] = microtime(TRUE);
 207    if ( MEMORY_LIMIT_ON )  $GLOBALS[$label]['_beginMem'] = memory_get_usage();
 208}
 209
 210// ?????????????????????
 211function debug_end($label='')
 212{
 213    $GLOBALS[$label]['_endTime'] = microtime(TRUE);
 214    echo '<div style="text-align:center;width:100%">Process '.$label.': Times '.number_format($GLOBALS[$label]['_endTime']-$GLOBALS[$label]['_beginTime'],6).'s ';
 215    if ( MEMORY_LIMIT_ON )  {
 216        $GLOBALS[$label]['_endMem'] = memory_get_usage();
 217        echo ' Memories '.number_format(($GLOBALS[$label]['_endMem']-$GLOBALS[$label]['_beginMem'])/1024).' k';
 218    }
 219    echo '</div>';
 220}
 221
 222// ??????????
 223function dump($var, $echo=true,$label=null, $strict=true)
 224{
 225    $label = ($label===null) ? '' : rtrim($label) . ' ';
 226    if(!$strict) {
 227        if (ini_get('html_errors')) {
 228            $output = print_r($var, true);
 229            $output = '<pre style="text-align:left">'.$label.htmlspecialchars($output,ENT_QUOTES).'</pre>';
 230        } else {
 231            $output = $label . " : " . print_r($var, true);
 232        }
 233    }else {
 234        ob_start();
 235        var_dump($var);
 236        $output = ob_get_clean();
 237        if(!extension_loaded('xdebug')) {
 238            $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
 239            $output = '<pre style="text-align:left">'. $label. htmlspecialchars($output, ENT_QUOTES). '</pre>';
 240        }
 241    }
 242    if ($echo) {
 243        echo($output);
 244        return null;
 245    }else
 246        return $output;
 247}
 248
 249// ?????? ??????????
 250function get_instance_of($name,$method='',$args=array())
 251{
 252    static $_instance = array();
 253    $identify   =   empty($args)?$name.$method:$name.$method.to_guid_string($args);
 254    if (!isset($_instance[$identify])) {
 255        if(class_exists($name)){
 256            $o = new $name();
 257            if(method_exists($o,$method)){
 258                if(!empty($args)) {
 259                    $_instance[$identify] = call_user_func_array(array(&$o, $method), $args);
 260                }else {
 261                    $_instance[$identify] = $o->$method();
 262                }
 263            }
 264            else
 265                $_instance[$identify] = $o;
 266        }
 267        else
 268            halt(L('_CLASS_NOT_EXIST_').':'.$name);
 269    }
 270    return $_instance[$identify];
 271}
 272
 273/**
 274 +----------------------------------------------------------
 275 * ??????ThinkPHP?????????model?Action??
 276 * ????????????
 277 +----------------------------------------------------------
 278 * @param string $name ????
 279 +----------------------------------------------------------
 280 * @return void
 281 +----------------------------------------------------------
 282 */
 283function __autoload($name)
 284{
 285    // ??????????
 286    if(alias_import($name)) return ;
 287    // ?????????Actioon??Model?
 288    if(substr($name,-5)=="Model") {
 289        require_cache(LIB_PATH.'Model/'.$name.'.class.php');
 290    }elseif(substr($name,-6)=="Action"){
 291        require_cache(LIB_PATH.'Action/'.$name.'.class.php');
 292    }else {
 293        // ????????????????
 294        if(C('APP_AUTOLOAD_PATH')) {
 295            $paths  =   explode(',',C('APP_AUTOLOAD_PATH'));
 296            foreach ($paths as $path){
 297                if(import($path.$name)) {
 298                    // ??????????
 299                    return ;
 300                }
 301            }
 302        }
 303    }
 304    return ;
 305}
 306
 307// ???require_once
 308function require_cache($filename)
 309{
 310    static $_importFiles = array();
 311    $filename   =  realpath($filename);
 312    if (!isset($_importFiles[$filename])) {
 313        if(file_exists_case($filename)){
 314            require $filename;
 315            $_importFiles[$filename] = true;
 316        }
 317        else
 318        {
 319            $_importFiles[$filename] = false;
 320        }
 321    }
 322    return $_importFiles[$filename];
 323}
 324
 325// ????????????
 326function file_exists_case($filename) {
 327    if(is_file($filename)) {
 328        if(IS_WIN && C('APP_FILE_CASE')) {
 329            if(basename(realpath($filename)) != basename($filename))
 330                return false;
 331        }
 332        return true;
 333    }
 334    return false;
 335}
 336
 337/**
 338 +----------------------------------------------------------
 339 * ??????? ?java?Import
 340 * ????????
 341 +----------------------------------------------------------
 342 * @param string $class ?????????
 343 * @param string $baseUrl ????
 344 * @param string $ext ????????
 345 +----------------------------------------------------------
 346 * @return boolen
 347 +----------------------------------------------------------
 348 */
 349function import($class,$baseUrl = '',$ext='.class.php')
 350{
 351    static $_file = array();
 352    static $_class = array();
 353    $class    =   str_replace(array('.','#'), array('/','.'), $class);
 354    if('' === $baseUrl && false === strpos($class,'/')) {
 355        // ??????
 356        return alias_import($class);
 357    }    //echo('<br>'.$class.$baseUrl);
 358    if(isset($_file[$class.$baseUrl]))
 359        return true;
 360    else
 361        $_file[$class.$baseUrl] = true;
 362    $class_strut = explode("/",$class);
 363    if(empty($baseUrl)) {
 364        if('@'==$class_strut[0] || APP_NAME == $class_strut[0] ) {
 365            //??????????
 366            $baseUrl   =  dirname(LIB_PATH);
 367            $class =  str_replace(array(APP_NAME.'/','@/'),LIB_DIR.'/',$class);
 368        }elseif(in_array(strtolower($class_strut[0]),array('think','org','com'))) {
 369            //??ThinkPHP?????????
 370            // think ????? org ??????? com ??????
 371            $baseUrl =  THINK_PATH.'/Lib/';
 372        }else {
 373            // ??????????
 374            $class    =   substr_replace($class, '', 0,strlen($class_strut[0])+1);
 375			$baseUrl =  APPS_PATH.'/'.$class_strut[0].'/'.LIB_DIR.'/';
 376        }
 377    }
 378    if(substr($baseUrl, -1) != "/")    $baseUrl .= "/";
 379    $classfile = $baseUrl . $class . $ext;
 380	if($ext == '.class.php' && is_file($classfile)) {
 381        // ????
 382        $class = basename($classfile,$ext);
 383        if(isset($_class[$class]))
 384            throw_exception(L('_CLASS_CONFLICT_').':'.$_class[$class].' '.$classfile);
 385        $_class[$class] = $classfile;
 386    }
 387    //????????????
 388    return require_cache($classfile);
 389}
 390
 391/**
 392 +----------------------------------------------------------
 393 * ?????????????
 394 * load('@.Util.Array')
 395 +----------------------------------------------------------
 396 * @param string $name ??????????
 397 * @param string $baseUrl ????
 398 * @param string $ext ????????
 399 +----------------------------------------------------------
 400 * @return void
 401 +----------------------------------------------------------
 402 */
 403function load($name,$baseUrl='',$ext='.php') {
 404    $name    =   str_replace(array('.','#'), array('/','.'), $name);
 405    if(empty($baseUrl)) {
 406        if(0 === strpos($name,'@/')) {
 407            //?????????
 408            $baseUrl   =  APP_PATH.'/Common/';
 409            $name =  substr($name,2);
 410        }else{
 411            //??ThinkPHP ?????
 412            $baseUrl =  THINK_PATH.'/Common/';
 413        }
 414    }
 415    if(substr($baseUrl, -1) != "/")    $baseUrl .= "/";
 416    include $baseUrl . $name . $ext;
 417}
 418
 419// ???????????
 420// ???????????????? ???Vendor????
 421// ???????.php????
 422function vendor($class,$baseUrl = '',$ext='.php')
 423{
 424    if(empty($baseUrl))  $baseUrl    =   VENDOR_PATH;
 425    return import($class,$baseUrl,$ext);
 426}
 427
 428// ?????????
 429function alias_import($alias,$classfile='') {
 430    static $_alias   =  array();
 431    if('' !== $classfile) {
 432        // ??????
 433        $_alias[$alias]  = $classfile;
 434        return ;
 435    }
 436    if(is_string($alias)) {
 437        if(isset($_alias[$alias]))
 438            return require_cache($_alias[$alias]);
 439    }elseif(is_array($alias)){
 440        foreach ($alias as $key=>$val)
 441            $_alias[$key]  =  $val;
 442        return ;
 443    }
 444    return false;
 445}
 446
 447/**
 448 +----------------------------------------------------------
 449 * D???????Model
 450 +----------------------------------------------------------
 451 * @param string name Model??
 452 * @param string app Model????
 453 +----------------------------------------------------------
 454 * @return Model
 455 +----------------------------------------------------------
 456 */
 457function D($name='',$app='')
 458{
 459    static $_model = array();
 460    static $_app   = array();
 461    if(empty($name)) return new Model;
 462    if(empty($app))   $app =  APP_NAME;
 463    if(isset($_model[$app.$name]))
 464        return $_model[$app.$name];
 465    $OriClassName = $name;
 466    if(strpos($name,C('APP_GROUP_DEPR'))) {
 467        $array   =  explode(C('APP_GROUP_DEPR'),$name);
 468        $name = array_pop($array);
 469        $className =  $name.'Model';
 470        import($app.'.Model.'.implode('.',$array).'.'.$className);
 471    }else{
 472        $className =  $name.'Model';
 473    	$_ENV['app'] = $app;
 474        import($app.'.Model.'.$className);
 475    }
 476    if(class_exists($className)) {
 477        $model = new $className();
 478    }else{
 479        $model  = new Model($name);
 480    }
 481    $_model[$app.$OriClassName] =  $model;
 482    return $model;
 483}
 484
 485/**
 486 +----------------------------------------------------------
 487 * M????????????????Model
 488 +----------------------------------------------------------
 489 * @param string name Model??
 490 +----------------------------------------------------------
 491 * @return Model
 492 +----------------------------------------------------------
 493 */
 494function M($name='',$class='Model') {
 495    static $_model = array();
 496    if(!isset($_model[$name.'_'.$class]))
 497        $_model[$name.'_'.$class]   = new $class($name);
 498    return $_model[$name.'_'.$class];
 499}
 500
 501/**
 502 +----------------------------------------------------------
 503 * A???????Action
 504 +----------------------------------------------------------
 505 * @param string name Action??
 506 * @param string app Model????
 507 +----------------------------------------------------------
 508 * @return Action
 509 +----------------------------------------------------------
 510 */
 511function A($name,$app='@')
 512{
 513    static $_action = array();
 514    if(isset($_action[$app.$name]))
 515        return $_action[$app.$name];
 516    $OriClassName = $name;
 517    if(strpos($name,C('APP_GROUP_DEPR'))) {
 518        $array   =  explode(C('APP_GROUP_DEPR'),$name);
 519        $name = array_pop($array);
 520        $className =  $name.'Action';
 521        import($app.'.Action.'.implode('.',$array).'.'.$className);
 522    }else{
 523        $className =  $name.'Action';
 524        import($app.'.Action.'.$className);
 525    }
 526    if(class_exists($className)) {
 527        $action = new $className();
 528        $_action[$app.$OriClassName] = $action;
 529        return $action;
 530    }else {
 531        return false;
 532    }
 533}
 534
 535function api($name) {
 536    static $_api = array();
 537//    $name = strtolower($name);
 538    if(isset($_api[$name])){
 539        return $_api[$name];
 540    }
 541    $OriClassName = $name;
 542    $className = $name.'Api';
 543    require_once(SITE_PATH.'/api/'.$name.'Api.class.php');
 544    if(class_exists($className)) {
 545        $api = new $className(true);
 546        $_api[$OriClassName] = $api;
 547        return $api;
 548    }else {
 549        return false;
 550    }     
 551}
 552
 553
 554
 555// ???????????
 556function R($module,$action,$app='@') {
 557    $class = A($module,$app);
 558    if($class)
 559        return call_user_func(array(&$class,$action));
 560    else
 561        return false;
 562}
 563
 564// ?????????(??????)
 565function L($name=null,$value=null) {
 566    static $_lang = array();
 567    // ?????????
 568    if(empty($name)) return $_lang;
 569    // ??????(???)
 570    // ????,???????$name
 571    if (is_string($name) )
 572    {
 573        $name = strtoupper($name);
 574        if (is_null($value))
 575            return isset($_lang[$name]) ? $_lang[$name] : $name;
 576        $_lang[$name] = $value;// ????
 577        return;
 578    }
 579    // ????
 580    if (is_array($name))
 581        $_lang += array_change_key_case($name,CASE_UPPER);
 582    return;
 583}
 584
 585// ?????
 586function C($name=null,$value=null)
 587{
 588    static $_config = array();
 589    // ????????
 590    if(empty($name)) return $_config;
 591    // ???????????
 592    if (is_string($name))
 593    {
 594        if (!strpos($name,'.')) {
 595            $name = strtolower($name);
 596            if (is_null($value))
 597                return isset($_config[$name])? $_config[$name] : null;
 598            $_config[$name] = $value;
 599            return;
 600        }
 601        // ???????????
 602        $name = explode('.',$name);
 603        $name[0]   = strtolower($name[0]);
 604        if (is_null($value))
 605            return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null;
 606        $_config[$name[0]][$name[1]] = $value;
 607        return;
 608    }
 609    // ????
 610    if(is_array($name))
 611        return $_config = array_merge($_config,array_change_key_case($name));
 612    return null;// ??????
 613}
 614
 615// ????
 616function tag($name,$params=array()) {
 617    $tags   =  C('_tags_.'.$name);
 618    if($tags) {
 619        foreach ($tags   as $key=>$call){
 620            if(is_callable($call))
 621                $result = call_user_func_array($call,$params);
 622        }
 623        return $result;
 624    }
 625    return false;
 626}
 627
 628// ???hook
 629function hook($name,$params=array()) {
 630    return X($name,$params=array(),'Hook');
 631}
 632
 633// ?????
 634function plugin($name,$params=array()) {
 635    return X($name,$params=array(),'Plugin');
 636}
 637
 638// ?????
 639function service($name,$params=array()) {
 640    return X($name,$params=array(),'Service');
 641}
 642
 643
 644// ???widget
 645function widget($name,$params=array(),$return=false) {
 646    return W($name,$params,$return);
 647}
 648
 649// ???model
 650function model($name,$params=array()) {
 651    return X($name,$params=array(),'Model');
 652}
 653
 654// ??????
 655function X($name,$params=array(),$domain='Service') {
 656    static $_service = array();
 657    //if(empty($app))
 658    $app =  C('DEFAULT_APP');
 659
 660    if(isset($_service[$domain.'_'.$app.'_'.$name]))
 661        return $_service[$domain.'_'.$app.'_'.$name];
 662
 663	$class = $name.$domain;
 664	if(file_exists(LIB_PATH.$domain.'/'.$class.'.class.php')){
 665		require_cache(LIB_PATH.$domain.'/'.$class.'.class.php');
 666	}else{
 667		require_cache(SITE_PATH.'/addons/'.strtolower($domain).'s/'.$class.'.class.php');
 668	}
 669	//?????? ???? ? ????
 670	if(class_exists($class)){
 671		$obj   =  new $class($params);
 672		$_service[$domain.'_'.$app.'_'.$name] =  $obj;
 673		return $obj;
 674	}else{
 675		throw_exception(L('_CLASS_NOT_EXIST_').':'.$class);
 676	}
 677}
 678
 679// ??????????
 680function medal($name) {
 681	if ( empty($name) )
 682		return ;
 683		
 684	static $_medal = array();
 685	if ( isset($_medal[$name]) )
 686		return $_medal[$name];
 687		
 688	$classname	= ucfirst($name) . 'Medal';
 689	$filename	= $classname . '.class.php';
 690	$basepath	= SITE_PATH . '/addons/plugins/Medal';
 691	$filepath	= $basepath . '/' . $name . '/' . $filename;
 692	
 693	// ????
 694	if ( ! class_exists('BaseMedal') )
 695		require_cache($basepath . '/BaseMedal.class.php');
 696	
 697	if ( file_exists($filepath) )
 698		require_cache($filepath);
 699		
 700	if ( class_exists($classname) ) {
 701		$_medal[$name]	= new $classname();
 702		return $_medal[$name];
 703	}else {
 704		throw_exception(L('_CLASS_NOT_EXIST_').':'.$classname);
 705	}
 706}
 707
 708
 709// ?? ??
 710//function B($name,$options=null) {
 711//    $class = 'BrowseBehavior';
 712//	if(file_exists(SITE_PATH.'/services/BrowseBehavior'.$class.'.class.php')){
 713//		require_cache(SITE_PATH.'/services/BrowseBehavior'.$class.'.class.php');
 714//	}else{
 715//		require_cache(SITE_PATH.'/addons/behaviors/'.$class.'.class.php');
 716//	}
 717//    $behavior   =  new $class($options);
 718//    return $behavior->run();
 719//}
 720
 721// ????Widget
 722function W($name,$data=array(),$return=false) {
 723    $class = $name.'Widget';
 724	if(file_exists(LIB_PATH.'Widget/'.$class.'.class.php')){
 725		require_cache(LIB_PATH.'Widget/'.$class.'.class.php');
 726	}else{
 727		require_cache(SITE_PATH.'/addons/widgets/'.$class.'.class.php');
 728	}
 729    if(!class_exists($class))
 730        throw_exception(L('_CLASS_NOT_EXIST_').':'.$class);
 731    $widget		=	new $class();
 732    $content	=	$widget->render($data);
 733    if($return)
 734        return $content;
 735    else
 736        echo $content;
 737}
 738
 739// ?????????
 740function S($name,$value='',$expire='',$type='') {
 741    static $_cache = array();
 742    alias_import('Cache');
 743    //????????
 744    $cache  = Cache::getInstance($type);
 745    if('' !== $value) {
 746        if(is_null($value)) {
 747            // ????
 748            $result =   $cache->rm($name);
 749            if($result)   unset($_cache[$type.'_'.$name]);
 750            return $result;
 751        }else{
 752            // ????
 753            $cache->set($name,$value,$expire);
 754            $_cache[$type.'_'.$name]     =   $value;
 755        }
 756        return ;
 757    }
 758    if(isset($_cache[$type.'_'.$name]))
 759        return $_cache[$type.'_'.$name];
 760    // ??????
 761    $value      =  $cache->get($name);
 762    $_cache[$type.'_'.$name]     =   $value;
 763    return $value;
 764}
 765
 766// ??????????? ???????? ??????
 767function F($name,$value='',$path=false) {
 768    static $_cache = array();
 769    if(!$path) {
 770    	$path	=	SITE_PATH.'/_runtime/_cache/';
 771    }
 772    if(!is_dir($path)) {
 773    	mkdir($path,0777,true);
 774    }
 775    $filename   =   $path.$name.'.php';
 776    if('' !== $value) {
 777        if(is_null($value)) {
 778            // ????
 779            return unlink($filename);
 780        }else{
 781            // ????
 782            $dir   =  dirname($filename);
 783            // ????????
 784            if(!is_dir($dir))  mkdir($dir);
 785            return file_put_contents($filename,"<?php\nreturn ".var_export($value,true).";\n?>");
 786        }
 787    }
 788    if(isset($_cache[$name])) return $_cache[$name];
 789    // ??????
 790    if(is_file($filename)) {
 791        $value   =  include $filename;
 792        $_cache[$name]   =   $value;
 793    }else{
 794        $value  =   false;
 795    }
 796    return $value;
 797}
 798
 799// ??PHP?????????????
 800function to_guid_string($mix)
 801{
 802    if(is_object($mix) && function_exists('spl_object_hash')) {
 803        return spl_object_hash($mix);
 804    }elseif(is_resource($mix)){
 805        $mix = get_resource_type($mix).strval($mix);
 806    }else{
 807        $mix = serialize($mix);
 808    }
 809    return md5($mix);
 810}
 811
 812//[RUNTIME]
 813// ????
 814function compile($filename,$runtime=false) {
 815    $content = file_get_contents($filename);
 816    if(true === $runtime)
 817        // ???????
 818        $content = preg_replace('/\/\/\[RUNTIME\](.*?)\/\/\[\/RUNTIME\]/s','',$content);
 819    $content = substr(trim($content),5);
 820    if('?>' == substr($content,-2))
 821        $content = substr($content,0,-2);
 822    return $content;
 823}
 824
 825// ???????????
 826function strip_whitespace($content) {
 827    $stripStr = '';
 828    //??php??
 829    $tokens =   token_get_all ($content);
 830    $last_space = false;
 831    for ($i = 0, $j = count ($tokens); $i < $j; $i++)
 832    {
 833        if (is_string ($tokens[$i]))
 834        {
 835            $last_space = false;
 836            $stripStr .= $tokens[$i];
 837        }
 838        else
 839        {
 840            switch ($tokens[$i][0])
 841            {
 842                //????PHP??
 843                case T_COMMENT:
 844                case T_DOC_COMMENT:
 845                    break;
 846                //????
 847                case T_WHITESPACE:
 848                    if (!$last_space)
 849                    {
 850                        $stripStr .= ' ';
 851                        $last_space = true;
 852                    }
 853                    break;
 854                default:
 855                    $last_space = false;
 856                    $stripStr .= $tokens[$i][1];
 857            }
 858        }
 859    }
 860    return $stripStr;
 861}
 862// ??????????
 863function array_define($array) {
 864    $content = '';
 865    foreach($array as $key=>$val) {
 866        $key =  strtoupper($key);
 867        if(in_array($key,array('THINK_PATH','APP_NAME','APP_PATH','RUNTIME_PATH','RUNTIME_ALLINONE','THINK_MODE')))
 868            $content .= 'if(!defined(\''.$key.'\')) ';
 869        if(is_int($val) || is_float($val)) {
 870            $content .= "define('".$key."',".$val.");";
 871        }elseif(is_bool($val)) {
 872            $val = ($val)?'true':'false';
 873            $content .= "define('".$key."',".$val.");";
 874        }elseif(is_string($val)) {
 875            $content .= "define('".$key."','".addslashes($val)."');";
 876        }
 877    }
 878    return $content;
 879}
 880//[/RUNTIME]
 881
 882// ??????
 883function mk_dir($dir, $mode = 0755)
 884{
 885  if (is_dir($dir) || @mkdir($dir,$mode)) return true;
 886  if (!mk_dir(dirname($dir),$mode)) return false;
 887  return @mkdir($dir,$mode);
 888}
 889
 890// ??????? ??????
 891function auto_charset($fContents,$from,$to){
 892    $from   =  strtoupper($from)=='UTF8'? 'utf-8':$from;
 893    $to       =  strtoupper($to)=='UTF8'? 'utf-8':$to;
 894    if( strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents)) ){
 895        //??????????????????
 896        return $fContents;
 897    }
 898    if(is_string($fContents) ) {
 899        if(function_exists('mb_convert_encoding')){
 900            return mb_convert_encoding ($fContents, $to, $from);
 901        }elseif(function_exists('iconv')){
 902            return iconv($from,$to,$fContents);
 903        }else{
 904            return $fContents;
 905        }
 906    }
 907    elseif(is_array($fContents)){
 908        foreach ( $fContents as $key => $val ) {
 909            $_key =     auto_charset($key,$from,$to);
 910            $fContents[$_key] = auto_charset($val,$from,$to);
 911            if($key != $_key )
 912                unset($fContents[$key]);
 913        }
 914        return $fContents;
 915    }
 916    else{
 917        return $fContents;
 918    }
 919}
 920
 921// xml??
 922function xml_encode($data,$encoding='utf-8',$root="think") {
 923    $xml = '<?xml version="1.0" encoding="'.$encoding.'"?>';
 924    $xml.= '<'.$root.'>';
 925    $xml.= data_to_xml($data);
 926    $xml.= '</'.$root.'>';
 927    return $xml;
 928}
 929
 930function data_to_xml($data) {
 931    if(is_object($data)) {
 932        $data = get_object_vars($data);
 933    }
 934    $xml = '';
 935    foreach($data as $key=>$val) {
 936        is_numeric($key) && $key="item id=\"$key\"";
 937        $xml.="<$key>";
 938        $xml.=(is_array($val)||is_object($val))?data_to_xml($val):$val;
 939        list($key,)=explode(' ',$key);
 940        $xml.="</$key>";
 941    }
 942    return $xml;
 943}
 944
 945/**
 946 +----------------------------------------------------------
 947 * Cookie ???????? (???????????) 2009-07-9
 948 +----------------------------------------------------------
 949 * 1 ??cookie: cookie('name')
 950 * 2 ???????????cookie: cookie(null)
 951 * 3 ????????cookie: cookie(null,'think_') | ???????????
 952 * 4 ??cookie: cookie('name','value') | ??????: cookie('name','value',3600)
 953 * 5 ??cookie: cookie('name',null)
 954 +----------------------------------------------------------
 955 * $option ????prefix,expire,path,domain
 956 * ??????:cookie('name','value',array('expire'=>1,'prefix'=>'think_'))
 957 * ??query?????:cookie('name','value','prefix=tp_&expire=10000')
 958 * 2010-1-17 ???????????????????
 959 */
 960function cookie($name,$value='',$option=null)
 961{
 962    // ????
 963    $config = array(
 964        'prefix' => C('COOKIE_PREFIX'), // cookie ????
 965        'expire' => C('COOKIE_EXPIRE'), // cookie ????
 966        'path'   => C('COOKIE_PATH'),   // cookie ????
 967        'domain' => C('COOKIE_DOMAIN'), // cookie ????
 968    );
 969
 970    // ????(???????)
 971    if (!empty($option)) {
 972        if (is_numeric($option)) {
 973            $option = array('expire'=>$option);
 974        }else if( is_string($option) ) {
 975            parse_str($option,$option);
 976    	}
 977    	$config	=	array_merge($config,array_change_key_case($option));
 978    }
 979
 980    // ?????????cookie
 981    if (is_null($name)) {
 982       if (empty($_COOKIE)) return;
 983       // ????cookie?????????config???????
 984       $prefix = empty($value)? $config['prefix'] : $value;
 985       if (!empty($prefix))// ??????????????????
 986       {
 987           foreach($_COOKIE as $key=>$val) {
 988               if (0 === stripos($key,$prefix)){
 989                    setcookie($_COOKIE[$key],'',time()-3600,$config['path'],$config['domain']);
 990                    unset($_COOKIE[$key]);
 991               }
 992           }
 993       }
 994       return;
 995    }
 996    $name = $config['prefix'].$name;
 997
 998    if (''===$value){
 999        //return isset($_COOKIE[$name]) ? unserialize($_COOKIE[$name]) : null;// ????Cookie
1000        return isset($_COOKIE[$name]) ? ($_COOKIE[$name]) : null;// ????Cookie
1001    }else {
1002        if (is_null($value)) {
1003            setcookie($name,'',time()-3600,$config['path'],$config['domain']);
1004            unset($_COOKIE[$name]);// ????cookie
1005        }else {
1006            // ??cookie
1007            $expire = !empty($config['expire'])? time()+ intval($config['expire']):0;
1008            //setcookie($name,serialize($value),$expire,$config['path'],$config['domain']);
1009            setcookie($name,($value),$expire,$config['path'],$config['domain']);
1010            //$_COOKIE[$name] = ($value);
1011        }
1012    }
1013}
1014function ts_cookie($name,$value='',$option=null)
1015{
1016    // ????
1017    $config = array(
1018        'prefix' => C('COOKIE_PREFIX'), // cookie ????
1019        'expire' => C('COOKIE_EXPIRE'), // cookie ????
1020        'path'   => C('COOKIE_PATH'),   // cookie ????
1021        'domain' => C('COOKIE_DOMAIN'), // cookie ????
1022    );
1023
1024    // ????(???????)
1025    if (!empty($option)) {
1026        if (is_numeric($option)) {
1027            $option = array('expire'=>$option);
1028        }else if( is_string($option) ) {
1029            parse_str($option,$option);
1030    	}
1031    	$config	=	array_merge($config,array_change_key_case($option));
1032    }
1033
1034    // ?????????cookie
1035    if (is_null($name)) {
1036       if (empty($_COOKIE)) return;
1037       // ????cookie?????????config???????
1038       $prefix = empty($value)? $config['prefix'] : $value;
1039       if (!empty($prefix))// ??????????????????
1040       {
1041           foreach($_COOKIE as $key=>$val) {
1042               if (0 === stripos($key,$prefix)){
1043                    setcookie($_COOKIE[$key],'',time()-3600,$config['path'],$config['domain']);
1044                    unset($_COOKIE[$key]);
1045               }
1046           }
1047       }
1048       return;
1049    }
1050    $name = $config['prefix'].$name;
1051
1052    if (''===$value){
1053        //return isset($_COOKIE[$name]) ? unserialize($_COOKIE[$name]) : null;// ????Cookie
1054        return isset($_COOKIE[$name]) ? ($_COOKIE[$name]) : null;// ????Cookie
1055    }else {
1056        if (is_null($value)) {
1057            setcookie($name,'',time()-3600,$config['path'],$config['domain']);
1058            unset($_COOKIE[$name]);// ????cookie
1059        }else {
1060            // ??cookie
1061            $expire = !empty($config['expire'])? time()+ intval($config['expire']):0;
1062            //setcookie($name,serialize($value),$expire,$config['path'],$config['domain']);
1063            setcookie($name,($value),$expire,$config['path'],$config['domain']);
1064            //$_COOKIE[$name] = ($value);
1065        }
1066    }
1067}
1068?>