/code/core/ThinkPHP/Common/functions.php
PHP | 831 lines | 610 code | 41 blank | 180 comment | 127 complexity | 22a35919de82fdd3f8562c1c08af94f9 MD5 | raw file
Possible License(s): LGPL-2.1
- <?php
- // +----------------------------------------------------------------------
- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
- // +----------------------------------------------------------------------
- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
- // +----------------------------------------------------------------------
- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
- // +----------------------------------------------------------------------
- // | Author: liu21st <liu21st@gmail.com>
- // +----------------------------------------------------------------------
- // $Id$
-
- /**
- +------------------------------------------------------------------------------
- * Think?????
- +------------------------------------------------------------------------------
- * @category Think
- * @package Common
- * @author liu21st <liu21st@gmail.com>
- * @version $Id$
- +------------------------------------------------------------------------------
- */
-
- // URL?? ?????????
- function U($url,$params=array(),$redirect=false,$suffix=true) {
- if(0===strpos($url,'/'))
- $url = substr($url,1);
- if(!strpos($url,'://')) // ??????? ???????
- $url = APP_NAME.'://'.$url;
- if(stripos($url,'@?')) { // ???????
- $url = str_replace('@?','@think?',$url);
- }elseif(stripos($url,'@')) { // ???????
- $url = $url.MODULE_NAME;
- }
- // ??URL??
- $array = parse_url($url);
- $app = isset($array['scheme'])? $array['scheme'] :APP_NAME;
- $route = isset($array['user'])?$array['user']:'';
- if(defined('GROUP_NAME') && strcasecmp(GROUP_NAME,C('DEFAULT_GROUP')))
- $group= GROUP_NAME;
- if(isset($array['path'])) {
- $action = substr($array['path'],1);
- if(!isset($array['host'])) {
- // ???????
- $module = MODULE_NAME;
- }else{// ????
- if(strpos($array['host'],'-')) {
- list($group,$module) = explode('-',$array['host']);
- }else{
- $module = $array['host'];
- }
- }
- }else{ // ?????
- $module = MODULE_NAME;
- $action = $array['host'];
- }
- if(isset($array['query'])) {
- parse_str($array['query'],$query);
- $params = array_merge($query,$params);
- }
-
- if(C('URL_DISPATCH_ON') && C('URL_MODEL')>0) {
- $depr = C('URL_PATHINFO_MODEL')==2?C('URL_PATHINFO_DEPR'):'/';
- $str = $depr;
- foreach ($params as $var=>$val)
- $str .= $var.$depr.$val.$depr;
- $str = substr($str,0,-1);
- $group = isset($group)?$group.$depr:'';
- if(!empty($route)) {
- $url = str_replace(APP_NAME,$app,__APP__).'/'.$group.$route.$str;
- }else{
- $url = str_replace(APP_NAME,$app,__APP__).'/'.$group.$module.$depr.$action.$str;
- }
- if($suffix && C('URL_HTML_SUFFIX'))
- $url .= C('URL_HTML_SUFFIX');
- }else{
- $params = http_build_query($params);
- if(isset($group)) {
- $url = str_replace(APP_NAME,$app,__APP__).'?'.C('VAR_GROUP').'='.$group.'&'.C('VAR_MODULE').'='.$module.'&'.C('VAR_ACTION').'='.$action.'&'.$params;
- }else{
- $url = str_replace(APP_NAME,$app,__APP__).'?'.C('VAR_MODULE').'='.$module.'&'.C('VAR_ACTION').'='.$action.'&'.$params;
- }
- }
- if($redirect)
- redirect($url);
- else
- return $url;
- }
-
- /**
- +----------------------------------------------------------
- * ?????????
- * type
- * =0 ?Java?????C???
- * =1 ?C?????Java???
- +----------------------------------------------------------
- * @access protected
- +----------------------------------------------------------
- * @param string $name ???
- * @param integer $type ????
- +----------------------------------------------------------
- * @return string
- +----------------------------------------------------------
- */
- function parse_name($name,$type=0) {
- if($type) {
- return ucfirst(preg_replace("/_([a-zA-Z])/e", "strtoupper('\\1')", $name));
- }else{
- $name = preg_replace("/[A-Z]/", "_\\0", $name);
- return strtolower(trim($name, "_"));
- }
- }
-
- // ????
- function halt($error) {
- if(IS_CLI) exit ($error);
- $e = array();
- if(C('APP_DEBUG')){
- //???????????
- if(!is_array($error)) {
- $trace = debug_backtrace();
- $e['message'] = $error;
- $e['file'] = $trace[0]['file'];
- $e['class'] = $trace[0]['class'];
- $e['function'] = $trace[0]['function'];
- $e['line'] = $trace[0]['line'];
- $traceInfo='';
- $time = date("y-m-d H:i:m");
- foreach($trace as $t)
- {
- $traceInfo .= '['.$time.'] '.$t['file'].' ('.$t['line'].') ';
- $traceInfo .= $t['class'].$t['type'].$t['function'].'(';
- $traceInfo .= implode(', ', $t['args']);
- $traceInfo .=")<br/>";
- }
- $e['trace'] = $traceInfo;
- }else {
- $e = $error;
- }
- // ????????
- include C('TMPL_EXCEPTION_FILE');
- }
- else
- {
- //?????????
- $error_page = C('ERROR_PAGE');
- if(!empty($error_page)){
- redirect($error_page);
- }else {
- if(C('SHOW_ERROR_MSG'))
- $e['message'] = is_array($error)?$error['message']:$error;
- else
- $e['message'] = C('ERROR_MESSAGE');
- // ????????
- include C('TMPL_EXCEPTION_FILE');
- }
- }
- exit;
- }
-
- // URL???
- function redirect($url,$time=0,$msg='')
- {
- //??URL????
- $url = str_replace(array("\n", "\r"), '', $url);
- if(empty($msg))
- $msg = "????{$time}????????{$url}?";
- if (!headers_sent()) {
- // redirect
- if(0===$time) {
- header("Location: ".$url);
- }else {
- header("refresh:{$time};url={$url}");
- echo($msg);
- }
- exit();
- }else {
- $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
- if($time!=0)
- $str .= $msg;
- exit($str);
- }
- }
-
- // ???????
- function throw_exception($msg,$type='ThinkException',$code=0)
- {
- if(IS_CLI) exit($msg);
- if(class_exists($type,false))
- throw new $type($msg,$code,true);
- else
- halt($msg); // ????????????????
- }
-
- // ??????
- function debug_start($label='')
- {
- $GLOBALS[$label]['_beginTime'] = microtime(TRUE);
- if ( MEMORY_LIMIT_ON ) $GLOBALS[$label]['_beginMem'] = memory_get_usage();
- }
-
- // ?????????????????????
- function debug_end($label='')
- {
- $GLOBALS[$label]['_endTime'] = microtime(TRUE);
- echo '<div style="text-align:center;width:100%">Process '.$label.': Times '.number_format($GLOBALS[$label]['_endTime']-$GLOBALS[$label]['_beginTime'],6).'s ';
- if ( MEMORY_LIMIT_ON ) {
- $GLOBALS[$label]['_endMem'] = memory_get_usage();
- echo ' Memories '.number_format(($GLOBALS[$label]['_endMem']-$GLOBALS[$label]['_beginMem'])/1024).' k';
- }
- echo '</div>';
- }
-
- // ??????????
- function dump($var, $echo=true,$label=null, $strict=true)
- {
- $label = ($label===null) ? '' : rtrim($label) . ' ';
- if(!$strict) {
- if (ini_get('html_errors')) {
- $output = print_r($var, true);
- $output = "<pre>".$label.htmlspecialchars($output,ENT_QUOTES)."</pre>";
- } else {
- $output = $label . " : " . print_r($var, true);
- }
- }else {
- ob_start();
- var_dump($var);
- $output = ob_get_clean();
- if(!extension_loaded('xdebug')) {
- $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
- $output = '<pre>'. $label. htmlspecialchars($output, ENT_QUOTES). '</pre>';
- }
- }
- if ($echo) {
- echo($output);
- return null;
- }else
- return $output;
- }
-
- // ?????? ??????????
- function get_instance_of($name,$method='',$args=array())
- {
- static $_instance = array();
- $identify = empty($args)?$name.$method:$name.$method.to_guid_string($args);
- if (!isset($_instance[$identify])) {
- if(class_exists($name)){
- $o = new $name();
- if(method_exists($o,$method)){
- if(!empty($args)) {
- $_instance[$identify] = call_user_func_array(array(&$o, $method), $args);
- }else {
- $_instance[$identify] = $o->$method();
- }
- }
- else
- $_instance[$identify] = $o;
- }
- else
- halt(L('_CLASS_NOT_EXIST_').':'.$name);
- }
- return $_instance[$identify];
- }
-
- /**
- +----------------------------------------------------------
- * ??????ThinkPHP?????????model?Action??
- * ????????????
- +----------------------------------------------------------
- * @param string $name ????
- +----------------------------------------------------------
- * @return void
- +----------------------------------------------------------
- */
- function __autoload($name)
- {
- // ??????????
- if(alias_import($name)) return ;
- // ?????????Actioon??Model?
- if(substr($name,-5)=="Model") {
- require_cache(LIB_PATH.'Model/'.$name.'.class.php');
- }elseif(substr($name,-6)=="Action"){
- require_cache(LIB_PATH.'Action/'.$name.'.class.php');
- }else {
- // ????????????????
- if(C('APP_AUTOLOAD_PATH')) {
- $paths = explode(',',C('APP_AUTOLOAD_PATH'));
- foreach ($paths as $path){
- if(import($path.$name)) {
- // ??????????
- return ;
- }
- }
- }
- }
- return ;
- }
-
- // ???require_once
- function require_cache($filename)
- {
- static $_importFiles = array();
- $filename = realpath($filename);
- if (!isset($_importFiles[$filename])) {
- if(file_exists_case($filename)){
- require $filename;
- $_importFiles[$filename] = true;
- }
- else
- {
- $_importFiles[$filename] = false;
- }
- }
- return $_importFiles[$filename];
- }
-
- // ????????????
- function file_exists_case($filename) {
- if(is_file($filename)) {
- if(IS_WIN && C('APP_FILE_CASE')) {
- if(basename(realpath($filename)) != basename($filename))
- return false;
- }
- return true;
- }
- return false;
- }
-
- /**
- +----------------------------------------------------------
- * ??????? ?java?Import
- * ????????
- +----------------------------------------------------------
- * @param string $class ?????????
- * @param string $baseUrl ????
- * @param string $ext ????????
- +----------------------------------------------------------
- * @return boolen
- +----------------------------------------------------------
- */
- function import($class)
- {
- static $_file = array();
- static $_class = array();
- if(isset($_file[$class])) {
- return true;
- } else if(file_exists($class)){
- $_file[$class] = true;
- return require_cache($class);
- } else {
- return alias_import($class);
- }
- }
-
- /**
- +----------------------------------------------------------
- * ?????????????
- * load('@.Util.Array')
- +----------------------------------------------------------
- * @param string $name ??????????
- * @param string $baseUrl ????
- * @param string $ext ????????
- +----------------------------------------------------------
- * @return void
- +----------------------------------------------------------
- */
- function load($name,$baseUrl='',$ext='.php') {
- $name = str_replace(array('.','#'), array('/','.'), $name);
- if(empty($baseUrl)) {
- if(0 === strpos($name,'@/')) {
- //?????????
- $baseUrl = APP_PATH.'/Common/';
- $name = substr($name,2);
- }else{
- //??ThinkPHP ?????
- $baseUrl = THINK_PATH.'/Common/';
- }
- }
- if(substr($baseUrl, -1) != "/") $baseUrl .= "/";
- include $baseUrl . $name . $ext;
- }
-
- // ?????????
- function alias_import($alias,$classfile='') {
- static $_alias = array();
- if('' !== $classfile) {
- // ??????
- $_alias[$alias] = $classfile;
- return ;
- }
- if(is_string($alias)) {
- if(isset($_alias[$alias]))
- return require_cache($_alias[$alias]);
- }elseif(is_array($alias)){
- foreach ($alias as $key=>$val)
- $_alias[$key] = $val;
- return ;
- }
- return false;
- }
-
- /**
- +----------------------------------------------------------
- * D???????Model
- +----------------------------------------------------------
- * @param string name Model??
- * @param string app Model????
- +----------------------------------------------------------
- * @return Model
- +----------------------------------------------------------
- */
- function D($name='',$app='')
- {
- static $_model = array();
- if(empty($name)) return new Model;
- if(empty($app)) $app = APP_NAME;
- if(isset($_model[$app.$name]))
- return $_model[$app.$name];
-
- $OriClassName = $name;
-
- $className = $name.'Model';
- import(APPS_PATH.'/'.$app.'./Model/'.$className.'.class.php');
-
- if(class_exists($className)) {
- $model = new $className();
- }else {
- $model = new Model($name);
- }
- $_model[$app.$OriClassName] = $model;
- return $model;
- }
-
- /**
- +----------------------------------------------------------
- * M????????????????Model
- +----------------------------------------------------------
- * @param string name Model??
- +----------------------------------------------------------
- * @return Model
- +----------------------------------------------------------
- */
- function M($name='',$class='Model') {
- static $_model = array();
- if(!isset($_model[$name.'_'.$class]))
- $_model[$name.'_'.$class] = new $class($name);
- return $_model[$name.'_'.$class];
- }
-
- /**
- +----------------------------------------------------------
- * A???????Action
- +----------------------------------------------------------
- * @param string name Action??
- * @param string app Model????
- +----------------------------------------------------------
- * @return Action
- +----------------------------------------------------------
- */
- function A($name='',$app='')
- {
- static $_action = array();
- if(empty($name)) return false;
- if(empty($app)) $app = APP_NAME;
-
- if(isset($_action[$app.$name]))
- return $_action[$app.$name];
- $OriClassName = $name;
-
- $className = $name.'Action';
- import(APPS_PATH.'/'.$app.'./Action/'.$className.'.class.php');
-
- if(class_exists($className)) {
- $action = new $className();
- $_action[$app.$OriClassName] = $action;
- return $action;
- }else {
- return false;
- }
- }
-
- // ???????????
- function R($module,$action,$app='@') {
- $class = A($module,$app);
- if($class)
- return call_user_func(array(&$class,$action));
- else
- return false;
- }
-
- // ?????????(??????)
- function L($name=null,$value=null) {
- static $_lang = array();
- // ?????????
- if(empty($name)) return $_lang;
- // ??????(???)
- // ????,???????$name
- if (is_string($name) )
- {
- $name = strtoupper($name);
- if (is_null($value))
- return isset($_lang[$name]) ? $_lang[$name] : $name;
- $_lang[$name] = $value;// ????
- return;
- }
- // ????
- if (is_array($name))
- $_lang = array_merge($_lang,array_change_key_case($name,CASE_UPPER));
- return;
- }
-
- // ?????
- function C($name=null,$value=null)
- {
- static $_config = array();
- // ????????
- if(empty($name)) return $_config;
- // ???????????
- if (is_string($name))
- {
- if (!strpos($name,'.')) {
- $name = strtolower($name);
- if (is_null($value))
- return isset($_config[$name])? $_config[$name] : null;
- $_config[$name] = $value;
- return;
- }
- // ???????????
- $name = explode('.',$name);
- $name[0] = strtolower($name[0]);
- if (is_null($value))
- return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null;
- $_config[$name[0]][$name[1]] = $value;
- return;
- }
- // ????
- if(is_array($name))
- return $_config = array_merge($_config,array_change_key_case($name));
- return null;// ??????
- }
-
- // ????
- function tag($name,$params=array()) {
- $tags = C('_tags_.'.$name);
- if($tags) {
- foreach ($tags as $key=>$call){
- if(is_callable($call))
- $result = call_user_func_array($call,$params);
- }
- return $result;
- }
- return false;
- }
-
- // ????Widget
- function W($name,$data=array(),$return=false) {
- $class = $name.'Widget';
- require_cache(LIB_PATH.'Widget/'.$class.'.class.php');
- if(!class_exists($class))
- throw_exception(L('_CLASS_NOT_EXIST_').':'.$class);
- $widget = Think::instance($class);
- $content = $widget->render($data);
- if($return)
- return $content;
- else
- echo $content;
- }
-
- // ?????????
- function S($name,$value='',$expire='',$type='') {
- static $_cache = array();
- import('Cache');
- //????????
- $cache = Cache::getInstance($type);
- if('' !== $value) {
- if(is_null($value)) {
- // ????
- $result = $cache->rm($name);
- if($result) unset($_cache[$type.'_'.$name]);
- return $result;
- }else{
- // ????
- $cache->set($name,$value,$expire);
- $_cache[$type.'_'.$name] = $value;
- }
- return ;
- }
- if(isset($_cache[$type.'_'.$name]))
- return $_cache[$type.'_'.$name];
- // ??????
- $value = $cache->get($name);
- $_cache[$type.'_'.$name] = $value;
- return $value;
- }
-
- // ??????????? ???????? ??????
- function F($name,$value='',$path=DATA_PATH) {
- static $_cache = array();
- $filename = $path.$name.'.php';
- if('' !== $value) {
- if(is_null($value)) {
- // ????
- return unlink($filename);
- }else{
- // ????
- $dir = dirname($filename);
- // ????????
- if(!is_dir($dir)) mkdir($dir);
- return file_put_contents($filename,"<?php\nreturn ".var_export($value,true).";\n?>");
- }
- }
- if(isset($_cache[$name])) return $_cache[$name];
- // ??????
- if(is_file($filename)) {
- $value = include $filename;
- $_cache[$name] = $value;
- }else{
- $value = false;
- }
- return $value;
- }
-
- // ??PHP?????????????
- function to_guid_string($mix)
- {
- if(is_object($mix) && function_exists('spl_object_hash')) {
- return spl_object_hash($mix);
- }elseif(is_resource($mix)){
- $mix = get_resource_type($mix).strval($mix);
- }else{
- $mix = serialize($mix);
- }
- return md5($mix);
- }
-
- //[RUNTIME]
- // ????
- function compile($filename,$runtime=false) {
- $content = file_get_contents($filename);
- if(true === $runtime)
- // ???????
- $content = preg_replace('/\/\/\[RUNTIME\](.*?)\/\/\[\/RUNTIME\]/s','',$content);
- $content = substr(trim($content),5);
- if('?>' == substr($content,-2))
- $content = substr($content,0,-2);
- return $content;
- }
-
- // ???????????
- function strip_whitespace($content) {
- $stripStr = '';
- //??php??
- $tokens = token_get_all ($content);
- $last_space = false;
- for ($i = 0, $j = count ($tokens); $i < $j; $i++)
- {
- if (is_string ($tokens[$i]))
- {
- $last_space = false;
- $stripStr .= $tokens[$i];
- }
- else
- {
- switch ($tokens[$i][0])
- {
- //????PHP??
- case T_COMMENT:
- case T_DOC_COMMENT:
- break;
- //????
- case T_WHITESPACE:
- if (!$last_space)
- {
- $stripStr .= ' ';
- $last_space = true;
- }
- break;
- default:
- $last_space = false;
- $stripStr .= $tokens[$i][1];
- }
- }
- }
- return $stripStr;
- }
- // ??????????
- function array_define($array) {
- $content = '';
- foreach($array as $key=>$val) {
- $key = strtoupper($key);
- if(in_array($key,array('THINK_PATH','APP_NAME','APP_PATH','RUNTIME_PATH','RUNTIME_ALLINONE','THINK_MODE')))
- $content .= 'if(!defined(\''.$key.'\')) ';
- if(is_int($val) || is_float($val)) {
- $content .= "define('".$key."',".$val.");";
- }elseif(is_bool($val)) {
- $val = ($val)?'true':'false';
- $content .= "define('".$key."',".$val.");";
- }elseif(is_string($val)) {
- $content .= "define('".$key."','".addslashes($val)."');";
- }
- }
- return $content;
- }
- //[/RUNTIME]
-
- // ??????
- function mk_dir($dir, $mode = 0755)
- {
- if (is_dir($dir) || @mkdir($dir,$mode)) return true;
- if (!mk_dir(dirname($dir),$mode)) return false;
- return @mkdir($dir,$mode);
- }
-
- // ??????? ??????
- function auto_charset($fContents,$from,$to){
- $from = strtoupper($from)=='UTF8'? 'utf-8':$from;
- $to = strtoupper($to)=='UTF8'? 'utf-8':$to;
- if( strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents)) ){
- //??????????????????
- return $fContents;
- }
- if(is_string($fContents) ) {
- if(function_exists('mb_convert_encoding')){
- return mb_convert_encoding ($fContents, $to, $from);
- }elseif(function_exists('iconv')){
- return iconv($from,$to,$fContents);
- }else{
- return $fContents;
- }
- }
- elseif(is_array($fContents)){
- foreach ( $fContents as $key => $val ) {
- $_key = auto_charset($key,$from,$to);
- $fContents[$_key] = auto_charset($val,$from,$to);
- if($key != $_key )
- unset($fContents[$key]);
- }
- return $fContents;
- }
- else{
- return $fContents;
- }
- }
-
- // xml??
- function xml_encode($data,$encoding='utf-8',$root="think") {
- $xml = '<?xml version="1.0" encoding="'.$encoding.'"?>';
- $xml.= '<'.$root.'>';
- $xml.= data_to_xml($data);
- $xml.= '</'.$root.'>';
- return $xml;
- }
-
- function data_to_xml($data) {
- if(is_object($data)) {
- $data = get_object_vars($data);
- }
- $xml = '';
- foreach($data as $key=>$val) {
- is_numeric($key) && $key="item id=\"$key\"";
- $xml.="<$key>";
- $xml.=(is_array($val)||is_object($val))?data_to_xml($val):$val;
- list($key,)=explode(' ',$key);
- $xml.="</$key>";
- }
- return $xml;
- }
-
- /**
- +----------------------------------------------------------
- * Cookie ???????? (???????????) 2009-07-9
- +----------------------------------------------------------
- * 1 ??cookie: cookie('name')
- * 2 ???????????cookie: cookie(null)
- * 3 ????????cookie: cookie(null,'think_') | ???????????
- * 4 ??cookie: cookie('name','value') | ??????: cookie('name','value',3600)
- * 5 ??cookie: cookie('name',null)
- +----------------------------------------------------------
- * $option ????prefix,expire,path,domain
- * ??????:cookie('name','value',array('expire'=>1,'prefix'=>'think_'))
- * ??query?????:cookie('name','value','prefix=tp_&expire=10000')
- */
- function cookie($name,$value='',$option=null)
- {
- // ????
- $config = array(
- 'prefix' => C('COOKIE_PREFIX'), // cookie ????
- 'expire' => C('COOKIE_EXPIRE'), // cookie ????
- 'path' => C('COOKIE_PATH'), // cookie ????
- 'domain' => C('COOKIE_DOMAIN'), // cookie ????
- );
- // ????(???????)
- if (!empty($option)) {
- if (is_numeric($option))
- $option = array('expire'=>$option);
- elseif( is_string($option) )
- parse_str($option,$option);
- array_merge($config,array_change_key_case($option));
- }
- // ?????????cookie
- if (is_null($name)) {
- if (empty($_COOKIE)) return;
- // ????cookie?????????config???????
- $prefix = empty($value)? $config['prefix'] : $value;
- if (!empty($prefix))// ??????????????????
- {
- foreach($_COOKIE as $key=>$val) {
- if (0 === stripos($key,$prefix)){
- setcookie($_COOKIE[$key],'',time()-3600,$config['path'],$config['domain']);
- unset($_COOKIE[$key]);
- }
- }
- }
- return;
- }
- $name = $config['prefix'].$name;
- if (''===$value){
- return isset($_COOKIE[$name]) ? unserialize($_COOKIE[$name]) : null;// ????Cookie
- }else {
- if (is_null($value)) {
- setcookie($name,'',time()-3600,$config['path'],$config['domain']);
- unset($_COOKIE[$name]);// ????cookie
- }else {
- // ??cookie
- $expire = !empty($config['expire'])? time()+ intval($config['expire']):0;
- setcookie($name,serialize($value),$expire,$config['path'],$config['domain']);
- $_COOKIE[$name] = serialize($value);
- }
- }
- }
- ?>