~runtime.php 121 KB

1
  1. <?php $GLOBALS['_beginTime'] = microtime(TRUE); defined('AINAPHP') or define('AINAPHP',true); defined('UPLOAD_PATH') or define('UPLOAD_PATH','./Uploads/'); defined('VERSION') or define('VERSION','v2.2 Released'); defined('UPDATETIME') or define('UPDATETIME','20121225'); defined('APP_NAME') or define('APP_NAME','Ainaphp'); defined('APP_PATH') or define('APP_PATH','./Ainaphp/'); defined('APP_LANG') or define('APP_LANG',false); defined('APP_DEBUG') or define('APP_DEBUG',false); defined('THINK_PATH') or define('THINK_PATH','./Core/'); defined('MEMORY_LIMIT_ON') or define('MEMORY_LIMIT_ON',true); defined('RUNTIME_PATH') or define('RUNTIME_PATH','./Cache/'); defined('RUNTIME_FILE') or define('RUNTIME_FILE','./Cache/~runtime.php'); defined('THINK_VERSION') or define('THINK_VERSION','3.1.3'); defined('MAGIC_QUOTES_GPC') or define('MAGIC_QUOTES_GPC',false); defined('IS_CGI') or define('IS_CGI',0); defined('IS_WIN') or define('IS_WIN',0); defined('IS_CLI') or define('IS_CLI',0); defined('_PHP_FILE_') or define('_PHP_FILE_','/index.php'); defined('__ROOT__') or define('__ROOT__',''); defined('URL_COMMON') or define('URL_COMMON',0); defined('URL_PATHINFO') or define('URL_PATHINFO',1); defined('URL_REWRITE') or define('URL_REWRITE',2); defined('URL_COMPAT') or define('URL_COMPAT',3); defined('CORE_PATH') or define('CORE_PATH','./Core/Lib/'); defined('EXTEND_PATH') or define('EXTEND_PATH','./Core/Extend/'); defined('MODE_PATH') or define('MODE_PATH','./Core/Extend/Mode/'); defined('ENGINE_PATH') or define('ENGINE_PATH','./Core/Extend/Engine/'); defined('VENDOR_PATH') or define('VENDOR_PATH','./Core/Extend/Vendor/'); defined('LIBRARY_PATH') or define('LIBRARY_PATH','./Core/Extend/Library/'); defined('COMMON_PATH') or define('COMMON_PATH','./Ainaphp/Common/'); defined('LIB_PATH') or define('LIB_PATH','./Ainaphp/Lib/'); defined('CONF_PATH') or define('CONF_PATH','./Ainaphp/Conf/'); defined('LANG_PATH') or define('LANG_PATH','./Ainaphp/Lang/'); defined('TMPL_PATH') or define('TMPL_PATH','./Ainaphp/Tpl/'); defined('HTML_PATH') or define('HTML_PATH','./Ainaphp/Html/'); defined('LOG_PATH') or define('LOG_PATH','./Cache/Logs/'); defined('TEMP_PATH') or define('TEMP_PATH','./Cache/Temp/'); defined('DATA_PATH') or define('DATA_PATH','./Cache/Data/'); defined('CACHE_PATH') or define('CACHE_PATH','./Cache/Cache/'); set_include_path(get_include_path() . PATH_SEPARATOR . VENDOR_PATH); function T($template='',$layer=''){ if(is_file($template)) { return $template; } if(false === strpos($template,'://')){ $template = APP_NAME.'://'.str_replace(':', '/',$template); } $info = parse_url($template); $file = $info['host'].(isset($info['path'])?$info['path']:''); $group = isset($info['user'])?$info['user'].'/':(defined('GROUP_NAME')?GROUP_NAME.'/':''); $app = $info['scheme']; $layer = $layer?$layer:C('DEFAULT_V_LAYER'); if(($list = C('EXTEND_GROUP_LIST')) && isset($list[$app])){ $baseUrl = $list[$app].'/'.$group.$layer.'/'; }elseif(1==C('APP_GROUP_MODE')){ $baseUrl = dirname(BASE_LIB_PATH).'/'.$group.$layer.'/'; }else{ $baseUrl = TMPL_PATH.$group; } if('' == $file) { $file = MODULE_NAME . C('TMPL_FILE_DEPR') . ACTION_NAME; }elseif(false === strpos($file, '/')){ $file = MODULE_NAME . C('TMPL_FILE_DEPR') . $file; } return $baseUrl.$file.C('TMPL_TEMPLATE_SUFFIX'); } function I($name,$default='',$filter=null) { if(strpos($name,'.')) { list($method,$name) = explode('.',$name,2); }else{ $method = 'param'; } switch(strtolower($method)) { case 'get' : $input =& $_GET;break; case 'post' : $input =& $_POST;break; case 'put' : parse_str(file_get_contents('php://input'), $input);break; case 'param' : switch($_SERVER['REQUEST_METHOD']) { case 'POST': $input = $_POST; break; case 'PUT': parse_str(file_get_contents('php://input'), $input); break; default: $input = $_GET; } if(C('VAR_URL_PARAMS') && isset($_GET[C('VAR_URL_PARAMS')])){ $input = array_merge($input,$_GET[C('VAR_URL_PARAMS')]); } break; case 'request' : $input =& $_REQUEST; break; case 'session' : $input =& $_SESSION; break; case 'cookie' : $input =& $_COOKIE; break; case 'server' : $input =& $_SERVER; break; case 'globals' : $input =& $GLOBALS; break; default: return NULL; } if(C('VAR_FILTERS')) { $_filters = explode(',',C('VAR_FILTERS')); foreach($_filters as $_filter){ array_walk_recursive($input,$_filter); } } if(empty($name)) { $data = $input; $filters = isset($filter)?$filter:C('DEFAULT_FILTER'); if($filters) { $filters = explode(',',$filters); foreach($filters as $filter){ $data = array_map($filter,$data); } } }elseif(isset($input[$name])) { $data = $input[$name]; $filters = isset($filter)?$filter:C('DEFAULT_FILTER'); if($filters) { $filters = explode(',',$filters); foreach($filters as $filter){ if(function_exists($filter)) { $data = is_array($data)?array_map($filter,$data):$filter($data); }else{ $data = filter_var($data,is_int($filter)?$filter:filter_id($filter)); if(false === $data) { return isset($default)?$default:NULL; } } } } }else{ $data = isset($default)?$default:NULL; } return $data; } function G($start,$end='',$dec=4) { static $_info = array(); static $_mem = array(); if(is_float($end)) { $_info[$start] = $end; }elseif(!empty($end)){ if(!isset($_info[$end])) $_info[$end] = microtime(TRUE); if(MEMORY_LIMIT_ON && $dec=='m'){ if(!isset($_mem[$end])) $_mem[$end] = memory_get_usage(); return number_format(($_mem[$end]-$_mem[$start])/1024); }else{ return number_format(($_info[$end]-$_info[$start]),$dec); } }else{ $_info[$start] = microtime(TRUE); if(MEMORY_LIMIT_ON) $_mem[$start] = memory_get_usage(); } } function N($key, $step=0,$save=false) { static $_num = array(); if (!isset($_num[$key])) { $_num[$key] = (false !== $save)? S('N_'.$key) : 0; } if (empty($step)) return $_num[$key]; else $_num[$key] = $_num[$key] + (int) $step; if(false !== $save){ S('N_'.$key,$_num[$key],$save); } } function parse_name($name, $type=0) { if ($type) { return ucfirst(preg_replace("/_([a-zA-Z])/e", "strtoupper('\\1')", $name)); } else { return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_")); } } function require_cache($filename) { static $_importFiles = array(); if (!isset($_importFiles[$filename])) { if (file_exists_case($filename)) { require $filename; $_importFiles[$filename] = true; } else { $_importFiles[$filename] = false; } } return $_importFiles[$filename]; } function require_array($array,$return=false){ foreach ($array as $file){ if (require_cache($file) && $return) return true; } if($return) return false; } 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; } function import($class, $baseUrl = '', $ext='.class.php') { static $_file = array(); $class = str_replace(array('.', '#'), array('/', '.'), $class); if ('' === $baseUrl && false === strpos($class, '/')) { return alias_import($class); } if (isset($_file[$class . $baseUrl])) return true; else $_file[$class . $baseUrl] = true; $class_strut = explode('/', $class); if (empty($baseUrl)) { $libPath = defined('BASE_LIB_PATH')?BASE_LIB_PATH:LIB_PATH; if ('@' == $class_strut[0] || APP_NAME == $class_strut[0]) { $baseUrl = dirname($libPath); $class = substr_replace($class, basename($libPath).'/', 0, strlen($class_strut[0]) + 1); }elseif ('think' == strtolower($class_strut[0])){ $baseUrl = CORE_PATH; $class = substr($class,6); }elseif (in_array(strtolower($class_strut[0]), array('org', 'com'))) { $baseUrl = LIBRARY_PATH; }else { $class = substr_replace($class, '', 0, strlen($class_strut[0]) + 1); $baseUrl = APP_PATH . '../' . $class_strut[0] . '/'.basename($libPath).'/'; } } if (substr($baseUrl, -1) != '/') $baseUrl .= '/'; $classfile = $baseUrl . $class . $ext; if (!class_exists(basename($class),false)) { return require_cache($classfile); } } function load($name, $baseUrl='', $ext='.php') { $name = str_replace(array('.', '#'), array('/', '.'), $name); if (empty($baseUrl)) { if (0 === strpos($name, '@/')) { $baseUrl = COMMON_PATH; $name = substr($name, 2); } else { $baseUrl = EXTEND_PATH . 'Function/'; } } if (substr($baseUrl, -1) != '/') $baseUrl .= '/'; require_cache($baseUrl . $name . $ext); } function vendor($class, $baseUrl = '', $ext='.php') { if (empty($baseUrl)) $baseUrl = VENDOR_PATH; return import($class, $baseUrl, $ext); } function alias_import($alias, $classfile='') { static $_alias = array(); if (is_string($alias)) { if(isset($_alias[$alias])) { return require_cache($_alias[$alias]); }elseif ('' !== $classfile) { $_alias[$alias] = $classfile; return; } }elseif (is_array($alias)) { $_alias = array_merge($_alias,$alias); return; } return false; } function D($name='',$layer='') { if(empty($name)) return new Model; static $_model = array(); $layer = $layer?$layer:C('DEFAULT_M_LAYER'); if(strpos($name,'://')) { list($app) = explode('://',$name); $name = str_replace('://','/'.$layer.'/',$name); }else{ $app = C('DEFAULT_APP'); $name = $app.'/'.$layer.'/'.$name; } if(isset($_model[$name])) return $_model[$name]; $path = explode('/',$name); if($list = C('EXTEND_GROUP_LIST') && isset($list[$app])){ $baseUrl = $list[$app]; import($path[2].'/'.$path[1].'/'.$path[3].$layer,$baseUrl); }elseif(count($path)>3 && 1 == C('APP_GROUP_MODE')) { $baseUrl = $path[0]== '@' ? dirname(BASE_LIB_PATH) : APP_PATH.'../'.$path[0].'/'.C('APP_GROUP_PATH').'/'; import($path[2].'/'.$path[1].'/'.$path[3].$layer,$baseUrl); }else{ import($name.$layer); } $class = basename($name.$layer); if(class_exists($class)) { $model = new $class(basename($name)); }else { $model = new Model(basename($name)); } $_model[$name] = $model; return $model; } function M($name='', $tablePrefix='',$connection='') { static $_model = array(); if(strpos($name,':')) { list($class,$name) = explode(':',$name); }else{ $class = 'Model'; } $guid = $tablePrefix . $name . '_' . $class; if (!isset($_model[$guid])) $_model[$guid] = new $class($name,$tablePrefix,$connection); return $_model[$guid]; } function A($name,$layer='',$common=false) { static $_action = array(); $layer = $layer?$layer:C('DEFAULT_C_LAYER'); if(strpos($name,'://')) { list($app) = explode('://',$name); $name = str_replace('://','/'.$layer.'/',$name); }else{ $app = '@'; $name = '@/'.$layer.'/'.$name; } if(isset($_action[$name])) return $_action[$name]; $path = explode('/',$name); if($list = C('EXTEND_GROUP_LIST') && isset($list[$app])){ $baseUrl = $list[$app]; import($path[2].'/'.$path[1].'/'.$path[3].$layer,$baseUrl); }elseif(count($path)>3 && 1 == C('APP_GROUP_MODE')) { $baseUrl = $path[0]== '@' ? dirname(BASE_LIB_PATH) : APP_PATH.'../'.$path[0].'/'.C('APP_GROUP_PATH').'/'; import($path[2].'/'.$path[1].'/'.$path[3].$layer,$baseUrl); }elseif($common) { import(str_replace('@/','',$name).$layer,LIB_PATH); }else{ import($name.$layer); } $class = basename($name.$layer); if(class_exists($class,false)) { $action = new $class(); $_action[$name] = $action; return $action; }else { return false; } } function R($url,$vars=array(),$layer='') { $info = pathinfo($url); $action = $info['basename']; $module = $info['dirname']; $class = A($module,$layer); if($class){ if(is_string($vars)) { parse_str($vars,$vars); } return call_user_func_array(array(&$class,$action.C('ACTION_SUFFIX')),$vars); }else{ return false; } } function L($name=null, $value=null) { static $_lang = array(); if (empty($name)) return $_lang; 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)) { if(!empty($value) && $array = S('c_'.$value)) { $_config = array_merge($_config, array_change_key_case($array)); } 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)){ $_config = array_merge($_config, array_change_key_case($name)); if(!empty($value)) { S('c_'.$value,$_config); } return; } return null; } function tag($tag, &$params=NULL) { $extends = C('extends.' . $tag); $tags = C('tags.' . $tag); if (!empty($tags)) { if(empty($tags['_overlay']) && !empty($extends)) { $tags = array_unique(array_merge($extends,$tags)); }elseif(isset($tags['_overlay'])){ unset($tags['_overlay']); } }elseif(!empty($extends)) { $tags = $extends; } if($tags) { if(APP_DEBUG) { G($tag.'Start'); trace('[ '.$tag.' ] --START--','','INFO'); } foreach ($tags as $key=>$name) { if(!is_int($key)) { $name = $key; } B($name, $params); } if(APP_DEBUG) { trace('[ '.$tag.' ] --END-- [ RunTime:'.G($tag.'Start',$tag.'End',6).'s ]','','INFO'); } }else{ return false; } } function add_tag_behavior($tag,$behavior,$path='') { $array = C('tags.'.$tag); if(!$array) { $array = array(); } if($path) { $array[$behavior] = $path; }else{ $array[] = $behavior; } C('tags.'.$tag,$array); } function B($name, &$params=NULL) { if(strpos($name,'/')){ list($name,$method) = explode('/',$name); }else{ $method = 'run'; } $class = $name.'Behavior'; if(APP_DEBUG) { G('behaviorStart'); } $behavior = new $class(); $behavior->$method($params); if(APP_DEBUG) { G('behaviorEnd'); trace($name.' Behavior ::'.$method.' [ RunTime:'.G('behaviorStart','behaviorEnd',6).'s ]','','INFO'); } } function strip_whitespace($content) { $stripStr = ''; $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]) { case T_COMMENT: case T_DOC_COMMENT: break; case T_WHITESPACE: if (!$last_space) { $stripStr .= ' '; $last_space = true; } break; case T_START_HEREDOC: $stripStr .= "<<<THINK\n"; break; case T_END_HEREDOC: $stripStr .= "THINK;\n"; for($k = $i+1; $k < $j; $k++) { if(is_string($tokens[$k]) && $tokens[$k] == ';') { $i = $k; break; } else if($tokens[$k][0] == T_CLOSE_TAG) { break; } } break; default: $last_space = false; $stripStr .= $tokens[$i][1]; } } } return $stripStr; } function trace($value='[think]',$label='',$level='DEBUG',$record=false) { static $_trace = array(); if('[think]' === $value){ return $_trace; }else{ $info = ($label?$label.':':'').print_r($value,true); if('ERR' == $level && C('TRACE_EXCEPTION')) { throw_exception($info); } $level = strtoupper($level); if(!isset($_trace[$level])) { $_trace[$level] = array(); } $_trace[$level][] = $info; if((defined('IS_AJAX') && IS_AJAX) || !C('SHOW_PAGE_TRACE') || $record) { Log::record($info,$level,$record); } } } class Think { private static $_instance = array(); static public function start() { register_shutdown_function(array('Think','fatalError')); set_error_handler(array('Think','appError')); set_exception_handler(array('Think','appException')); spl_autoload_register(array('Think', 'autoload')); App::run(); return ; } public static function autoload($class) { if(alias_import($class)) return ; $libPath = defined('BASE_LIB_PATH')?BASE_LIB_PATH:LIB_PATH; $group = defined('GROUP_NAME') && C('APP_GROUP_MODE')==0 ?GROUP_NAME.'/':''; $file = $class.'.class.php'; if(substr($class,-8)=='Behavior') { if(require_array(array( CORE_PATH.'Behavior/'.$file, EXTEND_PATH.'Behavior/'.$file, LIB_PATH.'Behavior/'.$file, $libPath.'Behavior/'.$file),true) || (defined('MODE_NAME') && require_cache(MODE_PATH.ucwords(MODE_NAME).'/Behavior/'.$file))) { return ; } }elseif(substr($class,-5)=='Model'){ if(require_array(array( LIB_PATH.'Model/'.$group.$file, $libPath.'Model/'.$file, EXTEND_PATH.'Model/'.$file),true)) { return ; } }elseif(substr($class,-6)=='Action'){ if(require_array(array( LIB_PATH.'Action/'.$group.$file, $libPath.'Action/'.$file, EXTEND_PATH.'Action/'.$file),true)) { return ; } }elseif(substr($class,0,5)=='Cache'){ if(require_array(array( EXTEND_PATH.'Driver/Cache/'.$file, CORE_PATH.'Driver/Cache/'.$file),true)){ return ; } }elseif(substr($class,0,2)=='Db'){ if(require_array(array( EXTEND_PATH.'Driver/Db/'.$file, CORE_PATH.'Driver/Db/'.$file),true)){ return ; } }elseif(substr($class,0,8)=='Template'){ if(require_array(array( EXTEND_PATH.'Driver/Template/'.$file, CORE_PATH.'Driver/Template/'.$file),true)){ return ; } }elseif(substr($class,0,6)=='TagLib'){ if(require_array(array( EXTEND_PATH.'Driver/TagLib/'.$file, CORE_PATH.'Driver/TagLib/'.$file),true)) { return ; } } $paths = explode(',',C('APP_AUTOLOAD_PATH')); foreach ($paths as $path){ if(import($path.'.'.$class)) return ; } } static public function instance($class,$method='') { $identify = $class.$method; if(!isset(self::$_instance[$identify])) { if(class_exists($class)){ $o = new $class(); if(!empty($method) && method_exists($o,$method)) self::$_instance[$identify] = call_user_func_array(array(&$o, $method)); else self::$_instance[$identify] = $o; } else halt(L('_CLASS_NOT_EXIST_').':'.$class); } return self::$_instance[$identify]; } static public function appException($e) { $error = array(); $error['message'] = $e->getMessage(); $trace = $e->getTrace(); if('throw_exception'==$trace[0]['function']) { $error['file'] = $trace[0]['file']; $error['line'] = $trace[0]['line']; }else{ $error['file'] = $e->getFile(); $error['line'] = $e->getLine(); } Log::record($error['message'],Log::ERR); halt($error); } static public function appError($errno, $errstr, $errfile, $errline) { switch ($errno) { case E_ERROR: case E_PARSE: case E_CORE_ERROR: case E_COMPILE_ERROR: case E_USER_ERROR: ob_end_clean(); if(C('OUTPUT_ENCODE')){ $zlib = ini_get('zlib.output_compression'); if(empty($zlib)) ob_start('ob_gzhandler'); } $errorStr = "$errstr ".$errfile." 第 $errline 行."; if(C('LOG_RECORD')) Log::write("[$errno] ".$errorStr,Log::ERR); function_exists('halt')?halt($errorStr):exit('ERROR:'.$errorStr); break; case E_STRICT: case E_USER_WARNING: case E_USER_NOTICE: default: $errorStr = "[$errno] $errstr ".$errfile." 第 $errline 行."; trace($errorStr,'','NOTIC'); break; } } static public function fatalError() { if(C('LOG_RECORD')) Log::save(); if ($e = error_get_last()) { switch($e['type']){ case E_ERROR: case E_PARSE: case E_CORE_ERROR: case E_COMPILE_ERROR: case E_USER_ERROR: ob_end_clean(); function_exists('halt')?halt($e):exit('ERROR:'.$e['message']); break; } } } } class ThinkException extends Exception { } abstract class Behavior { protected $options = array(); public function __construct() { if(!empty($this->options)) { foreach ($this->options as $name=>$val){ if(NULL !== C($name)) { $this->options[$name] = C($name); }else{ C($name,$val); } } array_change_key_case($this->options); } } public function __get($name){ return $this->options[strtolower($name)]; } abstract public function run(&$params); } class ReadHtmlCacheBehavior extends Behavior { protected $options = array( 'HTML_CACHE_ON' => false, 'HTML_CACHE_TIME' => 60, 'HTML_CACHE_RULES' => array(), 'HTML_FILE_SUFFIX' => '.html', ); public function run(&$params){ if(C('HTML_CACHE_ON')) { $cacheTime = $this->requireHtmlCache(); if( false !== $cacheTime && $this->checkHTMLCache(HTML_FILE_NAME,$cacheTime)) { readfile(HTML_FILE_NAME); exit(); } } } static private function requireHtmlCache() { $htmls = C('HTML_CACHE_RULES'); if(!empty($htmls)) { $htmls = array_change_key_case($htmls); $moduleName = strtolower(MODULE_NAME); $actionName = strtolower(ACTION_NAME); if(isset($htmls[$moduleName.':'.$actionName])) { $html = $htmls[$moduleName.':'.$actionName]; }elseif(isset($htmls[$moduleName.':'])){ $html = $htmls[$moduleName.':']; }elseif(isset($htmls[$actionName])){ $html = $htmls[$actionName]; }elseif(isset($htmls['*'])){ $html = $htmls['*']; }elseif(isset($htmls['empty:index']) && !class_exists(MODULE_NAME.'Action')){ $html = $htmls['empty:index']; }elseif(isset($htmls[$moduleName.':_empty']) && $this->isEmptyAction(MODULE_NAME,ACTION_NAME)){ $html = $htmls[$moduleName.':_empty']; } if(!empty($html)) { $rule = $html[0]; $rule = preg_replace('/{\$(_\w+)\.(\w+)\|(\w+)}/e',"\\3(\$\\1['\\2'])",$rule); $rule = preg_replace('/{\$(_\w+)\.(\w+)}/e',"\$\\1['\\2']",$rule); $rule = preg_replace('/{(\w+)\|(\w+)}/e',"\\2(\$_GET['\\1'])",$rule); $rule = preg_replace('/{(\w+)}/e',"\$_GET['\\1']",$rule); $rule = str_ireplace( array('{:app}','{:module}','{:action}','{:group}'), array(APP_NAME,MODULE_NAME,ACTION_NAME,defined('GROUP_NAME')?GROUP_NAME:''), $rule); $rule = preg_replace('/{|(\w+)}/e',"\\1()",$rule); if(!empty($html[2])) $rule = $html[2]($rule); $cacheTime = isset($html[1])?$html[1]:C('HTML_CACHE_TIME'); define('HTML_FILE_NAME',HTML_PATH . $rule.C('HTML_FILE_SUFFIX')); return $cacheTime; } } return false; } static public function checkHTMLCache($cacheFile='',$cacheTime='') { if(!is_file($cacheFile)){ return false; }elseif (filemtime(C('TEMPLATE_NAME')) > filemtime($cacheFile)) { return false; }elseif(!is_numeric($cacheTime) && function_exists($cacheTime)){ return $cacheTime($cacheFile); }elseif ($cacheTime != 0 && NOW_TIME > filemtime($cacheFile)+$cacheTime) { return false; } return true; } static private function isEmptyAction($module,$action) { $className = $module.'Action'; $class = new $className; return !method_exists($class,$action); } } class CheckRouteBehavior extends Behavior { protected $options = array( 'URL_ROUTER_ON' => false, 'URL_ROUTE_RULES' => array(), ); public function run(&$return){ $regx = trim($_SERVER['PATH_INFO'],'/'); if(empty($regx)) return $return = true; if(!C('URL_ROUTER_ON')) return $return = false; $routes = C('URL_ROUTE_RULES'); if(!empty($routes)) { $depr = C('URL_PATHINFO_DEPR'); $regx = str_replace($depr,'/',$regx); foreach ($routes as $rule=>$route){ if(0===strpos($rule,'/') && preg_match($rule,$regx,$matches)) { return $return = $this->parseRegex($matches,$route,$regx); }else{ $len1 = substr_count($regx,'/'); $len2 = substr_count($rule,'/'); if($len1>=$len2) { if('$' == substr($rule,-1,1)) { if($len1 != $len2) { continue; }else{ $rule = substr($rule,0,-1); } } $match = $this->checkUrlMatch($regx,$rule); if($match) return $return = $this->parseRule($rule,$route,$regx); } } } } $return = false; } private function checkUrlMatch($regx,$rule) { $m1 = explode('/',$regx); $m2 = explode('/',$rule); $match = true; foreach ($m2 as $key=>$val){ if(':' == substr($val,0,1)) { if(strpos($val,'\\')) { $type = substr($val,-1); if('d'==$type && !is_numeric($m1[$key])) { $match = false; break; } }elseif(strpos($val,'^')){ $array = explode('|',substr(strstr($val,'^'),1)); if(in_array($m1[$key],$array)) { $match = false; break; } } }elseif(0 !== strcasecmp($val,$m1[$key])){ $match = false; break; } } return $match; } private function parseUrl($url) { $var = array(); if(false !== strpos($url,'?')) { $info = parse_url($url); $path = explode('/',$info['path']); parse_str($info['query'],$var); }elseif(strpos($url,'/')){ $path = explode('/',$url); }else{ parse_str($url,$var); } if(isset($path)) { $var[C('VAR_ACTION')] = array_pop($path); if(!empty($path)) { $var[C('VAR_MODULE')] = array_pop($path); } if(!empty($path)) { $var[C('VAR_GROUP')] = array_pop($path); } } return $var; } private function parseRule($rule,$route,$regx) { $url = is_array($route)?$route[0]:$route; $paths = explode('/',$regx); $matches = array(); $rule = explode('/',$rule); foreach ($rule as $item){ if(0===strpos($item,':')) { if($pos = strpos($item,'^') ) { $var = substr($item,1,$pos-1); }elseif(strpos($item,'\\')){ $var = substr($item,1,-2); }else{ $var = substr($item,1); } $matches[$var] = array_shift($paths); }else{ array_shift($paths); } } if(0=== strpos($url,'/') || 0===strpos($url,'http')) { if(strpos($url,':')) { $values = array_values($matches); $url = preg_replace('/:(\d+)/e','$values[\\1-1]',$url); } header("Location: $url", true,(is_array($route) && isset($route[1]))?$route[1]:301); exit; }else{ $var = $this->parseUrl($url); $values = array_values($matches); foreach ($var as $key=>$val){ if(0===strpos($val,':')) { $var[$key] = $values[substr($val,1)-1]; } } $var = array_merge($matches,$var); if($paths) { preg_replace('@(\w+)\/([^\/]+)@e', '$var[strtolower(\'\\1\')]=strip_tags(\'\\2\');', implode('/',$paths)); } if(is_array($route) && isset($route[1])) { parse_str($route[1],$params); $var = array_merge($var,$params); } $_GET = array_merge($var,$_GET); } return true; } private function parseRegex($matches,$route,$regx) { $url = is_array($route)?$route[0]:$route; $url = preg_replace('/:(\d+)/e','$matches[\\1]',$url); if(0=== strpos($url,'/') || 0===strpos($url,'http')) { header("Location: $url", true,(is_array($route) && isset($route[1]))?$route[1]:301); exit; }else{ $var = $this->parseUrl($url); $regx = substr_replace($regx,'',0,strlen($matches[0])); if($regx) { preg_replace('@(\w+)\/([^,\/]+)@e', '$var[strtolower(\'\\1\')]=strip_tags(\'\\2\');', $regx); } if(is_array($route) && isset($route[1])) { parse_str($route[1],$params); $var = array_merge($var,$params); } $_GET = array_merge($var,$_GET); } return true; } } class ParseTemplateBehavior extends Behavior { protected $options = array( 'TMPL_ENGINE_TYPE' => 'Think', 'TMPL_CACHFILE_SUFFIX' => '.php', 'TMPL_DENY_FUNC_LIST' => 'echo,exit', 'TMPL_DENY_PHP' =>false, 'TMPL_L_DELIM' => '{', 'TMPL_R_DELIM' => '}', 'TMPL_VAR_IDENTIFY' => 'array', 'TMPL_STRIP_SPACE' => false, 'TMPL_CACHE_ON' => false, 'TMPL_CACHE_PREFIX' => '', 'TMPL_CACHE_TIME' => 0, 'TMPL_LAYOUT_ITEM' => '{__CONTENT__}', 'LAYOUT_ON' => false, 'LAYOUT_NAME' => 'layout', 'TAGLIB_BEGIN' => '<', 'TAGLIB_END' => '>', 'TAGLIB_LOAD' => true, 'TAGLIB_BUILD_IN' => 'cx', 'TAGLIB_PRE_LOAD' => '', ); public function run(&$_data){ $engine = strtolower(C('TMPL_ENGINE_TYPE')); $_content = empty($_data['content'])?$_data['file']:$_data['content']; $_data['prefix'] = !empty($_data['prefix'])?$_data['prefix']:C('TMPL_CACHE_PREFIX'); if('think'==$engine){ if((!empty($_data['content']) && $this->checkContentCache($_data['content'],$_data['prefix'])) || $this->checkCache($_data['file'],$_data['prefix'])) { extract($_data['var'], EXTR_OVERWRITE); include C('CACHE_PATH').$_data['prefix'].md5($_content).C('TMPL_CACHFILE_SUFFIX'); }else{ $tpl = Think::instance('ThinkTemplate'); $tpl->fetch($_content,$_data['var'],$_data['prefix']); } }else{ $class = 'Template'.ucwords($engine); if(class_exists($class)) { $tpl = new $class; $tpl->fetch($_content,$_data['var']); }else { throw_exception(L('_NOT_SUPPERT_').': ' . $class); } } } protected function checkCache($tmplTemplateFile,$prefix='') { if (!C('TMPL_CACHE_ON')) return false; $tmplCacheFile = C('CACHE_PATH').$prefix.md5($tmplTemplateFile).C('TMPL_CACHFILE_SUFFIX'); if(!is_file($tmplCacheFile)){ return false; }elseif (filemtime($tmplTemplateFile) > filemtime($tmplCacheFile)) { return false; }elseif (C('TMPL_CACHE_TIME') != 0 && time() > filemtime($tmplCacheFile)+C('TMPL_CACHE_TIME')) { return false; } if(C('LAYOUT_ON')) { $layoutFile = THEME_PATH.C('LAYOUT_NAME').C('TMPL_TEMPLATE_SUFFIX'); if(filemtime($layoutFile) > filemtime($tmplCacheFile)) { return false; } } return true; } protected function checkContentCache($tmplContent,$prefix='') { if(is_file(C('CACHE_PATH').$prefix.md5($tmplContent).C('TMPL_CACHFILE_SUFFIX'))){ return true; }else{ return false; } } } class ContentReplaceBehavior extends Behavior { protected $options = array( 'TMPL_PARSE_STRING' => array(), ); public function run(&$content){ $content = $this->templateContentReplace($content); } protected function templateContentReplace($content) { $replace = array( '__TMPL__' => APP_TMPL_PATH, '__ROOT__' => __ROOT__, '__APP__' => __APP__, '__GROUP__' => defined('GROUP_NAME')?__GROUP__:__APP__, '__ACTION__' => __ACTION__, '__SELF__' => __SELF__, '__URL__' => __URL__, '../Public' => APP_TMPL_PATH.'Public', '__PUBLIC__' => __ROOT__.'/Public', ); if(is_array(C('TMPL_PARSE_STRING')) ) $replace = array_merge($replace,C('TMPL_PARSE_STRING')); $content = str_replace(array_keys($replace),array_values($replace),$content); return $content; } } class TokenBuildBehavior extends Behavior { protected $options = array( 'TOKEN_ON' => false, 'TOKEN_NAME' => '__hash__', 'TOKEN_TYPE' => 'md5', 'TOKEN_RESET' => true, ); public function run(&$content){ if(C('TOKEN_ON')) { if(strpos($content,'{__TOKEN__}')) { $content = str_replace('{__TOKEN__}',$this->buildToken(),$content); }elseif(preg_match('/<\/form(\s*)>/is',$content,$match)) { $content = str_replace($match[0],$this->buildToken().$match[0],$content); } }else{ $content = str_replace('{__TOKEN__}','',$content); } } private function buildToken() { $tokenName = C('TOKEN_NAME'); $tokenType = C('TOKEN_TYPE'); if(!isset($_SESSION[$tokenName])) { $_SESSION[$tokenName] = array(); } $tokenKey = md5($_SERVER['REQUEST_URI']); if(isset($_SESSION[$tokenName][$tokenKey])) { $tokenValue = $_SESSION[$tokenName][$tokenKey]; }else{ $tokenValue = $tokenType(microtime(TRUE)); $_SESSION[$tokenName][$tokenKey] = $tokenValue; } $token = '<input type="hidden" name="'.$tokenName.'" value="'.$tokenKey.'_'.$tokenValue.'" />'; return $token; } } class WriteHtmlCacheBehavior extends Behavior { public function run(&$content){ if(C('HTML_CACHE_ON') && defined('HTML_FILE_NAME')) { if(!is_dir(dirname(HTML_FILE_NAME))) mkdir(dirname(HTML_FILE_NAME),0755,true); if( false === file_put_contents( HTML_FILE_NAME , $content )) throw_exception(L('_CACHE_WRITE_ERROR_').':'.HTML_FILE_NAME); } } } class ShowRuntimeBehavior extends Behavior { protected $options = array( 'SHOW_RUN_TIME' => false, 'SHOW_ADV_TIME' => false, 'SHOW_DB_TIMES' => false, 'SHOW_CACHE_TIMES' => false, 'SHOW_USE_MEM' => false, 'SHOW_LOAD_FILE' => false, 'SHOW_FUN_TIMES' => false , ); public function run(&$content){ if(C('SHOW_RUN_TIME')){ if(false !== strpos($content,'{__NORUNTIME__}')) { $content = str_replace('{__NORUNTIME__}','',$content); }else{ $runtime = $this->showTime(); if(strpos($content,'{__RUNTIME__}')) $content = str_replace('{__RUNTIME__}',$runtime,$content); else $content .= $runtime; } }else{ $content = str_replace(array('{__NORUNTIME__}','{__RUNTIME__}'),'',$content); } } private function showTime() { G('beginTime',$GLOBALS['_beginTime']); G('viewEndTime'); $showTime = 'Process: '.G('beginTime','viewEndTime').'s '; if(C('SHOW_ADV_TIME')) { $showTime .= '( Load:'.G('beginTime','loadTime').'s Init:'.G('loadTime','initTime').'s Exec:'.G('initTime','viewStartTime').'s Template:'.G('viewStartTime','viewEndTime').'s )'; } if(C('SHOW_DB_TIMES') && class_exists('Db',false) ) { $showTime .= ' | DB :'.N('db_query').' queries '.N('db_write').' writes '; } if(C('SHOW_CACHE_TIMES') && class_exists('Cache',false)) { $showTime .= ' | Cache :'.N('cache_read').' gets '.N('cache_write').' writes '; } if(MEMORY_LIMIT_ON && C('SHOW_USE_MEM')) { $showTime .= ' | UseMem:'. number_format((memory_get_usage() - $GLOBALS['_startUseMems'])/1024).' kb'; } if(C('SHOW_LOAD_FILE')) { $showTime .= ' | LoadFile:'.count(get_included_files()); } if(C('SHOW_FUN_TIMES')) { $fun = get_defined_functions(); $showTime .= ' | CallFun:'.count($fun['user']).','.count($fun['internal']); } return $showTime; } } class ShowPageTraceBehavior extends Behavior { protected $options = array( 'SHOW_PAGE_TRACE' => false, 'TRACE_PAGE_TABS' => array('BASE'=>'基本','FILE'=>'文件','INFO'=>'流程','ERR|NOTIC'=>'错误','SQL'=>'SQL','DEBUG'=>'调试'), 'PAGE_TRACE_SAVE' => false, ); public function run(&$params){ if(!IS_AJAX && C('SHOW_PAGE_TRACE')) { echo $this->showTrace(); } } private function showTrace() { $files = get_included_files(); $info = array(); foreach ($files as $key=>$file){ $info[] = $file.' ( '.number_format(filesize($file)/1024,2).' KB )'; } $trace = array(); $base = array( '请求信息' => date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']).' '.$_SERVER['SERVER_PROTOCOL'].' '.$_SERVER['REQUEST_METHOD'].' : '.__SELF__, '运行时间' => $this->showTime(), '吞吐率' => number_format(1/G('beginTime','viewEndTime'),2).'req/s', '内存开销' => MEMORY_LIMIT_ON?number_format((memory_get_usage() - $GLOBALS['_startUseMems'])/1024,2).' kb':'不支持', '查询信息' => N('db_query').' queries '.N('db_write').' writes ', '文件加载' => count(get_included_files()), '缓存信息' => N('cache_read').' gets '.N('cache_write').' writes ', '配置加载' => count(c()), '会话信息' => 'SESSION_ID='.session_id(), ); $traceFile = CONF_PATH.'trace.php'; if(is_file($traceFile)) { $base = array_merge($base,include $traceFile); } $debug = trace(); $tabs = C('TRACE_PAGE_TABS'); foreach ($tabs as $name=>$title){ switch(strtoupper($name)) { case 'BASE': $trace[$title] = $base; break; case 'FILE': $trace[$title] = $info; break; default: $name = strtoupper($name); if(strpos($name,'|')) { $array = explode('|',$name); $result = array(); foreach($array as $name){ $result += isset($debug[$name])?$debug[$name]:array(); } $trace[$title] = $result; }else{ $trace[$title] = isset($debug[$name])?$debug[$name]:''; } } } if($save = C('PAGE_TRACE_SAVE')) { if(is_array($save)) { $tabs = C('TRACE_PAGE_TABS'); $array = array(); foreach ($save as $tab){ $array[] = $tabs[$tab]; } } $content = date('[ c ]').' '.get_client_ip().' '.$_SERVER['REQUEST_URI']."\r\n"; foreach ($trace as $key=>$val){ if(!isset($array) || in_array($key,$array)) { $content .= '[ '.$key." ]\r\n"; if(is_array($val)) { foreach ($val as $k=>$v){ $content .= (!is_numeric($k)?$k.':':'').print_r($v,true)."\r\n"; } }else{ $content .= print_r($val,true)."\r\n"; } $content .= "\r\n"; } } error_log(str_replace('<br/>',"\r\n",$content), Log::FILE,LOG_PATH.date('y_m_d').'_trace.log'); } unset($files,$info,$base); ob_start(); include C('TMPL_TRACE_FILE')?C('TMPL_TRACE_FILE'):THINK_PATH.'Tpl/page_trace.tpl'; return ob_get_clean(); } private function showTime() { G('beginTime',$GLOBALS['_beginTime']); G('viewEndTime'); return G('beginTime','viewEndTime').'s ( Load:'.G('beginTime','loadTime').'s Init:'.G('loadTime','initTime').'s Exec:'.G('initTime','viewStartTime').'s Template:'.G('viewStartTime','viewEndTime').'s )'; } }define('YP_KEY',false);alias_import(array ( 'Model' => './Core/Lib/Core/Model.class.php', 'Db' => './Core/Lib/Core/Db.class.php', 'Log' => './Core/Lib/Core/Log.class.php', 'ThinkTemplate' => './Core/Lib/Template/ThinkTemplate.class.php', 'TagLib' => './Core/Lib/Template/TagLib.class.php', 'Cache' => './Core/Lib/Core/Cache.class.php', 'Widget' => './Core/Lib/Core/Widget.class.php', 'TagLibCx' => './Core/Lib/Driver/TagLib/TagLibCx.class.php', )); function halt($error) { $e = array(); if (APP_DEBUG) { if (!is_array($error)) { $trace = debug_backtrace(); $e['message'] = $error; $e['file'] = $trace[0]['file']; $e['line'] = $trace[0]['line']; ob_start(); debug_print_backtrace(); $e['trace'] = ob_get_clean(); } else { $e = $error; } } 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; } function throw_exception($msg, $type='ThinkException', $code=0) { if (class_exists($type, false)) throw new $type($msg, $code); else halt($msg); } 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 _404($msg='',$url='') { APP_DEBUG && throw_exception($msg); if($msg && C('LOG_EXCEPTION_RECORD')) Log::write($msg); if(empty($url) && C('URL_404_REDIRECT')) { $url = C('URL_404_REDIRECT'); } if($url) { redirect($url); }else{ send_http_status(404); exit; } } function layout($layout) { if(false !== $layout) { C('LAYOUT_ON',true); if(is_string($layout)) { C('LAYOUT_NAME',$layout); } }else{ C('LAYOUT_ON',false); } } function U($url='',$vars='',$suffix=true,$redirect=false,$domain=false) { $info = parse_url($url); $url = !empty($info['path'])?$info['path']:ACTION_NAME; if(isset($info['fragment'])) { $anchor = $info['fragment']; if(false !== strpos($anchor,'?')) { list($anchor,$info['query']) = explode('?',$anchor,2); } if(false !== strpos($anchor,'@')) { list($anchor,$host) = explode('@',$anchor, 2); } }elseif(false !== strpos($url,'@')) { list($url,$host) = explode('@',$info['path'], 2); } if(isset($host)) { $domain = $host.(strpos($host,'.')?'':strstr($_SERVER['HTTP_HOST'],'.')); }elseif($domain===true){ $domain = $_SERVER['HTTP_HOST']; if(C('APP_SUB_DOMAIN_DEPLOY') ) { $domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.'); foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) { if(false === strpos($key,'*') && 0=== strpos($url,$rule[0])) { $domain = $key.strstr($domain,'.'); $url = substr_replace($url,'',0,strlen($rule[0])); break; } } } } if(is_string($vars)) { parse_str($vars,$vars); }elseif(!is_array($vars)){ $vars = array(); } if(isset($info['query'])) { parse_str($info['query'],$params); $vars = array_merge($params,$vars); } $depr = C('URL_PATHINFO_DEPR'); if($url) { if(0=== strpos($url,'/')) { $route = true; $url = substr($url,1); if('/' != $depr) { $url = str_replace('/',$depr,$url); } }else{ if('/' != $depr) { $url = str_replace('/',$depr,$url); } $url = trim($url,$depr); $path = explode($depr,$url); $var = array(); $var[C('VAR_ACTION')] = !empty($path)?array_pop($path):ACTION_NAME; $var[C('VAR_MODULE')] = !empty($path)?array_pop($path):MODULE_NAME; if($maps = C('URL_ACTION_MAP')) { if(isset($maps[strtolower($var[C('VAR_MODULE')])])) { $maps = $maps[strtolower($var[C('VAR_MODULE')])]; if($action = array_search(strtolower($var[C('VAR_ACTION')]),$maps)){ $var[C('VAR_ACTION')] = $action; } } } if($maps = C('URL_MODULE_MAP')) { if($module = array_search(strtolower($var[C('VAR_MODULE')]),$maps)){ $var[C('VAR_MODULE')] = $module; } } if(C('URL_CASE_INSENSITIVE')) { $var[C('VAR_MODULE')] = parse_name($var[C('VAR_MODULE')]); } if(!C('APP_SUB_DOMAIN_DEPLOY') && C('APP_GROUP_LIST')) { if(!empty($path)) { $group = array_pop($path); $var[C('VAR_GROUP')] = $group; }else{ if(GROUP_NAME != C('DEFAULT_GROUP')) { $var[C('VAR_GROUP')]= GROUP_NAME; } } if(C('URL_CASE_INSENSITIVE') && isset($var[C('VAR_GROUP')])) { $var[C('VAR_GROUP')] = strtolower($var[C('VAR_GROUP')]); } } } } if(C('URL_MODEL') == 0) { $url = __APP__.'?'.http_build_query(array_reverse($var)); if(!empty($vars)) { $vars = urldecode(http_build_query($vars)); $url .= '&'.$vars; } }else{ if(isset($route)) { $url = __APP__.'/'.rtrim($url,$depr); }else{ $url = __APP__.'/'.implode($depr,array_reverse($var)); } if(!empty($vars)) { foreach ($vars as $var => $val){ if('' !== trim($val)) $url .= $depr . $var . $depr . urlencode($val); } } if($suffix) { $suffix = $suffix===true?C('URL_HTML_SUFFIX'):$suffix; if($pos = strpos($suffix, '|')){ $suffix = substr($suffix, 0, $pos); } if($suffix && '/' != substr($url,-1)){ $url .= '.'.ltrim($suffix,'.'); } } } if(isset($anchor)){ $url .= '#'.$anchor; } if($domain) { $url = (is_ssl()?'https://':'http://').$domain.$url; } if($redirect) redirect($url); else return $url; } function W($name, $data=array(), $return=false,$path='') { $class = $name . 'Widget'; $path = empty($path) ? BASE_LIB_PATH : $path; require_cache($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 filter($name, &$content) { $class = $name . 'Filter'; require_cache(BASE_LIB_PATH . 'Filter/' . $class . '.class.php'); $filter = new $class(); $content = $filter->run($content); } function is_ssl() { if(isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))){ return true; }elseif(isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'] )) { return true; } return false; } function redirect($url, $time=0, $msg='') { $url = str_replace(array("\n", "\r"), '', $url); if (empty($msg)) $msg = "系统将在{$time}秒之后自动跳转到{$url}!"; if (!headers_sent()) { 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 S($name,$value='',$options=null) { static $cache = ''; if(is_array($options) && empty($cache)){ $type = isset($options['type'])?$options['type']:''; $cache = Cache::getInstance($type,$options); }elseif(is_array($name)) { $type = isset($name['type'])?$name['type']:''; $cache = Cache::getInstance($type,$name); return $cache; }elseif(empty($cache)) { $cache = Cache::getInstance(); } if(''=== $value){ return $cache->get($name); }elseif(is_null($value)) { return $cache->rm($name); }else { if(is_array($options)) { $expire = isset($options['expire'])?$options['expire']:NULL; }else{ $expire = is_numeric($options)?$options:NULL; } return $cache->set($name, $value, $expire); } } function cache($name,$value='',$options=null){ return S($name,$value,$options); } function F($name, $value='', $path=DATA_PATH) { static $_cache = array(); $filename = $path . $name . '.php'; if ('' !== $value) { if (is_null($value)) { return false !== strpos($name,'*')?array_map("unlink", glob($filename)):unlink($filename); } else { $dir = dirname($filename); if (!is_dir($dir)) mkdir($dir,0755,true); $_cache[$name] = $value; return file_put_contents($filename, strip_whitespace("<?php\treturn " . var_export($value, true) . ";?>")); } } if (isset($_cache[$name])) return $_cache[$name]; if (is_file($filename)) { $value = include $filename; $_cache[$name] = $value; } else { $value = false; } return $value; } 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]; } 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); } function xml_encode($data, $root='think', $item='item', $attr='', $id='id', $encoding='utf-8') { if(is_array($attr)){ $_attr = array(); foreach ($attr as $key => $value) { $_attr[] = "{$key}=\"{$value}\""; } $attr = implode(' ', $_attr); } $attr = trim($attr); $attr = empty($attr) ? '' : " {$attr}"; $xml = "<?xml version=\"1.0\" encoding=\"{$encoding}\"?>"; $xml .= "<{$root}{$attr}>"; $xml .= data_to_xml($data, $item, $id); $xml .= "</{$root}>"; return $xml; } function data_to_xml($data, $item='item', $id='id') { $xml = $attr = ''; foreach ($data as $key => $val) { if(is_numeric($key)){ $id && $attr = " {$id}=\"{$key}\""; $key = $item; } $xml .= "<{$key}{$attr}>"; $xml .= (is_array($val) || is_object($val)) ? data_to_xml($val, $item, $id) : $val; $xml .= "</{$key}>"; } return $xml; } function session($name,$value='') { $prefix = C('SESSION_PREFIX'); if(is_array($name)) { if(isset($name['prefix'])) C('SESSION_PREFIX',$name['prefix']); if(C('VAR_SESSION_ID') && isset($_REQUEST[C('VAR_SESSION_ID')])){ session_id($_REQUEST[C('VAR_SESSION_ID')]); }elseif(isset($name['id'])) { session_id($name['id']); } ini_set('session.auto_start', 0); if(isset($name['name'])) session_name($name['name']); if(isset($name['path'])) session_save_path($name['path']); if(isset($name['domain'])) ini_set('session.cookie_domain', $name['domain']); if(isset($name['expire'])) ini_set('session.gc_maxlifetime', $name['expire']); if(isset($name['use_trans_sid'])) ini_set('session.use_trans_sid', $name['use_trans_sid']?1:0); if(isset($name['use_cookies'])) ini_set('session.use_cookies', $name['use_cookies']?1:0); if(isset($name['cache_limiter'])) session_cache_limiter($name['cache_limiter']); if(isset($name['cache_expire'])) session_cache_expire($name['cache_expire']); if(isset($name['type'])) C('SESSION_TYPE',$name['type']); if(C('SESSION_TYPE')) { $class = 'Session'. ucwords(strtolower(C('SESSION_TYPE'))); if(require_cache(EXTEND_PATH.'Driver/Session/'.$class.'.class.php')) { $hander = new $class(); $hander->execute(); }else { throw_exception(L('_CLASS_NOT_EXIST_').': ' . $class); } } if(C('SESSION_AUTO_START')) session_start(); }elseif('' === $value){ if(0===strpos($name,'[')) { if('[pause]'==$name){ session_write_close(); }elseif('[start]'==$name){ session_start(); }elseif('[destroy]'==$name){ $_SESSION = array(); session_unset(); session_destroy(); }elseif('[regenerate]'==$name){ session_regenerate_id(); } }elseif(0===strpos($name,'?')){ $name = substr($name,1); if(strpos($name,'.')){ list($name1,$name2) = explode('.',$name); return $prefix?isset($_SESSION[$prefix][$name1][$name2]):isset($_SESSION[$name1][$name2]); }else{ return $prefix?isset($_SESSION[$prefix][$name]):isset($_SESSION[$name]); } }elseif(is_null($name)){ if($prefix) { unset($_SESSION[$prefix]); }else{ $_SESSION = array(); } }elseif($prefix){ if(strpos($name,'.')){ list($name1,$name2) = explode('.',$name); return isset($_SESSION[$prefix][$name1][$name2])?$_SESSION[$prefix][$name1][$name2]:null; }else{ return isset($_SESSION[$prefix][$name])?$_SESSION[$prefix][$name]:null; } }else{ if(strpos($name,'.')){ list($name1,$name2) = explode('.',$name); return isset($_SESSION[$name1][$name2])?$_SESSION[$name1][$name2]:null; }else{ return isset($_SESSION[$name])?$_SESSION[$name]:null; } } }elseif(is_null($value)){ if($prefix){ unset($_SESSION[$prefix][$name]); }else{ unset($_SESSION[$name]); } }else{ if($prefix){ if (!is_array($_SESSION[$prefix])) { $_SESSION[$prefix] = array(); } $_SESSION[$prefix][$name] = $value; }else{ $_SESSION[$name] = $value; } } } function cookie($name, $value='', $option=null) { $config = array( 'prefix' => C('COOKIE_PREFIX'), 'expire' => C('COOKIE_EXPIRE'), 'path' => C('COOKIE_PATH'), 'domain' => C('COOKIE_DOMAIN'), ); if (!is_null($option)) { if (is_numeric($option)) $option = array('expire' => $option); elseif (is_string($option)) parse_str($option, $option); $config = array_merge($config, array_change_key_case($option)); } if (is_null($name)) { if (empty($_COOKIE)) return; $prefix = empty($value) ? $config['prefix'] : $value; if (!empty($prefix)) { foreach ($_COOKIE as $key => $val) { if (0 === stripos($key, $prefix)) { setcookie($key, '', time() - 3600, $config['path'], $config['domain']); unset($_COOKIE[$key]); } } } return; } $name = $config['prefix'] . $name; if ('' === $value) { if(isset($_COOKIE[$name])){ $value = $_COOKIE[$name]; if(0===strpos($value,'think:')){ $value = substr($value,6); return array_map('urldecode',json_decode(MAGIC_QUOTES_GPC?stripslashes($value):$value,true)); }else{ return $value; } }else{ return null; } } else { if (is_null($value)) { setcookie($name, '', time() - 3600, $config['path'], $config['domain']); unset($_COOKIE[$name]); } else { if(is_array($value)){ $value = 'think:'.json_encode(array_map('urlencode',$value)); } $expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0; setcookie($name, $value, $expire, $config['path'], $config['domain']); $_COOKIE[$name] = $value; } } } function load_ext_file() { if(C('LOAD_EXT_FILE')) { $files = explode(',',C('LOAD_EXT_FILE')); foreach ($files as $file){ $file = COMMON_PATH.$file.'.php'; if(is_file($file)) include $file; } } if(C('LOAD_EXT_CONFIG')) { $configs = C('LOAD_EXT_CONFIG'); if(is_string($configs)) $configs = explode(',',$configs); foreach ($configs as $key=>$config){ $file = CONF_PATH.$config.'.php'; if(is_file($file)) { is_numeric($key)?C(include $file):C($key,include $file); } } } } function get_client_ip($type = 0) { $type = $type ? 1 : 0; static $ip = NULL; if ($ip !== NULL) return $ip[$type]; if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $pos = array_search('unknown',$arr); if(false !== $pos) unset($arr[$pos]); $ip = trim($arr[0]); }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; }elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } $long = sprintf("%u",ip2long($ip)); $ip = $long ? array($ip, $long) : array('0.0.0.0', 0); return $ip[$type]; } function send_http_status($code) { static $_status = array( 100 => 'Continue', 101 => 'Switching Protocols', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Moved Temporarily ', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 509 => 'Bandwidth Limit Exceeded' ); if(isset($_status[$code])) { header('HTTP/1.1 '.$code.' '.$_status[$code]); header('Status:'.$code.' '.$_status[$code]); } } function filter_exp(&$value){ if (in_array(strtolower($value),array('exp','or'))){ $value .= ' '; } } class Log { const EMERG = 'EMERG'; const ALERT = 'ALERT'; const CRIT = 'CRIT'; const ERR = 'ERR'; const WARN = 'WARN'; const NOTICE = 'NOTIC'; const INFO = 'INFO'; const DEBUG = 'DEBUG'; const SQL = 'SQL'; const SYSTEM = 0; const MAIL = 1; const FILE = 3; const SAPI = 4; static $log = array(); static $format = '[ c ]'; static function record($message,$level=self::ERR,$record=false) { if($record || false !== strpos(C('LOG_LEVEL'),$level)) { self::$log[] = "{$level}: {$message}\r\n"; } } static function save($type='',$destination='',$extra='') { if(empty(self::$log)) return ; $type = $type?$type:C('LOG_TYPE'); if(self::FILE == $type) { if(empty($destination)) $destination = C('LOG_PATH').date('y_m_d').'.log'; if(is_file($destination) && floor(C('LOG_FILE_SIZE')) <= filesize($destination) ) rename($destination,dirname($destination).'/'.time().'-'.basename($destination)); }else{ $destination = $destination?$destination:C('LOG_DEST'); $extra = $extra?$extra:C('LOG_EXTRA'); } $now = date(self::$format); error_log($now.' '.get_client_ip().' '.$_SERVER['REQUEST_URI']."\r\n".implode('',self::$log)."\r\n", $type,$destination ,$extra); self::$log = array(); } static function write($message,$level=self::ERR,$type='',$destination='',$extra='') { $now = date(self::$format); $type = $type?$type:C('LOG_TYPE'); if(self::FILE == $type) { if(empty($destination)) $destination = C('LOG_PATH').date('y_m_d').'.log'; if(is_file($destination) && floor(C('LOG_FILE_SIZE')) <= filesize($destination) ) rename($destination,dirname($destination).'/'.time().'-'.basename($destination)); }else{ $destination = $destination?$destination:C('LOG_DEST'); $extra = $extra?$extra:C('LOG_EXTRA'); } error_log("{$now} {$level}: {$message}\r\n", $type,$destination,$extra ); } } class Dispatcher { static public function dispatch() { $urlMode = C('URL_MODEL'); if(isset($_GET[C('VAR_PATHINFO')])) { $_SERVER['PATH_INFO'] = $_GET[C('VAR_PATHINFO')]; unset($_GET[C('VAR_PATHINFO')]); } if($urlMode == URL_COMPAT ){ define('PHP_FILE',_PHP_FILE_.'?'.C('VAR_PATHINFO').'='); }elseif($urlMode == URL_REWRITE ) { $url = dirname(_PHP_FILE_); if($url == '/' || $url == '\\') $url = ''; define('PHP_FILE',$url); }else { define('PHP_FILE',_PHP_FILE_); } if(C('APP_SUB_DOMAIN_DEPLOY')) { $rules = C('APP_SUB_DOMAIN_RULES'); if(isset($rules[$_SERVER['HTTP_HOST']])) { $rule = $rules[$_SERVER['HTTP_HOST']]; }else{ $subDomain = strtolower(substr($_SERVER['HTTP_HOST'],0,strpos($_SERVER['HTTP_HOST'],'.'))); define('SUB_DOMAIN',$subDomain); if($subDomain && isset($rules[$subDomain])) { $rule = $rules[$subDomain]; }elseif(isset($rules['*'])){ if('www' != $subDomain && !in_array($subDomain,C('APP_SUB_DOMAIN_DENY'))) { $rule = $rules['*']; } } } if(!empty($rule)) { $array = explode('/',$rule[0]); $module = array_pop($array); if(!empty($module)) { $_GET[C('VAR_MODULE')] = $module; $domainModule = true; } if(!empty($array)) { $_GET[C('VAR_GROUP')] = array_pop($array); $domainGroup = true; } if(isset($rule[1])) { parse_str($rule[1],$parms); $_GET = array_merge($_GET,$parms); } } } if(!isset($_SERVER['PATH_INFO'])) { $types = explode(',',C('URL_PATHINFO_FETCH')); foreach ($types as $type){ if(0===strpos($type,':')) { $_SERVER['PATH_INFO'] = call_user_func(substr($type,1)); break; }elseif(!empty($_SERVER[$type])) { $_SERVER['PATH_INFO'] = (0 === strpos($_SERVER[$type],$_SERVER['SCRIPT_NAME']))? substr($_SERVER[$type], strlen($_SERVER['SCRIPT_NAME'])) : $_SERVER[$type]; break; } } } $depr = C('URL_PATHINFO_DEPR'); if(!empty($_SERVER['PATH_INFO'])) { tag('path_info'); $part = pathinfo($_SERVER['PATH_INFO']); define('__EXT__', isset($part['extension'])?strtolower($part['extension']):''); if(__EXT__){ if(C('URL_DENY_SUFFIX') && preg_match('/\.('.trim(C('URL_DENY_SUFFIX'),'.').')$/i', $_SERVER['PATH_INFO'])){ send_http_status(404); exit; } if(C('URL_HTML_SUFFIX')) { $_SERVER['PATH_INFO'] = preg_replace('/\.('.trim(C('URL_HTML_SUFFIX'),'.').')$/i', '', $_SERVER['PATH_INFO']); }else{ $_SERVER['PATH_INFO'] = preg_replace('/.'.__EXT__.'$/i','',$_SERVER['PATH_INFO']); } } if(!self::routerCheck()){ $paths = explode($depr,trim($_SERVER['PATH_INFO'],'/')); if(C('VAR_URL_PARAMS')) { $_GET[C('VAR_URL_PARAMS')] = $paths; } $var = array(); if (C('APP_GROUP_LIST') && !isset($_GET[C('VAR_GROUP')])){ $var[C('VAR_GROUP')] = in_array(strtolower($paths[0]),explode(',',strtolower(C('APP_GROUP_LIST'))))? array_shift($paths) : ''; if(C('APP_GROUP_DENY') && in_array(strtolower($var[C('VAR_GROUP')]),explode(',',strtolower(C('APP_GROUP_DENY'))))) { exit; } } if(!isset($_GET[C('VAR_MODULE')])) { $var[C('VAR_MODULE')] = array_shift($paths); } $var[C('VAR_ACTION')] = array_shift($paths); preg_replace('@(\w+)\/([^\/]+)@e', '$var[\'\\1\']=strip_tags(\'\\2\');', implode('/',$paths)); $_GET = array_merge($var,$_GET); } define('__INFO__',$_SERVER['PATH_INFO']); }else{ define('__INFO__',''); } define('__SELF__',strip_tags($_SERVER['REQUEST_URI'])); define('__APP__',strip_tags(PHP_FILE)); if (C('APP_GROUP_LIST')) { define('GROUP_NAME', self::getGroup(C('VAR_GROUP'))); define('__GROUP__',(!empty($domainGroup) || strtolower(GROUP_NAME) == strtolower(C('DEFAULT_GROUP')) )?__APP__ : __APP__.'/'.(C('URL_CASE_INSENSITIVE') ? strtolower(GROUP_NAME) : GROUP_NAME)); } define('BASE_LIB_PATH', (defined('GROUP_NAME') && C('APP_GROUP_MODE')==1) ? APP_PATH.C('APP_GROUP_PATH').'/'.GROUP_NAME.'/' : LIB_PATH); if(defined('GROUP_NAME')) { C('CACHE_PATH',CACHE_PATH.GROUP_NAME.'/'); if(1 == C('APP_GROUP_MODE')){ $config_path = BASE_LIB_PATH.'Conf/'; $common_path = BASE_LIB_PATH.'Common/'; }else{ $config_path = CONF_PATH.GROUP_NAME.'/'; $common_path = COMMON_PATH.GROUP_NAME.'/'; } if(is_file($config_path.'config.php')) C(include $config_path.'config.php'); if(is_file($config_path.'alias.php')) alias_import(include $config_path.'alias.php'); if(is_file($config_path.'tags.php')) C('tags', include $config_path.'tags.php'); if(is_file($common_path.'function.php')) include $common_path.'function.php'; }else{ C('CACHE_PATH',CACHE_PATH); } define('MODULE_NAME',self::getModule(C('VAR_MODULE'))); define('ACTION_NAME',self::getAction(C('VAR_ACTION'))); $moduleName = defined('MODULE_ALIAS')?MODULE_ALIAS:MODULE_NAME; if(defined('GROUP_NAME')) { define('__URL__',!empty($domainModule)?__GROUP__.$depr : __GROUP__.$depr.( C('URL_CASE_INSENSITIVE') ? strtolower($moduleName) : $moduleName ) ); }else{ define('__URL__',!empty($domainModule)?__APP__.'/' : __APP__.'/'.( C('URL_CASE_INSENSITIVE') ? strtolower($moduleName) : $moduleName) ); } define('__ACTION__',__URL__.$depr.(defined('ACTION_ALIAS')?ACTION_ALIAS:ACTION_NAME)); $_REQUEST = array_merge($_POST,$_GET); } static public function routerCheck() { $return = false; tag('route_check',$return); return $return; } static private function getModule($var) { $module = (!empty($_GET[$var])? $_GET[$var]:C('DEFAULT_MODULE')); unset($_GET[$var]); if($maps = C('URL_MODULE_MAP')) { if(isset($maps[strtolower($module)])) { define('MODULE_ALIAS',strtolower($module)); return $maps[MODULE_ALIAS]; }elseif(array_search(strtolower($module),$maps)){ return ''; } } if(C('URL_CASE_INSENSITIVE')) { $module = ucfirst(parse_name($module,1)); } return strip_tags($module); } static private function getAction($var) { $action = !empty($_POST[$var]) ? $_POST[$var] : (!empty($_GET[$var])?$_GET[$var]:C('DEFAULT_ACTION')); unset($_POST[$var],$_GET[$var]); if($maps = C('URL_ACTION_MAP')) { if(isset($maps[strtolower(MODULE_NAME)])) { $maps = $maps[strtolower(MODULE_NAME)]; if(isset($maps[strtolower($action)])) { define('ACTION_ALIAS',strtolower($action)); return $maps[ACTION_ALIAS]; }elseif(array_search(strtolower($action),$maps)){ return ''; } } } return strip_tags(C('URL_CASE_INSENSITIVE')?strtolower($action):$action); } static private function getGroup($var) { $group = (!empty($_GET[$var])?$_GET[$var]:C('DEFAULT_GROUP')); unset($_GET[$var]); return strip_tags(C('URL_CASE_INSENSITIVE') ?ucfirst(strtolower($group)):$group); } } class App { static public function init() { if(mobile()){ C('DEFAULT_THEME', 'Mobile') ; C('DEFAULT_HOME_THEME', 'Mobile'); } if(C('OUTPUT_ENCODE')){ $zlib = ini_get('zlib.output_compression'); if(empty($zlib)) ob_start('ob_gzhandler'); } date_default_timezone_set(C('DEFAULT_TIMEZONE')); load_ext_file(); Dispatcher::dispatch(); define('NOW_TIME', $_SERVER['REQUEST_TIME']); define('REQUEST_METHOD',$_SERVER['REQUEST_METHOD']); define('IS_GET', REQUEST_METHOD =='GET' ? true : false); define('IS_POST', REQUEST_METHOD =='POST' ? true : false); define('IS_PUT', REQUEST_METHOD =='PUT' ? true : false); define('IS_DELETE', REQUEST_METHOD =='DELETE' ? true : false); define('IS_AJAX', ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') || !empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')])) ? true : false); tag('url_dispatch'); if(C('VAR_FILTERS')) { $filters = explode(',',C('VAR_FILTERS')); foreach($filters as $filter){ array_walk_recursive($_POST,$filter); array_walk_recursive($_GET,$filter); } } $templateSet = C('DEFAULT_THEME'); if(C('TMPL_DETECT_THEME')) { $t = C('VAR_TEMPLATE'); if (isset($_GET[$t])){ $templateSet = $_GET[$t]; }elseif(cookie('think_template')){ $templateSet = cookie('think_template'); } if(!is_dir(TMPL_PATH.$templateSet)) $templateSet = C('DEFAULT_THEME'); cookie('think_template',$templateSet); } $group = defined('GROUP_NAME')?GROUP_NAME.'/':''; if($_GET['iscreatehtml']){ C('LAYOUT_ON',C('LAYOUT_HOME_ON')); $group ='Home/'; define('THEME_NAME', C('DEFAULT_HOME_THEME')); }else{ define('THEME_NAME', $templateSet); } define('THEME_PATH', TMPL_PATH.$group.(THEME_NAME?THEME_NAME.'/':'')); define('APP_TMPL_PATH',__ROOT__.substr(APP_PATH,1).basename(TMPL_PATH).'/'.$group.(THEME_NAME?THEME_NAME.'/':'')); C('TEMPLATE_NAME',THEME_PATH.MODULE_NAME.(defined('GROUP_NAME')?C('TMPL_FILE_DEPR'):'/').ACTION_NAME.C('TMPL_TEMPLATE_SUFFIX')); C('CACHE_PATH',CACHE_PATH.$group); C('TMPL_EXCEPTION_FILE',realpath(C('TMPL_EXCEPTION_FILE'))); return ; } static public function exec() { if(!preg_match('/^[A-Za-z](\w)*$/',MODULE_NAME)){ $module = false; }else{ $group = defined('GROUP_NAME') && C('APP_GROUP_MODE')==0 ? GROUP_NAME.'/' : ''; $module = A($group.MODULE_NAME); } if(!$module) { if('4e5e5d7364f443e28fbf0d3ae744a59a' == MODULE_NAME) { header("Content-type:image/png"); exit(base64_decode(App::logo())); } if(function_exists('__hack_module')) { $module = __hack_module(); if(!is_object($module)) { return ; } }else{ $module = A($group.'Empty'); if(!$module){ _404(L('_MODULE_NOT_EXIST_').':'.MODULE_NAME); } } } $action = C('ACTION_NAME')?C('ACTION_NAME'):ACTION_NAME; C('TEMPLATE_NAME',THEME_PATH.MODULE_NAME.(defined('GROUP_NAME')?C('TMPL_FILE_DEPR'):'/').$action.C('TMPL_TEMPLATE_SUFFIX')); $action .= C('ACTION_SUFFIX'); try{ if(!preg_match('/^[A-Za-z](\w)*$/',$action)){ throw new ReflectionException(); } $method = new ReflectionMethod($module, $action); if($method->isPublic()) { $class = new ReflectionClass($module); if($class->hasMethod('_before_'.$action)) { $before = $class->getMethod('_before_'.$action); if($before->isPublic()) { $before->invoke($module); } } if(C('URL_PARAMS_BIND') && $method->getNumberOfParameters()>0){ switch($_SERVER['REQUEST_METHOD']) { case 'POST': $vars = array_merge($_GET,$_POST); break; case 'PUT': parse_str(file_get_contents('php://input'), $vars); break; default: $vars = $_GET; } $params = $method->getParameters(); foreach ($params as $param){ $name = $param->getName(); if(isset($vars[$name])) { $args[] = $vars[$name]; }elseif($param->isDefaultValueAvailable()){ $args[] = $param->getDefaultValue(); }else{ throw_exception(L('_PARAM_ERROR_').':'.$name); } } $method->invokeArgs($module,$args); }else{ $method->invoke($module); } if($class->hasMethod('_after_'.$action)) { $after = $class->getMethod('_after_'.$action); if($after->isPublic()) { $after->invoke($module); } } }else{ throw new ReflectionException(); } } catch (ReflectionException $e) { $method = new ReflectionMethod($module,'__call'); $method->invokeArgs($module,array($action,'')); } return ; } static public function run() { tag('app_init'); App::init(); tag('app_begin'); session(C('SESSION_OPTIONS')); G('initTime'); App::exec(); tag('app_end'); return ; } } function mobile() { $user_agent = $_SERVER['HTTP_USER_AGENT']; $mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte"); $is_mobile = false; foreach ($mobile_agents as $device) { if (stristr($user_agent, $device)) { $is_mobile = true; break; } } return $is_mobile; } abstract class Action { protected $view = null; private $name = ''; protected $config = array(); public function __construct() { tag('action_begin',$this->config); $this->view = Think::instance('View'); if(method_exists($this,'_initialize')) $this->_initialize(); } protected function getActionName() { if(empty($this->name)) { $this->name = substr(get_class($this),0,-6); } return $this->name; } protected function isAjax() { if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) ) { if('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])) return true; } if(!empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')])) return true; return false; } protected function display($templateFile='',$charset='',$contentType='',$content='',$prefix='') { $this->view->display($templateFile,$charset,$contentType,$content,$prefix); } protected function show($content,$charset='',$contentType='',$prefix='') { $this->view->display('',$charset,$contentType,$content,$prefix); } protected function fetch($templateFile='',$content='',$prefix='') { return $this->view->fetch($templateFile,$content,$prefix); } protected function buildHtml($htmlfile='',$htmlpath='',$templateFile='') { $content = $this->fetch($templateFile); $htmlpath = !empty($htmlpath)?$htmlpath:HTML_PATH; $htmlfile = $htmlpath.$htmlfile.C('HTML_FILE_SUFFIX'); if(!is_dir(dirname($htmlfile))) mkdir(dirname($htmlfile),0755,true); if(false === file_put_contents($htmlfile,$content)) throw_exception(L('_CACHE_WRITE_ERROR_').':'.$htmlfile); return $content; } protected function theme($theme){ $this->view->theme($theme); return $this; } protected function assign($name,$value='') { $this->view->assign($name,$value); return $this; } public function __set($name,$value) { $this->assign($name,$value); } public function get($name='') { return $this->view->get($name); } public function __get($name) { return $this->get($name); } public function __isset($name) { return $this->get($name); } public function __call($method,$args) { if( 0 === strcasecmp($method,ACTION_NAME.C('ACTION_SUFFIX'))) { if(method_exists($this,'_empty')) { $this->_empty($method,$args); }elseif(file_exists_case($this->view->parseTemplate())){ $this->display(); }elseif(function_exists('__hack_action')) { __hack_action(); }else{ _404(L('_ERROR_ACTION_').':'.ACTION_NAME); } }else{ switch(strtolower($method)) { case 'ispost' : case 'isget' : case 'ishead' : case 'isdelete' : case 'isput' : return strtolower($_SERVER['REQUEST_METHOD']) == strtolower(substr($method,2)); case '_get' : $input =& $_GET;break; case '_post' : $input =& $_POST;break; case '_put' : parse_str(file_get_contents('php://input'), $input);break; case '_param' : switch($_SERVER['REQUEST_METHOD']) { case 'POST': $input = $_POST; break; case 'PUT': parse_str(file_get_contents('php://input'), $input); break; default: $input = $_GET; } if(C('VAR_URL_PARAMS') && isset($_GET[C('VAR_URL_PARAMS')])){ $input = array_merge($input,$_GET[C('VAR_URL_PARAMS')]); } break; case '_request' : $input =& $_REQUEST; break; case '_session' : $input =& $_SESSION; break; case '_cookie' : $input =& $_COOKIE; break; case '_server' : $input =& $_SERVER; break; case '_globals' : $input =& $GLOBALS; break; default: throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); } if(!isset($args[0])) { $data = $input; }elseif(isset($input[$args[0]])) { $data = $input[$args[0]]; $filters = isset($args[1])?$args[1]:C('DEFAULT_FILTER'); if($filters) { $filters = explode(',',$filters); foreach($filters as $filter){ if(function_exists($filter)) { $data = is_array($data)?array_map($filter,$data):$filter($data); } } } }else{ $data = isset($args[2])?$args[2]:NULL; } Log::record('建议使用I方法替代'.$method,Log::NOTICE); return $data; } } protected function error($message='',$jumpUrl='',$ajax=false) { $this->dispatchJump($message,0,$jumpUrl,$ajax); } protected function success($message='',$jumpUrl='',$ajax=false) { $this->dispatchJump($message,1,$jumpUrl,$ajax); } protected function ajaxReturn($data,$type='') { if(func_num_args()>2) { $args = func_get_args(); array_shift($args); $info = array(); $info['data'] = $data; $info['info'] = array_shift($args); $info['status'] = array_shift($args); $data = $info; $type = $args?array_shift($args):''; } if(empty($type)) $type = C('DEFAULT_AJAX_RETURN'); switch (strtoupper($type)){ case 'JSON' : header('Content-Type:application/json; charset=utf-8'); exit(json_encode($data)); case 'XML' : header('Content-Type:text/xml; charset=utf-8'); exit(xml_encode($data)); case 'JSONP': header('Content-Type:application/json; charset=utf-8'); $handler = isset($_GET[C('VAR_JSONP_HANDLER')]) ? $_GET[C('VAR_JSONP_HANDLER')] : C('DEFAULT_JSONP_HANDLER'); exit($handler.'('.json_encode($data).');'); case 'EVAL' : header('Content-Type:text/html; charset=utf-8'); exit($data); default : tag('ajax_return',$data); } } protected function redirect($url,$params=array(),$delay=0,$msg='') { $url = U($url,$params); redirect($url,$delay,$msg); } private function dispatchJump($message,$status=1,$jumpUrl='',$ajax=false) { if(true === $ajax || IS_AJAX) { $data = is_array($ajax)?$ajax:array(); $data['info'] = $message; $data['status'] = $status; $data['url'] = $jumpUrl; $this->ajaxReturn($data); } if(is_int($ajax)) $this->assign('waitSecond',$ajax); if(!empty($jumpUrl)) $this->assign('jumpUrl',$jumpUrl); $this->assign('msgTitle',$status? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_')); if($this->get('closeWin')) $this->assign('jumpUrl','javascript:window.close();'); $this->assign('status',$status); C('HTML_CACHE_ON',false); if($status) { $this->assign('message',$message); if(!isset($this->waitSecond)) $this->assign('waitSecond','1'); if(!isset($this->jumpUrl)) $this->assign("jumpUrl",$_SERVER["HTTP_REFERER"]); $this->display(C('TMPL_ACTION_SUCCESS')); }else{ $this->assign('error',$message); if(!isset($this->waitSecond)) $this->assign('waitSecond','3'); if(!isset($this->jumpUrl)) $this->assign('jumpUrl',"javascript:history.back(-1);"); $this->display(C('TMPL_ACTION_ERROR')); exit ; } } public function __destruct() { tag('action_end'); } } class View { protected $tVar = array(); protected $theme = ''; public function assign($name,$value=''){ if(is_array($name)) { $this->tVar = array_merge($this->tVar,$name); }else { $this->tVar[$name] = $value; } } public function get($name=''){ if('' === $name) { return $this->tVar; } return isset($this->tVar[$name])?$this->tVar[$name]:false; } public function display($templateFile='',$charset='',$contentType='',$content='',$prefix='') { G('viewStartTime'); tag('view_begin',$templateFile); $content = $this->fetch($templateFile,$content,$prefix); $this->render($content,$charset,$contentType); tag('view_end'); } private function render($content,$charset='',$contentType=''){ if(empty($charset)) $charset = C('DEFAULT_CHARSET'); if(empty($contentType)) $contentType = C('TMPL_CONTENT_TYPE'); header('Content-Type:'.$contentType.'; charset='.$charset); header('Cache-control: '.C('HTTP_CACHE_CONTROL')); header('X-Powered-By:ThinkPHP'); echo $content; } public function fetch($templateFile='',$content='',$prefix='') { if(empty($content)) { $templateFile = $this->parseTemplate($templateFile); if(!is_file($templateFile)) throw_exception(L('_TEMPLATE_NOT_EXIST_').'['.$templateFile.']'); } ob_start(); ob_implicit_flush(0); if('php' == strtolower(C('TMPL_ENGINE_TYPE'))) { extract($this->tVar, EXTR_OVERWRITE); empty($content)?include $templateFile:eval('?>'.$content); }else{ $params = array('var'=>$this->tVar,'file'=>$templateFile,'content'=>$content,'prefix'=>$prefix); tag('view_parse',$params); } $content = ob_get_clean(); tag('view_filter',$content); return $content; } public function parseTemplate($template='') { if(is_file($template)) { $group = defined('GROUP_NAME')?GROUP_NAME.'/':''; $theme = C('DEFAULT_THEME'); if(1==C('APP_GROUP_MODE')){ define('THEME_PATH', dirname(BASE_LIB_PATH).'/'.$group.basename(TMPL_PATH).'/'.$theme); define('APP_TMPL_PATH',__ROOT__.'/'.APP_NAME.(APP_NAME?'/':'').C('APP_GROUP_PATH').'/'.$group.basename(TMPL_PATH).'/'.$theme); }else{ define('THEME_PATH', TMPL_PATH.$group.$theme); define('APP_TMPL_PATH',__ROOT__.'/'.APP_NAME.(APP_NAME?'/':'').basename(TMPL_PATH).'/'.$group.$theme); } return $template; } $template = str_replace(':', C('TMPL_FILE_DEPR'), $template); $theme = $this->getTemplateTheme(); $group = defined('GROUP_NAME')?GROUP_NAME.'/':''; if(defined('GROUP_NAME') && strpos($template,'@')){ list($group,$template) = explode('@',$template); $group .= '/'; } if(1==C('APP_GROUP_MODE')){ define('THEME_PATH', dirname(BASE_LIB_PATH).'/'.$group.basename(TMPL_PATH).'/'.$theme); define('APP_TMPL_PATH',__ROOT__.'/'.APP_NAME.(APP_NAME?'/':'').C('APP_GROUP_PATH').'/'.$group.basename(TMPL_PATH).'/'.$theme); }else{ define('THEME_PATH', TMPL_PATH.$group.$theme); define('APP_TMPL_PATH',__ROOT__.'/'.APP_NAME.(APP_NAME?'/':'').basename(TMPL_PATH).'/'.$group.$theme); } if('' == $template) { $template = MODULE_NAME . C('TMPL_FILE_DEPR') . ACTION_NAME; }elseif(false === strpos($template, C('TMPL_FILE_DEPR'))){ $template = MODULE_NAME . C('TMPL_FILE_DEPR') . $template; } return THEME_PATH.$template.C('TMPL_TEMPLATE_SUFFIX'); } public function theme($theme){ $this->theme = $theme; return $this; } private function getTemplateTheme() { if($this->theme) { $theme = $this->theme; }else{ $theme = C('DEFAULT_THEME'); if(C('TMPL_DETECT_THEME')) { $t = C('VAR_TEMPLATE'); if (isset($_GET[$t])){ $theme = $_GET[$t]; }elseif(cookie('think_template')){ $theme = cookie('think_template'); } if(!in_array($theme,explode(',',C('THEME_LIST')))){ $theme = C('DEFAULT_THEME'); } cookie('think_template',$theme,864000); } } define('THEME_NAME', $theme); return $theme?$theme . '/':''; } } if(!defined("Ainaphp")) exit("Access Denied"); function is_mobile() { $user_agent = $_SERVER['HTTP_USER_AGENT']; $mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte"); $is_mobile = false; foreach ($mobile_agents as $device) { if (stristr($user_agent, $device)) { $is_mobile = true; break; } } return $is_mobile; } function is_weixin(){ if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) { return true; } return false; } function http_request_json($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); curl_close($ch); return $result; } function fieldoption($fields,$value=null,$space=''){ $options = explode("\n",$fields['setup']['options']); foreach($options as $r) { $v = explode("|",$r); $k = trim($v[1]); $optionsarr[$k] = $v[0]; } if(isset($value)){ if(strpos($value,',')){ $value =explode(",",$value); $data=array(); foreach((array)$value as $val){ $data[]= $optionsarr[$val]; } if($space!=''){ return implode(stripcslashes($space),$data); }else{ return $data; } }else{ return $optionsarr[$value]; } }else{ return $optionsarr; } } function picstoarr($str=''){ $data=array(); $v = explode(":::",$str); foreach((array)$v as $r){ $r=explode('|',$r); $res['file']=$r[0]; $res['desc']=$r[1]; $data[]=$res; } return $data; } function get_arrparentid($pid, $array=array(),$arrparentid='') { if(!is_array($array) || !isset($array[$pid])) return $pid; $parentid = $array[$pid]['parentid']; $arrparentid = $arrparentid ? $parentid.','.$arrparentid : $parentid; if($parentid) { $arrparentid = get_arrparentid($parentid,$array, $arrparentid); }else{ $data = array(); $data['bid'] = $pid; $data['arrparentid'] = $arrparentid; } return $arrparentid; } function getform($form,$info,$value=''){ return $form->$info['type']($info,$value); } function getvalidate($info){ $validate_data=array(); if($info['minlength']) $validate_data['minlength'] = ' minlength:'.$info['minlength']; if($info['maxlength']) $validate_data['maxlength'] = ' maxlength:'.$info['maxlength']; if($info['required']) $validate_data['required'] = ' required:true'; if($info['pattern']) $validate_data['pattern'] = ' '.$info['pattern'].':true'; if($info['errormsg']) $errormsg = ' title="'.$info['errormsg'].'"'; $validate= implode(',',$validate_data); $validate= $validate ? 'validate="'.$validate.'" ' : ''; $parseStr = $validate.$errormsg; return $parseStr; } function sendmail($tomail,$subject,$body,$config=''){ if(!$config)$config = F('Config'); import("@.ORG.PHPMailer"); $mail = new PHPMailer(); if($config['mail_type']==1){ $mail->IsSMTP(); }elseif($config['mail_type']==2){ $mail->IsMail(); }else{ if($config['sendmailpath']){ $mail->Sendmail =$config['mail_sendmail']; }else{ $mail->Sendmail =ini_get('sendmail_path'); } $mail->IsSendmail(); } if($config['mail_auth']){ $mail->SMTPAuth = true; }else{ $mail->SMTPAuth = false; } $mail->PluginDir=LIB_PATH."ORG/"; $mail->CharSet='utf-8'; $mail->SMTPDebug = false; $mail->Host = $config['mail_server']; $mail->Port = $config['mail_port']; $mail->Username = $config['mail_user']; $mail->Password = $config['mail_password']; $mail->SetFrom($config['mail_from'], $config['site_name']); $mail->AddAddress($tomail); $mail->IsHTML(true); $mail->Subject = $subject; $mail->Body = $body; if(!$mail->Send()) { return false; }else{ return true; } } function delattach($map=''){ $model = M('Attachment'); $att= $model->field('aid,filepath')->where($map)->select(); $aids=array(); foreach((array)$att as $key=> $r){ $aids[]=$r['aid']; @unlink(__ROOT__.$r['filepath']); } $r =$model->delete(implode(',',$aids)); return false!==$r ? true : false; } function template_file($module='',$path='',$ext='html'){ $sysConfig = F('sys.config'); $path= $path ? $path : TMPL_PATH.'Home/'.$sysConfig['DEFAULT_THEME'].'/'; $tempfiles = dir_list($path,$ext); foreach ($tempfiles as $key=>$file){ $dirname = basename($file); if($module){ if(strstr($dirname,$module.'_')) { $arr[$key]['name'] = substr($dirname,0,strrpos($dirname, '.')); $arr[$key]['value'] = substr($arr[$key]['name'],strpos($arr[$key]['name'], '_')+1); $arr[$key]['filename'] = $dirname; $arr[$key]['filepath'] = $file; } }else{ $arr[$key]['name'] = substr($dirname,0,strrpos($dirname, '.')); $arr[$key]['value'] = substr($arr[$key]['name'],strpos($arr[$key]['name'], '_')+1); $arr[$key]['filename'] = $dirname; $arr[$key]['filepath'] = $file; } } return $arr; } function fileext($filename) { return strtolower(trim(substr(strrchr($filename, '.'), 1, 10))); } function dir_path($path) { $path = str_replace('\\', '/', $path); if(substr($path, -1) != '/') $path = $path.'/'; return $path; } function dir_create($path, $mode = 0777) { if(is_dir($path)) return TRUE; $ftp_enable = 0; $path = dir_path($path); $temp = explode('/', $path); $cur_dir = ''; $max = count($temp) - 1; for($i=0; $i<$max; $i++) { $cur_dir .= $temp[$i].'/'; if (@is_dir($cur_dir)) continue; @mkdir($cur_dir, $mode,true); @chmod($cur_dir, $mode); } return is_dir($path); } function mk_dir($dir, $mode = 0777) { if (is_dir($dir) || @mkdir($dir, $mode)) return true; if (!mk_dir(dirname($dir), $mode)) return false; return @mkdir($dir, $mode); } function dir_copy($fromdir, $todir) { $fromdir = dir_path($fromdir); $todir = dir_path($todir); if (!is_dir($fromdir)) return FALSE; if (!is_dir($todir)) dir_create($todir); $list = glob($fromdir.'*'); if (!empty($list)) { foreach($list as $v) { $path = $todir.basename($v); if(is_dir($v)) { dir_copy($v, $path); } else { copy($v, $path); @chmod($path, 0777); } } } return TRUE; } function dir_list($path, $exts = '', $list= array()) { $path = dir_path($path); $files = glob($path.'*'); foreach($files as $v) { $fileext = fileext($v); if (!$exts || preg_match("/\.($exts)/i", $v)) { $list[] = $v; if (is_dir($v)) { $list = dir_list($v, $exts, $list); } } } return $list; } function dir_tree($dir, $parentid = 0, $dirs = array()) { if ($parentid == 0) $id = 0; $list = glob($dir.'*'); foreach($list as $v) { if (is_dir($v)) { $id++; $dirs[$id] = array('id'=>$id,'parentid'=>$parentid, 'name'=>basename($v), 'dir'=>$v.'/'); $dirs = dir_tree($v.'/', $id, $dirs); } } return $dirs; } function dir_delete($dir) { if (!is_dir($dir)) return FALSE; $handle = opendir($dir); while(($file = readdir($handle)) !== false) { if($file == '.' || $file == '..')continue; $d = $dir.DIRECTORY_SEPARATOR.$file; is_dir($d) ? dir_delete($d) : @unlink($d); } closedir($handle); return @rmdir($dir); } function toDate($time, $format = 'Y-m-d H:i:s') { if (empty ( $time )) { return ''; } $format = str_replace ( '#', ':', $format ); return date ($format, $time ); } function savecache($name = '',$id='') { unlink(RUNTIME_FILE); $Model = M ( $name ); if($name=='Lang'){ $list = $Model->order('listorder')->select (); $pkid = $Model->getPk (); $data = array (); foreach ( $list as $key => $val ) { $data [$val ['mark']] = $val; } F($name,$data); }elseif($name=='Module'){ $list = $Model->order('listorder')->select (); $pkid = $Model->getPk (); $data = array (); foreach ( $list as $key => $val ){ $data [$val [$pkid]] = $val; $smalldata[$val['name']] = $val [$pkid]; } F($name,$data); F('Mod',$smalldata); }elseif($name=='Config'){ $list = $Model->select (); $data=$sysdata=$temp=$memberconfig=array(); foreach($list as $key=>$r) { if($r['groupid']==6){ $sysdata[$r['varname']]=$r['value']; }elseif($r['groupid']==3){ if(APP_LANG) $memberconfig_temp[$r['lang']][$r['varname']]=$r['value']; else $memberconfig[$r['varname']]=$r['value']; }else{ if(APP_LANG) if($r['lang']){$temp[$r['lang']][$r['varname']]=$r['value'];}else{$data[$r['varname']]=$r['value'];} else $data[$r['varname']]=$r['value']; } } if(APP_LANG){ $lang=F('Lang'); foreach((array)$lang as $key=>$r){ $data1=array(); $data1 = array_merge($temp[$r['id']],$data); F('Config_'.$key,$data1); F('member.config_'.$key,$memberconfig_temp[$r['id']]); if(empty($data1['HOME_ISHTML'])){ @unlink('./index.html'); @unlink('./'.$key.'/index.html'); } } }else{ F('Config',$data); F('member.config',$memberconfig); if(empty($data['HOME_ISHTML']))@unlink('./index.html'); } $langs = M('Lang')->field('mark')->select();foreach((array)$langs as $r ) $lang1[]=$r['mark']; $sysdata['LANG_LIST'] = 'zh-cn,'.implode(',',$lang1); F('sys.config',$sysdata); }elseif($name=='Category'){ $data=$smalldata=$temp=array(); if(APP_LANG){ $lang=F('Lang'); foreach((array)$lang as $key=>$r){ $langid =$r['id']; if($langid){ $lang = $key; $list = $Model->where('lang='.$langid)->order('listorder')->select (); $pkid = $Model->getPk (); $data = array (); foreach ( $list as $key => $val ) { $data [$val [$pkid]] = $val; $smalldata[$val['catdir']] = $val [$pkid]; } F('Category_'.$lang,$data); F('Cat_'.$lang,$smalldata); } } }else{ $list = $Model->order('listorder')->select (); $pkid = $Model->getPk (); $data = array (); foreach ( $list as $key => $val ) { $data [$val [$pkid]] = $val; $smalldata[$val['catdir']] = $val [$pkid]; } F($name,$data); F('Cat',$smalldata); } }elseif($name=='Field'){ if($id){ $list = $Model->order('listorder')->where('moduleid='.$id)->select (); $pkid = 'field'; $data = array (); foreach ( $list as $key => $val ) { $data [$val [$pkid]] = $val; } $name=$id.'_'.$name; F($name,$data); }else{ $module = F('Module'); foreach ( $module as $key => $val ) { savecache($name,$key); } } }elseif($name=='Dbsource'){ $list = $Model->select (); $data = array (); foreach ( $list as $key => $val ) { $data [$val ['name']] = $val; } F($name,$data); }else{ $list = $Model->order('listorder')->select (); $pkid = $Model->getPk (); $data = array (); foreach ( $list as $key => $val ) { $data [$val [$pkid]] = $val; } F($name,$data); if($name=='Urlrule'){ $config = F('sys.config'); if($config['URL_URLRULE'])routes_cache($config['URL_URLRULE']); } } return true; } function checkfield($fields,$postdata){ foreach ( $postdata as $key => $val ) { $setup=$fields[$key]['setup']; if(!empty($fields[$key]['required']) && empty($postdata[$key])) return ''; if($setup['multiple'] || $setup['inputtype']=='checkbox' || $fields[$key]['type']=='checkbox'){ $postdata[$key] = implode(',',$postdata[$key]); }elseif($fields[$key]['type']=='datetime'){ $postdata[$key] =strtotime($postdata[$key]); }elseif($fields[$key]['type']=='textarea'){ $postdata[$key]=addslashes_array($postdata[$key]); }elseif($fields[$key]['type']=='images' || $fields[$key]['type']=='files'){ $name = $key.'_name'; $arrdata =array(); foreach($postdata[$key] as $k=>$res){ if(!empty($postdata[$key][$k])) $arrdata[]= safe_replace(strip_tags($postdata[$key][$k].'|'.$postdata[$name][$k])); } $postdata[$key]=implode(':::',$arrdata); }elseif($fields[$key]['type']=='editor'){ if(isset($postdata['add_description']) && $postdata['description'] == '' && isset($postdata['content'])) { $content = stripslashes($postdata['content']); $description_length = intval($postdata['description_length']); $postdata['description'] = str_cut(str_replace(array("\r\n","\t",'[page]','[/page]','&ldquo;','&rdquo;'), '', strip_tags($content)),$description_length); $postdata['description'] = addslashes_array($postdata['description']); } if(isset($postdata['auto_thumb']) && $postdata['thumb'] == '' && isset($postdata['content'])) { $content = $content ? $content : stripslashes($postdata['content']); $auto_thumb_no = intval($postdata['auto_thumb_no']) * 3; if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) { $postdata['thumb'] = $matches[$auto_thumb_no][0]; } } }elseif($fields[$key]['type']=='title' || $fields[$key]['type']=='text'){ $postdata[$key] = safe_replace(strip_tags($postdata[$key])); } } return $postdata; } function string2array($info) { if($info == '') return array(); $info=stripcslashes($info); eval("\$r = $info;"); return $r; } function array2string($info) { if($info == '') return ''; if(!is_array($info)) $string = stripslashes($info); foreach($info as $key => $val) $string[$key] = stripslashes($val); return addslashes(var_export($string, TRUE)); } function rand_string($len = 6, $type = '', $addChars = '') { $str = ''; switch ($type) { case 0 : $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars; break; case 1 : $chars = str_repeat ( '0123456789', 3 ); break; case 2 : $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars; break; case 3 : $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars; break; default : $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars; break; } if ($len > 10) { $chars = $type == 1 ? str_repeat ( $chars, $len ) : str_repeat ( $chars, 5 ); } if ($type != 4) { $chars = str_shuffle ( $chars ); $str = substr ( $chars, 0, $len ); } else { for($i = 0; $i < $len; $i ++) { $str .= msubstr ( $chars, floor ( mt_rand ( 0, mb_strlen ( $chars, 'utf-8' ) - 1 ) ), 1 ); } } return $str; } function sysmd5($str,$key='',$type='sha1'){ $key = $key ? $key : C('ADMIN_ACCESS'); return hash ( $type, $str.$key ); } function pwdHash($password, $type = 'md5') { return hash ( $type, $password ); } function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) { $ckey_length = 4; $keya = md5(substr($key, 0, 16)); $keyb = md5(substr($key, 16, 16)); $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : ''; $cryptkey = $keya.md5($keya.$keyc); $key_length = strlen($cryptkey); $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string; $string_length = strlen($string); $result = ''; $box = range(0, 255); $rndkey = array(); for($i = 0; $i <= 255; $i++) { $rndkey[$i] = ord($cryptkey[$i % $key_length]); } for($j = $i = 0; $i < 256; $i++) { $j = ($j + $box[$i] + $rndkey[$i]) % 256; $tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp; } for($a = $j = $i = 0; $i < $string_length; $i++) { $a = ($a + 1) % 256; $j = ($j + $box[$a]) % 256; $tmp = $box[$a]; $box[$a] = $box[$j]; $box[$j] = $tmp; $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); } if($operation == 'DECODE') { if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) { return substr($result, 26); } else { return ''; } } else { return $keyc.str_replace('=', '', base64_encode($result)); } } function str_cut($sourcestr,$cutlength,$suffix='...') { $str_length = strlen($sourcestr); if($str_length <= $cutlength) { return $sourcestr; } $returnstr=''; $n = $i = $noc = 0; while($n < $str_length) { $t = ord($sourcestr[$n]); if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) { $i = 1; $n++; $noc++; } elseif(194 <= $t && $t <= 223) { $i = 2; $n += 2; $noc += 2; } elseif(224 <= $t && $t <= 239) { $i = 3; $n += 3; $noc += 2; } elseif(240 <= $t && $t <= 247) { $i = 4; $n += 4; $noc += 2; } elseif(248 <= $t && $t <= 251) { $i = 5; $n += 5; $noc += 2; } elseif($t == 252 || $t == 253) { $i = 6; $n += 6; $noc += 2; } else { $n++; } if($noc >= $cutlength) { break; } } if($noc > $cutlength) { $n -= $i; } $returnstr = substr($sourcestr, 0, $n); if ( substr($sourcestr, $n, 6)){ $returnstr = $returnstr . $suffix; } return $returnstr; } function IP($ip='',$file='UTFWry.dat') { import("@.ORG.IpLocation"); $iplocation = new IpLocation($file); $location = $iplocation->getlocation($ip); return $location; } function byte_format($input, $dec=0) { $prefix_arr = array("B", "K", "M", "G", "T"); $value = round($input, $dec); $i=0; while ($value>1024) { $value /= 1024; $i++; } $return_str = round($value, $dec).$prefix_arr[$i]; return $return_str; } function build_verify ($length=4,$mode=1) { return rand_string($length,$mode); } function make_urlrule($url,$lang,$action,$MOREREQUEST=''){ preg_match_all ("/{([\w\$]+)}/",$url, $matches); if(strstr($url,'{$parentdir') && C('URL_PATHINFO_DEPR')=='/'){ if(APP_LANG){ foreach((array)$lang as $r){ $Category = F('Category_'.$r); foreach((array)$Category as $key =>$r){ if($r['parentid']==0)$pcatdir[]=$r['catdir']; } } }else{ $Category = F('Category'); foreach((array)$Category as $key =>$r){ if($r['parentid']==0)$pcatdir[]=$r['catdir']; } } unset($Category); $parent_rule = '('.implode('|',$pcatdir).')\/'; } $REQUEST=str_replace(array('{$parentdir}','{$module}','{$moduleid}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$id}','{$page}'),array('','module','moduleid','catdir','year','month','day','catid','id',C('VAR_PAGE')),$matches[0]); $rule=str_replace(array('{$parentdir}','{$module}','{$moduleid}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$id}','{$page}','/',C('URL_HTML_SUFFIX')),array('','([A-Z]{1}[a-z]+)','(\d+)','([\w^_]+)','(\d+)','(\d+)','(\d+)','(\d+)','(\d+)','(\d+)','\/',''),$url); $i=0;$j=1;$k=2;$n=3;$m=4; foreach($REQUEST as $key =>$r){ if($r){ $i=$i+1; $request .=$r.'=:'.$i.'&'; $j=$j+1; $request_lang .=$r.'=:'.$j.'&'; $k=$k+1; $request_lang_2 .=$r.'=:'.$k.'&'; $n=$n+1; $request_lang_3 .=$r.'=:'.$n.'&'; } } if(APP_LANG){ $langrule = '('.implode('|',$lang).')\/'; if($parent_rule){ $data[] = '\'/^'.$langrule.$parent_rule.'([\w^_]+)\/'.$rule.'$/\' => \'Urlrule/'.$action.'?l=:1&parentdir=:2&'.$request_lang_3.$MOREREQUEST.$langrequest.'\''; $data[] = '\'/^'.$langrule.$parent_rule.$rule.'$/\' => \'Urlrule/'.$action.'?l=:1&parentdir=:2&'.$request_lang_2.$MOREREQUEST.$langrequest.'\''; $data[] = '\'/^'.$parent_rule.'([\w^_]+)\/'.$rule.'$/\' => \'Urlrule/'.$action.'?parentdir=:1&'.$request_lang_2.$MOREREQUEST.$langrequest.'\''; $data[] = '\'/^'.$parent_rule.$rule.'$/\' => \'Urlrule/'.$action.'?parentdir=:1&'.$request_lang.$MOREREQUEST.$langrequest.'\''; if(strstr($url,'{$page')){ $data[] = '\'/^'.$langrule.$parent_rule.'(\d+)$/\' => \'Urlrule/'.$action.'?l=:1&catdir=:2&p=:3\''; $data[] = '\'/^'.$parent_rule.'(\d+)$/\' => \'Urlrule/'.$action.'?catdir=:1&p=:2\''; }else{ $data[] = '\'/^'.$langrule.$parent_rule.'$/\' => \'Urlrule/'.$action.'?l=:1&catdir=:2\''; $data[] = '\'/^'.$parent_rule.'$/\' => \'Urlrule/'.$action.'?catdir=:1\''; } }else{ $data[] = '\'/^'.$langrule.$rule.'$/\' => \'Urlrule/'.$action.'?l=:1&'.$request_lang.$MOREREQUEST.$langrequest.'\''; $data[]='\'/^'.$rule.'$/\' => \'Urlrule/'.$action.'?'.$request.$MOREREQUEST.'\''; } $data = str_replace('\/$','$',$data); $data= implode(",\n",$data); }else{ if($parent_rule){ $data[] = '\'/^'.$parent_rule.'([\w^_]+)\/'.$rule.'$/\' => \'Urlrule/'.$action.'?parentdir=:1&'.$request_lang_2.$MOREREQUEST.$langrequest.'\''; $data[] = '\'/^'.$parent_rule.$rule.'$/\' => \'Urlrule/'.$action.'?parentdir=:1&'.$request_lang.$MOREREQUEST.$langrequest.'\''; if(strstr($url,'{$page')){ $data[] = '\'/^'.$parent_rule.'(\d+)$/\' => \'Urlrule/'.$action.'?catdir=:1&p=:2\''; }else{ $data[] = '\'/^'.$parent_rule.'$/\' => \'Urlrule/'.$action.'?catdir=:1\''; } }else{ $urlrule='\'/^'.$rule.'$/\' => \'Urlrule/'.$action.'?'.$request.$MOREREQUEST.'\''; $data = str_replace('\/$','$',$urlrule); } } return $data; } function routes_cache($URL_URLRULE=''){ $urlstr .= '\':l'.C('URL_PATHINFO_DEPR').'Tags'.C('URL_PATHINFO_DEPR').':module'.C('URL_PATHINFO_DEPR').':tag'.C('URL_PATHINFO_DEPR').':p\' => \'Home/Tags/index\','."\n"; $urlstr .= '\':l'.C('URL_PATHINFO_DEPR').'Tags'.C('URL_PATHINFO_DEPR').':tag'.C('URL_PATHINFO_DEPR').':p\' => \'Home/Tags/index\','."\n"; $urlstr .= '\':l'.C('URL_PATHINFO_DEPR').'Tags'.C('URL_PATHINFO_DEPR').':module'.C('URL_PATHINFO_DEPR').':tag\' => \'Home/Tags/index\','."\n"; $urlstr .= '\':l'.C('URL_PATHINFO_DEPR').'Tags'.C('URL_PATHINFO_DEPR').':p\d\' => \'Home/Tags/index\','."\n"; $urlstr .= '\':l'.C('URL_PATHINFO_DEPR').'Tags'.C('URL_PATHINFO_DEPR').':tag\' => \'Home/Tags/index\','."\n"; $urlstr .= '\':l'.C('URL_PATHINFO_DEPR').'Tags\' => \'Home/Tags/index\','."\n"; $urlstr .= '\'Tags'.C('URL_PATHINFO_DEPR').':module'.C('URL_PATHINFO_DEPR').':tag'.C('URL_PATHINFO_DEPR').':p\' => \'Home/Tags/index\','."\n"; $urlstr .= '\'Tags'.C('URL_PATHINFO_DEPR').':tag'.C('URL_PATHINFO_DEPR').':p\' => \'Home/Tags/index\','."\n"; $urlstr .= '\'Tags'.C('URL_PATHINFO_DEPR').':module'.C('URL_PATHINFO_DEPR').':tag\' => \'Home/Tags/index\','."\n"; $urlstr .= '\'Tags'.C('URL_PATHINFO_DEPR').':p\d\' => \'Home/Tags/index\','."\n"; $urlstr .= '\'Tags'.C('URL_PATHINFO_DEPR').':tag\' => \'Home/Tags/index\','."\n"; $urlstr .= '\'Tags\' => \'Home/Tags/index\','."\n"; if(APP_LANG){ $Lang=F('Lang'); foreach((array)$Lang as $key =>$r){$langarr[]=$key;} $urlstr .= '\'/^('.implode('|',$langarr).')$/\' => \'Index/index?l=:1\','."\n"; } $URL_URLRULE = $URL_URLRULE ? $URL_URLRULE : C('URL_URLRULE'); $urlrule = is_array($URL_URLRULE) ? $URL_URLRULE : explode(':::',$URL_URLRULE); $list=explode('|',$urlrule[1]); $show=explode('|',$urlrule[0]); $listurls[]= make_urlrule($show[1],$langarr,'show'); $listurls[]= make_urlrule($show[0],$langarr,'show'); $listurls[]= make_urlrule($list[1],$langarr,'index'); $listurls[]= make_urlrule($list[0],$langarr,'index'); $url = implode(",\n",$listurls); file_put_contents(DATA_PATH.'Routes.php', "<?php\nreturn array(\n" . $urlstr.$url . "\n);\n?>"); if(is_file(RUNTIME_PATH.'~runtime.php'))@unlink(RUNTIME_PATH.'~runtime.php'); if(is_file(RUNTIME_PATH.'~allinone.php'))@unlink(RUNTIME_PATH.'~allinone.php'); } function HOMEURL($lang){ if(C('URL_M')==1)$index='/index.php/'; $lang= C('URL_LANG')!=$lang ? $lang : ''; if(C('URL_M') > 0){ $url =$lang ? __ROOT__.$index.$lang.'/' : __ROOT__.'/'; }else{ if(C('HOME_ISHTML')){ $url = $lang ? '/'.$lang.'/' : '/'; }else{ $url =$lang ? __ROOT__.'/index.php?l='.$lang : __ROOT__.'/'; } } return $url; } function URL($url='',$params=array()) { if(APP_LANG)$lang = getlang(); if(!empty($url)){ list($path, $query) = explode('?',$url); list($group, $a) = explode('/',$path); list($g, $m) = explode('-',$group); $params= http_build_query($params); $params = !empty($params) ? '&' . $params : ''; $query = !empty($query) ? '&'.$query : ''; if($lang) $langurl = '&l='.$lang; if (strcasecmp($g,'Home')== 0){ $url = __ROOT__.'/index.php?m='.$m.'&a='.$a.$query.$params.$langurl; }else{ $url = __ROOT__.'/index.php?g='.$g.'&m='.$m.'&a='.$a.$query.$params.$langurl; } }else{ if(C('URL_M')==1)$index='/index.php/'; if(C('URL_M') > 0){ $url = $lang ? __ROOT__.$index.$lang.'/' : __ROOT__.'/'; }else{ $url = $lang ? __ROOT__.'/index.php?l='.$lang : __ROOT__.'/'; } } return $url; } function TAGURL($data,$p=''){ $index= C('URL_M')==1 ? __ROOT__.'index.php/' : __ROOT__.'/'; if(APP_LANG)$lang=getlang(); if(C('URL_M')==0){ if($data['moduleid'] > 0 && $data['moduleid']!=2) $params['moduleid']=$data['moduleid'] ; if($data['slug']) $params['tag']=$data['slug'] ; if($lang)$params['l']=$lang; $url=URL('Home-Tags/index',$params); if($p)$url=$url.'&p={$page}'; }else{ $tag = $data['slug'] ? '/'.$data['slug'] : ''; $module = ($data['moduleid'] > 0 && $data['moduleid']!=2) ? '/'.$data['module'] : ''; $langurl = $lang ? $lang.'/' : '' ; $url=$index.$langurl.'Tags'.$module.$tag.'/'; if($p)$url=$url.'{$page}'.C('URL_HTML_SUFFIX'); } return $url; } function getlang($have=''){ if($have){ if(strcasecmp(GROUP_NAME,'Admin')== 0) $lang = LANG_NAME; else $lang = $_REQUEST['l'] ? $_REQUEST['l'] : C('URL_LANG'); }else{ if(strcasecmp(GROUP_NAME,'Admin')== 0) $lang = C('URL_LANG')!= LANG_NAME ? LANG_NAME : ''; else $lang = $_REQUEST['l'] && C('URL_LANG')!=$_REQUEST['l'] ? $_REQUEST['l'] : ''; } return $lang; } function geturl($cat,$data='',$Urlrule=''){ $id=$data['id']; $URL_MODEL =C('URL_M'); if(APP_LANG)$lang = getlang(); $parentdir = $cat['parentdir']; $catdir = $cat['catdir']; $year = date('Y',$data['createtime']); $month = date('m',$data['createtime']); $day = date('d',$data['createtime']); $module = $cat['module']; $moduleid =$cat['moduleid']; $catid=$cat['id']; if($cat['ishtml']){ if($cat['urlruleid'] && $Urlrule){ $showurlrule = $Urlrule[$cat['urlruleid']]['showurlrule']; $listurlrule = $Urlrule[$cat['urlruleid']]['listurlrule']; }else{ echo 'This cat has not urlruleid or no Urlrule.';exit; } }else{ if($URL_MODEL==0){ $langurl = $lang ? '&l='.LANG_NAME : ''; if($id){ $url[] = U("Home/$cat[module]/show?id=$id".$langurl); $url[] = U("Home/$cat[module]/show?id=".$id.$langurl.'&'.C('VAR_PAGE').'={$page}'); }else{ $url[] = U("Home/$cat[module]/index?id=$cat[id]".$langurl); $url[] = U("Home/$cat[module]/index?id=$cat[id]$langurl&".C('VAR_PAGE').'={$page}'); } $urls = str_replace('g=Admin&','',$url); $urls = str_replace('g=Home&','',$url); }else{ $urlrule = explode(':::',C('URL_URLRULE')); $showurlrule = $urlrule[0]; $listurlrule = $urlrule[1]; } } if(empty($urls)){ $index = $URL_MODEL==1 ? __ROOT__.'/index.php/' : __ROOT__.'/'; $langurl = $lang ? $lang.'/' : ''; if($id){ $urls = str_replace(array('{$parentdir}','{$module}','{$moduleid}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$id}'),array($parentdir,$module,$moduleid,$catdir,$year,$month,$day,$catid,$id),$showurlrule); }else{ $urls = str_replace(array('{$parentdir}','{$module}','{$moduleid}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$id}'),array($parentdir,$module,$moduleid,$catdir,$year,$month,$day,$catid,$id),$listurlrule); } $urls = explode('|',$urls); $urls[0]=$index.$langurl.$urls[0]; $urls[1]=$index.$langurl.$urls[1]; } return $urls; } function content_pages($num, $p,$pageurls) { $multipage = ''; $page = 11; $offset = 4; $pages = $num; $from = $p - $offset; $to = $p + $offset; $more = 0; if($page >= $pages) { $from = 2; $to = $pages-1; } else { if($from <= 1) { $to = $page-1; $from = 2; } elseif($to >= $pages) { $from = $pages-($page-2); $to = $pages-1; } $more = 1; } if($p>0) { $perpage = $p == 1 ? 1 : $p-1; if($perpage==1){ $multipage .= '<a class="a1" href="'.$pageurls[$perpage][0].'">'.L('previous').'</a>'; }else{ $multipage .= '<a class="a1" href="'.$pageurls[$perpage][1].'">'.L('previous').'</a>'; } if($p==1) { $multipage .= ' <span>1</span>'; } elseif($p>6 && $more) { $multipage .= ' <a href="'.$pageurls[1][0].'">1</a>..'; } else { $multipage .= ' <a href="'.$pageurls[1][0].'">1</a>'; } } for($i = $from; $i <= $to; $i++) { if($i != $p) { $multipage .= ' <a href="'.$pageurls[$i][1].'">'.$i.'</a>'; } else { $multipage .= ' <span>'.$i.'</span>'; } } if($p<$pages) { if($p<$pages-5 && $more) { $multipage .= ' ..<a href="'.$pageurls[$pages][1].'">'.$pages.'</a> <a class="a1" href="'.$pageurls[$p+1][1].'">'.L('next').'</a>'; } else { $multipage .= ' <a href="'.$pageurls[$pages][1].'">'.$pages.'</a> <a class="a1" href="'.$pageurls[$p+1][1].'">'.L('next').'</a>'; } } elseif($p==$pages) { $multipage .= ' <span>'.$pages.'</span> <a class="a1" href="'.$pageurls[$p][1].'">'.L('next').'</a>'; } return $multipage; } function thumb($f, $tw=300, $th=300 ,$autocat=0, $nopic = 'nopic.jpg',$t=''){ if(strstr($f,'://')) return $f; if(empty($f)) return __ROOT__.'/Public/Images/'.$nopic; $f= '.'.str_replace(__ROOT__,'',$f); $temp = array(1=>'gif', 2=>'jpeg', 3=>'png'); list($fw, $fh, $tmp) = getimagesize($f); if(empty($t)){ if($fw>$tw && $fh>$th){ $pathinfo = pathinfo($f); $t = $pathinfo['dirname'].'/thumb_'.$tw.'_'.$th.'_'.$pathinfo['basename']; if(is_file($t)){ return __ROOT__.substr($t,1); } }else{ return __ROOT__.substr($f,1); } } if(!$temp[$tmp]){ return false; } if($autocat){ if($fw/$tw > $fh/$th){ $fw = $tw * ($fh/$th); }else{ $fh = $th * ($fw/$tw); } }else{ $scale = min($tw/$fw, $th/$fh); if($scale>=1) { $tw = $fw; $th = $fh; }else{ $tw = (int)($fw*$scale); $th = (int)($fh*$scale); } } $tmp = $temp[$tmp]; $infunc = "imagecreatefrom$tmp"; $outfunc = "image$tmp"; $fimg = $infunc($f); if($tmp != 'gif' && function_exists('imagecreatetruecolor')){ $timg = imagecreatetruecolor($tw, $th); }else{ $timg = imagecreate($tw, $th); } if(function_exists('imagecopyresampled')) imagecopyresampled($timg, $fimg, 0,0, 0,0, $tw,$th, $fw,$fh); else imagecopyresized($timg, $fimg, 0,0, 0,0, $tw,$th, $fw,$fh); if($tmp=='gif' || $tmp=='png') { $background_color = imagecolorallocate($timg, 0, 255, 0); imagecolortransparent($timg, $background_color); } $outfunc($timg, $t); imagedestroy($timg); imagedestroy($fimg); return __ROOT__.substr($t,1); } function ubb2html($sUBB) { $sHtml=$sUBB; global $emotPath,$cnum,$arrcode,$bUbb2htmlFunctionInit;$cnum=0;$arrcode=array(); $emotPath='../xheditor_emot/'; if(!$bUbb2htmlFunctionInit){ function saveCodeArea($match) { global $cnum,$arrcode; $cnum++;$arrcode[$cnum]=$match[0]; return "[\tubbcodeplace_".$cnum."\t]"; }} $sHtml=preg_replace_callback('/\[code\s*(?:=\s*((?:(?!")[\s\S])+?)(?:"[\s\S]*?)?)?\]([\s\S]*?)\[\/code\]/i','saveCodeArea',$sHtml); $sHtml=preg_replace("/&/",'&amp;',$sHtml); $sHtml=preg_replace("/</",'&lt;',$sHtml); $sHtml=preg_replace("/>/",'&gt;',$sHtml); $sHtml=preg_replace("/\r?\n/",'<br />',$sHtml); $sHtml=preg_replace("/\[(\/?)(b|u|i|s|sup|sub)\]/i",'<$1$2>',$sHtml); $sHtml=preg_replace('/\[color\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i','<span style="color:$1;">',$sHtml); if(!$bUbb2htmlFunctionInit){ function getSizeName($match) { $arrSize=array('10px','13px','16px','18px','24px','32px','48px'); if(preg_match("/^\d+$/",$match[1]))$match[1]=$arrSize[$match[1]-1]; return '<span style="font-size:'.$match[1].';">'; }} $sHtml=preg_replace_callback('/\[size\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i','getSizeName',$sHtml); $sHtml=preg_replace('/\[font\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i','<span style="font-family:$1;">',$sHtml); $sHtml=preg_replace('/\[back\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i','<span style="background-color:$1;">',$sHtml); $sHtml=preg_replace("/\[\/(color|size|font|back)\]/i",'</span>',$sHtml); for($i=0;$i<3;$i++)$sHtml=preg_replace('/\[align\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\](((?!\[align(?:\s+[^\]]+)?\])[\s\S])*?)\[\/align\]/','<p align="$1">$2</p>',$sHtml); $sHtml=preg_replace('/\[img\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/img\]/i','<img src="$1" alt="" />',$sHtml); if(!$bUbb2htmlFunctionInit){ function getImg($match) { $alt=$match[1];$p1=$match[2];$p2=$match[3];$p3=$match[4];$src=$match[5]; $a=$p3?$p3:(!is_numeric($p1)?$p1:''); return '<img src="'.$src.'" alt="'.$alt.'"'.(is_numeric($p1)?' width="'.$p1.'"':'').(is_numeric($p2)?' height="'.$p2.'"':'').($a?' align="'.$a.'"':'').' />'; }} $sHtml=preg_replace_callback('/\[img\s*=([^,\]]*)(?:\s*,\s*(\d*%?)\s*,\s*(\d*%?)\s*)?(?:,?\s*(\w+))?\s*\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*)?\s*\[\/img\]/i','getImg',$sHtml); if(!$bUbb2htmlFunctionInit){ function getEmot($match) { global $emotPath; $arr=split(',',$match[1]); if(!isset($arr[1])){$arr[1]=$arr[0];$arr[0]='default';} $path=$emotPath.$arr[0].'/'.$arr[1].'.gif'; return '<img src="'.$path.'" alt="'.$arr[1].'" />'; }} $sHtml=preg_replace_callback('/\[emot\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\/\]/i','getEmot',$sHtml); $sHtml=preg_replace('/\[url\]\s*(((?!")[\s\S])*?)(?:"[\s\S]*?)?\s*\[\/url\]/i','<a href="$1">$1</a>',$sHtml); $sHtml=preg_replace('/\[url\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]\s*([\s\S]*?)\s*\[\/url\]/i','<a href="$1">$2</a>',$sHtml); $sHtml=preg_replace('/\[email\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/email\]/i','<a href="mailto:$1">$1</a>',$sHtml); $sHtml=preg_replace('/\[email\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]\s*([\s\S]+?)\s*\[\/email\]/i','<a href="mailto:$1">$2</a>',$sHtml); $sHtml=preg_replace("/\[quote\]([\s\S]*?)\[\/quote\]/i",'<blockquote>$1</blockquote>',$sHtml); if(!$bUbb2htmlFunctionInit){ function getFlash($match) { $w=$match[1];$h=$match[2];$url=$match[3]; if(!$w)$w=480;if(!$h)$h=400; return '<embed type="application/x-shockwave-flash" src="'.$url.'" wmode="opaque" quality="high" bgcolor="#ffffff" menu="false" play="true" loop="true" width="'.$w.'" height="'.$h.'" />'; }} $sHtml=preg_replace_callback('/\[flash\s*(?:=\s*(\d+)\s*,\s*(\d+)\s*)?\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/flash\]/i','getFlash',$sHtml); if(!$bUbb2htmlFunctionInit){ function getMedia($match) { $w=$match[1];$h=$match[2];$play=$match[3];$url=$match[4]; if(!$w)$w=480;if(!$h)$h=400; return '<embed type="application/x-mplayer2" src="'.$url.'" enablecontextmenu="false" autostart="'.($play=='1'?'true':'false').'" width="'.$w.'" height="'.$h.'" />'; }} $sHtml=preg_replace_callback('/\[media\s*(?:=\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+)\s*)?)?\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/media\]/i','getMedia',$sHtml); if(!$bUbb2htmlFunctionInit){ function getTable($match) { return '<table'.(isset($match[1])?' width="'.$match[1].'"':'').(isset($match[2])?' bgcolor="'.$match[2].'"':'').'>'; }} $sHtml=preg_replace_callback('/\[table\s*(?:=(\d{1,4}%?)\s*(?:,\s*([^\]"]+)(?:"[^\]]*?)?)?)?\s*\]/i','getTable',$sHtml); if(!$bUbb2htmlFunctionInit){ function getTR($match){return '<tr'.(isset($match[1])?' bgcolor="'.$match[1].'"':'').'>';}} $sHtml=preg_replace_callback('/\[tr\s*(?:=(\s*[^\]"]+))?(?:"[^\]]*?)?\s*\]/i','getTR',$sHtml); if(!$bUbb2htmlFunctionInit){ function getTD($match){ $col=isset($match[1])?$match[1]:0;$row=isset($match[2])?$match[2]:0;$w=isset($match[3])?$match[3]:null; return '<td'.($col>1?' colspan="'.$col.'"':'').($row>1?' rowspan="'.$row.'"':'').($w?' width="'.$w.'"':'').'>'; }} $sHtml=preg_replace_callback("/\[td\s*(?:=\s*(\d{1,2})\s*,\s*(\d{1,2})\s*(?:,\s*(\d{1,4}%?))?)?\s*\]/i",'getTD',$sHtml); $sHtml=preg_replace("/\[\/(table|tr|td)\]/i",'</$1>',$sHtml); $sHtml=preg_replace("/\[\*\]((?:(?!\[\*\]|\[\/list\]|\[list\s*(?:=[^\]]+)?\])[\s\S])+)/i",'<li>$1</li>',$sHtml); if(!$bUbb2htmlFunctionInit){ function getUL($match) { $str='<ul'; if(isset($match[1]))$str.=' type="'.$match[1].'"'; return $str.'>'; }} $sHtml=preg_replace_callback('/\[list\s*(?:=\s*([^\]"]+))?(?:"[^\]]*?)?\s*\]/i','getUL',$sHtml); $sHtml=preg_replace("/\[\/list\]/i",'</ul>',$sHtml); $sHtml=preg_replace("/\[hr\/\]/i",'<hr />',$sHtml); for($i=1;$i<=$cnum;$i++)$sHtml=str_replace("[\tubbcodeplace_".$i."\t]", $arrcode[$i],$sHtml); if(!$bUbb2htmlFunctionInit){ function fixText($match) { $text=$match[2]; $text=preg_replace("/\t/",'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',$text); $text=preg_replace("/ /",'&nbsp;',$text); return $match[1].$text; }} $sHtml=preg_replace_callback('/(^|<\/?\w+(?:\s+[^>]*?)?>)([^<$]+)/i','fixText',$sHtml); $bUbb2htmlFunctionInit=true; return $sHtml; } function Pinyin($_String) { $_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha". "|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|". "cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er". "|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui". "|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang". "|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang". "|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue". "|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne". "|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen". "|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang". "|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|". "she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|". "tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu". "|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you". "|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|". "zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo"; $_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990". "|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725". "|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263". "|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003". "|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697". "|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211". "|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922". "|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468". "|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664". "|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407". "|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959". "|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652". "|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369". "|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128". "|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914". "|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645". "|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149". "|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087". "|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658". "|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340". "|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888". "|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585". "|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847". "|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055". "|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780". "|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274". "|-10270|-10262|-10260|-10256|-10254"; $_TDataKey = explode('|', $_DataKey); $_TDataValue = explode('|', $_DataValue); $_Data = array_combine($_TDataKey, $_TDataValue); arsort($_Data); reset($_Data); $_String= auto_charset($_String,'utf-8','gbk'); $_Res = ''; for($i=0; $i<strlen($_String); $i++) { $_P = ord(substr($_String, $i, 1)); if($_P>160) { $_Q = ord(substr($_String, ++$i, 1)); $_P = $_P*256 + $_Q - 65536; } $_Res .= _Pinyin($_P, $_Data); } return preg_replace("/[^a-z0-9]*/", '', $_Res); } function auto_charset($fContents, $from='gbk', $to='utf-8') { $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; } } function _Pinyin($_Num, $_Data) { if ($_Num>0 && $_Num<160 ) return chr($_Num); elseif($_Num<-20319 || $_Num>-10247) return ''; else { foreach($_Data as $k=>$v){ if($v<=$_Num) break; } return $k; } } function return_url($code){ $config = APP_LANG ? F('Config_'.LANG_NAME) : F('Config'); return $config['site_url'].'/index.php?g=User&m=Pay&a=respond&code='.$code; } function order_pay_status($sn,$value){ $cart['status'] =1; $cart['pay_status'] =$value; if($value==2)$cart['pay_time'] =time(); $r = M('Order')->where("sn='{$sn}'")->save($cart); return $r; } function addslashes_array($array){ if(get_magic_quotes_gpc())return $array; if(!is_array($array))return addslashes($array); foreach($array as $k => $val) $array[$k] = addslashes_array($val); return $array; } function stripslashes_array($array) { if(!is_array($array)) return stripslashes($array); foreach($array as $k => $val) $array[$k] = stripslashes_array($val); return $array; } function htmlspecialchars_array($array) { if(!is_array($array)) return htmlspecialchars($array,ENT_QUOTES); foreach($array as $k => $val) $array[$k] = htmlspecialchars_array($val); return $array; } function safe_replace($string) { $string = trim($string); $string = str_replace(array('\\',';','\'','%2527','%27','%20','&', '"', '<', '>'), array('','','','','','','&amp;', '&quot;', '&lt;', '&gt;'), $string); $string=nl2br($string); return $string; } function get_safe_replace($array){ if(!is_array($array)) return safe_replace(strip_tags($array)); foreach($array as $k => $val) $array[$k] = get_safe_replace($val); return $array; } function sql_split($sql,$tablepre) { if($tablepre != "aina_") $sql = str_replace("aina_", $tablepre, $sql); if($r_tablepre != $s_tablepre) $sql = str_replace($s_tablepre, $r_tablepre, $sql); $sql = str_replace("\r", "\n", $sql); $ret = array(); $num = 0; $queriesarray = explode(";\n", trim($sql)); unset($sql); foreach($queriesarray as $query) { $ret[$num] = ''; $queries = explode("\n", trim($query)); $queries = array_filter($queries); foreach($queries as $query) { $str1 = substr($query, 0, 1); if($str1 != '#' && $str1 != '-') $ret[$num] .= $query; } $num++; } return $ret; } function prevnext($mod,$id,$catid,$num=''){ $prev = D($mod)->where("id < $id and catid = $catid")->order("id desc")->find(); $next = D($mod)->where("id > $id and catid = $catid")->order("id asc")->find(); if(!$prev){ $prev[content] = '没有了'; }else{ if($num){ $prev[sort_title] = str_cut($prev[title],$num); }else{ $prev[sort_title] = $prev[title]; } $prev[content] = '<a href="'.$prev[url].'" title="'.$prev[title].'">'.$prev[sort_title].'</a>'; } if(!$next){ $next[content] = '没有了'; }else{ if($num){ $next[sort_title] = str_cut($next[title],$num); }else{ $next[sort_title] = $next[title]; } $next[content] = '<a href="'.$next[url].'" title="'.$next[title].'">'.$next[sort_title].'</a>'; } $prevnext = "<p class=\"fl\">上一篇:$prev[content]</p><p class=\"fr\">下一篇:$next[content]</p>"; return $prevnext; } function exportexcel($data=array(),$title=array(),$filename='report'){ header("Content-type:application/octet-stream"); header("Accept-Ranges:bytes"); header("Content-type:application/vnd.ms-excel"); header("Content-Disposition:attachment;filename=".$filename.".xls"); header("Pragma: no-cache"); header("Expires: 0"); if (!empty($title)){ foreach ($title as $k => $v) { $title[$k]=iconv("UTF-8", "GB2312",$v); } $title= implode("\t", $title); echo "$title\n"; } if (!empty($data)){ foreach($data as $key=>$val){ foreach ($val as $ck => $cv) { $data[$key][$ck]=iconv("UTF-8", "GB2312", $cv); } $data[$key]=implode("\t", $data[$key]); } echo implode("\n",$data); } } function xml_to_array($xml) { $reg = "/<(\\w+)[^>]*?>([\\x00-\\xFF]*?)<\\/\\1>/"; if(preg_match_all($reg, $xml, $matches)) { $count = count($matches[0]); $arr = array(); for($i = 0; $i < $count; $i++) { $key = $matches[1][$i]; $val = $this->xml_to_array( $matches[2][$i] ); if(array_key_exists($key, $arr)){ if(is_array($arr[$key])){ if(!array_key_exists(0,$arr[$key])){ $arr[$key] = array($arr[$key]); } }else{ $arr[$key] = array($arr[$key]); } $arr[$key][] = $val; }else{ $arr[$key] = $val; } } return $arr; }else{ return $xml; } } function xmltoarray( $xml ) { $arr = $this->xml_to_array($xml); $key = array_keys($arr); return $arr[$key[0]]; } function checked($arr,$key){ if(in_array($key,$arr)){ return "checked"; } } L(array ( ));C(array ( 'app_status' => 'debug', 'app_file_case' => false, 'app_autoload_path' => '', 'app_tags_on' => true, 'app_sub_domain_deploy' => false, 'app_sub_domain_rules' => array ( ), 'app_sub_domain_deny' => array ( ), 'app_group_list' => 'Home,Admin,User', 'app_group_mode' => 0, 'app_group_path' => 'Modules', 'action_suffix' => '', 'cookie_expire' => '', 'cookie_domain' => '', 'cookie_path' => '/', 'cookie_prefix' => 'YP_', 'default_m_layer' => 'Model', 'default_c_layer' => 'Action', 'default_v_layer' => 'Tpl', 'default_app' => '@', 'default_lang' => 'cn', 'default_theme' => 'Default', 'default_group' => 'Home', 'default_module' => 'Index', 'default_action' => 'index', 'default_charset' => 'utf-8', 'default_timezone' => 'PRC', 'default_ajax_return' => 'JSON', 'default_jsonp_handler' => 'jsonpReturn', 'default_filter' => 'htmlspecialchars', 'db_type' => 'mysql', 'db_host' => 'localhost', 'db_name' => 'bangju_com', 'db_user' => 'bangju_com', 'db_pwd' => 'bangju2015++', 'db_port' => '3306', 'db_prefix' => 'bangju_', 'db_fieldtype_check' => true, 'db_fields_cache' => false, 'db_charset' => 'utf8', 'db_deploy_type' => 0, 'db_rw_separate' => false, 'db_master_num' => 1, 'db_slave_no' => '', 'db_sql_build_cache' => false, 'db_sql_build_queue' => 'file', 'db_sql_build_length' => 20, 'db_sql_log' => false, 'data_cache_time' => 0, 'data_cache_compress' => false, 'data_cache_check' => false, 'data_cache_prefix' => '', 'data_cache_type' => 'File', 'data_cache_path' => './Cache/Temp/', 'data_cache_subdir' => false, 'data_path_level' => 1, 'error_message' => '您浏览的页面暂时发生了错误!请稍后再试~', 'error_page' => '', 'show_error_msg' => false, 'trace_exception' => false, 'log_record' => false, 'log_type' => 3, 'log_dest' => '', 'log_extra' => '', 'log_level' => 'EMERG,ALERT,CRIT,ERR', 'log_file_size' => 2097152, 'log_exception_record' => false, 'session_auto_start' => true, 'session_options' => array ( ), 'session_type' => '', 'session_prefix' => '', 'tmpl_content_type' => 'text/html', 'tmpl_action_error' => './Ainaphp//Tpl/Home/Default/Public/success.html', 'tmpl_action_success' => './Ainaphp//Tpl/Home/Default/Public/success.html', 'tmpl_exception_file' => './Ainaphp//Tpl/Home/Default/Public/exception.html', 'tmpl_detect_theme' => false, 'tmpl_template_suffix' => '.html', 'tmpl_file_depr' => '_', 'url_case_insensitive' => false, 'url_model' => '2', 'url_pathinfo_depr' => '/', 'url_pathinfo_fetch' => 'ORIG_PATH_INFO,REDIRECT_PATH_INFO,REDIRECT_URL', 'url_html_suffix' => '.html', 'url_params_bind' => true, 'var_group' => 'g', 'var_module' => 'm', 'var_action' => 'a', 'var_ajax_submit' => 'ajax', 'var_jsonp_handler' => 'callback', 'var_pathinfo' => 's', 'var_url_params' => '_URL_', 'var_template' => 't', 'var_filters' => 'filter_exp', 'output_encode' => false, 'http_cache_control' => 'private', 'url_router_on' => true, 'lang_switch_on' => true, 'taglib_load' => true, 'taglib_pre_load' => 'Yp', 'var_page' => 'p', 'layout_home_on' => '1', 'url_route_rules' => array ( ':l/Tags/:module/:tag/:p' => 'Home/Tags/index', ':l/Tags/:tag/:p' => 'Home/Tags/index', ':l/Tags/:module/:tag' => 'Home/Tags/index', ':l/Tags/:p\\d' => 'Home/Tags/index', ':l/Tags/:tag' => 'Home/Tags/index', ':l/Tags' => 'Home/Tags/index', 'Tags/:module/:tag/:p' => 'Home/Tags/index', 'Tags/:tag/:p' => 'Home/Tags/index', 'Tags/:module/:tag' => 'Home/Tags/index', 'Tags/:p\\d' => 'Home/Tags/index', 'Tags/:tag' => 'Home/Tags/index', 'Tags' => 'Home/Tags/index', '/^([\\w^_]+)_(\\d+)-(\\d+)$/' => 'Urlrule/show?catdir=:1&id=:2&p=:3&', '/^([\\w^_]+)_(\\d+)$/' => 'Urlrule/show?catdir=:1&id=:2&', '/^([\\w^_]+)-(\\d+)$/' => 'Urlrule/index?catdir=:1&p=:2&', '/^([\\w^_]+)$/' => 'Urlrule/index?catdir=:1&', ), 'page_listrows' => '15', 'token_on' => '0', 'token_name' => '__hash__', 'tmpl_cache_on' => '0', 'tmpl_cache_time' => '-1', 'html_cache_on' => '0', 'html_cache_time' => '60', 'html_read_type' => '0', 'html_file_suffix' => '.html', 'admin_access' => '2e162fa101f424dc6ad3bb6a65a42118', 'home_ishtml' => '0', 'url_urlrule' => '{$catdir}_{$id}.html|{$catdir}_{$id}-{$page}.html:::{$catdir}.html|{$catdir}-{$page}.html', 'layout_on' => '1', 'admin_verify' => '1', 'lang_list' => 'zh-cn,cn', 'extends' => array ( 'app_init' => array ( ), 'app_begin' => array ( 0 => 'ReadHtmlCache', ), 'route_check' => array ( 0 => 'CheckRoute', ), 'app_end' => array ( ), 'path_info' => array ( ), 'action_begin' => array ( ), 'action_end' => array ( ), 'view_begin' => array ( ), 'view_parse' => array ( 0 => 'ParseTemplate', ), 'view_filter' => array ( 0 => 'ContentReplace', 1 => 'TokenBuild', 2 => 'WriteHtmlCache', 3 => 'ShowRuntime', ), 'view_end' => array ( 0 => 'ShowPageTrace', ), ), 'tags' => array ( 'app_begin' => array ( 0 => 'CheckLang', ), ), ));G('loadTime');Think::Start();