code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: TagLibCx.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* CX标签库解析类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Template
* @author liu21st <liu21st@gmail.com>
* @version $Id: TagLibCx.class.php 2702 2012-02-02 12:35:01Z liu21st $
+------------------------------------------------------------------------------
*/
class TagLibCx extends TagLib {
// 标签定义
protected $tags = array(
// 标签定义: attr 属性列表 close 是否闭合(0 或者1 默认1) alias 标签别名 level 嵌套层次
'php'=>array(),
'volist'=>array('attr'=>'name,id,offset,length,key,mod','level'=>3),
'foreach' =>array('attr'=>'name,item,key','level'=>3),
'if'=>array('attr'=>'condition','level'=>2),
'elseif'=>array('attr'=>'condition','close'=>0),
'else'=>array('attr'=>'','close'=>0),
'switch'=>array('attr'=>'name','level'=>2),
'case'=>array('attr'=>'value,break'),
'default'=>array('attr'=>'','close'=>0),
'compare'=>array('attr'=>'name,value,type','level'=>3,'alias'=>'eq,equal,notequal,neq,gt,lt,egt,elt,heq,nheq'),
'range'=>array('attr'=>'name,value,type','level'=>3,'alias'=>'in,notin,between,notbetween'),
'empty'=>array('attr'=>'name','level'=>3),
'notempty'=>array('attr'=>'name','level'=>3),
'present'=>array('attr'=>'name','level'=>3),
'notpresent'=>array('attr'=>'name','level'=>3),
'defined'=>array('attr'=>'name','level'=>3),
'notdefined'=>array('attr'=>'name','level'=>3),
'import'=>array('attr'=>'file,href,type,value,basepath','close'=>0,'alias'=>'load,css,js'),
'assign'=>array('attr'=>'name,value','close'=>0),
'define'=>array('attr'=>'name,value','close'=>0),
'for'=>array('attr'=>'start,end,name,comparison,step', 'level'=>3),
);
/**
+----------------------------------------------------------
* php标签解析
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _php($attr,$content) {
$parseStr = '<?php '.$content.' ?>';
return $parseStr;
}
/**
+----------------------------------------------------------
* volist标签解析 循环输出数据集
* 格式:
* <volist name="userList" id="user" empty="" >
* {user.username}
* {user.email}
* </volist>
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string|void
+----------------------------------------------------------
*/
public function _volist($attr,$content) {
static $_iterateParseCache = array();
//如果已经解析过,则直接返回变量值
$cacheIterateId = md5($attr.$content);
if(isset($_iterateParseCache[$cacheIterateId]))
return $_iterateParseCache[$cacheIterateId];
$tag = $this->parseXmlAttr($attr,'volist');
$name = $tag['name'];
$id = $tag['id'];
$empty = isset($tag['empty'])?$tag['empty']:'';
$key = !empty($tag['key'])?$tag['key']:'i';
$mod = isset($tag['mod'])?$tag['mod']:'2';
// 允许使用函数设定数据集 <volist name=":fun('arg')" id="vo">{$vo.name}</volist>
$parseStr = '<?php ';
if(0===strpos($name,':')) {
$parseStr .= '$_result='.substr($name,1).';';
$name = '$_result';
}else{
$name = $this->autoBuildVar($name);
}
$parseStr .= 'if(is_array('.$name.')): $'.$key.' = 0;';
if(isset($tag['length']) && '' !=$tag['length'] ) {
$parseStr .= ' $__LIST__ = array_slice('.$name.','.$tag['offset'].','.$tag['length'].',true);';
}elseif(isset($tag['offset']) && '' !=$tag['offset']){
$parseStr .= ' $__LIST__ = array_slice('.$name.','.$tag['offset'].',count($__LIST__),true);';
}else{
$parseStr .= ' $__LIST__ = '.$name.';';
}
$parseStr .= 'if( count($__LIST__)==0 ) : echo "'.$empty.'" ;';
$parseStr .= 'else: ';
$parseStr .= 'foreach($__LIST__ as $key=>$'.$id.'): ';
$parseStr .= '$mod = ($'.$key.' % '.$mod.' );';
$parseStr .= '++$'.$key.';?>';
$parseStr .= $this->tpl->parse($content);
$parseStr .= '<?php endforeach; endif; else: echo "'.$empty.'" ;endif; ?>';
$_iterateParseCache[$cacheIterateId] = $parseStr;
if(!empty($parseStr)) {
return $parseStr;
}
return ;
}
public function _foreach($attr,$content) {
static $_iterateParseCache = array();
//如果已经解析过,则直接返回变量值
$cacheIterateId = md5($attr.$content);
if(isset($_iterateParseCache[$cacheIterateId]))
return $_iterateParseCache[$cacheIterateId];
$tag = $this->parseXmlAttr($attr,'foreach');
$name= $tag['name'];
$item = $tag['item'];
$key = !empty($tag['key'])?$tag['key']:'key';
$name= $this->autoBuildVar($name);
$parseStr = '<?php if(is_array('.$name.')): foreach('.$name.' as $'.$key.'=>$'.$item.'): ?>';
$parseStr .= $this->tpl->parse($content);
$parseStr .= '<?php endforeach; endif; ?>';
$_iterateParseCache[$cacheIterateId] = $parseStr;
if(!empty($parseStr)) {
return $parseStr;
}
return ;
}
/**
+----------------------------------------------------------
* if标签解析
* 格式:
* <if condition=" $a eq 1" >
* <elseif condition="$a eq 2" />
* <else />
* </if>
* 表达式支持 eq neq gt egt lt elt == > >= < <= or and || &&
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _if($attr,$content) {
$tag = $this->parseXmlAttr($attr,'if');
$condition = $this->parseCondition($tag['condition']);
$parseStr = '<?php if('.$condition.'): ?>'.$content.'<?php endif; ?>';
return $parseStr;
}
/**
+----------------------------------------------------------
* else标签解析
* 格式:见if标签
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _elseif($attr,$content) {
$tag = $this->parseXmlAttr($attr,'elseif');
$condition = $this->parseCondition($tag['condition']);
$parseStr = '<?php elseif('.$condition.'): ?>';
return $parseStr;
}
/**
+----------------------------------------------------------
* else标签解析
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _else($attr) {
$parseStr = '<?php else: ?>';
return $parseStr;
}
/**
+----------------------------------------------------------
* switch标签解析
* 格式:
* <switch name="a.name" >
* <case value="1" break="false">1</case>
* <case value="2" >2</case>
* <default />other
* </switch>
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _switch($attr,$content) {
$tag = $this->parseXmlAttr($attr,'switch');
$name = $tag['name'];
$varArray = explode('|',$name);
$name = array_shift($varArray);
$name = $this->autoBuildVar($name);
if(count($varArray)>0)
$name = $this->tpl->parseVarFunction($name,$varArray);
$parseStr = '<?php switch('.$name.'): ?>'.$content.'<?php endswitch;?>';
return $parseStr;
}
/**
+----------------------------------------------------------
* case标签解析 需要配合switch才有效
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _case($attr,$content) {
$tag = $this->parseXmlAttr($attr,'case');
$value = $tag['value'];
if('$' == substr($value,0,1)) {
$varArray = explode('|',$value);
$value = array_shift($varArray);
$value = $this->autoBuildVar(substr($value,1));
if(count($varArray)>0)
$value = $this->tpl->parseVarFunction($value,$varArray);
$value = 'case '.$value.': ';
}elseif(strpos($value,'|')){
$values = explode('|',$value);
$value = '';
foreach ($values as $val){
$value .= 'case "'.addslashes($val).'": ';
}
}else{
$value = 'case "'.$value.'": ';
}
$parseStr = '<?php '.$value.' ?>'.$content;
$isBreak = isset($tag['break']) ? $tag['break'] : '';
if('' ==$isBreak || $isBreak) {
$parseStr .= '<?php break;?>';
}
return $parseStr;
}
/**
+----------------------------------------------------------
* default标签解析 需要配合switch才有效
* 使用: <default />ddfdf
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _default($attr) {
$parseStr = '<?php default: ?>';
return $parseStr;
}
/**
+----------------------------------------------------------
* compare标签解析
* 用于值的比较 支持 eq neq gt lt egt elt heq nheq 默认是eq
* 格式: <compare name="" type="eq" value="" >content</compare>
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _compare($attr,$content,$type='eq') {
$tag = $this->parseXmlAttr($attr,'compare');
$name = $tag['name'];
$value = $tag['value'];
$type = isset($tag['type'])?$tag['type']:$type;
$type = $this->parseCondition(' '.$type.' ');
$varArray = explode('|',$name);
$name = array_shift($varArray);
$name = $this->autoBuildVar($name);
if(count($varArray)>0)
$name = $this->tpl->parseVarFunction($name,$varArray);
if('$' == substr($value,0,1)) {
$value = $this->autoBuildVar(substr($value,1));
}else {
$value = '"'.$value.'"';
}
$parseStr = '<?php if(('.$name.') '.$type.' '.$value.'): ?>'.$content.'<?php endif; ?>';
return $parseStr;
}
public function _eq($attr,$content) {
return $this->_compare($attr,$content,'eq');
}
public function _equal($attr,$content) {
return $this->_compare($attr,$content,'eq');
}
public function _neq($attr,$content) {
return $this->_compare($attr,$content,'neq');
}
public function _notequal($attr,$content) {
return $this->_compare($attr,$content,'neq');
}
public function _gt($attr,$content) {
return $this->_compare($attr,$content,'gt');
}
public function _lt($attr,$content) {
return $this->_compare($attr,$content,'lt');
}
public function _egt($attr,$content) {
return $this->_compare($attr,$content,'egt');
}
public function _elt($attr,$content) {
return $this->_compare($attr,$content,'elt');
}
public function _heq($attr,$content) {
return $this->_compare($attr,$content,'heq');
}
public function _nheq($attr,$content) {
return $this->_compare($attr,$content,'nheq');
}
/**
+----------------------------------------------------------
* range标签解析
* 如果某个变量存在于某个范围 则输出内容 type= in 表示在范围内 否则表示在范围外
* 格式: <range name="var|function" value="val" type='in|notin' >content</range>
* example: <range name="a" value="1,2,3" type='in' >content</range>
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
* @param string $type 比较类型
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _range($attr,$content,$type='in') {
$tag = $this->parseXmlAttr($attr,'range');
$name = $tag['name'];
$value = $tag['value'];
$varArray = explode('|',$name);
$name = array_shift($varArray);
$name = $this->autoBuildVar($name);
if(count($varArray)>0)
$name = $this->tpl->parseVarFunction($name,$varArray);
$type = isset($tag['type'])?$tag['type']:$type;
if('$' == substr($value,0,1)) {
$value = $this->autoBuildVar(substr($value,1));
$str = 'is_array('.$value.')?'.$value.':explode(\',\','.$value.')';
}else{
$value = '"'.$value.'"';
$str = 'explode(\',\','.$value.')';
}
if($type=='between') {
$parseStr = '<?php $_RANGE_VAR_='.$str.';if('.$name.'>= $_RANGE_VAR_[0] && '.$name.'<= $_RANGE_VAR_[1]):?>'.$content.'<?php endif; ?>';
}elseif($type=='notbetween'){
$parseStr = '<?php $_RANGE_VAR_='.$str.';if('.$name.'<$_RANGE_VAR_[0] && '.$name.'>$_RANGE_VAR_[1]):?>'.$content.'<?php endif; ?>';
}else{
$fun = ($type == 'in')? 'in_array' : '!in_array';
$parseStr = '<?php if('.$fun.'(('.$name.'), '.$str.')): ?>'.$content.'<?php endif; ?>';
}
return $parseStr;
}
// range标签的别名 用于in判断
public function _in($attr,$content) {
return $this->_range($attr,$content,'in');
}
// range标签的别名 用于notin判断
public function _notin($attr,$content) {
return $this->_range($attr,$content,'notin');
}
public function _between($attr,$content){
return $this->_range($attr,$content,'between');
}
public function _notbetween($attr,$content){
return $this->_range($attr,$content,'notbetween');
}
/**
+----------------------------------------------------------
* present标签解析
* 如果某个变量已经设置 则输出内容
* 格式: <present name="" >content</present>
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _present($attr,$content) {
$tag = $this->parseXmlAttr($attr,'present');
$name = $tag['name'];
$name = $this->autoBuildVar($name);
$parseStr = '<?php if(isset('.$name.')): ?>'.$content.'<?php endif; ?>';
return $parseStr;
}
/**
+----------------------------------------------------------
* notpresent标签解析
* 如果某个变量没有设置,则输出内容
* 格式: <notpresent name="" >content</notpresent>
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _notpresent($attr,$content) {
$tag = $this->parseXmlAttr($attr,'notpresent');
$name = $tag['name'];
$name = $this->autoBuildVar($name);
$parseStr = '<?php if(!isset('.$name.')): ?>'.$content.'<?php endif; ?>';
return $parseStr;
}
/**
+----------------------------------------------------------
* empty标签解析
* 如果某个变量为empty 则输出内容
* 格式: <empty name="" >content</empty>
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _empty($attr,$content) {
$tag = $this->parseXmlAttr($attr,'empty');
$name = $tag['name'];
$name = $this->autoBuildVar($name);
$parseStr = '<?php if(empty('.$name.')): ?>'.$content.'<?php endif; ?>';
return $parseStr;
}
public function _notempty($attr,$content) {
$tag = $this->parseXmlAttr($attr,'notempty');
$name = $tag['name'];
$name = $this->autoBuildVar($name);
$parseStr = '<?php if(!empty('.$name.')): ?>'.$content.'<?php endif; ?>';
return $parseStr;
}
/**
* 判断是否已经定义了该常量
* <defined name='TXT'>已定义</defined>
* @param <type> $attr
* @param <type> $content
* @return string
*/
public function _defined($attr,$content) {
$tag = $this->parseXmlAttr($attr,'defined');
$name = $tag['name'];
$parseStr = '<?php if(defined("'.$name.'")): ?>'.$content.'<?php endif; ?>';
return $parseStr;
}
public function _notdefined($attr,$content) {
$tag = $this->parseXmlAttr($attr,'_notdefined');
$name = $tag['name'];
$parseStr = '<?php if(!defined("'.$name.'")): ?>'.$content.'<?php endif; ?>';
return $parseStr;
}
/**
+----------------------------------------------------------
* import 标签解析 <import file="Js.Base" /> <import file="Css.Base" type="css" />
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
* @param boolean $isFile 是否文件方式
* @param string $type 类型
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _import($attr,$content,$isFile=false,$type='') {
$tag = $this->parseXmlAttr($attr,'import');
$file = isset($tag['file'])?$tag['file']:$tag['href'];
$parseStr = '';
$endStr = '';
// 判断是否存在加载条件 允许使用函数判断(默认为isset)
if (isset($tag['value'])) {
$varArray = explode('|',$tag['value']);
$name = array_shift($varArray);
$name = $this->autoBuildVar($name);
if (!empty($varArray))
$name = $this->tpl->parseVarFunction($name,$varArray);
else
$name = 'isset('.$name.')';
$parseStr .= '<?php if('.$name.'): ?>';
$endStr = '<?php endif; ?>';
}
if($isFile) {
// 根据文件名后缀自动识别
$type = $type?$type:(!empty($tag['type'])?strtolower($tag['type']):null);
// 文件方式导入
$array = explode(',',$file);
foreach ($array as $val){
if (!$type || isset($reset)) {
$type = $reset = strtolower(substr(strrchr($val, '.'),1));
}
switch($type) {
case 'js':
$parseStr .= '<script type="text/javascript" src="'.$val.'"></script>';
break;
case 'css':
$parseStr .= '<link rel="stylesheet" type="text/css" href="'.$val.'" />';
break;
case 'php':
$parseStr .= '<?php require_cache("'.$val.'"); ?>';
break;
}
}
}else{
// 命名空间导入模式 默认是js
$type = $type?$type:(!empty($tag['type'])?strtolower($tag['type']):'js');
$basepath = !empty($tag['basepath'])?$tag['basepath']:__ROOT__.'/Public';
// 命名空间方式导入外部文件
$array = explode(',',$file);
foreach ($array as $val){
switch($type) {
case 'js':
$parseStr .= '<script type="text/javascript" src="'.$basepath.'/'.str_replace(array('.','#'), array('/','.'),$val).'.js"></script>';
break;
case 'css':
$parseStr .= '<link rel="stylesheet" type="text/css" href="'.$basepath.'/'.str_replace(array('.','#'), array('/','.'),$val).'.css" />';
break;
case 'php':
$parseStr .= '<?php import("'.$val.'"); ?>';
break;
}
}
}
return $parseStr.$endStr;
}
// import别名 采用文件方式加载(要使用命名空间必须用import) 例如 <load file="__PUBLIC__/Js/Base.js" />
public function _load($attr,$content) {
return $this->_import($attr,$content,true);
}
// import别名使用 导入css文件 <css file="__PUBLIC__/Css/Base.css" />
public function _css($attr,$content) {
return $this->_import($attr,$content,true,'css');
}
// import别名使用 导入js文件 <js file="__PUBLIC__/Js/Base.js" />
public function _js($attr,$content) {
return $this->_import($attr,$content,true,'js');
}
/**
+----------------------------------------------------------
* assign标签解析
* 在模板中给某个变量赋值 支持变量赋值
* 格式: <assign name="" value="" />
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _assign($attr,$content) {
$tag = $this->parseXmlAttr($attr,'assign');
$name = $this->autoBuildVar($tag['name']);
if('$'==substr($tag['value'],0,1)) {
$value = $this->autoBuildVar(substr($tag['value'],1));
}else{
$value = '\''.$tag['value']. '\'';
}
$parseStr = '<?php '.$name.' = '.$value.'; ?>';
return $parseStr;
}
/**
+----------------------------------------------------------
* define标签解析
* 在模板中定义常量 支持变量赋值
* 格式: <define name="" value="" />
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _define($attr,$content) {
$tag = $this->parseXmlAttr($attr,'define');
$name = '\''.$tag['name']. '\'';
if('$'==substr($tag['value'],0,1)) {
$value = $this->autoBuildVar(substr($tag['value'],1));
}else{
$value = '\''.$tag['value']. '\'';
}
$parseStr = '<?php define('.$name.', '.$value.'); ?>';
return $parseStr;
}
/**
+----------------------------------------------------------
* for标签解析
* 格式: <for start="" end="" comparison="" step="" name="" />
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function _for($attr, $content){
//设置默认值
$start = 0;
$end = 0;
$step = 1;
$comparison = 'lt';
$name = 'i';
//获取属性
foreach ($this->parseXmlAttr($attr, 'for') as $key => $value){
$value = trim($value);
if(':'==substr($value,0,1))
$value = substr($value,1);
elseif('$'==substr($value,0,1))
$value = $this->autoBuildVar(substr($value,1));
switch ($key){
case 'start': $start = $value; break;
case 'end' : $end = $value; break;
case 'step': $step = $value; break;
case 'comparison':$comparison = $value;break;
case 'name':$name = $value;break;
}
}
$parseStr = '<?php $__FOR_START__='.$start.';$__FOR_END__='.$end.';';
$parseStr .= 'for($'.$name.'=$__FOR_START__;'.$this->parseCondition('$'.$name.' '.$comparison.' $__FOR_END__').';$'.$name.'+='.$step.'){ ?>';
$parseStr .= $content;
$parseStr .= '<?php } ?>';
return $parseStr;
}
} | 10npsite | trunk/DThinkPHP/Lib/Driver/TagLib/TagLibCx.class.php | PHP | asf20 | 29,622 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: ThinkTemplate.class.php 2791 2012-02-29 10:08:57Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP内置模板引擎类
* 支持XML标签和普通标签的模板解析
* 编译型模板引擎 支持动态缓存
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Template
* @author liu21st <liu21st@gmail.com>
* @version $Id: ThinkTemplate.class.php 2791 2012-02-29 10:08:57Z liu21st $
+------------------------------------------------------------------------------
*/
class ThinkTemplate {
// 模板页面中引入的标签库列表
protected $tagLib = array();
// 当前模板文件
protected $templateFile = '';
// 模板变量
public $tVar = array();
public $config = array();
private $literal = array();
/**
+----------------------------------------------------------
* 取得模板实例对象
* 静态方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return ThinkTemplate
+----------------------------------------------------------
*/
static public function getInstance() {
return get_instance_of(__CLASS__);
}
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 模板引擎配置数组
+----------------------------------------------------------
*/
public function __construct(){
$this->config['cache_path'] = C('CACHE_PATH');
$this->config['template_suffix'] = C('TMPL_TEMPLATE_SUFFIX');
$this->config['cache_suffix'] = C('TMPL_CACHFILE_SUFFIX');
$this->config['tmpl_cache'] = C('TMPL_CACHE_ON');
$this->config['cache_time'] = C('TMPL_CACHE_TIME');
$this->config['taglib_begin'] = $this->stripPreg(C('TAGLIB_BEGIN'));
$this->config['taglib_end'] = $this->stripPreg(C('TAGLIB_END'));
$this->config['tmpl_begin'] = $this->stripPreg(C('TMPL_L_DELIM'));
$this->config['tmpl_end'] = $this->stripPreg(C('TMPL_R_DELIM'));
$this->config['default_tmpl'] = C('TEMPLATE_NAME');
$this->config['layout_item'] = C('TMPL_LAYOUT_ITEM');
}
private function stripPreg($str) {
return str_replace(array('{','}','(',')','|','[',']'),array('\{','\}','\(','\)','\|','\[','\]'),$str);
}
// 模板变量获取和设置
public function get($name) {
if(isset($this->tVar[$name]))
return $this->tVar[$name];
else
return false;
}
public function set($name,$value) {
$this->tVar[$name]= $value;
}
// 加载模板
public function fetch($templateFile,$templateVar) {
$this->tVar = $templateVar;
$templateCacheFile = $this->loadTemplate($templateFile);
// 模板阵列变量分解成为独立变量
extract($templateVar, EXTR_OVERWRITE);
//载入模版缓存文件
include $templateCacheFile;
}
/**
+----------------------------------------------------------
* 加载主模板并缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $tmplTemplateFile 模板文件
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function loadTemplate ($tmplTemplateFile) {
$this->templateFile = $tmplTemplateFile;
// 根据模版文件名定位缓存文件
$tmplCacheFile = $this->config['cache_path'].md5($tmplTemplateFile).$this->config['cache_suffix'];
// 读取模板文件内容
$tmplContent = file_get_contents($tmplTemplateFile);
// 判断是否启用布局
if(C('LAYOUT_ON')) {
if(false !== strpos($tmplContent,'{__NOLAYOUT__}')) { // 可以单独定义不使用布局
$tmplContent = str_replace('{__NOLAYOUT__}','',$tmplContent);
}else{ // 替换布局的主体内容
$layoutFile = THEME_PATH.C('LAYOUT_NAME').$this->config['template_suffix'];
$tmplContent = str_replace($this->config['layout_item'],$tmplContent,file_get_contents($layoutFile));
}
}
//编译模板内容
$tmplContent = $this->compiler($tmplContent);
// 检测分组目录
if(!is_dir($this->config['cache_path']))
mk_dir($this->config['cache_path']);
//重写Cache文件
if( false === file_put_contents($tmplCacheFile,trim($tmplContent)))
throw_exception(L('_CACHE_WRITE_ERROR_').':'.$tmplCacheFile);
return $tmplCacheFile;
}
/**
+----------------------------------------------------------
* 编译模板文件内容
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $tmplContent 模板内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function compiler($tmplContent) {
//模板解析
$tmplContent = $this->parse($tmplContent);
// 还原被替换的Literal标签
$tmplContent = preg_replace('/<!--###literal(\d)###-->/eis',"\$this->restoreLiteral('\\1')",$tmplContent);
// 添加安全代码
$tmplContent = '<?php if (!defined(\'THINK_PATH\')) exit();?>'.$tmplContent;
if(C('TMPL_STRIP_SPACE')) {
/* 去除html空格与换行 */
$find = array("~>\s+<~","~>(\s+\n|\r)~");
$replace = array('><','>');
$tmplContent = preg_replace($find, $replace, $tmplContent);
}
// 优化生成的php代码
$tmplContent = str_replace('?><?php','',$tmplContent);
return strip_whitespace($tmplContent);
}
/**
+----------------------------------------------------------
* 模板解析入口
* 支持普通标签和TagLib解析 支持自定义标签库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $content 要解析的模板内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parse($content) {
// 内容为空不解析
if(empty($content)) return '';
$begin = $this->config['taglib_begin'];
$end = $this->config['taglib_end'];
// 首先替换literal标签内容
$content = preg_replace('/'.$begin.'literal'.$end.'(.*?)'.$begin.'\/literal'.$end.'/eis',"\$this->parseLiteral('\\1')",$content);
// 检查include语法
$content = $this->parseInclude($content);
// 检查PHP语法
$content = $this->parsePhp($content);
// 获取需要引入的标签库列表
// 标签库只需要定义一次,允许引入多个一次
// 一般放在文件的最前面
// 格式:<taglib name="html,mytag..." />
// 当TAGLIB_LOAD配置为true时才会进行检测
if(C('TAGLIB_LOAD')) {
$this->getIncludeTagLib($content);
if(!empty($this->tagLib)) {
// 对导入的TagLib进行解析
foreach($this->tagLib as $tagLibName) {
$this->parseTagLib($tagLibName,$content);
}
}
}
// 预先加载的标签库 无需在每个模板中使用taglib标签加载 但必须使用标签库XML前缀
if(C('TAGLIB_PRE_LOAD')) {
$tagLibs = explode(',',C('TAGLIB_PRE_LOAD'));
foreach ($tagLibs as $tag){
$this->parseTagLib($tag,$content);
}
}
// 内置标签库 无需使用taglib标签导入就可以使用 并且不需使用标签库XML前缀
$tagLibs = explode(',',C('TAGLIB_BUILD_IN'));
foreach ($tagLibs as $tag){
$this->parseTagLib($tag,$content,true);
}
//解析普通模板标签 {tagName}
$content = preg_replace('/('.$this->config['tmpl_begin'].')(\S.+?)('.$this->config['tmpl_end'].')/eis',"\$this->parseTag('\\2')",$content);
return $content;
}
// 检查PHP语法
protected function parsePhp($content) {
// PHP语法检查
if(C('TMPL_DENY_PHP') && false !== strpos($content,'<?php')) {
throw_exception(L('_NOT_ALLOW_PHP_'));
}elseif(ini_get('short_open_tag')){
// 开启短标签的情况要将<?标签用echo方式输出 否则无法正常输出xml标识
$content = preg_replace('/(<\?(?!php|=|$))/i', '<?php echo \'\\1\'; ?>'."\n", $content );
}
return $content;
}
// 解析模板中的布局标签
protected function parseLayout($content) {
// 读取模板中的布局标签
$find = preg_match('/'.$this->config['taglib_begin'].'layout\s(.+?)\s*?\/'.$this->config['taglib_end'].'/is',$content,$matches);
if($find) {
//替换Layout标签
$content = str_replace($matches[0],'',$content);
//解析Layout标签
$layout = $matches[1];
$xml = '<tpl><tag '.$layout.' /></tpl>';
$xml = simplexml_load_string($xml);
if(!$xml)
throw_exception(L('_XML_TAG_ERROR_'));
$xml = (array)($xml->tag->attributes());
$array = array_change_key_case($xml['@attributes']);
if(!C('LAYOUT_ON') || C('LAYOUT_NAME') !=$array['name'] ) {
// 读取布局模板
$layoutFile = THEME_PATH.$array['name'].$this->config['template_suffix'];
$replace = isset($array['replace'])?$array['replace']:$this->config['layout_item'];
// 替换布局的主体内容
$content = str_replace($replace,$content,file_get_contents($layoutFile));
}
}
return $content;
}
// 解析模板中的include标签
protected function parseInclude($content) {
// 解析布局
$content = $this->parseLayout($content);
// 读取模板中的布局标签
$find = preg_match_all('/'.$this->config['taglib_begin'].'include\s(.+?)\s*?\/'.$this->config['taglib_end'].'/is',$content,$matches);
if($find) {
for($i=0;$i<$find;$i++) {
$include = $matches[1][$i];
$xml = '<tpl><tag '.$include.' /></tpl>';
$xml = simplexml_load_string($xml);
if(!$xml)
throw_exception(L('_XML_TAG_ERROR_'));
$xml = (array)($xml->tag->attributes());
$array = array_change_key_case($xml['@attributes']);
$file = $array['file'];
unset($array['file']);
$content = str_replace($matches[0][$i],$this->parseIncludeItem($file,$array),$content);
}
}
return $content;
}
/**
+----------------------------------------------------------
* 替换页面中的literal标签
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $content 模板内容
+----------------------------------------------------------
* @return string|false
+----------------------------------------------------------
*/
private function parseLiteral($content) {
if(trim($content)=='')
return '';
$content = stripslashes($content);
$i = count($this->literal);
$parseStr = "<!--###literal{$i}###-->";
$this->literal[$i] = $content;
return $parseStr;
}
/**
+----------------------------------------------------------
* 还原被替换的literal标签
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $tag literal标签序号
+----------------------------------------------------------
* @return string|false
+----------------------------------------------------------
*/
private function restoreLiteral($tag) {
// 还原literal标签
$parseStr = $this->literal[$tag];
// 销毁literal记录
unset($this->literal[$tag]);
return $parseStr;
}
/**
+----------------------------------------------------------
* 搜索模板页面中包含的TagLib库
* 并返回列表
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $content 模板内容
+----------------------------------------------------------
* @return string|false
+----------------------------------------------------------
*/
public function getIncludeTagLib(& $content) {
//搜索是否有TagLib标签
$find = preg_match('/'.$this->config['taglib_begin'].'taglib\s(.+?)(\s*?)\/'.$this->config['taglib_end'].'\W/is',$content,$matches);
if($find) {
//替换TagLib标签
$content = str_replace($matches[0],'',$content);
//解析TagLib标签
$tagLibs = $matches[1];
$xml = '<tpl><tag '.$tagLibs.' /></tpl>';
$xml = simplexml_load_string($xml);
if(!$xml)
throw_exception(L('_XML_TAG_ERROR_'));
$xml = (array)($xml->tag->attributes());
$array = array_change_key_case($xml['@attributes']);
$this->tagLib = explode(',',$array['name']);
}
return;
}
/**
+----------------------------------------------------------
* TagLib库解析
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $tagLib 要解析的标签库
* @param string $content 要解析的模板内容
* @param boolen $hide 是否隐藏标签库前缀
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseTagLib($tagLib,&$content,$hide=false) {
$begin = $this->config['taglib_begin'];
$end = $this->config['taglib_end'];
$className = 'TagLib'.ucwords($tagLib);
if(!import($className)) {
if(is_file(EXTEND_PATH.'Driver/TagLib/'.$className.'.class.php')) {
// 扩展标签库优先识别
$file = EXTEND_PATH.'Driver/TagLib/'.$className.'.class.php';
}else{
// 系统目录下面的标签库
$file = CORE_PATH.'Driver/TagLib/'.$className.'.class.php';
}
require_cache($file);
}
$tLib = Think::instance($className);
foreach ($tLib->getTags() as $name=>$val){
$tags = array($name);
if(isset($val['alias'])) {// 别名设置
$tags = explode(',',$val['alias']);
$tags[] = $name;
}
$level = isset($val['level'])?$val['level']:1;
$closeTag = isset($val['close'])?$val['close']:true;
foreach ($tags as $tag){
$parseTag = !$hide? $tagLib.':'.$tag: $tag;// 实际要解析的标签名称
if(!method_exists($tLib,'_'.$tag)) {
// 别名可以无需定义解析方法
$tag = $name;
}
$n1 = empty($val['attr'])?'(\s*?)':'\s(.*?)';
if (!$closeTag){
$patterns = '/'.$begin.$parseTag.$n1.'\/(\s*?)'.$end.'/eis';
$replacement = "\$this->parseXmlTag('$tagLib','$tag','$1','')";
$content = preg_replace($patterns, $replacement,$content);
}else{
$patterns = '/'.$begin.$parseTag.$n1.$end.'(.*?)'.$begin.'\/'.$parseTag.'(\s*?)'.$end.'/eis';
$replacement = "\$this->parseXmlTag('$tagLib','$tag','$1','$2')";
for($i=0;$i<$level;$i++) $content=preg_replace($patterns,$replacement,$content);
}
}
}
}
/**
+----------------------------------------------------------
* 解析标签库的标签
* 需要调用对应的标签库文件解析类
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $tagLib 标签库名称
* @param string $tag 标签名
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string|false
+----------------------------------------------------------
*/
public function parseXmlTag($tagLib,$tag,$attr,$content) {
//if (MAGIC_QUOTES_GPC) {
$attr = stripslashes($attr);
$content = stripslashes($content);
//}
if(ini_get('magic_quotes_sybase'))
$attr = str_replace('\"','\'',$attr);
$tLib = Think::instance('TagLib'.ucwords(strtolower($tagLib)));
$parse = '_'.$tag;
$content = trim($content);
return $tLib->$parse($attr,$content);
}
/**
+----------------------------------------------------------
* 模板标签解析
* 格式: {TagName:args [|content] }
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $tagStr 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseTag($tagStr){
//if (MAGIC_QUOTES_GPC) {
$tagStr = stripslashes($tagStr);
//}
//还原非模板标签
if(preg_match('/^[\s|\d]/is',$tagStr))
//过滤空格和数字打头的标签
return C('TMPL_L_DELIM') . $tagStr .C('TMPL_R_DELIM');
$flag = substr($tagStr,0,1);
$name = substr($tagStr,1);
if('$' == $flag){ //解析模板变量 格式 {$varName}
return $this->parseVar($name);
}elseif('-' == $flag || '+'== $flag){ // 输出计算
return '<?php echo '.$flag.$name.';?>';
}elseif(':' == $flag){ // 输出某个函数的结果
return '<?php echo '.$name.';?>';
}elseif('~' == $flag){ // 执行某个函数
return '<?php '.$name.';?>';
}elseif(substr($tagStr,0,2)=='//' || (substr($tagStr,0,2)=='/*' && substr($tagStr,-2)=='*/')){
//注释标签
return '';
}
// 未识别的标签直接返回
return C('TMPL_L_DELIM') . $tagStr .C('TMPL_R_DELIM');
}
/**
+----------------------------------------------------------
* 模板变量解析,支持使用函数
* 格式: {$varname|function1|function2=arg1,arg2}
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $varStr 变量数据
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseVar($varStr){
$varStr = trim($varStr);
static $_varParseList = array();
//如果已经解析过该变量字串,则直接返回变量值
if(isset($_varParseList[$varStr])) return $_varParseList[$varStr];
$parseStr ='';
$varExists = true;
if(!empty($varStr)){
$varArray = explode('|',$varStr);
//取得变量名称
$var = array_shift($varArray);
//非法变量过滤 不允许在变量里面使用 ->
//TODO:还需要继续完善
if(preg_match('/->/is',$var))
return '';
if('Think.' == substr($var,0,6)){
// 所有以Think.打头的以特殊变量对待 无需模板赋值就可以输出
$name = $this->parseThinkVar($var);
}elseif( false !== strpos($var,'.')) {
//支持 {$var.property}
$vars = explode('.',$var);
$var = array_shift($vars);
switch(strtolower(C('TMPL_VAR_IDENTIFY'))) {
case 'array': // 识别为数组
$name = '$'.$var;
foreach ($vars as $key=>$val)
$name .= '["'.$val.'"]';
break;
case 'obj': // 识别为对象
$name = '$'.$var;
foreach ($vars as $key=>$val)
$name .= '->'.$val;
break;
default: // 自动判断数组或对象 只支持二维
$name = 'is_array($'.$var.')?$'.$var.'["'.$vars[0].'"]:$'.$var.'->'.$vars[0];
}
}elseif(false !==strpos($var,':')){
//支持 {$var:property} 方式输出对象的属性
$vars = explode(':',$var);
$var = str_replace(':','->',$var);
$name = "$".$var;
$var = $vars[0];
}elseif(false !== strpos($var,'[')) {
//支持 {$var['key']} 方式输出数组
$name = "$".$var;
preg_match('/(.+?)\[(.+?)\]/is',$var,$match);
$var = $match[1];
}else {
$name = "$$var";
}
//对变量使用函数
if(count($varArray)>0)
$name = $this->parseVarFunction($name,$varArray);
$parseStr = '<?php echo ('.$name.'); ?>';
}
$_varParseList[$varStr] = $parseStr;
return $parseStr;
}
/**
+----------------------------------------------------------
* 对模板变量使用函数
* 格式 {$varname|function1|function2=arg1,arg2}
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 变量名
* @param array $varArray 函数列表
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseVarFunction($name,$varArray){
//对变量使用函数
$length = count($varArray);
//取得模板禁止使用函数列表
$template_deny_funs = explode(',',C('TMPL_DENY_FUNC_LIST'));
for($i=0;$i<$length ;$i++ ){
$args = explode('=',$varArray[$i],2);
//模板函数过滤
$fun = strtolower(trim($args[0]));
switch($fun) {
case 'default': // 特殊模板函数
$name = '('.$name.')?('.$name.'):'.$args[1];
break;
default: // 通用模板函数
if(!in_array($fun,$template_deny_funs)){
if(isset($args[1])){
if(strstr($args[1],'###')){
$args[1] = str_replace('###',$name,$args[1]);
$name = "$fun($args[1])";
}else{
$name = "$fun($name,$args[1])";
}
}else if(!empty($args[0])){
$name = "$fun($name)";
}
}
}
}
return $name;
}
/**
+----------------------------------------------------------
* 特殊模板变量解析
* 格式 以 $Think. 打头的变量属于特殊模板变量
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $varStr 变量字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseThinkVar($varStr){
$vars = explode('.',$varStr);
$vars[1] = strtoupper(trim($vars[1]));
$parseStr = '';
if(count($vars)>=3){
$vars[2] = trim($vars[2]);
switch($vars[1]){
case 'SERVER':
$parseStr = '$_SERVER[\''.strtoupper($vars[2]).'\']';break;
case 'GET':
$parseStr = '$_GET[\''.$vars[2].'\']';break;
case 'POST':
$parseStr = '$_POST[\''.$vars[2].'\']';break;
case 'COOKIE':
if(isset($vars[3])) {
$parseStr = '$_COOKIE[\''.$vars[2].'\'][\''.$vars[3].'\']';
}else{
$parseStr = '$_COOKIE[\''.$vars[2].'\']';
}break;
case 'SESSION':
if(isset($vars[3])) {
$parseStr = '$_SESSION[\''.$vars[2].'\'][\''.$vars[3].'\']';
}else{
$parseStr = '$_SESSION[\''.$vars[2].'\']';
}
break;
case 'ENV':
$parseStr = '$_ENV[\''.strtoupper($vars[2]).'\']';break;
case 'REQUEST':
$parseStr = '$_REQUEST[\''.$vars[2].'\']';break;
case 'CONST':
$parseStr = strtoupper($vars[2]);break;
case 'LANG':
$parseStr = 'L("'.$vars[2].'")';break;
case 'CONFIG':
if(isset($vars[3])) {
$vars[2] .= '.'.$vars[3];
}
$parseStr = 'C("'.$vars[2].'")';break;
default:break;
}
}else if(count($vars)==2){
switch($vars[1]){
case 'NOW':
$parseStr = "date('Y-m-d g:i a',time())";
break;
case 'VERSION':
$parseStr = 'THINK_VERSION';
break;
case 'TEMPLATE':
$parseStr = "'".$this->templateFile."'";//'C("TEMPLATE_NAME")';
break;
case 'LDELIM':
$parseStr = 'C("TMPL_L_DELIM")';
break;
case 'RDELIM':
$parseStr = 'C("TMPL_R_DELIM")';
break;
default:
if(defined($vars[1]))
$parseStr = $vars[1];
}
}
return $parseStr;
}
/**
+----------------------------------------------------------
* 加载公共模板并缓存 和当前模板在同一路径,否则使用相对路径
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $tmplPublicName 公共模板文件名
* @param array $vars 要传递的变量列表
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseIncludeItem($tmplPublicName,$vars=array()){
if(substr($tmplPublicName,0,1)=='$')
//支持加载变量文件名
$tmplPublicName = $this->get(substr($tmplPublicName,1));
if(false === strpos($tmplPublicName,$this->config['template_suffix'])) {
// 解析规则为 模板主题:模块:操作 不支持 跨项目和跨分组调用
$path = explode(':',$tmplPublicName);
$action = array_pop($path);
$module = !empty($path)?array_pop($path):MODULE_NAME;
if(!empty($path)) {// 设置模板主题
$path = dirname(THEME_PATH).'/'.array_pop($path).'/';
}else{
$path = THEME_PATH;
}
$depr = defined('GROUP_NAME')?C('TMPL_FILE_DEPR'):'/';
$tmplPublicName = $path.$module.$depr.$action.$this->config['template_suffix'];
}
// 获取模板文件内容
$parseStr = file_get_contents($tmplPublicName);
foreach ($vars as $key=>$val) {
$parseStr = str_replace('['.$key.']',$val,$parseStr);
}
//再次对包含文件进行模板分析
return $this->parseInclude($parseStr);
}
} | 10npsite | trunk/DThinkPHP/Lib/Template/ThinkTemplate.class.php | PHP | asf20 | 31,222 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: TagLib.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP标签库TagLib解析基类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Template
* @author liu21st <liu21st@gmail.com>
* @version $Id: TagLib.class.php 2702 2012-02-02 12:35:01Z liu21st $
+------------------------------------------------------------------------------
*/
class TagLib {
/**
+----------------------------------------------------------
* 标签库定义XML文件
+----------------------------------------------------------
* @var string
* @access protected
+----------------------------------------------------------
*/
protected $xml = '';
protected $tags = array();// 标签定义
/**
+----------------------------------------------------------
* 标签库名称
+----------------------------------------------------------
* @var string
* @access protected
+----------------------------------------------------------
*/
protected $tagLib ='';
/**
+----------------------------------------------------------
* 标签库标签列表
+----------------------------------------------------------
* @var string
* @access protected
+----------------------------------------------------------
*/
protected $tagList = array();
/**
+----------------------------------------------------------
* 标签库分析数组
+----------------------------------------------------------
* @var string
* @access protected
+----------------------------------------------------------
*/
protected $parse = array();
/**
+----------------------------------------------------------
* 标签库是否有效
+----------------------------------------------------------
* @var string
* @access protected
+----------------------------------------------------------
*/
protected $valid = false;
/**
+----------------------------------------------------------
* 当前模板对象
+----------------------------------------------------------
* @var object
* @access protected
+----------------------------------------------------------
*/
protected $tpl;
protected $comparison = array(' nheq '=>' !== ',' heq '=>' === ',' neq '=>' != ',' eq '=>' == ',' egt '=>' >= ',' gt '=>' > ',' elt '=>' <= ',' lt '=>' < ');
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct() {
$this->tagLib = strtolower(substr(get_class($this),6));
$this->tpl = Think::instance('ThinkTemplate');//ThinkTemplate::getInstance();
}
/**
+----------------------------------------------------------
* TagLib标签属性分析 返回标签属性数组
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $tagStr 标签内容
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function parseXmlAttr($attr,$tag) {
//XML解析安全过滤
$attr = str_replace('&','___', $attr);
$xml = '<tpl><tag '.$attr.' /></tpl>';
$xml = simplexml_load_string($xml);
if(!$xml) {
throw_exception(L('_XML_TAG_ERROR_').' : '.$attr);
}
$xml = (array)($xml->tag->attributes());
$array = array_change_key_case($xml['@attributes']);
if($array) {
$attrs = explode(',',$this->tags[strtolower($tag)]['attr']);
foreach($attrs as $name) {
if( isset($array[$name])) {
$array[$name] = str_replace('___','&',$array[$name]);
}
}
return $array;
}
}
/**
+----------------------------------------------------------
* 解析条件表达式
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $condition 表达式标签内容
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function parseCondition($condition) {
$condition = str_ireplace(array_keys($this->comparison),array_values($this->comparison),$condition);
$condition = preg_replace('/\$(\w+):(\w+)\s/is','$\\1->\\2 ',$condition);
switch(strtolower(C('TMPL_VAR_IDENTIFY'))) {
case 'array': // 识别为数组
$condition = preg_replace('/\$(\w+)\.(\w+)\s/is','$\\1["\\2"] ',$condition);
break;
case 'obj': // 识别为对象
$condition = preg_replace('/\$(\w+)\.(\w+)\s/is','$\\1->\\2 ',$condition);
break;
default: // 自动判断数组或对象 只支持二维
$condition = preg_replace('/\$(\w+)\.(\w+)\s/is','(is_array($\\1)?$\\1["\\2"]:$\\1->\\2) ',$condition);
}
return $condition;
}
/**
+----------------------------------------------------------
* 自动识别构建变量
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 变量描述
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function autoBuildVar($name) {
if('Think.' == substr($name,0,6)){
// 特殊变量
return $this->parseThinkVar($name);
}elseif(strpos($name,'.')) {
$vars = explode('.',$name);
$var = array_shift($vars);
switch(strtolower(C('TMPL_VAR_IDENTIFY'))) {
case 'array': // 识别为数组
$name = '$'.$var;
foreach ($vars as $key=>$val){
if(0===strpos($val,'$')) {
$name .= '["{'.$val.'}"]';
}else{
$name .= '["'.$val.'"]';
}
}
break;
case 'obj': // 识别为对象
$name = '$'.$var;
foreach ($vars as $key=>$val)
$name .= '->'.$val;
break;
default: // 自动判断数组或对象 只支持二维
$name = 'is_array($'.$var.')?$'.$var.'["'.$vars[0].'"]:$'.$var.'->'.$vars[0];
}
}elseif(strpos($name,':')){
// 额外的对象方式支持
$name = '$'.str_replace(':','->',$name);
}elseif(!defined($name)) {
$name = '$'.$name;
}
return $name;
}
/**
+----------------------------------------------------------
* 用于标签属性里面的特殊模板变量解析
* 格式 以 Think. 打头的变量属于特殊模板变量
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $varStr 变量字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseThinkVar($varStr){
$vars = explode('.',$varStr);
$vars[1] = strtoupper(trim($vars[1]));
$parseStr = '';
if(count($vars)>=3){
$vars[2] = trim($vars[2]);
switch($vars[1]){
case 'SERVER': $parseStr = '$_SERVER[\''.$vars[2].'\']';break;
case 'GET': $parseStr = '$_GET[\''.$vars[2].'\']';break;
case 'POST': $parseStr = '$_POST[\''.$vars[2].'\']';break;
case 'COOKIE': $parseStr = '$_COOKIE[\''.$vars[2].'\']';break;
case 'SESSION': $parseStr = '$_SESSION[\''.$vars[2].'\']';break;
case 'ENV': $parseStr = '$_ENV[\''.$vars[2].'\']';break;
case 'REQUEST': $parseStr = '$_REQUEST[\''.$vars[2].'\']';break;
case 'CONST': $parseStr = strtoupper($vars[2]);break;
case 'LANG': $parseStr = 'L("'.$vars[2].'")';break;
case 'CONFIG': $parseStr = 'C("'.$vars[2].'")';break;
}
}else if(count($vars)==2){
switch($vars[1]){
case 'NOW': $parseStr = "date('Y-m-d g:i a',time())";break;
case 'VERSION': $parseStr = 'THINK_VERSION';break;
case 'TEMPLATE':$parseStr = 'C("TEMPLATE_NAME")';break;
case 'LDELIM': $parseStr = 'C("TMPL_L_DELIM")';break;
case 'RDELIM': $parseStr = 'C("TMPL_R_DELIM")';break;
default: if(defined($vars[1])) $parseStr = $vars[1];
}
}
return $parseStr;
}
// 获取标签定义
public function getTags(){
return $this->tags;
}
} | 10npsite | trunk/DThinkPHP/Lib/Template/TagLib.class.php | PHP | asf20 | 10,662 |
<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: TokenBuildBehavior.class.php 2659 2012-01-23 15:04:24Z liu21st $
/**
+------------------------------------------------------------------------------
* 系统行为扩展 表单令牌生成
+------------------------------------------------------------------------------
*/
class TokenBuildBehavior extends Behavior {
// 行为参数定义
protected $options = array(
'TOKEN_ON' => true, // 开启令牌验证
'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);
}
}
}
// 创建表单令牌
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])) {// 相同页面不重复生成session
$tokenValue = $_SESSION[$tokenName][$tokenKey];
}else{
$tokenValue = $tokenType(microtime(TRUE));
$_SESSION[$tokenName][$tokenKey] = $tokenValue;
}
// 执行一次额外动作防止远程非法提交
if($action = C('TOKEN_ACTION')){
$_SESSION[$action($tokenKey)] = true;
}
$token = '<input type="hidden" name="'.$tokenName.'" value="'.$tokenKey.'_'.$tokenValue.'" />';
return $token;
}
} | 10npsite | trunk/DThinkPHP/Lib/Behavior/TokenBuildBehavior.class.php | PHP | asf20 | 2,779 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: ShowRuntimeBehavior.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* 系统行为扩展 运行时间信息显示
+------------------------------------------------------------------------------
*/
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 , // 显示函数调用次数
);
// 行为扩展的执行入口必须是run
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);
}
}
/**
+----------------------------------------------------------
* 显示运行时间、数据库操作、缓存次数、内存使用信息
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
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;
}
} | 10npsite | trunk/DThinkPHP/Lib/Behavior/ShowRuntimeBehavior.class.php | PHP | asf20 | 4,054 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CheckRouteBehavior.class.php 2840 2012-03-23 05:56:20Z liu21st@gmail.com $
/**
+------------------------------------------------------------------------------
* 系统行为扩展 路由检测
+------------------------------------------------------------------------------
*/
class CheckRouteBehavior extends Behavior {
// 行为参数定义(默认值) 可在项目配置中覆盖
protected $options = array(
'URL_ROUTER_ON' => false, // 是否开启URL路由
'URL_ROUTE_RULES' => array(), // 默认路由规则,注:分组配置无法替代
);
// 行为扩展的执行入口必须是run
public function run(&$return){
// 优先检测是否存在PATH_INFO
$regx = trim($_SERVER['PATH_INFO'],'/');
if(empty($regx)) return $return = true;
// 是否开启路由使用
if(!C('URL_ROUTER_ON')) return $return = false;
// 路由定义文件优先于config中的配置定义
$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;
}
// 检测URL和规则路由是否匹配
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;
}
// 解析规范的路由地址
// 地址格式 [分组/模块/操作?]参数1=值1&参数2=值2...
private function parseUrl($url) {
$var = array();
if(false !== strpos($url,'?')) { // [分组/模块/操作?]参数1=值1&参数2=值2...
$info = parse_url($url);
$path = explode('/',$info['path']);
parse_str($info['query'],$var);
}elseif(strpos($url,'/')){ // [分组/模块/操作]
$path = explode('/',$url);
}else{ // 参数1=值1&参数2=值2...
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;
}
// 解析规则路由
// '路由规则'=>'[分组/模块/操作]?额外参数1=值1&额外参数2=值2...'
// '路由规则'=>array('[分组/模块/操作]','额外参数1=值1&额外参数2=值2...')
// '路由规则'=>'外部地址'
// '路由规则'=>array('外部地址','重定向代码')
// 路由规则中 :开头 表示动态变量
// 外部地址中可以用动态变量 采用 :1 :2 的方式
// 'news/:month/:day/:id'=>array('News/read?cate=1','status=1'),
// 'new/:id'=>array('/new.php?id=:1',301), 重定向
private function parseRule($rule,$route,$regx) {
// 获取路由地址规则
$url = is_array($route)?$route[0]:$route;
// 获取URL地址中的参数
$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{ // 过滤URL中的静态变量
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);
// 解析剩余的URL参数
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;
}
// 解析正则路由
// '路由正则'=>'[分组/模块/操作]?参数1=值1&参数2=值2...'
// '路由正则'=>array('[分组/模块/操作]?参数1=值1&参数2=值2...','额外参数1=值1&额外参数2=值2...')
// '路由正则'=>'外部地址'
// '路由正则'=>array('外部地址','重定向代码')
// 参数值和外部地址中可以用动态变量 采用 :1 :2 的方式
// '/new\/(\d+)\/(\d+)/'=>array('News/read?id=:1&page=:2&cate=1','status=1'),
// '/new\/(\d+)/'=>array('/new.php?id=:1&page=:2&status=1','301'), 重定向
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);
// 解析剩余的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;
}
} | 10npsite | trunk/DThinkPHP/Lib/Behavior/CheckRouteBehavior.class.php | PHP | asf20 | 9,322 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: WriteHtmlCacheBehavior.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* 系统行为扩展 静态缓存写入
* 增加配置参数如下:
+------------------------------------------------------------------------------
*/
class WriteHtmlCacheBehavior extends Behavior {
// 行为扩展的执行入口必须是run
public function run(&$content){
if(C('HTML_CACHE_ON') && defined('HTML_FILE_NAME')) {
//静态文件写入
// 如果开启HTML功能 检查并重写HTML文件
// 没有模版的操作不生成静态文件
if(!is_dir(dirname(HTML_FILE_NAME)))
mk_dir(dirname(HTML_FILE_NAME));
if( false === file_put_contents( HTML_FILE_NAME , $content ))
throw_exception(L('_CACHE_WRITE_ERROR_').':'.HTML_FILE_NAME);
}
}
} | 10npsite | trunk/DThinkPHP/Lib/Behavior/WriteHtmlCacheBehavior.class.php | PHP | asf20 | 1,566 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: ReadHtmlCacheBehavior.class.php 2744 2012-02-18 11:27:14Z liu21st $
/**
+------------------------------------------------------------------------------
* 系统行为扩展 静态缓存读取
+------------------------------------------------------------------------------
*/
class ReadHtmlCacheBehavior extends Behavior {
protected $options = array(
'HTML_CACHE_ON'=>false,
'HTML_CACHE_TIME'=>60,
'HTML_CACHE_RULES'=>array(),
'HTML_FILE_SUFFIX'=>'.html',
);
// 行为扩展的执行入口必须是run
public function run(&$params){
// 开启静态缓存
if(C('HTML_CACHE_ON')) {
if(($cacheTime = $this->requireHtmlCache()) && $this->checkHTMLCache(HTML_FILE_NAME,$cacheTime)) { //静态页面有效
// 读取静态页面输出
readfile(HTML_FILE_NAME);
exit();
}
}
}
// 判断是否需要静态缓存
static private function requireHtmlCache() {
// 分析当前的静态规则
$htmls = C('HTML_CACHE_RULES'); // 读取静态规则
if(!empty($htmls)) {
// 静态规则文件定义格式 actionName=>array(‘静态规则’,’缓存时间’,’附加规则')
// 'read'=>array('{id},{name}',60,'md5') 必须保证静态规则的唯一性 和 可判断性
// 检测静态规则
$moduleName = strtolower(MODULE_NAME);
if(isset($htmls[$moduleName.':'.ACTION_NAME])) {
$html = $htmls[$moduleName.':'.ACTION_NAME]; // 某个模块的操作的静态规则
}elseif(isset($htmls[$moduleName.':'])){// 某个模块的静态规则
$html = $htmls[$moduleName.':'];
}elseif(isset($htmls[ACTION_NAME])){
$html = $htmls[ACTION_NAME]; // 所有操作的静态规则
}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);
// {ID|FUN} GET变量的简写
$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);
// {|FUN} 单独使用函数
$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;
}
/**
+----------------------------------------------------------
* 检查静态HTML文件是否有效
* 如果无效需要重新更新
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $cacheFile 静态文件名
* @param integer $cacheTime 缓存有效期
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
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 && 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);
}
} | 10npsite | trunk/DThinkPHP/Lib/Behavior/ReadHtmlCacheBehavior.class.php | PHP | asf20 | 5,869 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: ParseTemplateBehavior.class.php 2740 2012-02-17 08:16:42Z liu21st $
/**
+------------------------------------------------------------------------------
* 系统行为扩展 模板解析
+------------------------------------------------------------------------------
*/
class ParseTemplateBehavior extends Behavior {
// 行为参数定义(默认值) 可在项目配置中覆盖
protected $options = array(
// 布局设置
'TMPL_ENGINE_TYPE' => 'Think', // 默认模板引擎 以下设置仅对使用Think模板引擎有效
'TMPL_CACHFILE_SUFFIX' => '.php', // 默认模板缓存后缀
'TMPL_DENY_FUNC_LIST' => 'echo,exit', // 模板引擎禁用函数
'TMPL_DENY_PHP' =>false, // 默认模板引擎是否禁用PHP原生代码
'TMPL_L_DELIM' => '{', // 模板引擎普通标签开始标记
'TMPL_R_DELIM' => '}', // 模板引擎普通标签结束标记
'TMPL_VAR_IDENTIFY' => 'array', // 模板变量识别。留空自动判断,参数为'obj'则表示对象
'TMPL_STRIP_SPACE' => true, // 是否去除模板文件里面的html空格与换行
'TMPL_CACHE_ON' => true, // 是否开启模板编译缓存,设为false则每次都会重新编译
'TMPL_CACHE_TIME' => 0, // 模板缓存有效期 0 为永久,(以数字为值,单位:秒)
'TMPL_LAYOUT_ITEM' => '{__CONTENT__}', // 布局模板的内容替换标识
'LAYOUT_ON' => false, // 是否启用布局
'LAYOUT_NAME' => 'layout', // 当前布局名称 默认为layout
// Think模板引擎标签库相关设定
'TAGLIB_BEGIN' => '<', // 标签库标签开始标记
'TAGLIB_END' => '>', // 标签库标签结束标记
'TAGLIB_LOAD' => true, // 是否使用内置标签库之外的其它标签库,默认自动检测
'TAGLIB_BUILD_IN' => 'cx', // 内置标签库名称(标签使用不必指定标签库名称),以逗号分隔 注意解析顺序
'TAGLIB_PRE_LOAD' => '', // 需要额外加载的标签库(须指定标签库名称),多个以逗号分隔
);
// 行为扩展的执行入口必须是run
public function run(&$_data){
$engine = strtolower(C('TMPL_ENGINE_TYPE'));
if('think'==$engine){ // 采用Think模板引擎
if($this->checkCache($_data['file'])) { // 缓存有效
// 分解变量并载入模板缓存
extract($_data['var'], EXTR_OVERWRITE);
//载入模版缓存文件
include C('CACHE_PATH').md5($_data['file']).C('TMPL_CACHFILE_SUFFIX');
}else{
$tpl = Think::instance('ThinkTemplate');
// 编译并加载模板文件
$tpl->fetch($_data['file'],$_data['var']);
}
}else{
// 调用第三方模板引擎解析和输出
$class = 'Template'.ucwords($engine);
if(is_file(CORE_PATH.'Driver/Template/'.$class.'.class.php')) {
// 内置驱动
$path = CORE_PATH;
}else{ // 扩展驱动
$path = EXTEND_PATH;
}
if(require_cache($path.'Driver/Template/'.$class.'.class.php')) {
$tpl = new $class;
$tpl->fetch($_data['file'],$_data['var']);
}else { // 类没有定义
throw_exception(L('_NOT_SUPPERT_').': ' . $class);
}
}
}
/**
+----------------------------------------------------------
* 检查缓存文件是否有效
* 如果无效则需要重新编译
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $tmplTemplateFile 模板文件名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
protected function checkCache($tmplTemplateFile) {
if (!C('TMPL_CACHE_ON')) // 优先对配置设定检测
return false;
$tmplCacheFile = C('CACHE_PATH').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;
}
} | 10npsite | trunk/DThinkPHP/Lib/Behavior/ParseTemplateBehavior.class.php | PHP | asf20 | 5,796 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: ContentReplaceBehavior.class.php 2777 2012-02-23 13:07:50Z liu21st $
/**
+------------------------------------------------------------------------------
* 系统行为扩展 模板内容输出替换
+------------------------------------------------------------------------------
*/
class ContentReplaceBehavior extends Behavior {
// 行为参数定义
protected $options = array(
'TMPL_PARSE_STRING'=>array(),
);
// 行为扩展的执行入口必须是run
public function run(&$content){
$content = $this->templateContentReplace($content);
}
/**
+----------------------------------------------------------
* 模板内容替换
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $content 模板内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
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;
}
} | 10npsite | trunk/DThinkPHP/Lib/Behavior/ContentReplaceBehavior.class.php | PHP | asf20 | 2,753 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: LocationTemplateBehavior.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* 系统行为扩展 自动定位模板文件
+------------------------------------------------------------------------------
*/
class LocationTemplateBehavior extends Behavior {
// 行为扩展的执行入口必须是run
public function run(&$templateFile){
// 自动定位模板文件
if(!file_exists_case($templateFile))
$templateFile = $this->parseTemplateFile($templateFile);
}
/**
+----------------------------------------------------------
* 自动定位模板文件
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $templateFile 文件名
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
private function parseTemplateFile($templateFile) {
if(''==$templateFile) {
// 如果模板文件名为空 按照默认规则定位
$templateFile = C('TEMPLATE_NAME');
}elseif(false === strpos($templateFile,C('TMPL_TEMPLATE_SUFFIX'))){
// 解析规则为 模板主题:模块:操作 不支持 跨项目和跨分组调用
$path = explode(':',$templateFile);
$action = array_pop($path);
$module = !empty($path)?array_pop($path):MODULE_NAME;
if(!empty($path)) {// 设置模板主题
$path = dirname(THEME_PATH).'/'.array_pop($path).'/';
}else{
$path = THEME_PATH;
}
$depr = defined('GROUP_NAME')?C('TMPL_FILE_DEPR'):'/';
$templateFile = $path.$module.$depr.$action.C('TMPL_TEMPLATE_SUFFIX');
}
if(!file_exists_case($templateFile))
throw_exception(L('_TEMPLATE_NOT_EXIST_').'['.$templateFile.']');
return $templateFile;
}
} | 10npsite | trunk/DThinkPHP/Lib/Behavior/LocationTemplateBehavior.class.php | PHP | asf20 | 2,855 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: ShowPageTraceBehavior.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* 系统行为扩展 页面Trace显示输出
+------------------------------------------------------------------------------
*/
class ShowPageTraceBehavior extends Behavior {
// 行为参数定义
protected $options = array(
'SHOW_PAGE_TRACE' => false, // 显示页面Trace信息
);
// 行为扩展的执行入口必须是run
public function run(&$params){
if(C('SHOW_PAGE_TRACE')) {
echo $this->showTrace();
}
}
/**
+----------------------------------------------------------
* 显示页面Trace信息
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
*/
private function showTrace() {
// 系统默认显示信息
$log = Log::$log;
$files = get_included_files();
$trace = array(
'请求时间'=> date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']),
'当前页面'=> __SELF__,
'请求协议'=> $_SERVER['SERVER_PROTOCOL'].' '.$_SERVER['REQUEST_METHOD'],
'运行信息'=> $this->showTime(),
'会话ID' => session_id(),
'日志记录'=> count($log)?count($log).'条日志<br/>'.implode('<br/>',$log):'无日志记录',
'加载文件'=> count($files).str_replace("\n",'<br/>',substr(substr(print_r($files,true),7),0,-2)),
);
// 读取项目定义的Trace文件
$traceFile = CONF_PATH.'trace.php';
if(is_file($traceFile)) {
// 定义格式 return array('当前页面'=>$_SERVER['PHP_SELF'],'通信协议'=>$_SERVER['SERVER_PROTOCOL'],...);
$trace = array_merge(include $traceFile,$trace);
}
// 设置trace信息
trace($trace);
// 调用Trace页面模板
ob_start();
include C('TMPL_TRACE_FILE')?C('TMPL_TRACE_FILE'):THINK_PATH.'Tpl/page_trace.tpl';
return ob_get_clean();
}
/**
+----------------------------------------------------------
* 显示运行时间、数据库操作、缓存次数、内存使用信息
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function showTime() {
// 显示运行时间
G('beginTime',$GLOBALS['_beginTime']);
G('viewEndTime');
$showTime = 'Process: '.G('beginTime','viewEndTime').'s ';
// 显示详细运行时间
$showTime .= '( Load:'.G('beginTime','loadTime').'s Init:'.G('loadTime','initTime').'s Exec:'.G('initTime','viewStartTime').'s Template:'.G('viewStartTime','viewEndTime').'s )';
// 显示数据库操作次数
if(class_exists('Db',false) ) {
$showTime .= ' | DB :'.N('db_query').' queries '.N('db_write').' writes ';
}
// 显示缓存读写次数
if( class_exists('Cache',false)) {
$showTime .= ' | Cache :'.N('cache_read').' gets '.N('cache_write').' writes ';
}
// 显示内存开销
if(MEMORY_LIMIT_ON ) {
$showTime .= ' | UseMem:'. number_format((memory_get_usage() - $GLOBALS['_startUseMems'])/1024).' kb';
}
// 显示文件加载数
$showTime .= ' | LoadFile:'.count(get_included_files());
// 显示函数调用次数 自定义函数,内置函数
$fun = get_defined_functions();
$showTime .= ' | CallFun:'.count($fun['user']).','.count($fun['internal']);
return $showTime;
}
} | 10npsite | trunk/DThinkPHP/Lib/Behavior/ShowPageTraceBehavior.class.php | PHP | asf20 | 4,583 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Cache.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* 缓存管理类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id: Cache.class.php 2702 2012-02-02 12:35:01Z liu21st $
+------------------------------------------------------------------------------
*/
class Cache {
/**
+----------------------------------------------------------
* 是否连接
+----------------------------------------------------------
* @var string
* @access protected
+----------------------------------------------------------
*/
protected $connected ;
/**
+----------------------------------------------------------
* 操作句柄
+----------------------------------------------------------
* @var string
* @access protected
+----------------------------------------------------------
*/
protected $handler ;
/**
+----------------------------------------------------------
* 缓存连接参数
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $options = array();
/**
+----------------------------------------------------------
* 连接缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $type 缓存类型
* @param array $options 配置数组
+----------------------------------------------------------
* @return object
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function connect($type='',$options=array()) {
if(empty($type)) $type = C('DATA_CACHE_TYPE');
$type = strtolower(trim($type));
$class = 'Cache'.ucwords($type);
if(is_file(CORE_PATH.'Driver/Cache/'.$class.'.class.php')) {
// 内置驱动
$path = CORE_PATH;
}else{ // 扩展驱动
$path = EXTEND_PATH;
}
if(require_cache($path.'Driver/Cache/'.$class.'.class.php'))
$cache = new $class($options);
else
throw_exception(L('_CACHE_TYPE_INVALID_').':'.$type);
return $cache;
}
public function __get($name) {
return $this->get($name);
}
public function __set($name,$value) {
return $this->set($name,$value);
}
public function __unset($name) {
$this->rm($name);
}
public function setOptions($name,$value) {
$this->options[$name] = $value;
}
public function getOptions($name) {
return $this->options[$name];
}
/**
+----------------------------------------------------------
* 取得缓存类实例
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
static function getInstance() {
$param = func_get_args();
return get_instance_of(__CLASS__,'connect',$param);
}
// 队列缓存
protected function queue($key) {
static $_handler = array(
'file'=>array('F','F'),
'xcache'=>array('xcache_get','xcache_set'),
'apc'=>array('apc_fetch','apc_store'),
);
$queue = isset($this->options['queue'])?$this->options['queue']:'file';
$fun = $_handler[$queue];
$value = $fun[0]('think_queue');
if(!$value) {
$value = array();
}
// 进列
array_push($value,$key);
if(count($value) > $this->options['length']) {
// 出列
$key = array_shift($value);
// 删除缓存
$this->rm($key);
}
return $fun[1]('think_queue',$value);
}
} | 10npsite | trunk/DThinkPHP/Lib/Core/Cache.class.php | PHP | asf20 | 5,064 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Log.class.php 2791 2012-02-29 10:08:57Z liu21st $
/**
+------------------------------------------------------------------------------
* 日志处理类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: Log.class.php 2791 2012-02-29 10:08:57Z liu21st $
+------------------------------------------------------------------------------
*/
class Log {
// 日志级别 从上到下,由低到高
const EMERG = 'EMERG'; // 严重错误: 导致系统崩溃无法使用
const ALERT = 'ALERT'; // 警戒性错误: 必须被立即修改的错误
const CRIT = 'CRIT'; // 临界值错误: 超过临界值的错误,例如一天24小时,而输入的是25小时这样
const ERR = 'ERR'; // 一般错误: 一般性错误
const WARN = 'WARN'; // 警告性错误: 需要发出警告的错误
const NOTICE = 'NOTIC'; // 通知: 程序可以运行但是还不够完美的错误
const INFO = 'INFO'; // 信息: 程序输出信息
const DEBUG = 'DEBUG'; // 调试: 调试信息
const SQL = 'SQL'; // SQL:SQL语句 注意只在调试模式开启时有效
// 日志记录方式
const SYSTEM = 0;
const MAIL = 1;
const FILE = 3;
const SAPI = 4;
// 日志信息
static $log = array();
// 日期格式
static $format = '[ c ]';
/**
+----------------------------------------------------------
* 记录日志 并且会过滤未经设置的级别
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $message 日志信息
* @param string $level 日志级别
* @param boolean $record 是否强制记录
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function record($message,$level=self::ERR,$record=false) {
if($record || strpos(C('LOG_LEVEL'),$level)) {
$now = date(self::$format);
self::$log[] = "{$now} ".$_SERVER['REQUEST_URI']." | {$level}: {$message}\r\n";
}
}
/**
+----------------------------------------------------------
* 日志保存
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param integer $type 日志记录方式
* @param string $destination 写入目标
* @param string $extra 额外参数
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function save($type='',$destination='',$extra='') {
$type = $type?$type:C('LOG_TYPE');
if(self::FILE == $type) { // 文件方式记录日志信息
if(empty($destination))
$destination = 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(implode('',self::$log), $type,$destination ,$extra);
// 保存后清空日志缓存
self::$log = array();
//clearstatcache();
}
/**
+----------------------------------------------------------
* 日志直接写入
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $message 日志信息
* @param string $level 日志级别
* @param integer $type 日志记录方式
* @param string $destination 写入目标
* @param string $extra 额外参数
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
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 = 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} ".$_SERVER['REQUEST_URI']." | {$level}: {$message}\r\n", $type,$destination,$extra );
//clearstatcache();
}
} | 10npsite | trunk/DThinkPHP/Lib/Core/Log.class.php | PHP | asf20 | 6,108 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: View.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP 视图输出
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: View.class.php 2702 2012-02-02 12:35:01Z liu21st $
+------------------------------------------------------------------------------
*/
class View {
protected $tVar = array(); // 模板输出变量
/**
+----------------------------------------------------------
* 模板变量赋值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $name
* @param mixed $value
+----------------------------------------------------------
*/
public function assign($name,$value=''){
if(is_array($name)) {
$this->tVar = array_merge($this->tVar,$name);
}elseif(is_object($name)){
foreach($name as $key =>$val)
$this->tVar[$key] = $val;
}else {
$this->tVar[$name] = $value;
}
}
/**
+----------------------------------------------------------
* 取得模板变量的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function get($name){
if(isset($this->tVar[$name]))
return $this->tVar[$name];
else
return false;
}
/* 取得所有模板变量 */
public function getAllVar(){
return $this->tVar;
}
// 调试页面所有的模板变量
public function traceVar(){
foreach ($this->tVar as $name=>$val){
dump($val,1,'['.$name.']<br/>');
}
}
/**
+----------------------------------------------------------
* 加载模板和页面输出 可以返回输出内容
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $templateFile 模板文件名
* @param string $charset 模板输出字符集
* @param string $contentType 输出类型
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function display($templateFile='',$charset='',$contentType='') {
G('viewStartTime');
// 视图开始标签
tag('view_begin',$templateFile);
// 解析并获取模板内容
$content = $this->fetch($templateFile);
// 输出模板内容
$this->show($content,$charset,$contentType);
// 视图结束标签
tag('view_end');
}
/**
+----------------------------------------------------------
* 输出内容文本可以包括Html
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $content 输出内容
* @param string $charset 模板输出字符集
* @param string $contentType 输出类型
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function show($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: private'); //支持页面回跳
header('X-Powered-By:ThinkPHP');
// 输出模板文件
echo $content;
}
/**
+----------------------------------------------------------
* 解析和获取模板内容 用于输出
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $templateFile 模板文件名
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function fetch($templateFile='') {
// 模板文件解析标签
tag('view_template',$templateFile);
// 模板文件不存在直接返回
if(!is_file($templateFile)) return NULL;
// 页面缓存
ob_start();
ob_implicit_flush(0);
if('php' == strtolower(C('TMPL_ENGINE_TYPE'))) { // 使用PHP原生模板
// 模板阵列变量分解成为独立变量
extract($this->tVar, EXTR_OVERWRITE);
// 直接载入PHP模板
include $templateFile;
}else{
// 视图解析标签
$params = array('var'=>$this->tVar,'file'=>$templateFile);
tag('view_parse',$params);
}
// 获取并清空缓存
$content = ob_get_clean();
// 内容过滤标签
tag('view_filter',$content);
// 输出模板文件
return $content;
}
} | 10npsite | trunk/DThinkPHP/Lib/Core/View.class.php | PHP | asf20 | 6,362 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: App.class.php 2792 2012-03-02 03:36:36Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP 应用程序类 执行应用过程管理
* 可以在模式扩展中重新定义 但是必须具有Run方法接口
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: App.class.php 2792 2012-03-02 03:36:36Z liu21st $
+------------------------------------------------------------------------------
*/
class App {
/**
+----------------------------------------------------------
* 应用程序初始化
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function init() {
// 设置系统时区
date_default_timezone_set(C('DEFAULT_TIMEZONE'));
// 加载动态项目公共文件和配置
load_ext_file();
// URL调度
Dispatcher::dispatch();
if(defined('GROUP_NAME')) {
// 加载分组配置文件
if(is_file(CONF_PATH.GROUP_NAME.'/config.php'))
C(include CONF_PATH.GROUP_NAME.'/config.php');
// 加载分组函数文件
if(is_file(COMMON_PATH.GROUP_NAME.'/function.php'))
include COMMON_PATH.GROUP_NAME.'/function.php';
}
/* 获取模板主题名称 */
$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);
}
/* 模板相关目录常量 */
define('THEME_NAME', $templateSet); // 当前模板主题名称
$group = defined('GROUP_NAME')?GROUP_NAME.'/':'';
define('THEME_PATH', TMPL_PATH.$group.(THEME_NAME?THEME_NAME.'/':''));
define('APP_TMPL_PATH',__ROOT__.'/'.APP_NAME.(APP_NAME?'/':'').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);
return ;
}
/**
+----------------------------------------------------------
* 执行应用程序
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
static public function exec() {
// 安全检测
if(!preg_match('/^[A-Za-z_0-9]+$/',MODULE_NAME)){
$module = false;
}else{
//创建Action控制器实例
$group = defined('GROUP_NAME') ? GROUP_NAME.'/' : '';
$module = A($group.MODULE_NAME);
}
if(!$module) {
if(function_exists('__hack_module')) {
// hack 方式定义扩展模块 返回Action对象
$module = __hack_module();
if(!is_object($module)) {
// 不再继续执行 直接返回
return ;
}
}else{
// 是否定义Empty模块
$module = A('Empty');
if(!$module){
$msg = L('_MODULE_NOT_EXIST_').MODULE_NAME;
if(APP_DEBUG) {
// 模块不存在 抛出异常
throw_exception($msg);
}else{
if(C('LOG_EXCEPTION_RECORD')) Log::write($msg);
send_http_status(404);
exit;
}
}
}
}
//获取当前操作名
$action = ACTION_NAME;
// 获取操作方法名标签
tag('action_name',$action);
if (method_exists($module,'_before_'.$action)) {
// 执行前置操作
call_user_func(array(&$module,'_before_'.$action));
}
//执行当前操作
call_user_func(array(&$module,$action));
if (method_exists($module,'_after_'.$action)) {
// 执行后缀操作
call_user_func(array(&$module,'_after_'.$action));
}
return ;
}
/**
+----------------------------------------------------------
* 运行应用实例 入口文件使用的快捷方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function run() {
// 项目初始化标签
tag('app_init');
App::init();
// 项目开始标签
tag('app_begin');
// Session初始化
session(C('SESSION_OPTIONS'));
// 记录应用初始化时间
G('initTime');
App::exec();
// 项目结束标签
tag('app_end');
// 保存日志记录
if(C('LOG_RECORD')) Log::save();
return ;
}
} | 10npsite | trunk/DThinkPHP/Lib/Core/App.class.php | PHP | asf20 | 6,664 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Db.class.php 2813 2012-03-13 02:55:55Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP 数据库中间层实现类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Db
* @author liu21st <liu21st@gmail.com>
* @version $Id: Db.class.php 2813 2012-03-13 02:55:55Z liu21st $
+------------------------------------------------------------------------------
*/
class Db {
// 数据库类型
protected $dbType = null;
// 是否自动释放查询结果
protected $autoFree = false;
// 是否显示调试信息 如果启用会在日志文件记录sql语句
public $debug = false;
// 当前操作所属的模型名
protected $model = '_think_';
// 是否使用永久连接
protected $pconnect = false;
// 当前SQL指令
protected $queryStr = '';
protected $modelSql = array();
// 最后插入ID
protected $lastInsID = null;
// 返回或者影响记录数
protected $numRows = 0;
// 返回字段数
protected $numCols = 0;
// 事务指令数
protected $transTimes = 0;
// 错误信息
protected $error = '';
// 数据库连接ID 支持多个连接
protected $linkID = array();
// 当前连接ID
protected $_linkID = null;
// 当前查询ID
protected $queryID = null;
// 是否已经连接数据库
protected $connected = false;
// 数据库连接参数配置
protected $config = '';
// 数据库表达式
protected $comparison = array('eq'=>'=','neq'=>'<>','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE');
// 查询表达式
protected $selectSql = 'SELECT%DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%';
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 数据库配置数组
+----------------------------------------------------------
*/
public function __construct($config=''){
return $this->factory($config);
}
/**
+----------------------------------------------------------
* 取得数据库类实例
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return mixed 返回数据库驱动类
+----------------------------------------------------------
*/
public static function getInstance() {
$args = func_get_args();
return get_instance_of(__CLASS__,'factory',$args);
}
/**
+----------------------------------------------------------
* 加载数据库 支持配置文件或者 DSN
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $db_config 数据库配置信息
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function factory($db_config='') {
// 读取数据库配置
$db_config = $this->parseConfig($db_config);
if(empty($db_config['dbms']))
throw_exception(L('_NO_DB_CONFIG_'));
// 数据库类型
$this->dbType = ucwords(strtolower($db_config['dbms']));
$class = 'Db'. $this->dbType;
if(is_file(CORE_PATH.'Driver/Db/'.$class.'.class.php')) {
// 内置驱动
$path = CORE_PATH;
}else{ // 扩展驱动
$path = EXTEND_PATH;
}
// 检查驱动类
if(require_cache($path.'Driver/Db/'.$class.'.class.php')) {
$db = new $class($db_config);
// 获取当前的数据库类型
if( 'pdo' != strtolower($db_config['dbms']) )
$db->dbType = strtoupper($this->dbType);
else
$db->dbType = $this->_getDsnType($db_config['dsn']);
if(APP_DEBUG) $db->debug = true;
}else {
// 类没有定义
throw_exception(L('_NOT_SUPPORT_DB_').': ' . $db_config['dbms']);
}
return $db;
}
/**
+----------------------------------------------------------
* 根据DSN获取数据库类型 返回大写
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $dsn dsn字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function _getDsnType($dsn) {
$match = explode(':',$dsn);
$dbType = strtoupper(trim($match[0]));
return $dbType;
}
/**
+----------------------------------------------------------
* 分析数据库配置信息,支持数组和DSN
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param mixed $db_config 数据库配置信息
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function parseConfig($db_config='') {
if ( !empty($db_config) && is_string($db_config)) {
// 如果DSN字符串则进行解析
$db_config = $this->parseDSN($db_config);
}elseif(is_array($db_config)) { // 数组配置
$db_config = array(
'dbms' => $db_config['db_type'],
'username' => $db_config['db_user'],
'password' => $db_config['db_pwd'],
'hostname' => $db_config['db_host'],
'hostport' => $db_config['db_port'],
'database' => $db_config['db_name'],
'dsn' => $db_config['db_dsn'],
'params' => $db_config['db_params'],
);
}elseif(empty($db_config)) {
// 如果配置为空,读取配置文件设置
if( C('DB_DSN') && 'pdo' != strtolower(C('DB_TYPE')) ) { // 如果设置了DB_DSN 则优先
$db_config = $this->parseDSN(C('DB_DSN'));
}else{
$db_config = array (
'dbms' => C('DB_TYPE'),
'username' => C('DB_USER'),
'password' => C('DB_PWD'),
'hostname' => C('DB_HOST'),
'hostport' => C('DB_PORT'),
'database' => C('DB_NAME'),
'dsn' => C('DB_DSN'),
'params' => C('DB_PARAMS'),
);
}
}
return $db_config;
}
/**
+----------------------------------------------------------
* 初始化数据库连接
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param boolean $master 主服务器
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function initConnect($master=true) {
if(1 == C('DB_DEPLOY_TYPE'))
// 采用分布式数据库
$this->_linkID = $this->multiConnect($master);
else
// 默认单数据库
if ( !$this->connected ) $this->_linkID = $this->connect();
}
/**
+----------------------------------------------------------
* 连接分布式服务器
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param boolean $master 主服务器
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function multiConnect($master=false) {
static $_config = array();
if(empty($_config)) {
// 缓存分布式数据库配置解析
foreach ($this->config as $key=>$val){
$_config[$key] = explode(',',$val);
}
}
// 数据库读写是否分离
if(C('DB_RW_SEPARATE')){
// 主从式采用读写分离
if($master)
// 主服务器写入
$r = floor(mt_rand(0,C('DB_MASTER_NUM')-1));
else
// 读操作连接从服务器
$r = floor(mt_rand(C('DB_MASTER_NUM'),count($_config['hostname'])-1)); // 每次随机连接的数据库
}else{
// 读写操作不区分服务器
$r = floor(mt_rand(0,count($_config['hostname'])-1)); // 每次随机连接的数据库
}
$db_config = array(
'username' => isset($_config['username'][$r])?$_config['username'][$r]:$_config['username'][0],
'password' => isset($_config['password'][$r])?$_config['password'][$r]:$_config['password'][0],
'hostname' => isset($_config['hostname'][$r])?$_config['hostname'][$r]:$_config['hostname'][0],
'hostport' => isset($_config['hostport'][$r])?$_config['hostport'][$r]:$_config['hostport'][0],
'database' => isset($_config['database'][$r])?$_config['database'][$r]:$_config['database'][0],
'dsn' => isset($_config['dsn'][$r])?$_config['dsn'][$r]:$_config['dsn'][0],
'params' => isset($_config['params'][$r])?$_config['params'][$r]:$_config['params'][0],
);
return $this->connect($db_config,$r);
}
/**
+----------------------------------------------------------
* DSN解析
* 格式: mysql://username:passwd@localhost:3306/DbName
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $dsnStr
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function parseDSN($dsnStr) {
if( empty($dsnStr) ){return false;}
$info = parse_url($dsnStr);
if($info['scheme']){
$dsn = array(
'dbms' => $info['scheme'],
'username' => isset($info['user']) ? $info['user'] : '',
'password' => isset($info['pass']) ? $info['pass'] : '',
'hostname' => isset($info['host']) ? $info['host'] : '',
'hostport' => isset($info['port']) ? $info['port'] : '',
'database' => isset($info['path']) ? substr($info['path'],1) : ''
);
}else {
preg_match('/^(.*?)\:\/\/(.*?)\:(.*?)\@(.*?)\:([0-9]{1, 6})\/(.*?)$/',trim($dsnStr),$matches);
$dsn = array (
'dbms' => $matches[1],
'username' => $matches[2],
'password' => $matches[3],
'hostname' => $matches[4],
'hostport' => $matches[5],
'database' => $matches[6]
);
}
$dsn['dsn'] = ''; // 兼容配置信息数组
return $dsn;
}
/**
+----------------------------------------------------------
* 数据库调试 记录当前SQL
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
*/
protected function debug() {
$this->modelSql[$this->model] = $this->queryStr;
$this->model = '_think_';
// 记录操作结束时间
if ( $this->debug ) {
G('queryEndTime');
Log::record($this->queryStr.' [ RunTime:'.G('queryStartTime','queryEndTime',6).'s ]',Log::SQL);
}
}
/**
+----------------------------------------------------------
* 设置锁机制
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseLock($lock=false) {
if(!$lock) return '';
if('ORACLE' == $this->dbType) {
return ' FOR UPDATE NOWAIT ';
}
return ' FOR UPDATE ';
}
/**
+----------------------------------------------------------
* set分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseSet($data) {
foreach ($data as $key=>$val){
$value = $this->parseValue($val);
if(is_scalar($value)) // 过滤非标量数据
$set[] = $this->parseKey($key).'='.$value;
}
return ' SET '.implode(',',$set);
}
/**
+----------------------------------------------------------
* 字段名分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $key
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseKey(&$key) {
return $key;
}
/**
+----------------------------------------------------------
* value分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $value
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseValue($value) {
if(is_string($value)) {
$value = '\''.$this->escapeString($value).'\'';
}elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){
$value = $this->escapeString($value[1]);
}elseif(is_array($value)) {
$value = array_map(array($this, 'parseValue'),$value);
}elseif(is_null($value)){
$value = 'null';
}
return $value;
}
/**
+----------------------------------------------------------
* field分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $fields
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseField($fields) {
if(is_string($fields) && strpos($fields,',')) {
$fields = explode(',',$fields);
}
if(is_array($fields)) {
// 完善数组方式传字段名的支持
// 支持 'field1'=>'field2' 这样的字段别名定义
$array = array();
foreach ($fields as $key=>$field){
if(!is_numeric($key))
$array[] = $this->parseKey($key).' AS '.$this->parseKey($field);
else
$array[] = $this->parseKey($field);
}
$fieldsStr = implode(',', $array);
}elseif(is_string($fields) && !empty($fields)) {
$fieldsStr = $this->parseKey($fields);
}else{
$fieldsStr = '*';
}
//TODO 如果是查询全部字段,并且是join的方式,那么就把要查的表加个别名,以免字段被覆盖
return $fieldsStr;
}
/**
+----------------------------------------------------------
* table分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $table
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseTable($tables) {
if(is_array($tables)) {// 支持别名定义
$array = array();
foreach ($tables as $table=>$alias){
if(!is_numeric($table))
$array[] = $this->parseKey($table).' '.$this->parseKey($alias);
else
$array[] = $this->parseKey($table);
}
$tables = $array;
}elseif(is_string($tables)){
$tables = explode(',',$tables);
array_walk($tables, array(&$this, 'parseKey'));
}
return implode(',',$tables);
}
/**
+----------------------------------------------------------
* where分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $where
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseWhere($where) {
$whereStr = '';
if(is_string($where)) {
// 直接使用字符串条件
$whereStr = $where;
}else{ // 使用数组或者对象条件表达式
if(isset($where['_logic'])) {
// 定义逻辑运算规则 例如 OR XOR AND NOT
$operate = ' '.strtoupper($where['_logic']).' ';
unset($where['_logic']);
}else{
// 默认进行 AND 运算
$operate = ' AND ';
}
foreach ($where as $key=>$val){
$whereStr .= '( ';
if(0===strpos($key,'_')) {
// 解析特殊条件表达式
$whereStr .= $this->parseThinkWhere($key,$val);
}else{
// 查询字段的安全过滤
if(!preg_match('/^[A-Z_\|\&\-.a-z0-9\(\)\,]+$/',trim($key))){
throw_exception(L('_EXPRESS_ERROR_').':'.$key);
}
// 多条件支持
$multi = is_array($val) && isset($val['_multi']);
$key = trim($key);
if(strpos($key,'|')) { // 支持 name|title|nickname 方式定义查询字段
$array = explode('|',$key);
$str = array();
foreach ($array as $m=>$k){
$v = $multi?$val[$m]:$val;
$str[] = '('.$this->parseWhereItem($this->parseKey($k),$v).')';
}
$whereStr .= implode(' OR ',$str);
}elseif(strpos($key,'&')){
$array = explode('&',$key);
$str = array();
foreach ($array as $m=>$k){
$v = $multi?$val[$m]:$val;
$str[] = '('.$this->parseWhereItem($this->parseKey($k),$v).')';
}
$whereStr .= implode(' AND ',$str);
}else{
$whereStr .= $this->parseWhereItem($this->parseKey($key),$val);
}
}
$whereStr .= ' )'.$operate;
}
$whereStr = substr($whereStr,0,-strlen($operate));
}
return empty($whereStr)?'':' WHERE '.$whereStr;
}
// where子单元分析
protected function parseWhereItem($key,$val) {
$whereStr = '';
if(is_array($val)) {
if(is_string($val[0])) {
if(preg_match('/^(EQ|NEQ|GT|EGT|LT|ELT|NOTLIKE|LIKE)$/i',$val[0])) { // 比较运算
$whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' '.$this->parseValue($val[1]);
}elseif('exp'==strtolower($val[0])){ // 使用表达式
$whereStr .= ' ('.$key.' '.$val[1].') ';
}elseif(preg_match('/IN/i',$val[0])){ // IN 运算
if(isset($val[2]) && 'exp'==$val[2]) {
$whereStr .= $key.' '.strtoupper($val[0]).' '.$val[1];
}else{
if(is_string($val[1])) {
$val[1] = explode(',',$val[1]);
}
$zone = implode(',',$this->parseValue($val[1]));
$whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')';
}
}elseif(preg_match('/BETWEEN/i',$val[0])){ // BETWEEN运算
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
$whereStr .= ' ('.$key.' '.strtoupper($val[0]).' '.$this->parseValue($data[0]).' AND '.$this->parseValue($data[1]).' )';
}else{
throw_exception(L('_EXPRESS_ERROR_').':'.$val[0]);
}
}else {
$count = count($val);
if(in_array(strtoupper(trim($val[$count-1])),array('AND','OR','XOR'))) {
$rule = strtoupper(trim($val[$count-1]));
$count = $count -1;
}else{
$rule = 'AND';
}
for($i=0;$i<$count;$i++) {
$data = is_array($val[$i])?$val[$i][1]:$val[$i];
if('exp'==strtolower($val[$i][0])) {
$whereStr .= '('.$key.' '.$data.') '.$rule.' ';
}else{
$op = is_array($val[$i])?$this->comparison[strtolower($val[$i][0])]:'=';
$whereStr .= '('.$key.' '.$op.' '.$this->parseValue($data).') '.$rule.' ';
}
}
$whereStr = substr($whereStr,0,-4);
}
}else {
//对字符串类型字段采用模糊匹配
if(C('DB_LIKE_FIELDS') && preg_match('/('.C('DB_LIKE_FIELDS').')/i',$key)) {
$val = '%'.$val.'%';
$whereStr .= $key.' LIKE '.$this->parseValue($val);
}else {
$whereStr .= $key.' = '.$this->parseValue($val);
}
}
return $whereStr;
}
/**
+----------------------------------------------------------
* 特殊条件分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $key
* @param mixed $val
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseThinkWhere($key,$val) {
$whereStr = '';
switch($key) {
case '_string':
// 字符串模式查询条件
$whereStr = $val;
break;
case '_complex':
// 复合查询条件
$whereStr = substr($this->parseWhere($val),6);
break;
case '_query':
// 字符串模式查询条件
parse_str($val,$where);
if(isset($where['_logic'])) {
$op = ' '.strtoupper($where['_logic']).' ';
unset($where['_logic']);
}else{
$op = ' AND ';
}
$array = array();
foreach ($where as $field=>$data)
$array[] = $this->parseKey($field).' = '.$this->parseValue($data);
$whereStr = implode($op,$array);
break;
}
return $whereStr;
}
/**
+----------------------------------------------------------
* limit分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $lmit
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseLimit($limit) {
return !empty($limit)? ' LIMIT '.$limit.' ':'';
}
/**
+----------------------------------------------------------
* join分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $join
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseJoin($join) {
$joinStr = '';
if(!empty($join)) {
if(is_array($join)) {
foreach ($join as $key=>$_join){
if(false !== stripos($_join,'JOIN'))
$joinStr .= ' '.$_join;
else
$joinStr .= ' LEFT JOIN ' .$_join;
}
}else{
$joinStr .= ' LEFT JOIN ' .$join;
}
}
//将__TABLE_NAME__这样的字符串替换成正规的表名,并且带上前缀和后缀
$joinStr = preg_replace("/__([A-Z_-]+)__/esU",C("DB_PREFIX").".strtolower('$1')",$joinStr);
return $joinStr;
}
/**
+----------------------------------------------------------
* order分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $order
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseOrder($order) {
if(is_array($order)) {
$array = array();
foreach ($order as $key=>$val){
if(is_numeric($key)) {
$array[] = $this->parseKey($val);
}else{
$array[] = $this->parseKey($key).' '.$val;
}
}
$order = implode(',',$array);
}
return !empty($order)? ' ORDER BY '.$order:'';
}
/**
+----------------------------------------------------------
* group分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $group
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseGroup($group) {
return !empty($group)? ' GROUP BY '.$group:'';
}
/**
+----------------------------------------------------------
* having分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $having
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseHaving($having) {
return !empty($having)? ' HAVING '.$having:'';
}
/**
+----------------------------------------------------------
* distinct分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $distinct
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseDistinct($distinct) {
return !empty($distinct)? ' DISTINCT ' :'';
}
/**
+----------------------------------------------------------
* union分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $union
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseUnion($union) {
if(empty($union)) return '';
if(isset($union['_all'])) {
$str = 'UNION ALL ';
unset($union['_all']);
}else{
$str = 'UNION ';
}
foreach ($union as $u){
$sql[] = $str.(is_array($u)?$this->buildSelectSql($u):$u);
}
return implode(' ',$sql);
}
/**
+----------------------------------------------------------
* 插入记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 参数表达式
* @param boolean $replace 是否replace
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function insert($data,$options=array(),$replace=false) {
$values = $fields = array();
$this->model = $options['model'];
foreach ($data as $key=>$val){
$value = $this->parseValue($val);
if(is_scalar($value)) { // 过滤非标量数据
$values[] = $value;
$fields[] = $this->parseKey($key);
}
}
$sql = ($replace?'REPLACE':'INSERT').' INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')';
$sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 通过Select方式插入记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $fields 要插入的数据表字段名
* @param string $table 要插入的数据表名
* @param array $option 查询数据参数
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function selectInsert($fields,$table,$options=array()) {
$this->model = $options['model'];
if(is_string($fields)) $fields = explode(',',$fields);
array_walk($fields, array($this, 'parseKey'));
$sql = 'INSERT INTO '.$this->parseTable($table).' ('.implode(',', $fields).') ';
$sql .= $this->buildSelectSql($options);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 更新记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function update($data,$options) {
$this->model = $options['model'];
$sql = 'UPDATE '
.$this->parseTable($options['table'])
.$this->parseSet($data)
.$this->parseWhere(isset($options['where'])?$options['where']:'')
.$this->parseOrder(isset($options['order'])?$options['order']:'')
.$this->parseLimit(isset($options['limit'])?$options['limit']:'')
.$this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 删除记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function delete($options=array()) {
$this->model = $options['model'];
$sql = 'DELETE FROM '
.$this->parseTable($options['table'])
.$this->parseWhere(isset($options['where'])?$options['where']:'')
.$this->parseOrder(isset($options['order'])?$options['order']:'')
.$this->parseLimit(isset($options['limit'])?$options['limit']:'')
.$this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 查找记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function select($options=array()) {
$this->model = $options['model'];
$sql = $this->buildSelectSql($options);
$cache = isset($options['cache'])?$options['cache']:false;
if($cache) { // 查询缓存检测
$key = is_string($cache['key'])?$cache['key']:md5($sql);
$value = S($key,'','',$cache['type']);
if(false !== $value) {
return $value;
}
}
$result = $this->query($sql);
if($cache && false !== $result ) { // 查询缓存写入
S($key,$result,$cache['expire'],$cache['type']);
}
return $result;
}
/**
+----------------------------------------------------------
* 生成查询SQL
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function buildSelectSql($options=array()) {
if(isset($options['page'])) {
// 根据页数计算limit
if(strpos($options['page'],',')) {
list($page,$listRows) = explode(',',$options['page']);
}else{
$page = $options['page'];
}
$page = $page?$page:1;
$listRows = isset($listRows)?$listRows:(is_numeric($options['limit'])?$options['limit']:20);
$offset = $listRows*((int)$page-1);
$options['limit'] = $offset.','.$listRows;
}
if(C('DB_SQL_BUILD_CACHE')) { // SQL创建缓存
$key = md5(serialize($options));
$value = S($key);
if(false !== $value) {
return $value;
}
}
$sql = $this->parseSql($this->selectSql,$options);
$sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false);
if(isset($key)) { // 写入SQL创建缓存
S($key,$sql,0,'',array('length'=>C('DB_SQL_BUILD_LENGTH'),'queue'=>C('DB_SQL_BUILD_QUEUE')));
}
return $sql;
}
/**
+----------------------------------------------------------
* 替换SQL语句中表达式
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseSql($sql,$options=array()){
$sql = str_replace(
array('%TABLE%','%DISTINCT%','%FIELD%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%','%UNION%'),
array(
$this->parseTable($options['table']),
$this->parseDistinct(isset($options['distinct'])?$options['distinct']:false),
$this->parseField(isset($options['field'])?$options['field']:'*'),
$this->parseJoin(isset($options['join'])?$options['join']:''),
$this->parseWhere(isset($options['where'])?$options['where']:''),
$this->parseGroup(isset($options['group'])?$options['group']:''),
$this->parseHaving(isset($options['having'])?$options['having']:''),
$this->parseOrder(isset($options['order'])?$options['order']:''),
$this->parseLimit(isset($options['limit'])?$options['limit']:''),
$this->parseUnion(isset($options['union'])?$options['union']:'')
),$sql);
return $sql;
}
/**
+----------------------------------------------------------
* 获取最近一次查询的sql语句
+----------------------------------------------------------
* @param string $model 模型名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastSql($model='') {
return $model?$this->modelSql[$model]:$this->queryStr;
}
/**
+----------------------------------------------------------
* 获取最近插入的ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastInsID() {
return $this->lastInsID;
}
/**
+----------------------------------------------------------
* 获取最近的错误信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getError() {
return $this->error;
}
/**
+----------------------------------------------------------
* SQL指令安全过滤
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str SQL字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function escapeString($str) {
return addslashes($str);
}
public function setModel($model){
$this->model = $model;
}
/**
+----------------------------------------------------------
* 析构方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __destruct() {
// 释放查询
if ($this->queryID){
$this->free();
}
// 关闭连接
$this->close();
}
// 关闭数据库 由驱动类定义
public function close(){}
} | 10npsite | trunk/DThinkPHP/Lib/Core/Db.class.php | PHP | asf20 | 42,906 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Model.class.php 2815 2012-03-13 07:08:56Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP Model模型类
* 实现了ORM和ActiveRecords模式
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: Model.class.php 2815 2012-03-13 07:08:56Z liu21st $
+------------------------------------------------------------------------------
*/
class Model {
// 操作状态
const MODEL_INSERT = 1; // 插入模型数据
const MODEL_UPDATE = 2; // 更新模型数据
const MODEL_BOTH = 3; // 包含上面两种方式
const MUST_VALIDATE = 1;// 必须验证
const EXISTS_VAILIDATE = 0;// 表单存在字段则验证
const VALUE_VAILIDATE = 2;// 表单值不为空则验证
// 当前使用的扩展模型
private $_extModel = null;
// 当前数据库操作对象
protected $db = null;
// 主键名称
protected $pk = 'id';
// 数据表前缀
protected $tablePrefix = '';
// 模型名称
protected $name = '';
// 数据库名称
protected $dbName = '';
// 数据表名(不包含表前缀)
protected $tableName = '';
// 实际数据表名(包含表前缀)
protected $trueTableName ='';
// 最近错误信息
protected $error = '';
// 字段信息
protected $fields = array();
// 数据信息
protected $data = array();
// 查询表达式参数
protected $options = array();
protected $_validate = array(); // 自动验证定义
protected $_auto = array(); // 自动完成定义
protected $_map = array(); // 字段映射定义
// 是否自动检测数据表字段信息
protected $autoCheckFields = true;
// 是否批处理验证
protected $patchValidate = false;
/**
+----------------------------------------------------------
* 架构函数
* 取得DB类的实例对象 字段检查
+----------------------------------------------------------
* @param string $name 模型名称
* @param string $tablePrefix 表前缀
* @param mixed $connection 数据库连接信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($name='',$tablePrefix='',$connection='') {
// 模型初始化
$this->_initialize();
// 获取模型名称
if(!empty($name)) {
if(strpos($name,'.')) { // 支持 数据库名.模型名的 定义
list($this->dbName,$this->name) = explode('.',$name);
}else{
$this->name = $name;
}
}elseif(empty($this->name)){
$this->name = $this->getModelName();
}
// 设置表前缀
if(is_null($tablePrefix)) {// 前缀为Null表示没有前缀
$this->tablePrefix = '';
}elseif('' != $tablePrefix) {
$this->tablePrefix = $tablePrefix;
}else{
$this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX');
}
// 数据库初始化操作
// 获取数据库操作对象
// 当前模型有独立的数据库连接信息
$this->db(0,empty($this->connection)?$connection:$this->connection);
}
/**
+----------------------------------------------------------
* 自动检测数据表信息
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function _checkTableInfo() {
// 如果不是Model类 自动记录数据表信息
// 只在第一次执行记录
if(empty($this->fields)) {
// 如果数据表字段没有定义则自动获取
if(C('DB_FIELDS_CACHE')) {
$db = $this->dbName?$this->dbName:C('DB_NAME');
$this->fields = F('_fields/'.$db.'.'.$this->name);
if(!$this->fields) $this->flush();
}else{
// 每次都会读取数据表信息
$this->flush();
}
}
}
/**
+----------------------------------------------------------
* 获取字段信息并缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function flush() {
// 缓存不存在则查询数据表信息
$this->db->setModel($this->name);
$fields = $this->db->getFields($this->getTableName());
if(!$fields) { // 无法获取字段信息
return false;
}
$this->fields = array_keys($fields);
$this->fields['_autoinc'] = false;
foreach ($fields as $key=>$val){
// 记录字段类型
$type[$key] = $val['type'];
if($val['primary']) {
$this->fields['_pk'] = $key;
if($val['autoinc']) $this->fields['_autoinc'] = true;
}
}
// 记录字段类型信息
if(C('DB_FIELDTYPE_CHECK')) $this->fields['_type'] = $type;
// 2008-3-7 增加缓存开关控制
if(C('DB_FIELDS_CACHE')){
// 永久缓存数据表信息
$db = $this->dbName?$this->dbName:C('DB_NAME');
F('_fields/'.$db.'.'.$this->name,$this->fields);
}
}
/**
+----------------------------------------------------------
* 动态切换扩展模型
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $type 模型类型名称
* @param mixed $vars 要传入扩展模型的属性变量
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function switchModel($type,$vars=array()) {
$class = ucwords(strtolower($type)).'Model';
if(!class_exists($class))
throw_exception($class.L('_MODEL_NOT_EXIST_'));
// 实例化扩展模型
$this->_extModel = new $class($this->name);
if(!empty($vars)) {
// 传入当前模型的属性到扩展模型
foreach ($vars as $var)
$this->_extModel->setProperty($var,$this->$var);
}
return $this->_extModel;
}
/**
+----------------------------------------------------------
* 设置数据对象的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
* @param mixed $value 值
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function __set($name,$value) {
// 设置数据对象属性
$this->data[$name] = $value;
}
/**
+----------------------------------------------------------
* 获取数据对象的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __get($name) {
return isset($this->data[$name])?$this->data[$name]:null;
}
/**
+----------------------------------------------------------
* 检测数据对象的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function __isset($name) {
return isset($this->data[$name]);
}
/**
+----------------------------------------------------------
* 销毁数据对象的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function __unset($name) {
unset($this->data[$name]);
}
/**
+----------------------------------------------------------
* 利用__call方法实现一些特殊的Model方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名称
* @param array $args 调用参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$args) {
if(in_array(strtolower($method),array('table','where','order','limit','page','alias','having','group','lock','distinct'),true)) {
// 连贯操作的实现
$this->options[strtolower($method)] = $args[0];
return $this;
}elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){
// 统计查询的实现
$field = isset($args[0])?$args[0]:'*';
return $this->getField(strtoupper($method).'('.$field.') AS tp_'.$method);
}elseif(strtolower(substr($method,0,5))=='getby') {
// 根据某个字段获取记录
$field = parse_name(substr($method,5));
$where[$field] = $args[0];
return $this->where($where)->find();
}elseif(strtolower(substr($method,0,10))=='getfieldby') {
// 根据某个字段获取记录的某个值
$name = parse_name(substr($method,10));
$where[$name] =$args[0];
return $this->where($where)->getField($args[1]);
}else{
throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
return;
}
}
// 回调方法 初始化模型
protected function _initialize() {}
/**
+----------------------------------------------------------
* 对保存到数据库的数据进行处理
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 要操作的数据
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
protected function _facade($data) {
// 检查非数据字段
if(!empty($this->fields)) {
foreach ($data as $key=>$val){
if(!in_array($key,$this->fields,true)){
unset($data[$key]);
}elseif(C('DB_FIELDTYPE_CHECK') && is_scalar($val)) {
// 字段类型检查
$this->_parseType($data,$key);
}
}
}
$this->_before_write($data);
return $data;
}
// 写入数据前的回调方法 包括新增和更新
protected function _before_write(&$data) {}
/**
+----------------------------------------------------------
* 新增数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
* @param boolean $replace 是否replace
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function add($data='',$options=array(),$replace=false) {
if(empty($data)) {
// 没有传递数据,获取当前数据对象的值
if(!empty($this->data)) {
$data = $this->data;
// 重置数据
$this->data = array();
}else{
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
}
// 分析表达式
$options = $this->_parseOptions($options);
// 数据处理
$data = $this->_facade($data);
if(false === $this->_before_insert($data,$options)) {
return false;
}
// 写入数据到数据库
$result = $this->db->insert($data,$options,$replace);
if(false !== $result ) {
$insertId = $this->getLastInsID();
if($insertId) {
// 自增主键返回插入ID
$data[$this->getPk()] = $insertId;
$this->_after_insert($data,$options);
return $insertId;
}
}
return $result;
}
// 插入数据前的回调方法
protected function _before_insert(&$data,$options) {}
// 插入成功后的回调方法
protected function _after_insert($data,$options) {}
public function addAll($dataList,$options=array(),$replace=false){
if(empty($dataList)) {
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
// 分析表达式
$options = $this->_parseOptions($options);
// 数据处理
foreach ($dataList as $key=>$data){
$dataList[$key] = $this->_facade($data);
}
// 写入数据到数据库
$result = $this->db->insertAll($dataList,$options,$replace);
if(false !== $result ) {
$insertId = $this->getLastInsID();
if($insertId) {
return $insertId;
}
}
return $result;
}
/**
+----------------------------------------------------------
* 通过Select方式添加记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $fields 要插入的数据表字段名
* @param string $table 要插入的数据表名
* @param array $options 表达式
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function selectAdd($fields='',$table='',$options=array()) {
// 分析表达式
$options = $this->_parseOptions($options);
// 写入数据到数据库
if(false === $result = $this->db->selectInsert($fields?$fields:$options['field'],$table?$table:$this->getTableName(),$options)){
// 数据库插入操作失败
$this->error = L('_OPERATION_WRONG_');
return false;
}else {
// 插入成功
return $result;
}
}
/**
+----------------------------------------------------------
* 保存数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function save($data='',$options=array()) {
if(empty($data)) {
// 没有传递数据,获取当前数据对象的值
if(!empty($this->data)) {
$data = $this->data;
// 重置数据
$this->data = array();
}else{
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
}
// 数据处理
$data = $this->_facade($data);
// 分析表达式
$options = $this->_parseOptions($options);
if(false === $this->_before_update($data,$options)) {
return false;
}
if(!isset($options['where']) ) {
// 如果存在主键数据 则自动作为更新条件
if(isset($data[$this->getPk()])) {
$pk = $this->getPk();
$where[$pk] = $data[$pk];
$options['where'] = $where;
$pkValue = $data[$pk];
unset($data[$pk]);
}else{
// 如果没有任何更新条件则不执行
$this->error = L('_OPERATION_WRONG_');
return false;
}
}
$result = $this->db->update($data,$options);
if(false !== $result) {
if(isset($pkValue)) $data[$pk] = $pkValue;
$this->_after_update($data,$options);
}
return $result;
}
// 更新数据前的回调方法
protected function _before_update(&$data,$options) {}
// 更新成功后的回调方法
protected function _after_update($data,$options) {}
/**
+----------------------------------------------------------
* 删除数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $options 表达式
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function delete($options=array()) {
if(empty($options) && empty($this->options['where'])) {
// 如果删除条件为空 则删除当前数据对象所对应的记录
if(!empty($this->data) && isset($this->data[$this->getPk()]))
return $this->delete($this->data[$this->getPk()]);
else
return false;
}
if(is_numeric($options) || is_string($options)) {
// 根据主键删除记录
$pk = $this->getPk();
if(strpos($options,',')) {
$where[$pk] = array('IN', $options);
}else{
$where[$pk] = $options;
$pkValue = $options;
}
$options = array();
$options['where'] = $where;
}
// 分析表达式
$options = $this->_parseOptions($options);
$result= $this->db->delete($options);
if(false !== $result) {
$data = array();
if(isset($pkValue)) $data[$pk] = $pkValue;
$this->_after_delete($data,$options);
}
// 返回删除记录个数
return $result;
}
// 删除成功后的回调方法
protected function _after_delete($data,$options) {}
/**
+----------------------------------------------------------
* 查询数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function select($options=array()) {
if(is_string($options) || is_numeric($options)) {
// 根据主键查询
$pk = $this->getPk();
if(strpos($options,',')) {
$where[$pk] = array('IN',$options);
}else{
$where[$pk] = $options;
}
$options = array();
$options['where'] = $where;
}elseif(false === $options){ // 用于子查询 不查询只返回SQL
$options = array();
// 分析表达式
$options = $this->_parseOptions($options);
return '( '.$this->db->buildSelectSql($options).' )';
}
// 分析表达式
$options = $this->_parseOptions($options);
$resultSet = $this->db->select($options);
if(false === $resultSet) {
return false;
}
if(empty($resultSet)) { // 查询结果为空
return null;
}
$this->_after_select($resultSet,$options);
return $resultSet;
}
// 查询成功后的回调方法
protected function _after_select(&$resultSet,$options) {}
/**
+----------------------------------------------------------
* 生成查询SQL 可用于子查询
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式参数
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function buildSql($options=array()) {
// 分析表达式
$options = $this->_parseOptions($options);
return '( '.$this->db->buildSelectSql($options).' )';
}
/**
+----------------------------------------------------------
* 分析表达式
+----------------------------------------------------------
* @access proteced
+----------------------------------------------------------
* @param array $options 表达式参数
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function _parseOptions($options=array()) {
if(is_array($options))
$options = array_merge($this->options,$options);
// 查询过后清空sql表达式组装 避免影响下次查询
$this->options = array();
if(!isset($options['table']))
// 自动获取表名
$options['table'] =$this->getTableName();
if(!empty($options['alias'])) {
$options['table'] .= ' '.$options['alias'];
}
// 记录操作的模型名称
$options['model'] = $this->name;
// 字段类型验证
if(C('DB_FIELDTYPE_CHECK')) {
if(isset($options['where']) && is_array($options['where'])) {
// 对数组查询条件进行字段类型检查
foreach ($options['where'] as $key=>$val){
if(in_array($key,$this->fields,true) && is_scalar($val)){
$this->_parseType($options['where'],$key);
}
}
}
}
// 表达式过滤
$this->_options_filter($options);
return $options;
}
// 表达式过滤回调方法
protected function _options_filter(&$options) {}
/**
+----------------------------------------------------------
* 数据类型检测
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 数据
* @param string $key 字段名
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function _parseType(&$data,$key) {
$fieldType = strtolower($this->fields['_type'][$key]);
if(false === strpos($fieldType,'bigint') && false !== strpos($fieldType,'int')) {
$data[$key] = intval($data[$key]);
}elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){
$data[$key] = floatval($data[$key]);
}elseif(false !== strpos($fieldType,'bool')){
$data[$key] = (bool)$data[$key];
}
}
/**
+----------------------------------------------------------
* 查询数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $options 表达式参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function find($options=array()) {
if(is_numeric($options) || is_string($options)) {
$where[$this->getPk()] =$options;
$options = array();
$options['where'] = $where;
}
// 总是查找一条记录
$options['limit'] = 1;
// 分析表达式
$options = $this->_parseOptions($options);
$resultSet = $this->db->select($options);
if(false === $resultSet) {
return false;
}
if(empty($resultSet)) {// 查询结果为空
return null;
}
$this->data = $resultSet[0];
$this->_after_find($this->data,$options);
return $this->data;
}
// 查询成功的回调方法
protected function _after_find(&$result,$options) {}
/**
+----------------------------------------------------------
* 处理字段映射
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $data 当前数据
* @param integer $type 类型 0 写入 1 读取
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function parseFieldsMap($data,$type=1) {
// 检查字段映射
if(!empty($this->_map)) {
foreach ($this->_map as $key=>$val){
if($type==1) { // 读取
if(isset($data[$val])) {
$data[$key] = $data[$val];
unset($data[$val]);
}
}else{
if(isset($data[$key])) {
$data[$val] = $data[$key];
unset($data[$key]);
}
}
}
}
return $data;
}
/**
+----------------------------------------------------------
* 设置记录的某个字段值
* 支持使用数据库字段和方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string|array $field 字段名
* @param string $value 字段值
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function setField($field,$value='') {
if(is_array($field)) {
$data = $field;
}else{
$data[$field] = $value;
}
return $this->save($data);
}
/**
+----------------------------------------------------------
* 字段值增长
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $field 字段名
* @param integer $step 增长值
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function setInc($field,$step=1) {
return $this->setField($field,array('exp',$field.'+'.$step));
}
/**
+----------------------------------------------------------
* 字段值减少
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $field 字段名
* @param integer $step 减少值
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function setDec($field,$step=1) {
return $this->setField($field,array('exp',$field.'-'.$step));
}
/**
+----------------------------------------------------------
* 获取一条记录的某个字段值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $field 字段名
* @param string $spea 字段数据间隔符号 NULL返回数组
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function getField($field,$sepa=null) {
$options['field'] = $field;
$options = $this->_parseOptions($options);
if(strpos($field,',')) { // 多字段
$resultSet = $this->db->select($options);
if(!empty($resultSet)) {
$_field = explode(',', $field);
$field = array_keys($resultSet[0]);
$move = $_field[0]==$_field[1]?false:true;
$key = array_shift($field);
$key2 = array_shift($field);
$cols = array();
$count = count($_field);
foreach ($resultSet as $result){
$name = $result[$key];
if($move) { // 删除键值记录
unset($result[$key]);
}
if(2==$count) {
$cols[$name] = $result[$key2];
}else{
$cols[$name] = is_null($sepa)?$result:implode($sepa,$result);
}
}
return $cols;
}
}else{ // 查找一条记录
$options['limit'] = 1;
$result = $this->db->select($options);
if(!empty($result)) {
return reset($result[0]);
}
}
return null;
}
/**
+----------------------------------------------------------
* 创建数据对象 但不保存到数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 创建数据
* @param string $type 状态
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function create($data='',$type='') {
// 如果没有传值默认取POST数据
if(empty($data)) {
$data = $_POST;
}elseif(is_object($data)){
$data = get_object_vars($data);
}
// 验证数据
if(empty($data) || !is_array($data)) {
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
// 检查字段映射
$data = $this->parseFieldsMap($data,0);
// 状态
$type = $type?$type:(!empty($data[$this->getPk()])?self::MODEL_UPDATE:self::MODEL_INSERT);
// 数据自动验证
if(!$this->autoValidation($data,$type)) return false;
// 表单令牌验证
if(C('TOKEN_ON') && !$this->autoCheckToken($data)) {
$this->error = L('_TOKEN_ERROR_');
return false;
}
// 验证完成生成数据对象
if($this->autoCheckFields) { // 开启字段检测 则过滤非法字段数据
$vo = array();
foreach ($this->fields as $key=>$name){
if(substr($key,0,1)=='_') continue;
$val = isset($data[$name])?$data[$name]:null;
//保证赋值有效
if(!is_null($val)){
$vo[$name] = (MAGIC_QUOTES_GPC && is_string($val))? stripslashes($val) : $val;
}
}
}else{
$vo = $data;
}
// 创建完成对数据进行自动处理
$this->autoOperation($vo,$type);
// 赋值当前数据对象
$this->data = $vo;
// 返回创建的数据以供其他调用
return $vo;
}
// 自动表单令牌验证
// TODO ajax无刷新多次提交暂不能满足
public function autoCheckToken($data) {
if(C('TOKEN_ON')){
$name = C('TOKEN_NAME');
if(!isset($data[$name]) || !isset($_SESSION[$name])) { // 令牌数据无效
return false;
}
// 令牌验证
list($key,$value) = explode('_',$data[$name]);
if($_SESSION[$name][$key] == $value) { // 防止重复提交
unset($_SESSION[$name][$key]); // 验证完成销毁session
return true;
}
// 开启TOKEN重置
if(C('TOKEN_RESET')) unset($_SESSION[$name][$key]);
return false;
}
return true;
}
/**
+----------------------------------------------------------
* 使用正则验证数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $value 要验证的数据
* @param string $rule 验证规则
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function regex($value,$rule) {
$validate = array(
'require'=> '/.+/',
'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
'url' => '/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/',
'currency' => '/^\d+(\.\d+)?$/',
'number' => '/^\d+$/',
'zip' => '/^[1-9]\d{5}$/',
'integer' => '/^[-\+]?\d+$/',
'double' => '/^[-\+]?\d+(\.\d+)?$/',
'english' => '/^[A-Za-z]+$/',
);
// 检查是否有内置的正则表达式
if(isset($validate[strtolower($rule)]))
$rule = $validate[strtolower($rule)];
return preg_match($rule,$value)===1;
}
/**
+----------------------------------------------------------
* 自动表单处理
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $data 创建数据
* @param string $type 创建类型
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
private function autoOperation(&$data,$type) {
// 自动填充
if(!empty($this->_auto)) {
foreach ($this->_auto as $auto){
// 填充因子定义格式
// array('field','填充内容','填充条件','附加规则',[额外参数])
if(empty($auto[2])) $auto[2] = self::MODEL_INSERT; // 默认为新增的时候自动填充
if( $type == $auto[2] || $auto[2] == self::MODEL_BOTH) {
switch($auto[3]) {
case 'function': // 使用函数进行填充 字段的值作为参数
case 'callback': // 使用回调方法
$args = isset($auto[4])?(array)$auto[4]:array();
if(isset($data[$auto[0]])) {
array_unshift($args,$data[$auto[0]]);
}
if('function'==$auto[3]) {
$data[$auto[0]] = call_user_func_array($auto[1], $args);
}else{
$data[$auto[0]] = call_user_func_array(array(&$this,$auto[1]), $args);
}
break;
case 'field': // 用其它字段的值进行填充
$data[$auto[0]] = $data[$auto[1]];
break;
case 'string':
default: // 默认作为字符串填充
$data[$auto[0]] = $auto[1];
}
if(false === $data[$auto[0]] ) unset($data[$auto[0]]);
}
}
}
return $data;
}
/**
+----------------------------------------------------------
* 自动表单验证
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data 创建数据
* @param string $type 创建类型
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
protected function autoValidation($data,$type) {
// 属性验证
if(!empty($this->_validate)) { // 如果设置了数据自动验证则进行数据验证
if($this->patchValidate) { // 重置验证错误信息
$this->error = array();
}
foreach($this->_validate as $key=>$val) {
// 验证因子定义格式
// array(field,rule,message,condition,type,when,params)
// 判断是否需要执行验证
if(empty($val[5]) || $val[5]== self::MODEL_BOTH || $val[5]== $type ) {
if(0==strpos($val[2],'{%') && strpos($val[2],'}'))
// 支持提示信息的多语言 使用 {%语言定义} 方式
$val[2] = L(substr($val[2],2,-1));
$val[3] = isset($val[3])?$val[3]:self::EXISTS_VAILIDATE;
$val[4] = isset($val[4])?$val[4]:'regex';
// 判断验证条件
switch($val[3]) {
case self::MUST_VALIDATE: // 必须验证 不管表单是否有设置该字段
if(false === $this->_validationField($data,$val))
return false;
break;
case self::VALUE_VAILIDATE: // 值不为空的时候才验证
if('' != trim($data[$val[0]]))
if(false === $this->_validationField($data,$val))
return false;
break;
default: // 默认表单存在该字段就验证
if(isset($data[$val[0]]))
if(false === $this->_validationField($data,$val))
return false;
}
}
}
// 批量验证的时候最后返回错误
if(!empty($this->error)) return false;
}
return true;
}
/**
+----------------------------------------------------------
* 验证表单字段 支持批量验证
* 如果批量验证返回错误的数组信息
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data 创建数据
* @param array $val 验证因子
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
protected function _validationField($data,$val) {
if(false === $this->_validationFieldItem($data,$val)){
if($this->patchValidate) {
$this->error[$val[0]] = $val[2];
}else{
$this->error = $val[2];
return false;
}
}
return ;
}
/**
+----------------------------------------------------------
* 根据验证因子验证字段
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data 创建数据
* @param array $val 验证因子
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
protected function _validationFieldItem($data,$val) {
switch($val[4]) {
case 'function':// 使用函数进行验证
case 'callback':// 调用方法进行验证
$args = isset($val[6])?(array)$val[6]:array();
array_unshift($args,$data[$val[0]]);
if('function'==$val[4]) {
return call_user_func_array($val[1], $args);
}else{
return call_user_func_array(array(&$this, $val[1]), $args);
}
case 'confirm': // 验证两个字段是否相同
return $data[$val[0]] == $data[$val[1]];
case 'unique': // 验证某个值是否唯一
if(is_string($val[0]) && strpos($val[0],','))
$val[0] = explode(',',$val[0]);
$map = array();
if(is_array($val[0])) {
// 支持多个字段验证
foreach ($val[0] as $field)
$map[$field] = $data[$field];
}else{
$map[$val[0]] = $data[$val[0]];
}
if(!empty($data[$this->getPk()])) { // 完善编辑的时候验证唯一
$map[$this->getPk()] = array('neq',$data[$this->getPk()]);
}
if($this->field($this->getPk())->where($map)->find()) return false;
return true;
default: // 检查附加规则
return $this->check($data[$val[0]],$val[1],$val[4]);
}
}
/**
+----------------------------------------------------------
* 验证数据 支持 in between equal length regex expire ip_allow ip_deny
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $value 验证数据
* @param mixed $rule 验证表达式
* @param string $type 验证方式 默认为正则验证
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function check($value,$rule,$type='regex'){
switch(strtolower($type)) {
case 'in': // 验证是否在某个指定范围之内 逗号分隔字符串或者数组
$range = is_array($rule)?$rule:explode(',',$rule);
return in_array($value ,$range);
case 'between': // 验证是否在某个范围
list($min,$max) = explode(',',$rule);
return $value>=$min && $value<=$max;
case 'equal': // 验证是否等于某个值
return $value == $rule;
case 'length': // 验证长度
$length = mb_strlen($value,'utf-8'); // 当前数据长度
if(strpos($rule,',')) { // 长度区间
list($min,$max) = explode(',',$rule);
return $length >= $min && $length <= $max;
}else{// 指定长度
return $length == $rule;
}
case 'expire':
list($start,$end) = explode(',',$rule);
if(!is_numeric($start)) $start = strtotime($start);
if(!is_numeric($end)) $end = strtotime($end);
return $_SERVER['REQUEST_TIME'] >= $start && $_SERVER['REQUEST_TIME'] <= $end;
case 'ip_allow': // IP 操作许可验证
return in_array(get_client_ip(),explode(',',$rule));
case 'ip_deny': // IP 操作禁止验证
return !in_array(get_client_ip(),explode(',',$rule));
case 'regex':
default: // 默认使用正则验证 可以使用验证类中定义的验证名称
// 检查附加规则
return $this->regex($value,$rule);
}
}
/**
+----------------------------------------------------------
* SQL查询
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $sql SQL指令
* @param boolean $parse 是否需要解析SQL
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function query($sql,$parse=false) {
$sql = $this->parseSql($sql,$parse);
return $this->db->query($sql);
}
/**
+----------------------------------------------------------
* 执行SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $sql SQL指令
* @param boolean $parse 是否需要解析SQL
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function execute($sql,$parse=false) {
$sql = $this->parseSql($sql,$parse);
return $this->db->execute($sql);
}
/**
+----------------------------------------------------------
* 解析SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $sql SQL指令
* @param boolean $parse 是否需要解析SQL
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseSql($sql,$parse) {
// 分析表达式
if($parse) {
$options = $this->_parseOptions();
$sql = $this->db->parseSql($sql,$options);
}else{
if(strpos($sql,'__TABLE__'))
$sql = str_replace('__TABLE__',$this->getTableName(),$sql);
}
$this->db->setModel($this->name);
return $sql;
}
/**
+----------------------------------------------------------
* 切换当前的数据库连接
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param integer $linkNum 连接序号
* @param mixed $config 数据库连接信息
* @param array $params 模型参数
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function db($linkNum,$config='',$params=array()){
static $_db = array();
if(!isset($_db[$linkNum])) {
// 创建一个新的实例
if(!empty($config) && is_string($config) && false === strpos($config,'/')) { // 支持读取配置参数
$config = C($config);
}
$_db[$linkNum] = Db::getInstance($config);
}elseif(NULL === $config){
$_db[$linkNum]->close(); // 关闭数据库连接
unset($_db[$linkNum]);
return ;
}
if(!empty($params)) {
if(is_string($params)) parse_str($params,$params);
foreach ($params as $name=>$value){
$this->setProperty($name,$value);
}
}
// 切换数据库连接
$this->db = $_db[$linkNum];
$this->_after_db();
// 字段检测
if(!empty($this->name) && $this->autoCheckFields) $this->_checkTableInfo();
return $this;
}
// 数据库切换后回调方法
protected function _after_db() {}
/**
+----------------------------------------------------------
* 得到当前的数据对象名称
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getModelName() {
if(empty($this->name))
$this->name = substr(get_class($this),0,-5);
return $this->name;
}
/**
+----------------------------------------------------------
* 得到完整的数据表名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getTableName() {
if(empty($this->trueTableName)) {
$tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
if(!empty($this->tableName)) {
$tableName .= $this->tableName;
}else{
$tableName .= parse_name($this->name);
}
$this->trueTableName = strtolower($tableName);
}
return (!empty($this->dbName)?$this->dbName.'.':'').$this->trueTableName;
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function startTrans() {
$this->commit();
$this->db->startTrans();
return ;
}
/**
+----------------------------------------------------------
* 提交事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function commit() {
return $this->db->commit();
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function rollback() {
return $this->db->rollback();
}
/**
+----------------------------------------------------------
* 返回模型的错误信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getError(){
return $this->error;
}
/**
+----------------------------------------------------------
* 返回数据库的错误信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getDbError() {
return $this->db->getError();
}
/**
+----------------------------------------------------------
* 返回最后插入的ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastInsID() {
return $this->db->getLastInsID();
}
/**
+----------------------------------------------------------
* 返回最后执行的sql语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastSql() {
return $this->db->getLastSql($this->name);
}
// 鉴于getLastSql比较常用 增加_sql 别名
public function _sql(){
return $this->getLastSql();
}
/**
+----------------------------------------------------------
* 获取主键名称
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getPk() {
return isset($this->fields['_pk'])?$this->fields['_pk']:$this->pk;
}
/**
+----------------------------------------------------------
* 获取数据表字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getDbFields(){
if($this->fields) {
$fields = $this->fields;
unset($fields['_autoinc'],$fields['_pk'],$fields['_type']);
return $fields;
}
return false;
}
/**
+----------------------------------------------------------
* 设置数据对象值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function data($data){
if(is_object($data)){
$data = get_object_vars($data);
}elseif(is_string($data)){
parse_str($data,$data);
}elseif(!is_array($data)){
throw_exception(L('_DATA_TYPE_INVALID_'));
}
$this->data = $data;
return $this;
}
/**
+----------------------------------------------------------
* 查询SQL组装 join
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $join
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function join($join) {
if(is_array($join)) {
$this->options['join'] = $join;
}elseif(!empty($join)) {
$this->options['join'][] = $join;
}
return $this;
}
/**
+----------------------------------------------------------
* 查询SQL组装 union
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $union
* @param boolean $all
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function union($union,$all=false) {
if(empty($union)) return $this;
if($all) {
$this->options['union']['_all'] = true;
}
if(is_object($union)) {
$union = get_object_vars($union);
}
// 转换union表达式
if(is_string($union) ) {
$options = $union;
}elseif(is_array($union)){
if(isset($union[0])) {
$this->options['union'] = array_merge($this->options['union'],$union);
return $this;
}else{
$options = $union;
}
}else{
throw_exception(L('_DATA_TYPE_INVALID_'));
}
$this->options['union'][] = $options;
return $this;
}
/**
+----------------------------------------------------------
* 查询缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $key
* @param integer $expire
* @param string $type
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function cache($key=true,$expire='',$type=''){
$this->options['cache'] = array('key'=>$key,'expire'=>$expire,'type'=>$type);
return $this;
}
/**
+----------------------------------------------------------
* 指定查询字段 支持字段排除
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $field
* @param boolean $except 是否排除
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function field($field,$except=false){
if(true === $field) {// 获取全部字段
$fields = $this->getDbFields();
$field = $fields?$fields:'*';
}elseif($except) {// 字段排除
if(is_string($field)) {
$field = explode(',',$field);
}
$fields = $this->getDbFields();
$field = $fields?array_diff($fields,$field):$field;
}
$this->options['field'] = $field;
return $this;
}
/**
+----------------------------------------------------------
* 设置模型的属性值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
* @param mixed $value 值
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function setProperty($name,$value) {
if(property_exists($this,$name))
$this->$name = $value;
return $this;
}
} | 10npsite | trunk/DThinkPHP/Lib/Core/Model.class.php | PHP | asf20 | 62,017 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Widget.class.php 2783 2012-02-25 06:49:45Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP Widget类 抽象类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id: Widget.class.php 2783 2012-02-25 06:49:45Z liu21st $
+------------------------------------------------------------------------------
*/
abstract class Widget {
// 使用的模板引擎 每个Widget可以单独配置不受系统影响
protected $template = '';
/**
+----------------------------------------------------------
* 渲染输出 render方法是Widget唯一的接口
* 使用字符串返回 不能有任何输出
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 要渲染的数据
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
abstract public function render($data);
/**
+----------------------------------------------------------
* 渲染模板输出 供render方法内部调用
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $templateFile 模板文件
* @param mixed $var 模板变量
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function renderFile($templateFile='',$var='') {
ob_start();
ob_implicit_flush(0);
if(!file_exists_case($templateFile)){
// 自动定位模板文件
$name = substr(get_class($this),0,-6);
$filename = empty($templateFile)?$name:$templateFile;
$templateFile = LIB_PATH.'Widget/'.$name.'/'.$filename.C('TMPL_TEMPLATE_SUFFIX');
if(!file_exists_case($templateFile))
throw_exception(L('_TEMPLATE_NOT_EXIST_').'['.$templateFile.']');
}
$template = strtolower($this->template?$this->template:(C('TMPL_ENGINE_TYPE')?C('TMPL_ENGINE_TYPE'):'php'));
if('php' == $template) {
// 使用PHP模板
if(!empty($var)) extract($var, EXTR_OVERWRITE);
// 直接载入PHP模板
include $templateFile;
}elseif('think'==$template){ // 采用Think模板引擎
if($this->checkCache($templateFile)) { // 缓存有效
// 分解变量并载入模板缓存
extract($var, EXTR_OVERWRITE);
//载入模版缓存文件
include C('CACHE_PATH').md5($templateFile).C('TMPL_CACHFILE_SUFFIX');
}else{
$tpl = Think::instance('ThinkTemplate');
// 编译并加载模板文件
$tpl->fetch($templateFile,$var);
}
}else{
$class = 'Template'.ucwords($template);
if(is_file(CORE_PATH.'Driver/Template/'.$class.'.class.php')) {
// 内置驱动
$path = CORE_PATH;
}else{ // 扩展驱动
$path = EXTEND_PATH;
}
require_cache($path.'Driver/Template/'.$class.'.class.php');
$tpl = new $class;
$tpl->fetch($templateFile,$var);
}
$content = ob_get_clean();
return $content;
}
/**
+----------------------------------------------------------
* 检查缓存文件是否有效
* 如果无效则需要重新编译
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $tmplTemplateFile 模板文件名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
protected function checkCache($tmplTemplateFile) {
if (!C('TMPL_CACHE_ON')) // 优先对配置设定检测
return false;
$tmplCacheFile = C('CACHE_PATH').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;
}
// 缓存有效
return true;
}
} | 10npsite | trunk/DThinkPHP/Lib/Core/Widget.class.php | PHP | asf20 | 5,649 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: ThinkException.class.php 2791 2012-02-29 10:08:57Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP系统异常基类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Exception
* @author liu21st <liu21st@gmail.com>
* @version $Id: ThinkException.class.php 2791 2012-02-29 10:08:57Z liu21st $
+------------------------------------------------------------------------------
*/
class ThinkException extends Exception {
/**
+----------------------------------------------------------
* 异常类型
+----------------------------------------------------------
* @var string
* @access private
+----------------------------------------------------------
*/
private $type;
// 是否存在多余调试信息
private $extra;
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $message 异常信息
+----------------------------------------------------------
*/
public function __construct($message,$code=0,$extra=false) {
parent::__construct($message,$code);
$this->type = get_class($this);
$this->extra = $extra;
}
/**
+----------------------------------------------------------
* 异常输出 所有异常处理类均通过__toString方法输出错误
* 每次异常都会写入系统日志
* 该方法可以被子类重载
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function __toString() {
$trace = $this->getTrace();
if($this->extra)
// 通过throw_exception抛出的异常要去掉多余的调试信息
array_shift($trace);
$this->class = $trace[0]['class'];
$this->function = $trace[0]['function'];
$this->file = $trace[0]['file'];
$this->line = $trace[0]['line'];
$file = file($this->file);
$traceInfo='';
$time = date('y-m-d H:i:m');
foreach($trace as $t) {
$traceInfo .= '['.$time.'] '.$t['file'].' ('.$t['line'].') ';
$traceInfo .= $t['class'].$t['type'].$t['function'].'(';
$traceInfo .= implode(', ', $t['args']);
$traceInfo .=")\n";
}
$error['message'] = $this->message;
$error['type'] = $this->type;
$error['detail'] = L('_MODULE_').'['.MODULE_NAME.'] '.L('_ACTION_').'['.ACTION_NAME.']'."\n";
$error['detail'] .= ($this->line-2).': '.$file[$this->line-3];
$error['detail'] .= ($this->line-1).': '.$file[$this->line-2];
$error['detail'] .= '<font color="#FF6600" >'.($this->line).': <strong>'.$file[$this->line-1].'</strong></font>';
$error['detail'] .= ($this->line+1).': '.$file[$this->line];
$error['detail'] .= ($this->line+2).': '.$file[$this->line+1];
$error['class'] = $this->class;
$error['function'] = $this->function;
$error['file'] = $this->file;
$error['line'] = $this->line;
$error['trace'] = $traceInfo;
// 记录 Exception 日志
if(C('LOG_EXCEPTION_RECORD')) {
Log::Write('('.$this->type.') '.$this->message);
}
return $error ;
}
} | 10npsite | trunk/DThinkPHP/Lib/Core/ThinkException.class.php | PHP | asf20 | 4,437 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Dispatcher.class.php 2840 2012-03-23 05:56:20Z liu21st@gmail.com $
/**
+------------------------------------------------------------------------------
* ThinkPHP内置的Dispatcher类
* 完成URL解析、路由和调度
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id: Dispatcher.class.php 2840 2012-03-23 05:56:20Z liu21st@gmail.com $
+------------------------------------------------------------------------------
*/
class Dispatcher {
/**
+----------------------------------------------------------
* URL映射到控制器
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function dispatch() {
$urlMode = C('URL_MODEL');
if(!empty($_GET[C('VAR_PATHINFO')])) { // 判断URL里面是否有兼容模式参数
$_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');
$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('分组名/[模块名]','var1=a&var2=b');
$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);
}
}
}
// 分析PATHINFO信息
if(empty($_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');
if(C('URL_HTML_SUFFIX')) {
$_SERVER['PATH_INFO'] = preg_replace('/\.'.trim(C('URL_HTML_SUFFIX'),'.').'$/i', '', $_SERVER['PATH_INFO']);
}
if(!self::routerCheck()){ // 检测路由规则 如果没有则按默认规则调度URL
$paths = explode($depr,trim($_SERVER['PATH_INFO'],'/'));
//===============分解url问号后台参数--jroam
$APP_GROUP_LISTtemp=C("APP_GROUP_LIST");
//启用二级域名和没有启用二级域名有区别
if(C("APP_SUB_DOMAIN_DEPLOY")==1){
$stemp=($APP_GROUP_LISTtemp!="")?$paths[1]:$paths[0];
}else{
$stemp=($APP_GROUP_LISTtemp!="")?$paths[2]:$paths[1];
}
if($stemp){
$tecan=C("URL_PATHINFO_DEPR_CAN");
$pathscan=explode($tecan, $stemp);
for($ji=1;$ji<count($pathscan);$ji=$ji+2){
$_GET[$pathscan[$ji]]=$pathscan[$ji+1];
}
}
//==========================
if(C('VAR_URL_PARAMS')) {
// 直接通过$_GET['_URL_'][1] $_GET['_URL_'][2] 获取URL参数 方便不用路由时参数获取
$_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);
// 解析剩余的URL参数
// $res= preg_replace('@(\w+)'.$depr.'([^'.$depr.'\/]+)@e', '$var[\'\\1\']=strip_tags(\'\\2\');', implode($depr,$paths));
$res= preg_replace('@([a-zA-Z0-9]+)'.$depr.'([^'.$depr.'\/]+)@e', '$var[\'\\1\']=strip_tags(\'\\2\');', implode($depr,$paths));
//$res = preg_replace('@(\w+)'.$depr.'([^'.$depr.'\/]+)@e', '$var[\'\\1\']="\\2";', implode($depr,$paths));
$_GET = array_merge($var,$_GET);
// mydie($_GET);
}
define('__INFO__',$_SERVER['PATH_INFO']);
}
// 获取分组 模块和操作名称
if (C('APP_GROUP_LIST')) {
define('GROUP_NAME', self::getGroup(C('VAR_GROUP')));
}
define('MODULE_NAME',self::getModule(C('VAR_MODULE')));
define('ACTION_NAME',self::getAction(C('VAR_ACTION')));
// URL常量
define('__SELF__',strip_tags($_SERVER['REQUEST_URI']));
// 当前项目地址
define('__APP__',strip_tags(PHP_FILE));
// 当前模块和分组地址
$module = defined('P_MODULE_NAME')?P_MODULE_NAME:MODULE_NAME;
if(defined('GROUP_NAME')) {
define('__GROUP__',(!empty($domainGroup) || strtolower(GROUP_NAME) == strtolower(C('DEFAULT_GROUP')) )?__APP__ : __APP__.'/'.GROUP_NAME);
define('__URL__',!empty($domainModule)?__GROUP__.$depr : __GROUP__.$depr.$module);
}else{
define('__URL__',!empty($domainModule)?__APP__.'/' : __APP__.'/'.$module);
}
// 当前操作地址
define('__ACTION__',__URL__.$depr.ACTION_NAME);
//保证$_REQUEST正常取值
$_REQUEST = array_merge($_POST,$_GET);
}
/**
+----------------------------------------------------------
* 路由检测
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function routerCheck() {
$return = false;
// 路由检测标签
tag('route_check',$return);
return $return;
}
/**
+----------------------------------------------------------
* 获得实际的模块名称
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static private function getModule($var) {
$module = (!empty($_GET[$var])? $_GET[$var]:C('DEFAULT_MODULE'));
unset($_GET[$var]);
if(C('URL_CASE_INSENSITIVE')) {
// URL地址不区分大小写
define('P_MODULE_NAME',strtolower($module));
// 智能识别方式 index.php/user_type/index/ 识别到 UserTypeAction 模块
$module = ucfirst(parse_name(P_MODULE_NAME,1));
}
return strip_tags($module);
}
/**
+----------------------------------------------------------
* 获得实际的操作名称
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static private function getAction($var) {
$action = !empty($_POST[$var]) ?
$_POST[$var] :
(!empty($_GET[$var])?$_GET[$var]:C('DEFAULT_ACTION'));
unset($_POST[$var],$_GET[$var]);
define('P_ACTION_NAME',$action);
$temp=strip_tags(C('URL_CASE_INSENSITIVE')?strtolower($action):$action);
if(C("URL_PATHINFO_DEPR")!= C("URL_PATHINFO_DEPR_CAN"))//jroam
{
$temp=preg_replace("/".C("URL_PATHINFO_DEPR_CAN")."[\s\S]*$/", "", $temp);
}
return $temp;
}
/**
+----------------------------------------------------------
* 获得实际的分组名称
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
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);
}
} | 10npsite | trunk/DThinkPHP/Lib/Core/Dispatcher.class.php | PHP | asf20 | 11,751 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Think.class.php 2791 2012-02-29 10:08:57Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP Portal类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: Think.class.php 2791 2012-02-29 10:08:57Z liu21st $
+------------------------------------------------------------------------------
*/
class Think {
private static $_instance = array();
/**
+----------------------------------------------------------
* 应用程序初始化
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function Start() {
// 设定错误和异常处理
set_error_handler(array('Think','appError'));
set_exception_handler(array('Think','appException'));
// 注册AUTOLOAD方法
spl_autoload_register(array('Think', 'autoload'));
//[RUNTIME]
Think::buildApp(); // 预编译项目
//[/RUNTIME]
// 运行应用
App::run();
return ;
}
//[RUNTIME]
/**
+----------------------------------------------------------
* 读取配置信息 编译项目
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static private function buildApp() {
// 加载底层惯例配置文件
C(include THINK_PATH.'Conf/convention.php');
// 读取运行模式
if(defined('MODE_NAME')) { // 模式的设置并入核心模式
$mode = include MODE_PATH.strtolower(MODE_NAME).'.php';
}else{
$mode = array();
}
// 加载模式配置文件
if(isset($mode['config'])) {
C( is_array($mode['config'])?$mode['config']:include $mode['config'] );
}
// 加载项目配置文件
if(is_file(CONF_PATH.'config.php'))
C(include CONF_PATH.'config.php');
// 加载框架底层语言包
L(include THINK_PATH.'Lang/'.strtolower(C('DEFAULT_LANG')).'.php');
// 加载模式系统行为定义
if(C('APP_TAGS_ON')) {
if(isset($mode['extends'])) {
C('extends',is_array($mode['extends'])?$mode['extends']:include $mode['extends']);
}else{ // 默认加载系统行为扩展定义
C('extends', include THINK_PATH.'Conf/tags.php');
}
}
// 加载应用行为定义
if(isset($mode['tags'])) {
C('tags', is_array($mode['tags'])?$mode['tags']:include $mode['tags']);
}elseif(is_file(CONF_PATH.'tags.php')){
// 默认加载项目配置目录的tags文件定义
C('tags', include CONF_PATH.'tags.php');
}
$compile = '';
// 读取核心编译文件列表
if(isset($mode['core'])) {
$list = $mode['core'];
}else{
$list = array(
THINK_PATH.'Common/functions.php', // 标准模式函数库
CORE_PATH.'Core/Log.class.php', // 日志处理类
CORE_PATH.'Core/Dispatcher.class.php', // URL调度类
CORE_PATH.'Core/App.class.php', // 应用程序类
CORE_PATH.'Core/Action.class.php', // 控制器类
CORE_PATH.'Core/View.class.php', // 视图类
);
}
// 项目追加核心编译列表文件
if(is_file(CONF_PATH.'core.php')) {
$list = array_merge($list,include CONF_PATH.'core.php');
}
foreach ($list as $file){
if(is_file($file)) {
require_cache($file);
if(!APP_DEBUG) $compile .= compile($file);
}
}
// 加载项目公共文件
if(is_file(COMMON_PATH.'common.php')) {
include COMMON_PATH.'common.php';
// 编译文件
if(!APP_DEBUG) $compile .= compile(COMMON_PATH.'common.php');
}
// 加载模式别名定义
if(isset($mode['alias'])) {
$alias = is_array($mode['alias'])?$mode['alias']:include $mode['alias'];
alias_import($alias);
if(!APP_DEBUG) $compile .= 'alias_import('.var_export($alias,true).');';
}
// 加载项目别名定义
if(is_file(CONF_PATH.'alias.php')){
$alias = include CONF_PATH.'alias.php';
alias_import($alias);
if(!APP_DEBUG) $compile .= 'alias_import('.var_export($alias,true).');';
}
if(APP_DEBUG) {
// 调试模式加载系统默认的配置文件
C(include THINK_PATH.'Conf/debug.php');
// 读取调试模式的应用状态
$status = C('APP_STATUS');
// 加载对应的项目配置文件
if(is_file(CONF_PATH.$status.'.php'))
// 允许项目增加开发模式配置定义
C(include CONF_PATH.$status.'.php');
}else{
// 部署模式下面生成编译文件
build_runtime_cache($compile);
}
return ;
}
//[/RUNTIME]
/**
+----------------------------------------------------------
* 系统自动加载ThinkPHP类库
* 并且支持配置自动加载路径
+----------------------------------------------------------
* @param string $class 对象类名
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public static function autoload($class) {
// 检查是否存在别名定义
if(alias_import($class)) return ;
if(substr($class,-8)=='Behavior') { // 加载行为
if(require_cache(CORE_PATH.'Behavior/'.$class.'.class.php')
|| require_cache(EXTEND_PATH.'Behavior/'.$class.'.class.php')
|| require_cache(LIB_PATH.'Behavior/'.$class.'.class.php')
|| (defined('MODE_NAME') && require_cache(MODE_PATH.ucwords(MODE_NAME).'/Behavior/'.$class.'.class.php'))) {
return ;
}
}elseif(substr($class,-5)=='Model'){ // 加载模型
if(require_cache(LIB_PATH.'Model/'.$class.'.class.php')
|| require_cache(EXTEND_PATH.'Model/'.$class.'.class.php') ) {
return ;
}
}elseif(substr($class,-6)=='Action'){ // 加载控制器
if((defined('GROUP_NAME') && require_cache(LIB_PATH.'Action/'.GROUP_NAME.'/'.$class.'.class.php'))
|| require_cache(LIB_PATH.'Action/'.$class.'.class.php')
|| require_cache(EXTEND_PATH.'Action/'.$class.'.class.php') ) {
return ;
}
}
// 根据自动加载路径设置进行尝试搜索
$paths = explode(',',C('APP_AUTOLOAD_PATH'));
foreach ($paths as $path){
if(import($path.'.'.$class))
// 如果加载类成功则返回
return ;
}
}
/**
+----------------------------------------------------------
* 取得对象实例 支持调用类的静态方法
+----------------------------------------------------------
* @param string $class 对象类名
* @param string $method 类的静态方法名
+----------------------------------------------------------
* @return object
+----------------------------------------------------------
*/
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];
}
/**
+----------------------------------------------------------
* 自定义异常处理
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $e 异常对象
+----------------------------------------------------------
*/
static public function appException($e) {
halt($e->__toString());
}
/**
+----------------------------------------------------------
* 自定义错误处理
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param int $errno 错误类型
* @param string $errstr 错误信息
* @param string $errfile 错误文件
* @param int $errline 错误行数
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function appError($errno, $errstr, $errfile, $errline) {
switch ($errno) {
case E_ERROR:
case E_USER_ERROR:
$errorStr = "[$errno] $errstr ".basename($errfile)." 第 $errline 行.";
if(C('LOG_RECORD')) Log::write($errorStr,Log::ERR);
halt($errorStr);
break;
case E_STRICT:
case E_USER_WARNING:
case E_USER_NOTICE:
default:
$errorStr = "[$errno] $errstr ".basename($errfile)." 第 $errline 行.";
Log::record($errorStr,Log::NOTICE);
break;
}
}
/**
+----------------------------------------------------------
* 自动变量设置
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param $name 属性名称
* @param $value 属性值
+----------------------------------------------------------
*/
public function __set($name ,$value) {
if(property_exists($this,$name))
$this->$name = $value;
}
/**
+----------------------------------------------------------
* 自动变量获取
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param $name 属性名称
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __get($name) {
return isset($this->$name)?$this->$name:null;
}
} | 10npsite | trunk/DThinkPHP/Lib/Core/Think.class.php | PHP | asf20 | 12,159 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Action.class.php 2791 2012-02-29 10:08:57Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP Action控制器基类 抽象类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: Action.class.php 2791 2012-02-29 10:08:57Z liu21st $
+------------------------------------------------------------------------------
*/
abstract class Action {
// 视图实例对象
protected $view = null;
// 当前Action名称
private $name = '';
/**
+----------------------------------------------------------
* 架构函数 取得模板对象实例
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct() {
tag('action_begin');
//实例化视图类
$this->view = Think::instance('View');
//控制器初始化
if(method_exists($this,'_initialize'))
$this->_initialize();
}
/**
+----------------------------------------------------------
* 获取当前Action名称
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
*/
protected function getActionName() {
if(empty($this->name)) {
// 获取Action名称
$this->name = substr(get_class($this),0,-6);
}
return $this->name;
}
/**
+----------------------------------------------------------
* 是否AJAX请求
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return bool
+----------------------------------------------------------
*/
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')]))
// 判断Ajax方式提交
return true;
return false;
}
/**
+----------------------------------------------------------
* 模板显示
* 调用内置的模板引擎显示方法,
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $templateFile 指定要调用的模板文件
* 默认为空 由系统自动定位模板文件
* @param string $charset 输出编码
* @param string $contentType 输出类型
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function display($templateFile='',$charset='',$contentType='') {
$this->view->display($templateFile,$charset,$contentType);
}
/**
+----------------------------------------------------------
* 获取输出页面内容
* 调用内置的模板引擎fetch方法,
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $templateFile 指定要调用的模板文件
* 默认为空 由系统自动定位模板文件
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function fetch($templateFile='') {
return $this->view->fetch($templateFile);
}
/**
+----------------------------------------------------------
* 创建静态页面
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @htmlfile 生成的静态文件名称
* @htmlpath 生成的静态文件路径
* @param string $templateFile 指定要调用的模板文件
* 默认为空 由系统自动定位模板文件
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
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)))
// 如果静态目录不存在 则创建
mk_dir(dirname($htmlfile));
if(false === file_put_contents($htmlfile,$content))
throw_exception(L('_CACHE_WRITE_ERROR_').':'.$htmlfile);
return $content;
}
/**
+----------------------------------------------------------
* 模板变量赋值
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $name 要显示的模板变量
* @param mixed $value 变量的值
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function assign($name,$value='') {
$this->view->assign($name,$value);
}
public function __set($name,$value) {
$this->view->assign($name,$value);
}
/**
+----------------------------------------------------------
* 取得模板显示变量的值
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $name 模板显示变量
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __get($name) {
return $this->view->get($name);
}
/**
+----------------------------------------------------------
* 魔术方法 有不存在的操作的时候执行
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名
* @param array $args 参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$args) {
if( 0 === strcasecmp($method,ACTION_NAME)) {
if(method_exists($this,'_empty')) {
// 如果定义了_empty操作 则调用
$this->_empty($method,$args);
}elseif(file_exists_case(C('TEMPLATE_NAME'))){
// 检查是否存在默认模版 如果有直接输出模版
$this->display();
}elseif(function_exists('__hack_action')) {
// hack 方式定义扩展操作
__hack_action();
}elseif(APP_DEBUG) {
// 抛出异常
throw_exception(L('_ERROR_ACTION_').ACTION_NAME);
}else{
if(C('LOG_EXCEPTION_RECORD')) Log::write(L('_ERROR_ACTION_').ACTION_NAME);
send_http_status(404);
exit;
}
}else{
switch(strtolower($method)) {
// 判断提交方式
case 'ispost':
case 'isget':
case 'ishead':
case 'isdelete':
case 'isput':
return strtolower($_SERVER['REQUEST_METHOD']) == strtolower(substr($method,2));
// 获取变量 支持过滤和默认值 调用方式 $this->_post($key,$filter,$default);
case '_get': $input =& $_GET;break;
case '_post':$input =& $_POST;break;
case '_put': parse_str(file_get_contents('php://input'), $input);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($input[$args[0]])) { // 取值操作
$data = $input[$args[0]];
$fun = $args[1]?$args[1]:C('DEFAULT_FILTER');
$data = $fun($data); // 参数过滤
}else{ // 变量默认值
$data = isset($args[2])?$args[2]:NULL;
}
return $data;
}
}
/**
+----------------------------------------------------------
* 操作错误跳转的快捷方法
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $message 错误信息
* @param string $jumpUrl 页面跳转地址
* @param Boolean $ajax 是否为Ajax方式
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function error($message,$jumpUrl='',$ajax=false) {
$this->dispatchJump($message,0,$jumpUrl,$ajax);
}
/**
+----------------------------------------------------------
* 操作成功跳转的快捷方法
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $message 提示信息
* @param string $jumpUrl 页面跳转地址
* @param Boolean $ajax 是否为Ajax方式
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function success($message,$jumpUrl='',$ajax=false) {
$this->dispatchJump($message,1,$jumpUrl,$ajax);
}
/**
+----------------------------------------------------------
* Ajax方式返回数据到客户端
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 要返回的数据
* @param String $info 提示信息
* @param boolean $status 返回状态
* @param String $status ajax返回类型 JSON XML
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function ajaxReturn($data,$info='',$status=1,$type='') {
$result = array();
$result['status'] = $status;
$result['info'] = $info;
$result['data'] = $data;
//扩展ajax返回数据, 在Action中定义function ajaxAssign(&$result){} 方法 扩展ajax返回数据。
if(method_exists($this,'ajaxAssign'))
$this->ajaxAssign($result);
if(empty($type)) $type = C('DEFAULT_AJAX_RETURN');
if(strtoupper($type)=='JSON') {
// 返回JSON数据格式到客户端 包含状态信息
header('Content-Type:text/html; charset=utf-8');
exit(json_encode($result));
}elseif(strtoupper($type)=='XML'){
// 返回xml格式数据
header('Content-Type:text/xml; charset=utf-8');
exit(xml_encode($result));
}elseif(strtoupper($type)=='EVAL'){
// 返回可执行的js脚本
header('Content-Type:text/html; charset=utf-8');
exit($data);
}else{
// TODO 增加其它格式
}
}
/**
+----------------------------------------------------------
* Action跳转(URL重定向) 支持指定模块和延时跳转
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $url 跳转的URL表达式
* @param array $params 其它URL参数
* @param integer $delay 延时跳转的时间 单位为秒
* @param string $msg 跳转提示信息
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function redirect($url,$params=array(),$delay=0,$msg='') {
$url = U($url,$params);
redirect($url,$delay,$msg);
}
/**
+----------------------------------------------------------
* 默认跳转操作 支持错误导向和正确跳转
* 调用模板显示 默认为public目录下面的success页面
* 提示页面为可配置 支持模板标签
+----------------------------------------------------------
* @param string $message 提示信息
* @param Boolean $status 状态
* @param string $jumpUrl 页面跳转地址
* @param Boolean $ajax 是否为Ajax方式
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
private function dispatchJump($message,$status=1,$jumpUrl='',$ajax=false) {
// 判断是否为AJAX返回
if($ajax || $this->isAjax()) $this->ajaxReturn($ajax,$message,$status);
if(!empty($jumpUrl)) $this->assign('jumpUrl',$jumpUrl);
// 提示标题
$this->assign('msgTitle',$status? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_'));
//如果设置了关闭窗口,则提示完毕后自动关闭窗口
if($this->view->get('closeWin')) $this->assign('jumpUrl','javascript:window.close();');
$this->assign('status',$status); // 状态
//保证输出不受静态缓存影响
C('HTML_CACHE_ON',false);
if($status) { //发送成功信息
$this->assign('message',$message);// 提示信息
// 成功操作后默认停留1秒
if(!$this->view->get('waitSecond')) $this->assign('waitSecond','1');
// 默认操作成功自动返回操作前页面
if(!$this->view->get('jumpUrl')) $this->assign("jumpUrl",$_SERVER["HTTP_REFERER"]);
$this->display(C('TMPL_ACTION_SUCCESS'));
}else{
$this->assign('error',$message);// 提示信息
//发生错误时候默认停留3秒
if(!$this->view->get('waitSecond')) $this->assign('waitSecond','3');
// 默认发生错误的话自动返回上页
if(!$this->view->get('jumpUrl')) $this->assign('jumpUrl',"javascript:history.back(-1);");
$this->display(C('TMPL_ACTION_ERROR'));
// 中止执行 避免出错后继续执行
exit ;
}
}
/**
+----------------------------------------------------------
* 析构方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __destruct() {
// 保存日志
if(C('LOG_RECORD')) Log::save();
// 执行后续操作
tag('action_end');
}
} | 10npsite | trunk/DThinkPHP/Lib/Core/Action.class.php | PHP | asf20 | 16,905 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Behavior.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP Behavior基础类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id: Behavior.class.php 2702 2012-02-02 12:35:01Z liu21st $
+------------------------------------------------------------------------------
*/
abstract class Behavior {
// 行为参数 和配置参数设置相同
protected $options = array();
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
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)];
}
/**
+----------------------------------------------------------
* 执行行为 run方法是Behavior唯一的接口
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $params 行为参数
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
abstract public function run(&$params);
} | 10npsite | trunk/DThinkPHP/Lib/Core/Behavior.class.php | PHP | asf20 | 2,660 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: ThinkPHP.php 2791 2012-02-29 10:08:57Z liu21st $
// ThinkPHP 入口文件
//记录开始运行时间
$GLOBALS['_beginTime'] = microtime(TRUE);
// 记录内存初始使用
define('MEMORY_LIMIT_ON',function_exists('memory_get_usage'));
if(MEMORY_LIMIT_ON) $GLOBALS['_startUseMems'] = memory_get_usage();
defined('APP_PATH') or define('APP_PATH', dirname($_SERVER['SCRIPT_FILENAME']).'/');
defined('RUNTIME_PATH') or define('RUNTIME_PATH',APP_PATH.'Runtime/');
defined('APP_DEBUG') or define('APP_DEBUG',false); // 是否调试模式
$runtime = defined('MODE_NAME')?'~'.strtolower(MODE_NAME).'_runtime.php':'~runtime.php';
defined('RUNTIME_FILE') or define('RUNTIME_FILE',RUNTIME_PATH.$runtime);
if(!APP_DEBUG && is_file(RUNTIME_FILE)) {
// 部署模式直接载入运行缓存
require RUNTIME_FILE;
}else{
// 系统目录定义
defined('THINK_PATH') or define('THINK_PATH', dirname(__FILE__).'/');
// 加载运行时文件
require THINK_PATH.'Common/runtime.php';
} | 10npsite | trunk/DThinkPHP/ThinkPHP.php | PHP | asf20 | 1,626 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
/**
+------------------------------------------------------------------------------
* Think 标准模式公共函数库
+------------------------------------------------------------------------------
* @category Think
* @package Common
* @author liu21st <liu21st@gmail.com>
* @version $Id$
+------------------------------------------------------------------------------
*/
// 错误输出
function halt($error) {
$e = array();
if (APP_DEBUG) {
//调试模式下输出错误信息
if (!is_array($error)) {
$trace = debug_backtrace();
$e['message'] = $error;
$e['file'] = $trace[0]['file'];
$e['class'] = $trace[0]['class'];
$e['function'] = $trace[0]['function'];
$e['line'] = $trace[0]['line'];
$traceInfo = '';
$time = date('y-m-d H:i:m');
foreach ($trace as $t) {
$traceInfo .= '[' . $time . '] ' . $t['file'] . ' (' . $t['line'] . ') ';
$traceInfo .= $t['class'] . $t['type'] . $t['function'] . '(';
$traceInfo .= implode(', ', $t['args']);
$traceInfo .=')<br/>';
}
$e['trace'] = $traceInfo;
} else {
$e = $error;
}
// 包含异常页面模板
include C('TMPL_EXCEPTION_FILE');
} else {
//否则定向到错误页面
$error_page = C('ERROR_PAGE');
if (!empty($error_page)) {
redirect($error_page);
} else {
if (C('SHOW_ERROR_MSG'))
$e['message'] = is_array($error) ? $error['message'] : $error;
else
$e['message'] = C('ERROR_MESSAGE');
// 包含异常页面模板
include C('TMPL_EXCEPTION_FILE');
}
}
exit;
}
// 自定义异常处理
function throw_exception($msg, $type='ThinkException', $code=0) {
if (class_exists($type, false))
throw new $type($msg, $code, true);
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 debug_start($label='') {
$GLOBALS[$label]['_beginTime'] = microtime(TRUE);
if (MEMORY_LIMIT_ON)
$GLOBALS[$label]['_beginMem'] = memory_get_usage();
}
// 区间调试结束,显示指定标记到当前位置的调试
function debug_end($label='') {
$GLOBALS[$label]['_endTime'] = microtime(TRUE);
echo '<div style="text-align:center;width:100%">Process ' . $label . ': Times ' . number_format($GLOBALS[$label]['_endTime'] - $GLOBALS[$label]['_beginTime'], 6) . 's ';
if (MEMORY_LIMIT_ON) {
$GLOBALS[$label]['_endMem'] = memory_get_usage();
echo ' Memories ' . number_format(($GLOBALS[$label]['_endMem'] - $GLOBALS[$label]['_beginMem']) / 1024) . ' k';
}
echo '</div>';
}
// 添加和获取页面Trace记录
function trace($title='',$value='') {
if(!C('SHOW_PAGE_TRACE')) return;
static $_trace = array();
if(is_array($title)) { // 批量赋值
$_trace = array_merge($_trace,$title);
}elseif('' !== $value){ // 赋值
$_trace[$title] = $value;
}elseif('' !== $title){ // 取值
return $_trace[$title];
}else{ // 获取全部Trace数据
return $_trace;
}
}
// 设置当前页面的布局
function layout($layout) {
if(false !== $layout) {
// 开启布局
C('LAYOUT_ON',true);
if(is_string($layout)) {
C('LAYOUT_NAME',$layout);
}
}
}
// URL组装 支持不同模式
// 格式:U('[分组/模块/操作]?参数','参数','伪静态后缀','是否跳转','显示域名')
function U($url,$vars='',$suffix=true,$redirect=false,$domain=false) {
// 解析URL
$info = parse_url($url);
$url = !empty($info['path'])?$info['path']:ACTION_NAME;
// 解析子域名
if($domain===true){
$domain = $_SERVER['HTTP_HOST'];
if(C('APP_SUB_DOMAIN_DEPLOY') ) { // 开启子域名部署
$domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.');
// '子域名'=>array('项目[/分组]');
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)) { // aaa=1&bbb=2 转换成数组
parse_str($vars,$vars);
}elseif(!is_array($vars)){
$vars = array();
}
if(isset($info['query'])) { // 解析地址里面参数 合并到vars
parse_str($info['query'],$params);
$vars = array_merge($params,$vars);
}
// URL组装
$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(C('URL_CASE_INSENSITIVE')) {
$var[C('VAR_MODULE')] = parse_name($var[C('VAR_MODULE')]);
}
if(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_MODEL') == 0) { // 普通模式URL转换
$url = __APP__.'?'.http_build_query($var);
if(!empty($vars)) {
$vars = http_build_query($vars);
$url .= '&'.$vars;
}
}else{ // PATHINFO模式或者兼容URL模式
if(isset($route)) {
$url = __APP__.'/'.$url;
}else{
$url = __APP__.'/'.implode($depr,array_reverse($var));
}
if(!empty($vars)) { // 添加参数
$vars = http_build_query($vars);
$url .= $depr.str_replace(array('=','&'),$depr,$vars);
}
if($suffix) {
$suffix = $suffix===true?C('URL_HTML_SUFFIX'):$suffix;
if($suffix) {
$url .= '.'.ltrim($suffix,'.');
}
}
}
if($domain) {
$url = 'http://'.$domain.$url;
}
if($redirect) // 直接跳转URL
redirect($url);
else
return $url;
}
// URL重定向
function redirect($url, $time=0, $msg='') {
//多行URL地址支持
$url = str_replace(array("\n", "\r"), '', $url);
if (empty($msg))
$msg = "系统将在{$time}秒之后自动跳转到{$url}!";
if (!headers_sent()) {
// redirect
if (0 === $time) {
header('Location: ' . $url);
} else {
header("refresh:{$time};url={$url}");
echo($msg);
}
exit();
} else {
$str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
if ($time != 0)
$str .= $msg;
exit($str);
}
}
// 全局缓存设置和读取
function S($name, $value='', $expire=null, $type='',$options=null) {
static $_cache = array();
//取得缓存对象实例
$cache = Cache::getInstance($type,$options);
if ('' !== $value) {
if (is_null($value)) {
// 删除缓存
$result = $cache->rm($name);
if ($result)
unset($_cache[$type . '_' . $name]);
return $result;
}else {
// 缓存数据
$cache->set($name, $value, $expire);
$_cache[$type . '_' . $name] = $value;
}
return;
}
if (isset($_cache[$type . '_' . $name]))
return $_cache[$type . '_' . $name];
// 获取缓存数据
$value = $cache->get($name);
$_cache[$type . '_' . $name] = $value;
return $value;
}
// 快速文件数据读取和保存 针对简单类型数据 字符串、数组
function F($name, $value='', $path=DATA_PATH) {
static $_cache = array();
$filename = $path . $name . '.php';
if ('' !== $value) {
if (is_null($value)) {
// 删除缓存
return unlink($filename);
} else {
// 缓存数据
$dir = dirname($filename);
// 目录不存在则创建
if (!is_dir($dir))
mkdir($dir);
$_cache[$name] = $value;
return file_put_contents($filename, strip_whitespace("<?php\nreturn " . var_export($value, true) . ";\n?>"));
}
}
if (isset($_cache[$name]))
return $_cache[$name];
// 获取缓存数据
if (is_file($filename)) {
$value = include $filename;
$_cache[$name] = $value;
} else {
$value = false;
}
return $value;
}
// 取得对象实例 支持调用类的静态方法
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];
}
// 根据PHP各种类型变量生成唯一标识号
function to_guid_string($mix) {
if (is_object($mix) && function_exists('spl_object_hash')) {
return spl_object_hash($mix);
} elseif (is_resource($mix)) {
$mix = get_resource_type($mix) . strval($mix);
} else {
$mix = serialize($mix);
}
return md5($mix);
}
// xml编码
function xml_encode($data, $encoding='utf-8', $root='think') {
$xml = '<?xml version="1.0" encoding="' . $encoding . '"?>';
$xml.= '<' . $root . '>';
$xml.= data_to_xml($data);
$xml.= '</' . $root . '>';
return $xml;
}
function data_to_xml($data) {
$xml = '';
foreach ($data as $key => $val) {
is_numeric($key) && $key = "item id=\"$key\"";
$xml.="<$key>";
$xml.= ( is_array($val) || is_object($val)) ? data_to_xml($val) : $val;
list($key, ) = explode(' ', $key);
$xml.="</$key>";
}
return $xml;
}
// session管理函数
function session($name,$value='') {
$prefix = C('SESSION_PREFIX');
if(is_array($name)) { // session初始化 在session_start 之前调用
if(isset($name['prefix'])) C('SESSION_PREFIX',$name['prefix']);
if(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['type'])) C('SESSION_TYPE',$name['type']);
if(C('SESSION_TYPE')) { // 读取session驱动
$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);
}
}
// 启动session
if(C('SESSION_AUTO_START')) session_start();
}elseif('' === $value){
if(0===strpos($name,'[')) { // session 操作
if('[pause]'==$name){ // 暂停session
session_write_close();
}elseif('[start]'==$name){ // 启动session
session_start();
}elseif('[destroy]'==$name){ // 销毁session
$_SESSION = array();
session_unset();
session_destroy();
}elseif('[regenerate]'==$name){ // 重新生成id
session_regenerate_id();
}
}elseif(0===strpos($name,'?')){ // 检查session
$name = substr($name,1);
if($prefix) {
return isset($_SESSION[$prefix][$name]);
}else{
return isset($_SESSION[$name]);
}
}elseif(is_null($name)){ // 清空session
if($prefix) {
unset($_SESSION[$prefix]);
}else{
$_SESSION = array();
}
}elseif($prefix){ // 获取session
return $_SESSION[$prefix][$name];
}else{
return $_SESSION[$name];
}
}elseif(is_null($value)){ // 删除session
if($prefix){
unset($_SESSION[$prefix][$name]);
}else{
unset($_SESSION[$name]);
}
}else{ // 设置session
if($prefix){
if (!is_array($_SESSION[$prefix])) {
$_SESSION[$prefix] = array();
}
$_SESSION[$prefix][$name] = $value;
}else{
$_SESSION[$name] = $value;
}
}
}
// Cookie 设置、获取、删除
function cookie($name, $value='', $option=null) {
// 默认设置
$config = array(
'prefix' => C('COOKIE_PREFIX'), // cookie 名称前缀
'expire' => C('COOKIE_EXPIRE'), // cookie 保存时间
'path' => C('COOKIE_PATH'), // cookie 保存路径
'domain' => C('COOKIE_DOMAIN'), // cookie 有效域名
);
// 参数设置(会覆盖黙认设置)
if (!empty($option)) {
if (is_numeric($option))
$option = array('expire' => $option);
elseif (is_string($option))
parse_str($option, $option);
$config = array_merge($config, array_change_key_case($option));
}
// 清除指定前缀的所有cookie
if (is_null($name)) {
if (empty($_COOKIE))
return;
// 要删除的cookie前缀,不指定则删除config设置的指定前缀
$prefix = empty($value) ? $config['prefix'] : $value;
if (!empty($prefix)) {// 如果前缀为空字符串将不作处理直接返回
foreach ($_COOKIE as $key => $val) {
if (0 === stripos($key, $prefix)) {
setcookie($key, '', time() - 3600, $config['path'], $config['domain']);
unset($_COOKIE[$key]);
}
}
}
return;
}
$name = $config['prefix'] . $name;
if ('' === $value) {
return isset($_COOKIE[$name]) ? $_COOKIE[$name] : null; // 获取指定Cookie
} else {
if (is_null($value)) {
setcookie($name, '', time() - 3600, $config['path'], $config['domain']);
unset($_COOKIE[$name]); // 删除指定cookie
} else {
// 设置cookie
$expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0;
setcookie($name, $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);
}
}
}
}
// 获取客户端IP地址
function get_client_ip() {
static $ip = NULL;
if ($ip !== NULL) return $ip;
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'];
}
// IP地址合法验证
$ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0';
return $ip;
}
function send_http_status($code) {
static $_status = array(
// Success 2xx
200 => 'OK',
// Redirection 3xx
301 => 'Moved Permanently',
302 => 'Moved Temporarily ', // 1.1
// Client Error 4xx
400 => 'Bad Request',
403 => 'Forbidden',
404 => 'Not Found',
// Server Error 5xx
500 => 'Internal Server Error',
503 => 'Service Unavailable',
);
if(isset($_status[$code])) {
header('HTTP/1.1 '.$code.' '.$_status[$code]);
// 确保FastCGI模式下正常
header('Status:'.$code.' '.$_status[$code]);
}
} | 10npsite | trunk/DThinkPHP/Common/functions.php | PHP | asf20 | 20,420 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
/**
+------------------------------------------------------------------------------
* ThinkPHP 运行时文件 编译后不再加载
+------------------------------------------------------------------------------
*/
if (!defined('THINK_PATH')) exit();
if(version_compare(PHP_VERSION,'5.2.0','<')) die('require PHP > 5.2.0 !');
// 版本信息
define('THINK_VERSION', '3.0');
define('THINK_RELEASE', '20120323');
// 系统信息
if(version_compare(PHP_VERSION,'5.4.0','<') ) {
@set_magic_quotes_runtime (0);
define('MAGIC_QUOTES_GPC',get_magic_quotes_gpc()?True:False);
}
define('IS_CGI',substr(PHP_SAPI, 0,3)=='cgi' ? 1 : 0 );
define('IS_WIN',strstr(PHP_OS, 'WIN') ? 1 : 0 );
define('IS_CLI',PHP_SAPI=='cli'? 1 : 0);
// 项目名称
defined('APP_NAME') or define('APP_NAME', basename(dirname($_SERVER['SCRIPT_FILENAME'])));
if(!IS_CLI) {
// 当前文件名
if(!defined('_PHP_FILE_')) {
if(IS_CGI) {
//CGI/FASTCGI模式下
$_temp = explode('.php',$_SERVER['PHP_SELF']);
define('_PHP_FILE_', rtrim(str_replace($_SERVER['HTTP_HOST'],'',$_temp[0].'.php'),'/'));
}else {
define('_PHP_FILE_', rtrim($_SERVER['SCRIPT_NAME'],'/'));
}
}
if(!defined('__ROOT__')) {
// 网站URL根目录
if( strtoupper(APP_NAME) == strtoupper(basename(dirname(_PHP_FILE_))) ) {
$_root = dirname(dirname(_PHP_FILE_));
}else {
$_root = dirname(_PHP_FILE_);
}
define('__ROOT__', (($_root=='/' || $_root=='\\')?'':$_root));
}
//支持的URL模式
define('URL_COMMON', 0); //普通模式
define('URL_PATHINFO', 1); //PATHINFO模式
define('URL_REWRITE', 2); //REWRITE模式
define('URL_COMPAT', 3); // 兼容模式
}
// 路径设置 可在入口文件中重新定义 所有路径常量都必须以/ 结尾
defined('CORE_PATH') or define('CORE_PATH',THINK_PATH.'Lib/'); // 系统核心类库目录
defined('EXTEND_PATH') or define('EXTEND_PATH',THINK_PATH.'Extend/'); // 系统扩展目录
defined('MODE_PATH') or define('MODE_PATH',EXTEND_PATH.'Mode/'); // 模式扩展目录
defined('ENGINE_PATH') or define('ENGINE_PATH',EXTEND_PATH.'Engine/'); // 引擎扩展目录
defined('VENDOR_PATH') or define('VENDOR_PATH',EXTEND_PATH.'Vendor/'); // 第三方类库目录
defined('LIBRARY_PATH') or define('LIBRARY_PATH',EXTEND_PATH.'Library/'); // 扩展类库目录
defined('COMMON_PATH') or define('COMMON_PATH', APP_PATH.'Common/'); // 项目公共目录
defined('LIB_PATH') or define('LIB_PATH', APP_PATH.'Lib/'); // 项目类库目录
defined('CONF_PATH') or define('CONF_PATH', APP_PATH.'Conf/'); // 项目配置目录
defined('LANG_PATH') or define('LANG_PATH', APP_PATH.'Lang/'); // 项目语言包目录
defined('TMPL_PATH') or define('TMPL_PATH',APP_PATH.'Tpl/'); // 项目模板目录
defined('HTML_PATH') or define('HTML_PATH',APP_PATH.'Html/'); // 项目静态目录
defined('LOG_PATH') or define('LOG_PATH', RUNTIME_PATH.'Logs/'); // 项目日志目录
defined('TEMP_PATH') or define('TEMP_PATH', RUNTIME_PATH.'Temp/'); // 项目缓存目录
defined('DATA_PATH') or define('DATA_PATH', RUNTIME_PATH.'Data/'); // 项目数据目录
defined('CACHE_PATH') or define('CACHE_PATH', RUNTIME_PATH.'Cache/'); // 项目模板缓存目录
// 为了方便导入第三方类库 设置Vendor目录到include_path
set_include_path(get_include_path() . PATH_SEPARATOR . VENDOR_PATH);
// 加载运行时所需要的文件 并负责自动目录生成
function load_runtime_file() {
// 加载系统基础函数库
require THINK_PATH.'Common/common.php';
// 读取核心编译文件列表
$list = array(
CORE_PATH.'Core/Think.class.php',
CORE_PATH.'Core/ThinkException.class.php', // 异常处理类
CORE_PATH.'Core/Behavior.class.php',
);
// 加载模式文件列表
foreach ($list as $key=>$file){
if(is_file($file)) require_cache($file);
}
// 加载系统类库别名定义
alias_import(include THINK_PATH.'Conf/alias.php');
// 检查项目目录结构 如果不存在则自动创建
if(!is_dir(LIB_PATH)) {
// 创建项目目录结构
build_app_dir();
}elseif(!is_dir(CACHE_PATH)){
// 检查缓存目录
check_runtime();
}elseif(APP_DEBUG){
// 调试模式切换删除编译缓存
if(is_file(RUNTIME_FILE)) unlink(RUNTIME_FILE);
}
}
// 检查缓存目录(Runtime) 如果不存在则自动创建
function check_runtime() {
if(!is_dir(RUNTIME_PATH)) {
mkdir(RUNTIME_PATH);
}elseif(!is_writeable(RUNTIME_PATH)) {
header('Content-Type:text/html; charset=utf-8');
exit('目录 [ '.RUNTIME_PATH.' ] 不可写!');
}
mkdir(CACHE_PATH); // 模板缓存目录
if(!is_dir(LOG_PATH)) mkdir(LOG_PATH); // 日志目录
if(!is_dir(TEMP_PATH)) mkdir(TEMP_PATH); // 数据缓存目录
if(!is_dir(DATA_PATH)) mkdir(DATA_PATH); // 数据文件目录
return true;
}
// 创建编译缓存
function build_runtime_cache($append='') {
// 生成编译文件
$defs = get_defined_constants(TRUE);
$content = '$GLOBALS[\'_beginTime\'] = microtime(TRUE);';
if(defined('RUNTIME_DEF_FILE')) { // 编译后的常量文件外部引入
file_put_contents(RUNTIME_DEF_FILE,'<?php '.array_define($defs['user']));
$content .= 'require \''.RUNTIME_DEF_FILE.'\';';
}else{
$content .= array_define($defs['user']);
}
$content .= 'set_include_path(get_include_path() . PATH_SEPARATOR . VENDOR_PATH);';
// 读取核心编译文件列表
$list = array(
THINK_PATH.'Common/common.php',
CORE_PATH.'Core/Think.class.php',
CORE_PATH.'Core/ThinkException.class.php',
CORE_PATH.'Core/Behavior.class.php',
);
foreach ($list as $file){
$content .= compile($file);
}
// 系统行为扩展文件统一编译
if(C('APP_TAGS_ON')) {
$content .= build_tags_cache();
}
$alias = include THINK_PATH.'Conf/alias.php';
$content .= 'alias_import('.var_export($alias,true).');';
// 编译框架默认语言包和配置参数
$content .= $append."\nL(".var_export(L(),true).");C(".var_export(C(),true).');G(\'loadTime\');Think::Start();';
file_put_contents(RUNTIME_FILE,strip_whitespace('<?php '.$content));
}
// 编译系统行为扩展类库
function build_tags_cache() {
$tags = C('extends');
$content = '';
foreach ($tags as $tag=>$item){
foreach ($item as $key=>$name) {
$content .= is_int($key)?compile(CORE_PATH.'Behavior/'.$name.'Behavior.class.php'):compile($name);
}
}
return $content;
}
// 创建项目目录结构
function build_app_dir() {
// 没有创建项目目录的话自动创建
if(!is_dir(APP_PATH)) mk_dir(APP_PATH,0777);
if(is_writeable(APP_PATH)) {
$dirs = array(
LIB_PATH,
RUNTIME_PATH,
CONF_PATH,
COMMON_PATH,
LANG_PATH,
CACHE_PATH,
TMPL_PATH,
TMPL_PATH.C('DEFAULT_THEME').'/',
LOG_PATH,
TEMP_PATH,
DATA_PATH,
LIB_PATH.'Model/',
LIB_PATH.'Action/',
LIB_PATH.'Behavior/',
LIB_PATH.'Widget/',
);
foreach ($dirs as $dir){
if(!is_dir($dir)) mk_dir($dir,0777);
}
// 目录安全写入
defined('BUILD_DIR_SECURE') or define('BUILD_DIR_SECURE',false);
if(BUILD_DIR_SECURE) {
defined('DIR_SECURE_FILENAME') or define('DIR_SECURE_FILENAME','index.html');
defined('DIR_SECURE_CONTENT') or define('DIR_SECURE_CONTENT',' ');
// 自动写入目录安全文件
$content = DIR_SECURE_CONTENT;
$a = explode(',', DIR_SECURE_FILENAME);
foreach ($a as $filename){
foreach ($dirs as $dir)
file_put_contents($dir.$filename,$content);
}
}
// 写入配置文件
if(!is_file(CONF_PATH.'config.php'))
file_put_contents(CONF_PATH.'config.php',"<?php\nreturn array(\n\t//'配置项'=>'配置值'\n);\n?>");
// 写入测试Action
if(!is_file(LIB_PATH.'Action/IndexAction.class.php'))
build_first_action();
}else{
header('Content-Type:text/html; charset=utf-8');
exit('项目目录不可写,目录无法自动生成!<BR>请使用项目生成器或者手动生成项目目录~');
}
}
// 创建测试Action
function build_first_action() {
$content = file_get_contents(THINK_PATH.'Tpl/default_index.tpl');
file_put_contents(LIB_PATH.'Action/IndexAction.class.php',$content);
}
// 加载运行时所需文件
load_runtime_file();
// 记录加载文件时间
G('loadTime');
// 执行入口
Think::Start(); | 10npsite | trunk/DThinkPHP/Common/runtime.php | PHP | asf20 | 9,790 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: common.php 2799 2012-03-05 07:18:06Z liu21st $
/**
+------------------------------------------------------------------------------
* Think 基础函数库
+------------------------------------------------------------------------------
* @category Think
* @package Common
* @author liu21st <liu21st@gmail.com>
* @version $Id: common.php 2799 2012-03-05 07:18:06Z liu21st $
+------------------------------------------------------------------------------
*/
// 记录和统计时间(微秒)
function G($start,$end='',$dec=4) {
static $_info = array();
if(is_float($end)) { // 记录时间
$_info[$start] = $end;
}elseif(!empty($end)){ // 统计时间
if(!isset($_info[$end])) $_info[$end] = microtime(TRUE);
return number_format(($_info[$end]-$_info[$start]),$dec);
}else{ // 记录时间
$_info[$start] = microtime(TRUE);
}
}
// 设置和获取统计数据
function N($key, $step=0) {
static $_num = array();
if (!isset($_num[$key])) {
$_num[$key] = 0;
}
if (empty($step))
return $_num[$key];
else
$_num[$key] = $_num[$key] + (int) $step;
}
/**
+----------------------------------------------------------
* 字符串命名风格转换
* type
* =0 将Java风格转换为C的风格
* =1 将C风格转换为Java的风格
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $name 字符串
* @param integer $type 转换类型
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function parse_name($name, $type=0) {
if ($type) {
return ucfirst(preg_replace("/_([a-zA-Z])/e", "strtoupper('\\1')", $name));
} else {
return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
}
}
// 优化的require_once
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 file_exists_case($filename) {
if (is_file($filename)) {
if (IS_WIN && C('APP_FILE_CASE')) {
if (basename(realpath($filename)) != basename($filename))
return false;
}
return true;
}
return false;
}
/**
+----------------------------------------------------------
* 导入所需的类库 同java的Import
* 本函数有缓存功能
+----------------------------------------------------------
* @param string $class 类库命名空间字符串
* @param string $baseUrl 起始路径
* @param string $ext 导入的文件扩展名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
function import($class, $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)) {
if ('@' == $class_strut[0] || APP_NAME == $class_strut[0]) {
//加载当前项目应用类库
$baseUrl = dirname(LIB_PATH);
$class = substr_replace($class, basename(LIB_PATH).'/', 0, strlen($class_strut[0]) + 1);
}elseif ('think' == strtolower($class_strut[0])){ // think 官方基类库
$baseUrl = CORE_PATH;
$class = substr($class,6);
}elseif (in_array(strtolower($class_strut[0]), array('org', 'com'))) {
// org 第三方公共类库 com 企业公共类库
$baseUrl = LIBRARY_PATH;
}else { // 加载其他项目应用类库
$class = substr_replace($class, '', 0, strlen($class_strut[0]) + 1);
$baseUrl = APP_PATH . '../' . $class_strut[0] . '/'.basename(LIB_PATH).'/';
}
}
if (substr($baseUrl, -1) != '/')
$baseUrl .= '/';
$classfile = $baseUrl . $class . $ext;
if (!class_exists(basename($class),false)) {
// 如果类不存在 则导入类库文件
return require_cache($classfile);
}
}
/**
+----------------------------------------------------------
* 基于命名空间方式导入函数库
* load('@.Util.Array')
+----------------------------------------------------------
* @param string $name 函数库命名空间字符串
* @param string $baseUrl 起始路径
* @param string $ext 导入的文件扩展名
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
function load($name, $baseUrl='', $ext='.php') {
$name = str_replace(array('.', '#'), array('/', '.'), $name);
if (empty($baseUrl)) {
if (0 === strpos($name, '@/')) {
//加载当前项目函数库
$baseUrl = COMMON_PATH;
$name = substr($name, 2);
} else {
//加载ThinkPHP 系统函数库
$baseUrl = EXTEND_PATH . 'Function/';
}
}
if (substr($baseUrl, -1) != '/')
$baseUrl .= '/';
require_cache($baseUrl . $name . $ext);
}
// 快速导入第三方框架类库
// 所有第三方框架的类库文件统一放到 系统的Vendor目录下面
// 并且默认都是以.php后缀导入
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;
}
/**
+----------------------------------------------------------
* D函数用于实例化Model 格式 项目://分组/模块
+----------------------------------------------------------
* @param string name Model资源地址
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
function D($name='') {
if(empty($name)) return new Model;
static $_model = array();
if(isset($_model[$name]))
return $_model[$name];
if(strpos($name,'://')) {// 指定项目
$name = str_replace('://','/Model/',$name);
}else{
$name = C('DEFAULT_APP').'/Model/'.$name;
}
import($name.'Model');
$class = basename($name.'Model');
if(class_exists($class)) {
$model = new $class();
}else {
$model = new Model(basename($name));
}
$_model[$name] = $model;
return $model;
}
/**
+----------------------------------------------------------
* M函数用于实例化一个没有模型文件的Model
+----------------------------------------------------------
* @param string name Model名称 支持指定基础模型 例如 MongoModel:User
* @param string tablePrefix 表前缀
* @param mixed $connection 数据库连接信息
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
function M($name='', $tablePrefix='',$connection='') {
static $_model = array();
if(strpos($name,':')) {
list($class,$name) = explode(':',$name);
}else{
$class = 'Model';
}
if (!isset($_model[$name . '_' . $class]))
$_model[$name . '_' . $class] = new $class($name,$tablePrefix,$connection);
return $_model[$name . '_' . $class];
}
/**
+----------------------------------------------------------
* A函数用于实例化Action 格式:[项目://][分组/]模块
+----------------------------------------------------------
* @param string name Action资源地址
+----------------------------------------------------------
* @return Action
+----------------------------------------------------------
*/
function A($name) {
static $_action = array();
if(isset($_action[$name]))
return $_action[$name];
if(strpos($name,'://')) {// 指定项目
$name = str_replace('://','/Action/',$name);
}else{
$name = '@/Action/'.$name;
}
import($name.'Action');
$class = basename($name.'Action');
if(class_exists($class,false)) {
$action = new $class();
$_action[$name] = $action;
return $action;
}else {
return false;
}
}
// 远程调用模块的操作方法
// URL 参数格式 [项目://][分组/]模块/操作
function R($url,$vars=array()) {
$info = pathinfo($url);
$action = $info['basename'];
$module = $info['dirname'];
$class = A($module);
if($class)
return call_user_func_array(array(&$class,$action),$vars);
else
return false;
}
// 获取和设置语言定义(不区分大小写)
function L($name=null, $value=null) {
static $_lang = array();
// 空参数返回所有定义
if (empty($name))
return $_lang;
// 判断语言获取(或设置)
// 若不存在,直接返回全大写$name
if (is_string($name)) {
$name = strtoupper($name);
if (is_null($value))
return isset($_lang[$name]) ? $_lang[$name] : $name;
$_lang[$name] = $value; // 语言定义
return;
}
// 批量定义
if (is_array($name))
$_lang = array_merge($_lang, array_change_key_case($name, CASE_UPPER));
return;
}
// 获取配置值
function C($name=null, $value=null) {
static $_config = array();
// 无参数时获取所有
if (empty($name)) return $_config;
// 优先执行设置获取或赋值
if (is_string($name)) {
if (!strpos($name, '.')) {
$name = strtolower($name);
if (is_null($value))
return isset($_config[$name]) ? $_config[$name] : null;
$_config[$name] = $value;
return;
}
// 二维数组设置和获取支持
$name = explode('.', $name);
$name[0] = strtolower($name[0]);
if (is_null($value))
return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null;
$_config[$name[0]][$name[1]] = $value;
return;
}
// 批量设置
if (is_array($name)){
return $_config = array_merge($_config, array_change_key_case($name));
}
return null; // 避免非法参数
}
// 处理标签扩展
function tag($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'])){ // 通过设置 '_overlay'=>1 覆盖系统标签
unset($tags['_overlay']);
}
}elseif(!empty($extends)) {
$tags = $extends;
}
if($tags) {
if(APP_DEBUG) {
G($tag.'Start');
Log::record('Tag[ '.$tag.' ] --START--',Log::INFO);
}
// 执行扩展
foreach ($tags as $key=>$name) {
if(!is_int($key)) { // 指定行为类的完整路径 用于模式扩展
$name = $key;
}
B($name, $params);
}
if(APP_DEBUG) { // 记录行为的执行日志
Log::record('Tag[ '.$tag.' ] --END-- [ RunTime:'.G($tag.'Start',$tag.'End',6).'s ]',Log::INFO);
}
}else{ // 未执行任何行为 返回false
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 filter($name, &$content) {
$class = $name . 'Filter';
require_cache(LIB_PATH . 'Filter/' . $class . '.class.php');
$filter = new $class();
$content = $filter->run($content);
}
// 执行行为
function B($name, &$params=NULL) {
$class = $name.'Behavior';
G('behaviorStart');
$behavior = new $class();
$behavior->run($params);
if(APP_DEBUG) { // 记录行为的执行日志
G('behaviorEnd');
Log::record('Run '.$name.' Behavior [ RunTime:'.G('behaviorStart','behaviorEnd',6).'s ]',Log::INFO);
}
}
// 渲染输出Widget
function W($name, $data=array(), $return=false) {
$class = $name . 'Widget';
require_cache(LIB_PATH . 'Widget/' . $class . '.class.php');
if (!class_exists($class))
throw_exception(L('_CLASS_NOT_EXIST_') . ':' . $class);
$widget = Think::instance($class);
$content = $widget->render($data);
if ($return)
return $content;
else
echo $content;
}
// 去除代码中的空白和注释
function strip_whitespace($content) {
$stripStr = '';
//分析php源码
$tokens = token_get_all($content);
$last_space = false;
for ($i = 0, $j = count($tokens); $i < $j; $i++) {
if (is_string($tokens[$i])) {
$last_space = false;
$stripStr .= $tokens[$i];
} else {
switch ($tokens[$i][0]) {
//过滤各种PHP注释
case T_COMMENT:
case T_DOC_COMMENT:
break;
//过滤空格
case T_WHITESPACE:
if (!$last_space) {
$stripStr .= ' ';
$last_space = true;
}
break;
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 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);
}
//[RUNTIME]
// 编译文件
function compile($filename) {
$content = file_get_contents($filename);
// 替换预编译指令
$content = preg_replace('/\/\/\[RUNTIME\](.*?)\/\/\[\/RUNTIME\]/s', '', $content);
$content = substr(trim($content), 5);
if ('?>' == substr($content, -2))
$content = substr($content, 0, -2);
return $content;
}
// 根据数组生成常量定义
function array_define($array,$check=true) {
$content = "\n";
foreach ($array as $key => $val) {
$key = strtoupper($key);
if($check) $content .= 'defined(\'' . $key . '\') or ';
if (is_int($val) || is_float($val)) {
$content .= "define('" . $key . "'," . $val . ');';
} elseif (is_bool($val)) {
$val = ($val) ? 'true' : 'false';
$content .= "define('" . $key . "'," . $val . ');';
} elseif (is_string($val)) {
$content .= "define('" . $key . "','" . addslashes($val) . "');";
}
$content .= "\n";
}
return $content;
}
//[/RUNTIME] | 10npsite | trunk/DThinkPHP/Common/common.php | PHP | asf20 | 17,616 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: TemplateEase.class.php 2730 2012-02-12 04:45:34Z liu21st $
/**
+---------------------------------------
* EaseTemplate模板引擎驱动类
+---------------------------------------
*/
class TemplateEase {
/**
+----------------------------------------------------------
* 渲染模板输出
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $templateFile 模板文件名
* @param array $var 模板变量
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function fetch($templateFile,$var) {
$templateFile = substr($templateFile,strlen(TMPL_PATH),-5);
$CacheDir = substr(CACHE_PATH,0,-1);
$TemplateDir = substr(TMPL_PATH,0,-1);
vendor('EaseTemplate.template#ease');
if(C('TMPL_ENGINE_CONFIG')) {
$config = C('TMPL_ENGINE_CONFIG');
}else{
$config = array(
'CacheDir'=>$CacheDir,
'TemplateDir'=>$TemplateDir,
'TplType'=>'html'
);
}
$tpl = new EaseTemplate($config);
$tpl->set_var($var);
$tpl->set_file($templateFile);
$tpl->p();
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Template/TemplateEase.class.php | PHP | asf20 | 2,035 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: TemplateSmarty.class.php 2730 2012-02-12 04:45:34Z liu21st $
/**
+-------------------------------------
* Smarty模板引擎驱动类
+-------------------------------------
*/
class TemplateSmarty {
/**
+----------------------------------------------------------
* 渲染模板输出
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $templateFile 模板文件名
* @param array $var 模板变量
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function fetch($templateFile,$var) {
$templateFile=substr($templateFile,strlen(TMPL_PATH));
vendor('Smarty.Smarty#class');
$tpl = new Smarty();
if(C('TMPL_ENGINE_CONFIG')) {
$config = C('TMPL_ENGINE_CONFIG');
foreach ($config as $key=>$val){
$tpl->{$key} = $val;
}
}else{
$tpl->caching = C('TMPL_CACHE_ON');
$tpl->template_dir = TMPL_PATH;
$tpl->compile_dir = CACHE_PATH ;
$tpl->cache_dir = TEMP_PATH ;
}
$tpl->assign($var);
$tpl->display($templateFile);
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Template/TemplateSmarty.class.php | PHP | asf20 | 1,999 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: TemplateLite.class.php 2730 2012-02-12 04:45:34Z liu21st $
/**
+---------------------------------------
* TemplateLite模板引擎驱动类
+---------------------------------------
*/
class TemplateLite {
/**
+----------------------------------------------------------
* 渲染模板输出
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $templateFile 模板文件名
* @param array $var 模板变量
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function fetch($templateFile,$var) {
$templateFile=substr($templateFile,strlen(TMPL_PATH));
vendor("TemplateLite.class#template");
$tpl = new Template_Lite();
if(C('TMPL_ENGINE_CONFIG')) {
$config = C('TMPL_ENGINE_CONFIG');
foreach ($config as $key=>$val){
$tpl->{$key} = $val;
}
}else{
$tpl->template_dir = TMPL_PATH;
$tpl->compile_dir = CACHE_PATH ;
$tpl->cache_dir = TEMP_PATH ;
}
$tpl->assign($var);
$tpl->display($templateFile);
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Template/TemplateLite.class.php | PHP | asf20 | 1,969 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: TemplateSmart.class.php 2730 2012-02-12 04:45:34Z liu21st $
/**
+------------------------------------
* Smart模板引擎驱动类
+------------------------------------
*/
class TemplateSmart {
/**
+----------------------------------------------------------
* 渲染模板输出
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $templateFile 模板文件名
* @param array $var 模板变量
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function fetch($templateFile,$var) {
$templateFile=substr($templateFile,strlen(TMPL_PATH));
vendor('SmartTemplate.class#smarttemplate');
$tpl = new SmartTemplate($templateFile);
if(C('TMPL_ENGINE_CONFIG')) {
$config = C('TMPL_ENGINE_CONFIG');
foreach ($config as $key=>$val){
$tpl->{$key} = $val;
}
}else{
$tpl->caching = C('TMPL_CACHE_ON');
$tpl->template_dir = TMPL_PATH;
$tpl->temp_dir = CACHE_PATH ;
$tpl->cache_dir = TEMP_PATH ;
}
$tpl->assign($var);
$tpl->output();
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Template/TemplateSmart.class.php | PHP | asf20 | 2,009 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: SessionDb.class.php 2730 2012-02-12 04:45:34Z liu21st $
/**
+--------------------------------------------
* 数据库方式Session驱动
CREATE TABLE think_session (
session_id varchar(255) NOT NULL,
session_expire int(11) NOT NULL,
session_data blob,
UNIQUE KEY `session_id` (`session_id`)
);
+--------------------------------------------
*/
class SessionDb {//类定义开始
/**
+----------------------------------------------------------
* Session有效时间
+----------------------------------------------------------
*/
protected $lifeTime='';
/**
+----------------------------------------------------------
* session保存的数据库名
+----------------------------------------------------------
*/
protected $sessionTable='';
/**
+----------------------------------------------------------
* 数据库句柄
+----------------------------------------------------------
*/
protected $hander;
/**
+----------------------------------------------------------
* 打开Session
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $savePath
* @param mixed $sessName
+----------------------------------------------------------
*/
public function open($savePath, $sessName) {
$this->lifeTime = C('SESSION_EXPIRE');
$this->sessionTable = C('SESSION_TABLE');
$hander = mysql_connect(C('DB_HOST'),C('DB_USER'),C('DB_PWD'));
$dbSel = mysql_select_db(C('DB_NAME'),$hander);
if(!$hander || !$dbSel)
return false;
$this->hander = $hander;
return true;
}
/**
+----------------------------------------------------------
* 关闭Session
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function close() {
$this->gc(ini_get('session.gc_maxlifetime'));
return mysql_close($this->hander);
}
/**
+----------------------------------------------------------
* 读取Session
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $sessID
+----------------------------------------------------------
*/
public function read($sessID) {
$res = mysql_query("SELECT session_data AS data FROM ".$this->sessionTable." WHERE session_id = '$sessID' AND session_expire >".time(),$this->hander);
if($res) {
$row = mysql_fetch_assoc($res);
return $row['data'];
}
return "";
}
/**
+----------------------------------------------------------
* 写入Session
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $sessID
* @param String $sessData
+----------------------------------------------------------
*/
public function write($sessID,$sessData) {
$expire = time() + $this->lifeTime;
mysql_query("REPLACE INTO ".$this->sessionTable." ( session_id, session_expire, session_data) VALUES( '$sessID', '$expire', '$sessData')",$this->hander);
if(mysql_affected_rows($this->hander))
return true;
return false;
}
/**
+----------------------------------------------------------
* 删除Session
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $sessID
+----------------------------------------------------------
*/
public function destroy($sessID) {
mysql_query("DELETE FROM ".$this->sessionTable." WHERE session_id = '$sessID'",$this->hander);
if(mysql_affected_rows($this->hander))
return true;
return false;
}
/**
+----------------------------------------------------------
* Session 垃圾回收
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $sessMaxLifeTime
+----------------------------------------------------------
*/
public function gc($sessMaxLifeTime) {
mysql_query("DELETE FROM ".$this->sessionTable." WHERE session_expire < ".time(),$this->hander);
return mysql_affected_rows($this->hander);
}
/**
+----------------------------------------------------------
* 打开Session
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $savePath
* @param mixed $sessName
+----------------------------------------------------------
*/
public function execute() {
session_set_save_handler(array(&$this,"open"),
array(&$this,"close"),
array(&$this,"read"),
array(&$this,"write"),
array(&$this,"destroy"),
array(&$this,"gc"));
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Session/SessionDb.class.php | PHP | asf20 | 6,274 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 尘缘 <130775@qq.com>
// +----------------------------------------------------------------------
// $Id: CacheRedis.class.php 2787 2012-02-28 08:50:32Z shuhai.sir@gmail.com $
/**
+-------------------------------------
* CacheRedis缓存驱动类
* 要求安装phpredis扩展:https://github.com/owlient/phpredis
+-------------------------------------
*/
class CacheRedis extends Cache {
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($options='') {
if ( !extension_loaded('redis') ) {
throw_exception(L('_NOT_SUPPERT_').':redis');
}
if(empty($options)) {
$options = array (
'host' => C('REDIS_HOST') ? C('REDIS_HOST') : '127.0.0.1',
'port' => C('REDIS_PORT') ? C('REDIS_PORT') : 6379,
'timeout' => C('DATA_CACHE_TIMEOUT') ? C('DATA_CACHE_TIMEOUT') : false,
'persistent' => false,
'expire' => C('DATA_CACHE_TIME'),
'length' => 0,
);
}
$this->options = $options;
$func = $options['persistent'] ? 'pconnect' : 'connect';
$this->handler = new Redis;
$this->connected = $options['timeout'] === false ?
$this->handler->$func($options['host'], $options['port']) :
$this->handler->$func($options['host'], $options['port'], $options['timeout']);
}
/**
+----------------------------------------------------------
* 是否连接
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
private function isConnected() {
return $this->connected;
}
/**
+----------------------------------------------------------
* 读取缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function get($name) {
N('cache_read',1);
return $this->handler->get($name);
}
/**
+----------------------------------------------------------
* 写入缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function set($name, $value, $expire = null) {
N('cache_write',1);
if(is_null($expire)) {
$expire = $this->options['expire'];
}
if(is_int($expire)) {
$result = $this->handler->setex($name, $expire, $value);
}else{
$result = $this->handler->set($name, $value);
}
if($result && $this->options['length']>0) {
// 记录缓存队列
$this->queue($name);
}
return $result;
}
/**
+----------------------------------------------------------
* 删除缓存
*
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function rm($name) {
return $this->handler->delete($name);
}
/**
+----------------------------------------------------------
* 清除缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function clear() {
return $this->handler->flushDB();
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Cache/CacheRedis.class.php | PHP | asf20 | 5,243 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CacheApachenote.class.php 2728 2012-02-12 04:12:51Z liu21st $
/**
+-----------------------------------------
* Apachenote缓存驱动类
+-----------------------------------------
*/
class CacheApachenote extends Cache {
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($options='') {
if(empty($options)){
$options = array(
'host' => '127.0.0.1',
'port' => 1042,
'timeout' => 10,
'length' =>0
);
}
$this->handler = null;
$this->open();
$this->options = $options;
}
/**
+----------------------------------------------------------
* 是否连接
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function isConnected() {
return $this->connected;
}
/**
+----------------------------------------------------------
* 读取缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function get($name) {
$this->open();
$s = 'F' . pack('N', strlen($name)) . $name;
fwrite($this->handler, $s);
for ($data = ''; !feof($this->handler);) {
$data .= fread($this->handler, 4096);
}
N('cache_read',1);
$this->close();
return $data === '' ? '' : unserialize($data);
}
/**
+----------------------------------------------------------
* 写入缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
* @param mixed $value 存储数据
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function set($name, $value) {
N('cache_write',1);
$this->open();
$value = serialize($value);
$s = 'S' . pack('NN', strlen($name), strlen($value)) . $name . $value;
fwrite($this->handler, $s);
$ret = fgets($this->handler);
$this->close();
if($ret === "OK\n") {
if($this->options['length']>0) {
// 记录缓存队列
$this->queue($name);
}
return true;
}
return false;
}
/**
+----------------------------------------------------------
* 删除缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function rm($name) {
$this->open();
$s = 'D' . pack('N', strlen($name)) . $name;
fwrite($this->handler, $s);
$ret = fgets($this->handler);
$this->close();
return $ret === "OK\n";
}
/**
+----------------------------------------------------------
* 关闭缓存
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
*/
private function close() {
fclose($this->handler);
$this->handler = false;
}
/**
+----------------------------------------------------------
* 打开缓存
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
*/
private function open() {
if (!is_resource($this->handler)) {
$this->handler = fsockopen($this->options['host'], $this->options['port'], $_, $_, $this->options['timeout']);
$this->connected = is_resource($this->handler);
}
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Cache/CacheApachenote.class.php | PHP | asf20 | 5,463 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CacheShmop.class.php 2728 2012-02-12 04:12:51Z liu21st $
/**
+------------------------------------
* Shmop缓存驱动类
+------------------------------------
*/
class CacheShmop extends Cache {
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($options='') {
if ( !extension_loaded('shmop') ) {
throw_exception(L('_NOT_SUPPERT_').':shmop');
}
if(!empty($options)){
$options = array(
'size' => C('SHARE_MEM_SIZE'),
'tmp' => TEMP_PATH,
'project' => 's',
'length' =>0,
);
}
$this->options = $options;
$this->handler = $this->_ftok($this->options['project']);
}
/**
+----------------------------------------------------------
* 读取缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function get($name = false) {
N('cache_read',1);
$id = shmop_open($this->handler, 'c', 0600, 0);
if ($id !== false) {
$ret = unserialize(shmop_read($id, 0, shmop_size($id)));
shmop_close($id);
if ($name === false) {
return $ret;
}
if(isset($ret[$name])) {
$content = $ret[$name];
if(C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) {
//启用数据压缩
$content = gzuncompress($content);
}
return $content;
}else {
return null;
}
}else {
return false;
}
}
/**
+----------------------------------------------------------
* 写入缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
* @param mixed $value 存储数据
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function set($name, $value) {
N('cache_write',1);
$lh = $this->_lock();
$val = $this->get();
if (!is_array($val)) $val = array();
if( C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) {
//数据压缩
$value = gzcompress($value,3);
}
$val[$name] = $value;
$val = serialize($val);
if($this->_write($val, $lh)) {
if($this->options['length']>0) {
// 记录缓存队列
$this->queue($name);
}
return true;
}
return false;
}
/**
+----------------------------------------------------------
* 删除缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function rm($name) {
$lh = $this->_lock();
$val = $this->get();
if (!is_array($val)) $val = array();
unset($val[$name]);
$val = serialize($val);
return $this->_write($val, $lh);
}
/**
+----------------------------------------------------------
* 生成IPC key
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $project 项目标识名
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
private function _ftok($project) {
if (function_exists('ftok')) return ftok(__FILE__, $project);
if(strtoupper(PHP_OS) == 'WINNT'){
$s = stat(__FILE__);
return sprintf("%u", (($s['ino'] & 0xffff) | (($s['dev'] & 0xff) << 16) |
(($project & 0xff) << 24)));
}else {
$filename = __FILE__ . (string) $project;
for($key = array(); sizeof($key) < strlen($filename); $key[] = ord(substr($filename, sizeof($key), 1)));
return dechex(array_sum($key));
}
}
/**
+----------------------------------------------------------
* 写入操作
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return integer|boolen
+----------------------------------------------------------
*/
private function _write(&$val, &$lh) {
$id = shmop_open($this->handler, 'c', 0600, $this->options['size']);
if ($id) {
$ret = shmop_write($id, $val, 0) == strlen($val);
shmop_close($id);
$this->_unlock($lh);
return $ret;
}
$this->_unlock($lh);
return false;
}
/**
+----------------------------------------------------------
* 共享锁定
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
private function _lock() {
if (function_exists('sem_get')) {
$fp = sem_get($this->handler, 1, 0600, 1);
sem_acquire ($fp);
} else {
$fp = fopen($this->options['tmp'].$this->prefix.md5($this->handler), 'w');
flock($fp, LOCK_EX);
}
return $fp;
}
/**
+----------------------------------------------------------
* 解除共享锁定
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
private function _unlock(&$fp) {
if (function_exists('sem_release')) {
sem_release($fp);
} else {
fclose($fp);
}
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Cache/CacheShmop.class.php | PHP | asf20 | 8,043 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CacheApc.class.php 2728 2012-02-12 04:12:51Z liu21st $
/**
+-------------------------------
* Apc缓存驱动类
+-------------------------------
*/
class CacheApc extends Cache {
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($options='') {
if(!function_exists('apc_cache_info')) {
throw_exception(L('_NOT_SUPPERT_').':Apc');
}
if(!empty($options)) {
$this->options = $options;
}
$this->options['expire'] = isset($options['expire'])?$options['expire']:C('DATA_CACHE_TIME');
$this->options['length'] = isset($options['length'])?$options['length']:0;
}
/**
+----------------------------------------------------------
* 读取缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function get($name) {
N('cache_read',1);
return apc_fetch($name);
}
/**
+----------------------------------------------------------
* 写入缓存
*
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function set($name, $value, $expire = null) {
N('cache_write',1);
if(is_null($expire)) {
$expire = $this->options['expire'];
}
if($result = apc_store($name, $value, $expire)) {
if($this->options['length']>0) {
// 记录缓存队列
$this->queue($name);
}
}
return $result;
}
/**
+----------------------------------------------------------
* 删除缓存
*
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function rm($name) {
return apc_delete($name);
}
/**
+----------------------------------------------------------
* 清除缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function clear() {
return apc_clear_cache();
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Cache/CacheApc.class.php | PHP | asf20 | 4,044 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CacheXcache.class.php 2728 2012-02-12 04:12:51Z liu21st $
/**
+----------------------------
* Xcache缓存驱动类
+----------------------------
*/
class CacheXcache extends Cache {
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($options='') {
if ( !function_exists('xcache_info') ) {
throw_exception(L('_NOT_SUPPERT_').':Xcache');
}
if(!empty($options)) {
$this->options = $options;
}
$this->options['expire'] = isset($options['expire'])?$options['expire']:C('DATA_CACHE_TIME');
$this->options['length'] = isset($options['length'])?$options['length']:0;
}
/**
+----------------------------------------------------------
* 读取缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function get($name) {
N('cache_read',1);
if (xcache_isset($name)) {
return xcache_get($name);
}
return false;
}
/**
+----------------------------------------------------------
* 写入缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function set($name, $value,$expire=null) {
N('cache_write',1);
if(is_null($expire)) {
$expire = $this->options['expire'] ;
}
if(xcache_set($name, $value, $expire)) {
if($this->options['length']>0) {
// 记录缓存队列
$this->queue($name);
}
return true;
}
return false;
}
/**
+----------------------------------------------------------
* 删除缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function rm($name) {
return xcache_unset($name);
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Cache/CacheXcache.class.php | PHP | asf20 | 3,687 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CacheSqlite.class.php 2734 2012-02-14 06:55:15Z liu21st $
/**
+--------------------------------
* Sqlite缓存类
+--------------------------------
*/
class CacheSqlite extends Cache {
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($options='') {
if ( !extension_loaded('sqlite') ) {
throw_exception(L('_NOT_SUPPERT_').':sqlite');
}
if(empty($options)){
$options= array (
'db' => ':memory:',
'table' => 'sharedmemory',
'expire' => C('DATA_CACHE_TIME'),
'persistent'=> false,
'length' =>0,
);
}
$this->options = $options;
$func = $this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open';
$this->handler = $func($this->options['db']);
$this->connected = is_resource($this->handler);
}
/**
+----------------------------------------------------------
* 是否连接
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
private function isConnected() {
return $this->connected;
}
/**
+----------------------------------------------------------
* 读取缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function get($name) {
N('cache_read',1);
$name = sqlite_escape_string($name);
$sql = 'SELECT value FROM '.$this->options['table'].' WHERE var=\''.$name.'\' AND (expire=0 OR expire >'.time().') LIMIT 1';
$result = sqlite_query($this->handler, $sql);
if (sqlite_num_rows($result)) {
$content = sqlite_fetch_single($result);
if(C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) {
//启用数据压缩
$content = gzuncompress($content);
}
return unserialize($content);
}
return false;
}
/**
+----------------------------------------------------------
* 写入缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function set($name, $value,$expire=null) {
N('cache_write',1);
$expire = !empty($expireTime)? $expireTime : C('DATA_CACHE_TIME');
$name = sqlite_escape_string($name);
$value = sqlite_escape_string(serialize($value));
if(is_null($expire)) {
$expire = $this->options['expire'];
}
$expire = ($expire==0)?0: (time()+$expire) ;//缓存有效期为0表示永久缓存
if( C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) {
//数据压缩
$value = gzcompress($value,3);
}
$sql = 'REPLACE INTO '.$this->options['table'].' (var, value,expire) VALUES (\''.$name.'\', \''.$value.'\', \''.$expire.'\')';
if(sqlite_query($this->handler, $sql)){
if($this->options['length']>0) {
// 记录缓存队列
$this->queue($name);
}
return true;
}
return false;
}
/**
+----------------------------------------------------------
* 删除缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function rm($name) {
$name = sqlite_escape_string($name);
$sql = 'DELETE FROM '.$this->options['table'].' WHERE var=\''.$name.'\'';
sqlite_query($this->handler, $sql);
return true;
}
/**
+----------------------------------------------------------
* 清除缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function clear() {
$sql = 'DELETE FROM '.$this->options['table'];
sqlite_query($this->handler, $sql);
return ;
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Cache/CacheSqlite.class.php | PHP | asf20 | 6,102 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CacheWincache.class.php 2728 2012-02-12 04:12:51Z liu21st $
/**
+----------------------------
* WinCache 缓存驱动类
+----------------------------
*/
class CacheWincache extends Cache {
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($options='') {
if ( !function_exists('wincache_ucache_info') ) {
throw_exception(L('_NOT_SUPPERT_').':WinCache');
}
if(!empty($options)) {
$this->options = $options;
}
$this->options['expire'] = isset($options['expire'])?$options['expire']:C('DATA_CACHE_TIME');
$this->options['length'] = isset($options['length'])?$options['length']:0;
}
/**
+----------------------------------------------------------
* 读取缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function get($name) {
N('cache_read',1);
return wincache_ucache_exists($name)? wincache_ucache_get($name) : false;
}
/**
+----------------------------------------------------------
* 写入缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function set($name, $value,$expire=null) {
N('cache_write',1);
if(is_null($expire)) {
$expire = $this->options['expire'];
}
if(wincache_ucache_set($name, $value, $expire)) {
if($this->options['length']>0) {
// 记录缓存队列
$this->queue($name);
}
return true;
}
return false;
}
/**
+----------------------------------------------------------
* 删除缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function rm($name) {
return wincache_ucache_delete($name);
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Cache/CacheWincache.class.php | PHP | asf20 | 3,699 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CacheEaccelerator.class.php 2728 2012-02-12 04:12:51Z liu21st $
/**
+-------------------------------------
* Eaccelerator缓存驱动类
+-------------------------------------
*/
class CacheEaccelerator extends Cache {
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($options='') {
if(!empty($options)) {
$this->options = $options;
}
$this->options['expire'] = isset($options['expire'])?$options['expire']:C('DATA_CACHE_TIME');
$this->options['length'] = isset($options['length'])?$options['length']:0;
}
/**
+----------------------------------------------------------
* 读取缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function get($name) {
N('cache_read',1);
return eaccelerator_get($name);
}
/**
+----------------------------------------------------------
* 写入缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function set($name, $value, $expire = null) {
N('cache_write',1);
if(is_null($expire)) {
$expire = $this->options['expire'];
}
eaccelerator_lock($name);
if(eaccelerator_put($name, $value, $expire)) {
if($this->options['length']>0) {
// 记录缓存队列
$this->queue($name);
}
return true;
}
return false;
}
/**
+----------------------------------------------------------
* 删除缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function rm($name) {
return eaccelerator_rm($name);
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Cache/CacheEaccelerator.class.php | PHP | asf20 | 3,595 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CacheMemcache.class.php 2728 2012-02-12 04:12:51Z liu21st $
/**
+-------------------------------------
* Memcache缓存驱动类
+-------------------------------------
*/
class CacheMemcache extends Cache {
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
function __construct($options='') {
if ( !extension_loaded('memcache') ) {
throw_exception(L('_NOT_SUPPERT_').':memcache');
}
if(empty($options)) {
$options = array (
'host' => C('MEMCACHE_HOST') ? C('MEMCACHE_HOST') : '127.0.0.1',
'port' => C('MEMCACHE_PORT') ? C('MEMCACHE_PORT') : 11211,
'timeout' => C('DATA_CACHE_TIMEOUT') ? C('DATA_CACHE_TIMEOUT') : false,
'persistent' => false,
'expire' =>C('DATA_CACHE_TIME'),
'length' =>0,
);
}
$this->options = $options;
$func = $options['persistent'] ? 'pconnect' : 'connect';
$this->handler = new Memcache;
$this->connected = $options['timeout'] === false ?
$this->handler->$func($options['host'], $options['port']) :
$this->handler->$func($options['host'], $options['port'], $options['timeout']);
}
/**
+----------------------------------------------------------
* 是否连接
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
private function isConnected() {
return $this->connected;
}
/**
+----------------------------------------------------------
* 读取缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function get($name) {
N('cache_read',1);
return $this->handler->get($name);
}
/**
+----------------------------------------------------------
* 写入缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function set($name, $value, $expire = null) {
N('cache_write',1);
if(is_null($expire)) {
$expire = $this->options['expire'];
}
if($this->handler->set($name, $value, 0, $expire)) {
if($this->options['length']>0) {
// 记录缓存队列
$this->queue($name);
}
return true;
}
return false;
}
/**
+----------------------------------------------------------
* 删除缓存
*
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function rm($name, $ttl = false) {
return $ttl === false ?
$this->handler->delete($name) :
$this->handler->delete($name, $ttl);
}
/**
+----------------------------------------------------------
* 清除缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function clear() {
return $this->handler->flush();
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Cache/CacheMemcache.class.php | PHP | asf20 | 5,191 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CacheDb.class.php 2734 2012-02-14 06:55:15Z liu21st $
/**
+-----------------------------------------------
* 数据库类型缓存驱动类
CREATE TABLE think_cache (
cachekey varchar(255) NOT NULL,
expire int(11) NOT NULL,
data blob,
datacrc int(32),
UNIQUE KEY `cachekey` (`cachekey`)
);
+-----------------------------------------------
*/
class CacheDb extends Cache {
/**
+----------------------------------------------------------
* 缓存数据库对象 采用数据库方式有效
+----------------------------------------------------------
* @var string
* @access protected
+----------------------------------------------------------
*/
private $db ;
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($options='') {
if(empty($options)){
$options= array (
'db' => C('DB_NAME'),
'table' => C('DATA_CACHE_TABLE'),
'expire' => C('DATA_CACHE_TIME'),
'length' => 0,
);
}
$this->options = $options;
import('Db');
$this->db = DB::getInstance();
$this->connected = is_resource($this->db);
}
/**
+----------------------------------------------------------
* 是否连接
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
private function isConnected() {
return $this->connected;
}
/**
+----------------------------------------------------------
* 读取缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function get($name) {
$name = addslashes($name);
N('cache_read',1);
$result = $this->db->query('SELECT `data`,`datacrc` FROM `'.$this->options['table'].'` WHERE `cachekey`=\''.$name.'\' AND (`expire` =0 OR `expire`>'.time().') LIMIT 0,1');
if(false !== $result ) {
$result = $result[0];
if(C('DATA_CACHE_CHECK')) {//开启数据校验
if($result['datacrc'] != md5($result['data'])) {//校验错误
return false;
}
}
$content = $result['data'];
if(C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) {
//启用数据压缩
$content = gzuncompress($content);
}
$content = unserialize($content);
return $content;
}
else {
return false;
}
}
/**
+----------------------------------------------------------
* 写入缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param integer $expire 有效时间(秒)
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function set($name, $value,$expire=null) {
$data = serialize($value);
$name = addslashes($name);
N('cache_write',1);
if( C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) {
//数据压缩
$data = gzcompress($data,3);
}
if(C('DATA_CACHE_CHECK')) {//开启数据校验
$crc = md5($data);
}else {
$crc = '';
}
if(is_null($expire)) {
$expire = $this->options['expire'];
}
$expire = ($expire==0)?0: (time()+$expire) ;//缓存有效期为0表示永久缓存
$result = $this->db->query('select `cachekey` from `'.$this->options['table'].'` where `cachekey`=\''.$name.'\' limit 0,1');
if(!empty($result) ) {
//更新记录
$result = $this->db->execute('UPDATE '.$this->options['table'].' SET data=\''.$data.'\' ,datacrc=\''.$crc.'\',expire='.$expire.' WHERE `cachekey`=\''.$name.'\'');
}else {
//新增记录
$result = $this->db->execute('INSERT INTO '.$this->options['table'].' (`cachekey`,`data`,`datacrc`,`expire`) VALUES (\''.$name.'\',\''.$data.'\',\''.$crc.'\','.$expire.')');
}
if($result) {
if($this->options['length']>0) {
// 记录缓存队列
$this->queue($name);
}
return true;
}else {
return false;
}
}
/**
+----------------------------------------------------------
* 删除缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 缓存变量名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function rm($name) {
$name = addslashes($name);
return $this->db->execute('DELETE FROM `'.$this->options['table'].'` WHERE `cachekey`=\''.$name.'\'');
}
/**
+----------------------------------------------------------
* 清除缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function clear() {
return $this->db->execute('TRUNCATE TABLE `'.$this->options['table'].'`');
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Cache/CacheDb.class.php | PHP | asf20 | 7,184 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: ZhangXuehun <zhangxuehun@sohu.com>
// +----------------------------------------------------------------------
// $Id: DbOracle.class.php 2729 2012-02-12 04:13:34Z liu21st $
/**
+------------------------------
* Oracle数据库驱动类
+------------------------------
*/
class DbOracle extends Db{
private $mode = OCI_COMMIT_ON_SUCCESS;
private $table = '';
protected $selectSql = 'SELECT * FROM (SELECT thinkphp.*, rownum AS numrow FROM (SELECT %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%) thinkphp ) %LIMIT%';
/**
+----------------------------------------------------------
* 架构函数 读取数据库配置信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 数据库配置数组
+----------------------------------------------------------
*/
public function __construct($config=''){
putenv("NLS_LANG=AMERICAN_AMERICA.UTF8");
if ( !extension_loaded('oci8') ) {
throw_exception(L('_NOT_SUPPERT_').'oracle');
}
if(!empty($config)) {
$this->config = $config;
if(empty($this->config['params'])) {
$this->config['params'] = array();
}
}
}
/**
+----------------------------------------------------------
* 连接数据库方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function connect($config='',$linkNum=0) {
if ( !isset($this->linkID[$linkNum]) ) {
if(empty($config)) $config = $this->config;
$pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;
$conn = $pconnect ? 'oci_pconnect':'oci_new_connect';
$this->linkID[$linkNum] = $conn($config['username'], $config['password'],$config['database']);//modify by wyfeng at 2008.12.19
if (!$this->linkID[$linkNum]){
$error = $this->error(false);
throw_exception($error["message"], '', $error["code"]);
}
// 标记连接成功
$this->connected = true;
//注销数据库安全信息
if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
}
return $this->linkID[$linkNum];
}
/**
+----------------------------------------------------------
* 释放查询结果
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function free() {
oci_free_statement($this->queryID);
$this->queryID = null;
}
/**
+----------------------------------------------------------
* 执行查询 返回数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function query($str) {
$this->initConnect(false);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//更改事务模式
$this->mode = OCI_COMMIT_ON_SUCCESS;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID = oci_parse($this->_linkID,$str);
$this->debug();
if (false === oci_execute($this->queryID, $this->mode)) {
$this->error();
return false;
} else {
return $this->getAll();
}
}
/**
+----------------------------------------------------------
* 执行语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function execute($str) {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
// 判断新增操作
$flag = false;
if(preg_match("/^\s*(INSERT\s+INTO)\s+(\w+)\s+/i", $this->queryStr, $match)) {
$this->table = C("DB_SEQUENCE_PREFIX") .str_ireplace(C("DB_PREFIX"), "", $match[2]);
$flag = (boolean)$this->query("SELECT * FROM user_sequences WHERE sequence_name='" . strtoupper($this->table) . "'");
}//modify by wyfeng at 2009.08.28
//更改事务模式
$this->mode = OCI_COMMIT_ON_SUCCESS;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_write',1);
// 记录开始执行时间
G('queryStartTime');
$stmt = oci_parse($this->_linkID,$str);
$this->debug();
if (false === oci_execute($stmt)) {
$this->error();
return false;
} else {
$this->numRows = oci_num_rows($stmt);
$this->lastInsID = $flag?$this->insertLastId():0;//modify by wyfeng at 2009.08.28
return $this->numRows;
}
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function startTrans() {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
//数据rollback 支持
if ($this->transTimes == 0) {
$this->mode = OCI_DEFAULT;
}
$this->transTimes++;
return ;
}
/**
+----------------------------------------------------------
* 用于非自动提交状态下面的查询提交
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function commit(){
if ($this->transTimes > 0) {
$result = oci_commit($this->_linkID);
if(!$result){
throw_exception($this->error());
}
$this->transTimes = 0;
}
return true;
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function rollback(){
if ($this->transTimes > 0) {
$result = oci_rollback($this->_linkID);
if(!$result){
throw_exception($this->error());
}
$this->transTimes = 0;
}
return true;
}
/**
+----------------------------------------------------------
* 获得所有的查询数据
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
private function getAll() {
//返回数据集
$result = array();
$this->numRows = oci_fetch_all($this->queryID, $result, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
//add by wyfeng at 2008-12-23 强制将字段名转换为小写,以配合Model类函数如count等
if(C("DB_CASE_LOWER")) {
foreach($result as $k=>$v) {
$result[$k] = array_change_key_case($result[$k], CASE_LOWER);
}
}
return $result;
}
/**
+----------------------------------------------------------
* 取得数据表的字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function getFields($tableName) {
$result = $this->query("select a.column_name,data_type,decode(nullable,'Y',0,1) notnull,data_default,decode(a.column_name,b.column_name,1,0) pk "
."from user_tab_columns a,(select column_name from user_constraints c,user_cons_columns col "
."where c.constraint_name=col.constraint_name and c.constraint_type='P'and c.table_name='".strtoupper($tableName)
."') b where table_name='".strtoupper($tableName)."' and a.column_name=b.column_name(+)");
$info = array();
if($result) {
foreach ($result as $key => $val) {
$info[strtolower($val['column_name'])] = array(
'name' => strtolower($val['column_name']),
'type' => strtolower($val['data_type']),
'notnull' => $val['notnull'],
'default' => $val['data_default'],
'primary' => $val['pk'],
'autoinc' => $val['pk'],
);
}
}
return $info;
}
/**
+----------------------------------------------------------
* 取得数据库的表信息(暂时实现取得用户表信息)
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function getTables($dbName='') {
$result = $this->query("select table_name from user_tables");
$info = array();
foreach ($result as $key => $val) {
$info[$key] = current($val);
}
return $info;
}
/**
+----------------------------------------------------------
* 关闭数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function close() {
if($this->_linkID){
oci_close($this->_linkID);
}
$this->_linkID = null;
}
/**
+----------------------------------------------------------
* 数据库错误信息
* 并显示当前的SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function error($result = true) {
if($result){
$this->error = oci_error($this->queryID);
}elseif(!$this->_linkID){
$this->error = oci_error();
}else{
$this->error = oci_error($this->_linkID);
}
if($this->debug && '' != $this->queryStr){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
return $this->error;
}
/**
+----------------------------------------------------------
* SQL指令安全过滤
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mix $str SQL指令
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function escapeString($str) {
return str_ireplace("'", "''", $str);
}
/**
+----------------------------------------------------------
* 获取最后插入id ,仅适用于采用序列+触发器结合生成ID的方式
* 在config.php中指定
'DB_TRIGGER_PREFIX' => 'tr_',
'DB_SEQUENCE_PREFIX' => 'ts_',
* eg:表 tb_user
相对tb_user的序列为:
-- Create sequence
create sequence TS_USER
minvalue 1
maxvalue 999999999999999999999999999
start with 1
increment by 1
nocache;
相对tb_user,ts_user的触发器为:
create or replace trigger TR_USER
before insert on "TB_USER"
for each row
begin
select "TS_USER".nextval into :NEW.ID from dual;
end;
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function insertLastId() {
if(empty($this->table)) {
return 0;
}
$sequenceName = $this->table;
$vo = $this->query("SELECT {$sequenceName}.currval currval FROM dual");
return $vo?$vo[0]["currval"]:0;
}
/**
+----------------------------------------------------------
* limit
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseLimit($limit) {
$limitStr = '';
if(!empty($limit)) {
$limit = explode(',',$limit);
if(count($limit)>1)
$limitStr = "(numrow>" . $limit[0] . ") AND (numrow<=" . ($limit[0]+$limit[1]) . ")";
else
$limitStr = "(numrow>0 AND numrow<=".$limit[0].")";
}
return $limitStr?' WHERE '.$limitStr:'';
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Db/DbOracle.class.php | PHP | asf20 | 16,102 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: DbMssql.class.php 2729 2012-02-12 04:13:34Z liu21st $
/**
+-----------------------------------------
* MSsql数据库驱动类 针对sqlserver2005
+-----------------------------------------
*/
class DbMssql extends Db{
protected $selectSql = 'SELECT T1.* FROM (SELECT ROW_NUMBER() OVER (%ORDER%) AS ROW_NUMBER, thinkphp.* FROM (SELECT %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%) AS thinkphp) AS T1 WHERE %LIMIT%';
/**
+----------------------------------------------------------
* 架构函数 读取数据库配置信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 数据库配置数组
+----------------------------------------------------------
*/
public function __construct($config=''){
if ( !function_exists('mssql_connect') ) {
throw_exception(L('_NOT_SUPPERT_').':mssql');
}
if(!empty($config)) {
$this->config = $config;
if(empty($this->config['params'])) {
$this->config['params'] = array();
}
}
}
/**
+----------------------------------------------------------
* 连接数据库方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function connect($config='',$linkNum=0) {
if ( !isset($this->linkID[$linkNum]) ) {
if(empty($config)) $config = $this->config;
$pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;
$conn = $pconnect ? 'mssql_pconnect':'mssql_connect';
// 处理不带端口号的socket连接情况
$sepr = IS_WIN ? ',' : ':';
$host = $config['hostname'].($config['hostport']?$sepr."{$config['hostport']}":'');
$this->linkID[$linkNum] = $conn( $host, $config['username'], $config['password']);
if ( !$this->linkID[$linkNum] ) throw_exception("Couldn't connect to SQL Server on $host");
if ( !empty($config['database']) && !mssql_select_db($config['database'], $this->linkID[$linkNum]) ) {
throw_exception("Couldn't open database '".$config['database']);
}
// 标记连接成功
$this->connected = true;
//注销数据库安全信息
if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
}
return $this->linkID[$linkNum];
}
/**
+----------------------------------------------------------
* 释放查询结果
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function free() {
mssql_free_result($this->queryID);
$this->queryID = null;
}
/**
+----------------------------------------------------------
* 执行查询 返回数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function query($str) {
$this->initConnect(false);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID = mssql_query($str, $this->_linkID);
$this->debug();
if ( false === $this->queryID ) {
$this->error();
return false;
} else {
$this->numRows = mssql_num_rows($this->queryID);
return $this->getAll();
}
}
/**
+----------------------------------------------------------
* 执行语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function execute($str) {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_write',1);
// 记录开始执行时间
G('queryStartTime');
$result = mssql_query($str, $this->_linkID);
$this->debug();
if ( false === $result ) {
$this->error();
return false;
} else {
$this->numRows = mssql_rows_affected($this->_linkID);
$this->lastInsID = $this->mssql_insert_id();
return $this->numRows;
}
}
/**
+----------------------------------------------------------
* 用于获取最后插入的ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
public function mssql_insert_id() {
$query = "SELECT @@IDENTITY as last_insert_id";
$result = mssql_query($query, $this->_linkID);
list($last_insert_id) = mssql_fetch_row($result);
mssql_free_result($result);
return $last_insert_id;
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function startTrans() {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
//数据rollback 支持
if ($this->transTimes == 0) {
mssql_query('BEGIN TRAN', $this->_linkID);
}
$this->transTimes++;
return ;
}
/**
+----------------------------------------------------------
* 用于非自动提交状态下面的查询提交
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function commit() {
if ($this->transTimes > 0) {
$result = mssql_query('COMMIT TRAN', $this->_linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
}
}
return true;
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function rollback() {
if ($this->transTimes > 0) {
$result = mssql_query('ROLLBACK TRAN', $this->_linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
}
}
return true;
}
/**
+----------------------------------------------------------
* 获得所有的查询数据
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
private function getAll() {
//返回数据集
$result = array();
if($this->numRows >0) {
while($row = mssql_fetch_assoc($this->queryID))
$result[] = $row;
}
return $result;
}
/**
+----------------------------------------------------------
* 取得数据表的字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getFields($tableName) {
$result = $this->query("SELECT column_name, data_type, column_default, is_nullable
FROM information_schema.tables AS t
JOIN information_schema.columns AS c
ON t.table_catalog = c.table_catalog
AND t.table_schema = c.table_schema
AND t.table_name = c.table_name
WHERE t.table_name = '$tableName'");
$info = array();
if($result) {
foreach ($result as $key => $val) {
$info[$val['column_name']] = array(
'name' => $val['column_name'],
'type' => $val['data_type'],
'notnull' => (bool) ($val['is_nullable'] === ''), // not null is empty, null is yes
'default' => $val['column_default'],
'primary' => false,
'autoinc' => false,
);
}
}
return $info;
}
/**
+----------------------------------------------------------
* 取得数据表的字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getTables($dbName='') {
$result = $this->query("SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
");
$info = array();
foreach ($result as $key => $val) {
$info[$key] = current($val);
}
return $info;
}
/**
+----------------------------------------------------------
* order分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $order
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseOrder($order) {
return !empty($order)? ' ORDER BY '.$order:' ORDER BY rand()';
}
/**
+----------------------------------------------------------
* limit
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseLimit($limit) {
if(empty($limit)) $limit=1;
$limit = explode(',',$limit);
if(count($limit)>1)
$limitStr = '(T1.ROW_NUMBER BETWEEN '.$limit[0].' + 1 AND '.$limit[0].' + '.$limit[1].')';
else
$limitStr = '(T1.ROW_NUMBER BETWEEN 1 AND '.$limit[0].")";
return $limitStr;
}
/**
+----------------------------------------------------------
* 关闭数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function close() {
if ($this->_linkID){
mssql_close($this->_linkID);
}
$this->_linkID = null;
}
/**
+----------------------------------------------------------
* 数据库错误信息
* 并显示当前的SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function error() {
$this->error = mssql_get_last_message();
if($this->debug && '' != $this->queryStr){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
return $this->error;
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Db/DbMssql.class.php | PHP | asf20 | 14,114 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: DbIbase.class.php 2729 2012-02-12 04:13:34Z liu21st $
/**
+----------------------------------------
* Firebird数据库驱动类 剑雷 2007.12.28
+----------------------------------------
*/
class DbIbase extends Db{
protected $selectSql = 'SELECT %LIMIT% %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%';
/**
+----------------------------------------------------------
* 架构函数 读取数据库配置信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 数据库配置数组
+----------------------------------------------------------
*/
public function __construct($config='') {
if ( !extension_loaded('interbase') ) {
throw_exception(L('_NOT_SUPPERT_').':Interbase or Firebird');
}
if(!empty($config)) {
$this->config = $config;
if(empty($this->config['params'])) {
$this->config['params'] = array();
}
}
}
/**
+----------------------------------------------------------
* 连接数据库方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function connect($config='',$linkNum=0) {
if ( !isset($this->linkID[$linkNum]) ) {
if(empty($config)) $config = $this->config;
$pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;
$conn = $pconnect ? 'ibase_pconnect':'ibase_connect';
// 处理不带端口号的socket连接情况
$host = $config['hostname'].($config['hostport']?"/{$config['hostport']}":'');
$this->linkID[$linkNum] = $conn($host.':'.$config['database'], $config['username'], $config['password'],C('DB_CHARSET'),0,3);
if ( !$this->linkID[$linkNum]) {
throw_exception(ibase_errmsg());
}
// 标记连接成功
$this->connected = true;
// 注销数据库连接配置信息
if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
}
return $this->linkID[$linkNum];
}
/**
+----------------------------------------------------------
* 释放查询结果
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function free() {
ibase_free_result($this->queryID);
$this->queryID = null;
}
/**
+----------------------------------------------------------
* 执行查询 返回数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function query($str) {
$this->initConnect(false);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID = ibase_query($this->_linkID, $str);
$this->debug();
if ( false === $this->queryID ) {
$this->error();
return false;
} else {
return $this->getAll();
}
}
/**
+----------------------------------------------------------
* 执行语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function execute($str) {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_write',1);
// 记录开始执行时间
G('queryStartTime');
$result = ibase_query($this->_linkID, $str) ;
$this->debug();
if ( false === $result) {
$this->error();
return false;
} else {
$this->numRows = ibase_affected_rows($this->_linkID);
$this->lastInsID =0;
return $this->numRows;
}
}
public function startTrans() {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
//数据rollback 支持
if ($this->transTimes == 0) {
ibase_trans( IBASE_DEFAULT, $this->_linkID);
}
$this->transTimes++;
return ;
}
/**
+----------------------------------------------------------
* 用于非自动提交状态下面的查询提交
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function commit() {
if ($this->transTimes > 0) {
$result = ibase_commit($this->_linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
}
}
return true;
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function rollback() {
if ($this->transTimes > 0) {
$result =ibase_rollback($this->_linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
}
}
return true;
}
/**
+----------------------------------------------------------
* BLOB字段解密函数 Firebird特有
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param $blob 待解密的BLOB
+----------------------------------------------------------
* @return 二进制数据
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function BlobDecode($blob) {
$maxblobsize = 262144;
$blob_data = ibase_blob_info($this->_linkID, $blob );
$blobid = ibase_blob_open($this->_linkID, $blob );
if( $blob_data[0] > $maxblobsize ) {
$realblob = ibase_blob_get($blobid, $maxblobsize);
while($string = ibase_blob_get($blobid, 8192)){
$realblob .= $string;
}
} else {
$realblob = ibase_blob_get($blobid, $blob_data[0]);
}
ibase_blob_close( $blobid );
return( $realblob );
}
/**
+----------------------------------------------------------
* 获得所有的查询数据
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
private function getAll() {
//返回数据集
$result = array();
while ( $row = ibase_fetch_assoc($this->queryID)) {
$result[] = $row;
}
//剑雷 2007.12.30 自动解密BLOB字段
//取BLOB字段清单
$bloblist = array();
$fieldCount = ibase_num_fields($this->queryID);
for ($i = 0; $i < $fieldCount; $i++) {
$col_info = ibase_field_info($this->queryID, $i);
if ($col_info['type']=='BLOB') {
$bloblist[]=trim($col_info['name']);
}
}
//如果有BLOB字段,就进行解密处理
if (!empty($bloblist)) {
$i=0;
foreach ($result as $row) {
foreach($bloblist as $field) {
if (!empty($row[$field])) $result[$i][$field]=$this->BlobDecode($row[$field]);
}
$i++;
}
}
return $result;
}
/**
+----------------------------------------------------------
* 取得数据表的字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function getFields($tableName) {
$result = $this->query('SELECT RDB$FIELD_NAME AS FIELD, RDB$DEFAULT_VALUE AS DEFAULT1, RDB$NULL_FLAG AS NULL1 FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME=UPPER(\''.$tableName.'\') ORDER By RDB$FIELD_POSITION');
$info = array();
if($result) {
foreach ($result as $key => $val) {
$info[trim($val['FIELD'])] = array(
'name' => trim($val['FIELD']),
'type' => '',
'notnull' => (bool) ($val['NULL1'] ==1), // 1表示不为Null
'default' => $val['DEFAULT1'],
'primary' => false,
'autoinc' => false,
);
}
}
//剑雷 取表字段类型
$sql='select first 1 * from '. $tableName;
$rs_temp = ibase_query ($this->_linkID, $sql);
$fieldCount = ibase_num_fields($rs_temp);
for ($i = 0; $i < $fieldCount; $i++)
{
$col_info = ibase_field_info($rs_temp, $i);
$info[trim($col_info['name'])]['type']=$col_info['type'];
}
ibase_free_result ($rs_temp);
//剑雷 取表的主键
$sql='select b.rdb$field_name as FIELD_NAME from rdb$relation_constraints a join rdb$index_segments b
on a.rdb$index_name=b.rdb$index_name
where a.rdb$constraint_type=\'PRIMARY KEY\' and a.rdb$relation_name=UPPER(\''.$tableName.'\')';
$rs_temp = ibase_query ($this->_linkID, $sql);
while ($row=ibase_fetch_object($rs_temp)) {
$info[trim($row->FIELD_NAME)]['primary']=True;
}
ibase_free_result ($rs_temp);
return $info;
}
/**
+----------------------------------------------------------
* 取得数据库的表信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function getTables($dbName='') {
$sql='SELECT DISTINCT RDB$RELATION_NAME FROM RDB$RELATION_FIELDS WHERE RDB$SYSTEM_FLAG=0';
$result = $this->query($sql);
$info = array();
foreach ($result as $key => $val) {
$info[$key] = trim(current($val));
}
return $info;
}
/**
+----------------------------------------------------------
* 关闭数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function close() {
if ($this->_linkID){
ibase_close($this->_linkID);
}
$this->_linkID = null;
}
/**
+----------------------------------------------------------
* 数据库错误信息
* 并显示当前的SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function error() {
$this->error = ibase_errmsg();
if($this->debug && '' != $this->queryStr){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
return $this->error;
}
/**
+----------------------------------------------------------
* limit
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseLimit($limit) {
$limitStr = '';
if(!empty($limit)) {
$limit = explode(',',$limit);
if(count($limit)>1) {
$limitStr = ' FIRST '.($limit[1]-$limit[0]).' SKIP '.$limit[0].' ';
}else{
$limitStr = ' FIRST '.$limit[0].' ';
}
}
return $limitStr;
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Db/DbIbase.class.php | PHP | asf20 | 14,977 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: DbPdo.class.php 2729 2012-02-12 04:13:34Z liu21st $
/**
+-----------------------------
* PDO数据库驱动类
+-----------------------------
*/
class DbPdo extends Db{
protected $PDOStatement = null;
private $table = '';
/**
+----------------------------------------------------------
* 架构函数 读取数据库配置信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 数据库配置数组
+----------------------------------------------------------
*/
public function __construct($config=''){
if ( !class_exists('PDO') ) {
throw_exception(L('_NOT_SUPPERT_').':PDO');
}
if(!empty($config)) {
$this->config = $config;
if(empty($this->config['params'])) {
$this->config['params'] = array();
}
}
}
/**
+----------------------------------------------------------
* 连接数据库方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function connect($config='',$linkNum=0) {
if ( !isset($this->linkID[$linkNum]) ) {
if(empty($config)) $config = $this->config;
if($this->pconnect) {
$config['params'][PDO::ATTR_PERSISTENT] = true;
}
//$config['params'][PDO::ATTR_CASE] = C("DB_CASE_LOWER")?PDO::CASE_LOWER:PDO::CASE_UPPER;
try{
$this->linkID[$linkNum] = new PDO( $config['dsn'], $config['username'], $config['password'],$config['params']);
}catch (PDOException $e) {
throw_exception($e->getMessage());
}
// 因为PDO的连接切换可能导致数据库类型不同,因此重新获取下当前的数据库类型
$this->dbType = $this->_getDsnType($config['dsn']);
if(in_array($this->dbType,array('MSSQL','ORACLE','IBASE','OCI'))) {
// 由于PDO对于以上的数据库支持不够完美,所以屏蔽了 如果仍然希望使用PDO 可以注释下面一行代码
throw_exception('由于目前PDO暂时不能完美支持'.$this->dbType.' 请使用官方的'.$this->dbType.'驱动');
}
$this->linkID[$linkNum]->exec('SET NAMES '.C('DB_CHARSET'));
// 标记连接成功
$this->connected = true;
// 注销数据库连接配置信息
if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
}
return $this->linkID[$linkNum];
}
/**
+----------------------------------------------------------
* 释放查询结果
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function free() {
$this->PDOStatement = null;
}
/**
+----------------------------------------------------------
* 执行查询 返回数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function query($str) {
$this->initConnect(false);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( !empty($this->PDOStatement) ) $this->free();
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->PDOStatement = $this->_linkID->prepare($str);
if(false === $this->PDOStatement)
throw_exception($this->error());
$result = $this->PDOStatement->execute();
$this->debug();
if ( false === $result ) {
$this->error();
return false;
} else {
return $this->getAll();
}
}
/**
+----------------------------------------------------------
* 执行语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function execute($str) {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
$flag = false;
if($this->dbType == 'OCI')
{
if(preg_match("/^\s*(INSERT\s+INTO)\s+(\w+)\s+/i", $this->queryStr, $match)) {
$this->table = C("DB_SEQUENCE_PREFIX").str_ireplace(C("DB_PREFIX"), "", $match[2]);
$flag = (boolean)$this->query("SELECT * FROM user_sequences WHERE sequence_name='" . strtoupper($this->table) . "'");
}
}//modify by wyfeng at 2009.08.28
//释放前次的查询结果
if ( !empty($this->PDOStatement) ) $this->free();
N('db_write',1);
// 记录开始执行时间
G('queryStartTime');
$this->PDOStatement = $this->_linkID->prepare($str);
if(false === $this->PDOStatement) {
throw_exception($this->error());
}
$result = $this->PDOStatement->execute();
$this->debug();
if ( false === $result) {
$this->error();
return false;
} else {
$this->numRows = $result;
if($flag || preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {
$this->lastInsID = $this->getLastInsertId();
}
return $this->numRows;
}
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function startTrans() {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
//数据rollback 支持
if ($this->transTimes == 0) {
$this->_linkID->beginTransaction();
}
$this->transTimes++;
return ;
}
/**
+----------------------------------------------------------
* 用于非自动提交状态下面的查询提交
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function commit() {
if ($this->transTimes > 0) {
$result = $this->_linkID->commit();
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
}
}
return true;
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function rollback() {
if ($this->transTimes > 0) {
$result = $this->_linkID->rollback();
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
}
}
return true;
}
/**
+----------------------------------------------------------
* 获得所有的查询数据
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
private function getAll() {
//返回数据集
$result = $this->PDOStatement->fetchAll(constant('PDO::FETCH_ASSOC'));
$this->numRows = count( $result );
return $result;
}
/**
+----------------------------------------------------------
* 取得数据表的字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function getFields($tableName) {
$this->initConnect(true);
if(C('DB_DESCRIBE_TABLE_SQL')) {
// 定义特殊的字段查询SQL
$sql = str_replace('%table%',$tableName,C('DB_DESCRIBE_TABLE_SQL'));
}else{
switch($this->dbType) {
case 'MSSQL':
case 'SQLSRV':
$sql = "SELECT column_name as 'Name', data_type as 'Type', column_default as 'Default', is_nullable as 'Null'
FROM information_schema.tables AS t
JOIN information_schema.columns AS c
ON t.table_catalog = c.table_catalog
AND t.table_schema = c.table_schema
AND t.table_name = c.table_name
WHERE t.table_name = '$tableName'";
break;
case 'SQLITE':
$sql = 'PRAGMA table_info ('.$tableName.') ';
break;
case 'ORACLE':
case 'OCI':
$sql = "SELECT a.column_name \"Name\",data_type \"Type\",decode(nullable,'Y',0,1) notnull,data_default \"Default\",decode(a.column_name,b.column_name,1,0) \"pk\" "
."FROM user_tab_columns a,(SELECT column_name FROM user_constraints c,user_cons_columns col "
."WHERE c.constraint_name=col.constraint_name AND c.constraint_type='P' and c.table_name='".strtoupper($tableName)
."') b where table_name='".strtoupper($tableName)."' and a.column_name=b.column_name(+)";
break;
case 'PGSQL':
$sql = 'select fields_name as "Name",fields_type as "Type",fields_not_null as "Null",fields_key_name as "Key",fields_default as "Default",fields_default as "Extra" from table_msg('.$tableName.');';
break;
case 'IBASE':
break;
case 'MYSQL':
default:
$sql = 'DESCRIBE '.$tableName;//备注: 驱动类不只针对mysql,不能加``
}
}
$result = $this->query($sql);
$info = array();
if($result) {
foreach ($result as $key => $val) {
$val['Name'] = isset($val['name'])?$val['name']:$val['Name'];
$val['Type'] = isset($val['type'])?$val['type']: $val['Type'];
$name= strtolower(isset($val['Field'])?$val['Field']:$val['Name']);
$info[$name] = array(
'name' => $name ,
'type' => $val['Type'],
'notnull' => (bool)(((isset($val['Null'])) && ($val['Null'] === '')) || ((isset($val['notnull'])) && ($val['notnull'] === ''))), // not null is empty, null is yes
'default' => isset($val['Default'])? $val['Default'] :(isset($val['dflt_value'])?$val['dflt_value']:""),
'primary' => isset($val['Key'])?strtolower($val['Key']) == 'pri':(isset($val['pk'])?$val['pk']:false),
'autoinc' => isset($val['Extra'])?strtolower($val['Extra']) == 'auto_increment':(isset($val['Key'])?$val['Key']:false),
);
}
}
return $info;
}
/**
+----------------------------------------------------------
* 取得数据库的表信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function getTables($dbName='') {
if(C('DB_FETCH_TABLES_SQL')) {
// 定义特殊的表查询SQL
$sql = str_replace('%db%',$dnName,C('DB_FETCH_TABLES_SQL'));
}else{
switch($this->dbType) {
case 'ORACLE':
case 'OCI':
$sql = 'SELECT table_name FROM user_tables';
break;
case 'MSSQL':
case 'SQLSRV':
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
break;
case 'PGSQL':
$sql = "select tablename as Tables_in_test from pg_tables where schemaname ='public'";
break;
case 'IBASE':
// 暂时不支持
throw_exception(L('_NOT_SUPPORT_DB_').':IBASE');
break;
case 'SQLITE':
$sql = "SELECT name FROM sqlite_master WHERE type='table' "
. "UNION ALL SELECT name FROM sqlite_temp_master "
. "WHERE type='table' ORDER BY name";
break;
case 'MYSQL':
default:
if(!empty($dbName)) {
$sql = 'SHOW TABLES FROM '.$dbName;
}else{
$sql = 'SHOW TABLES ';
}
}
}
$result = $this->query($sql);
$info = array();
foreach ($result as $key => $val) {
$info[$key] = current($val);
}
return $info;
}
/**
+----------------------------------------------------------
* limit分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $lmit
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseLimit($limit) {
$limitStr = '';
if(!empty($limit)) {
switch($this->dbType){
case 'PGSQL':
case 'SQLITE':
$limit = explode(',',$limit);
if(count($limit)>1) {
$limitStr .= ' LIMIT '.$limit[1].' OFFSET '.$limit[0].' ';
}else{
$limitStr .= ' LIMIT '.$limit[0].' ';
}
break;
case 'MSSQL':
case 'SQLSRV':
break;
case 'IBASE':
// 暂时不支持
break;
case 'ORACLE':
case 'OCI':
break;
case 'MYSQL':
default:
$limitStr .= ' LIMIT '.$limit.' ';
}
}
return $limitStr;
}
/**
+----------------------------------------------------------
* 关闭数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function close() {
$this->_linkID = null;
}
/**
+----------------------------------------------------------
* 数据库错误信息
* 并显示当前的SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function error() {
if($this->PDOStatement) {
$error = $this->PDOStatement->errorInfo();
$this->error = $error[2];
}else{
$this->error = '';
}
if($this->debug && '' != $this->queryStr){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
return $this->error;
}
/**
+----------------------------------------------------------
* SQL指令安全过滤
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str SQL指令
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function escapeString($str) {
switch($this->dbType) {
case 'PGSQL':
case 'MSSQL':
case 'SQLSRV':
case 'IBASE':
case 'MYSQL':
return addslashes($str);
case 'SQLITE':
case 'ORACLE':
case 'OCI':
return str_ireplace("'", "''", $str);
}
}
/**
+----------------------------------------------------------
* 获取最后插入id
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
public function getLastInsertId() {
switch($this->dbType) {
case 'PGSQL':
case 'SQLITE':
case 'MSSQL':
case 'SQLSRV':
case 'IBASE':
case 'MYSQL':
return $this->_linkID->lastInsertId();
case 'ORACLE':
case 'OCI':
$sequenceName = $this->table;
$vo = $this->query("SELECT {$sequenceName}.currval currval FROM dual");
return $vo?$vo[0]["currval"]:0;
}
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Db/DbPdo.class.php | PHP | asf20 | 19,877 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: DbSqlsrv.class.php 2785 2012-02-27 01:55:37Z liu21st $
/**
+-------------------------------
* Sqlsrv数据库驱动类
+-------------------------------
*/
class DbSqlsrv extends Db{
protected $selectSql = 'SELECT T1.* FROM (SELECT ROW_NUMBER() OVER (%ORDER%) AS ROW_NUMBER, thinkphp.* FROM (SELECT %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%) AS thinkphp) AS T1 WHERE %LIMIT%';
/**
+----------------------------------------------------------
* 架构函数 读取数据库配置信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 数据库配置数组
+----------------------------------------------------------
*/
public function __construct($config='') {
if ( !function_exists('sqlsrv_connect') ) {
throw_exception(L('_NOT_SUPPERT_').':sqlsrv');
}
if(!empty($config)) {
$this->config = $config;
}
}
/**
+----------------------------------------------------------
* 连接数据库方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function connect($config='',$linkNum=0) {
if ( !isset($this->linkID[$linkNum]) ) {
if(empty($config)) $config = $this->config;
$host = $config['hostname'].($config['hostport']?",{$config['hostport']}":'');
$connectInfo = array('Database'=>$config['database'],'UID'=>$config['username'],'PWD'=>$config['password']);
$this->linkID[$linkNum] = sqlsrv_connect( $host, $connectInfo);
if ( !$this->linkID[$linkNum] ) throw_exception($this->error());
// 标记连接成功
$this->connected = true;
//注销数据库安全信息
if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
}
return $this->linkID[$linkNum];
}
/**
+----------------------------------------------------------
* 释放查询结果
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function free() {
sqlsrv_free_stmt($this->queryID);
$this->queryID = null;
}
/**
+----------------------------------------------------------
* 执行查询 返回数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function query($str) {
$this->initConnect(false);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID = sqlsrv_query($this->_linkID,$str,array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
$this->debug();
if ( false === $this->queryID ) {
$this->error();
return false;
} else {
$this->numRows = sqlsrv_num_rows($this->queryID);
return $this->getAll();
}
}
/**
+----------------------------------------------------------
* 执行语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function execute($str) {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_write',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID= sqlsrv_query($this->_linkID,$str,array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
$this->debug();
if ( false === $this->queryID ) {
$this->error();
return false;
} else {
$this->numRows = sqlsrv_rows_affected($this->queryID);
$this->lastInsID = $this->mssql_insert_id();
return $this->numRows;
}
}
/**
+----------------------------------------------------------
* 用于获取最后插入的ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
public function mssql_insert_id() {
$query = "SELECT @@IDENTITY as last_insert_id";
$result = sqlsrv_query($this->_linkID,$query);
list($last_insert_id) = sqlsrv_fetch_array($result);
sqlsrv_free_stmt($result);
return $last_insert_id;
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function startTrans() {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
//数据rollback 支持
if ($this->transTimes == 0) {
sqlsrv_begin_transaction($this->_linkID);
}
$this->transTimes++;
return ;
}
/**
+----------------------------------------------------------
* 用于非自动提交状态下面的查询提交
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function commit() {
if ($this->transTimes > 0) {
$result = sqlsrv_commit($this->_linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
}
}
return true;
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function rollback() {
if ($this->transTimes > 0) {
$result = sqlsrv_rollback($this->_linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
}
}
return true;
}
/**
+----------------------------------------------------------
* 获得所有的查询数据
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
private function getAll() {
//返回数据集
$result = array();
if($this->numRows >0) {
while($row = sqlsrv_fetch_array($this->queryID,SQLSRV_FETCH_ASSOC))
$result[] = $row;
}
return $result;
}
/**
+----------------------------------------------------------
* 取得数据表的字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getFields($tableName) {
$result = $this->query("SELECT column_name, data_type, column_default, is_nullable
FROM information_schema.tables AS t
JOIN information_schema.columns AS c
ON t.table_catalog = c.table_catalog
AND t.table_schema = c.table_schema
AND t.table_name = c.table_name
WHERE t.table_name = '$tableName'");
$info = array();
if($result) {
foreach ($result as $key => $val) {
$info[$val['column_name']] = array(
'name' => $val['column_name'],
'type' => $val['data_type'],
'notnull' => (bool) ($val['is_nullable'] === ''), // not null is empty, null is yes
'default' => $val['column_default'],
'primary' => false,
'autoinc' => false,
);
}
}
return $info;
}
/**
+----------------------------------------------------------
* 取得数据表的字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getTables($dbName='') {
$result = $this->query("SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
");
$info = array();
foreach ($result as $key => $val) {
$info[$key] = current($val);
}
return $info;
}
/**
+----------------------------------------------------------
* order分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $order
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseOrder($order) {
return !empty($order)? ' ORDER BY '.$order:' ORDER BY rand()';
}
/**
+----------------------------------------------------------
* limit
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseLimit($limit) {
if(empty($limit)) $limit=1;
$limit = explode(',',$limit);
if(count($limit)>1)
$limitStr = '(T1.ROW_NUMBER BETWEEN '.$limit[0].' + 1 AND '.$limit[0].' + '.$limit[1].')';
else
$limitStr = '(T1.ROW_NUMBER BETWEEN 1 AND '.$limit[0].")";
return $limitStr;
}
/**
+----------------------------------------------------------
* 关闭数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function close() {
if ($this->_linkID){
sqlsrv_close($this->_linkID);
}
$this->_linkID = null;
}
/**
+----------------------------------------------------------
* 数据库错误信息
* 并显示当前的SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function error() {
$this->error = sqlsrv_errors();
if($this->debug && '' != $this->queryStr){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
return $this->error;
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Db/DbSqlsrv.class.php | PHP | asf20 | 13,652 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: DbSqlite.class.php 2729 2012-02-12 04:13:34Z liu21st $
/**
+-------------------------------
* Sqlite数据库驱动类
+-------------------------------
*/
class DbSqlite extends Db {
/**
+----------------------------------------------------------
* 架构函数 读取数据库配置信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 数据库配置数组
+----------------------------------------------------------
*/
public function __construct($config='') {
if ( !extension_loaded('sqlite') ) {
throw_exception(L('_NOT_SUPPERT_').':sqlite');
}
if(!empty($config)) {
if(!isset($config['mode'])) {
$config['mode'] = 0666;
}
$this->config = $config;
if(empty($this->config['params'])) {
$this->config['params'] = array();
}
}
}
/**
+----------------------------------------------------------
* 连接数据库方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function connect($config='',$linkNum=0) {
if ( !isset($this->linkID[$linkNum]) ) {
if(empty($config)) $config = $this->config;
$pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;
$conn = $pconnect ? 'sqlite_popen':'sqlite_open';
$this->linkID[$linkNum] = $conn($config['database'],$config['mode']);
if ( !$this->linkID[$linkNum]) {
throw_exception(sqlite_error_string());
}
// 标记连接成功
$this->connected = true;
//注销数据库安全信息
if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
}
return $this->linkID[$linkNum];
}
/**
+----------------------------------------------------------
* 释放查询结果
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function free() {
$this->queryID = null;
}
/**
+----------------------------------------------------------
* 执行查询 返回数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function query($str) {
$this->initConnect(false);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID = sqlite_query($this->_linkID,$str);
$this->debug();
if ( false === $this->queryID ) {
$this->error();
return false;
} else {
$this->numRows = sqlite_num_rows($this->queryID);
return $this->getAll();
}
}
/**
+----------------------------------------------------------
* 执行语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function execute($str) {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_write',1);
// 记录开始执行时间
G('queryStartTime');
$result = sqlite_exec($this->_linkID,$str);
$this->debug();
if ( false === $result ) {
$this->error();
return false;
} else {
$this->numRows = sqlite_changes($this->_linkID);
$this->lastInsID = sqlite_last_insert_rowid($this->_linkID);
return $this->numRows;
}
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function startTrans() {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
//数据rollback 支持
if ($this->transTimes == 0) {
sqlite_query($this->_linkID,'BEGIN TRANSACTION');
}
$this->transTimes++;
return ;
}
/**
+----------------------------------------------------------
* 用于非自动提交状态下面的查询提交
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function commit() {
if ($this->transTimes > 0) {
$result = sqlite_query($this->_linkID,'COMMIT TRANSACTION');
if(!$result){
throw_exception($this->error());
}
$this->transTimes = 0;
}
return true;
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function rollback() {
if ($this->transTimes > 0) {
$result = sqlite_query($this->_linkID,'ROLLBACK TRANSACTION');
if(!$result){
throw_exception($this->error());
}
$this->transTimes = 0;
}
return true;
}
/**
+----------------------------------------------------------
* 获得所有的查询数据
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
private function getAll() {
//返回数据集
$result = array();
if($this->numRows >0) {
for($i=0;$i<$this->numRows ;$i++ ){
// 返回数组集
$result[$i] = sqlite_fetch_array($this->queryID,SQLITE_ASSOC);
}
sqlite_seek($this->queryID,0);
}
return $result;
}
/**
+----------------------------------------------------------
* 取得数据表的字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getFields($tableName) {
$result = $this->query('PRAGMA table_info( '.$tableName.' )');
$info = array();
if($result){
foreach ($result as $key => $val) {
$info[$val['Field']] = array(
'name' => $val['Field'],
'type' => $val['Type'],
'notnull' => (bool) ($val['Null'] === ''), // not null is empty, null is yes
'default' => $val['Default'],
'primary' => (strtolower($val['Key']) == 'pri'),
'autoinc' => (strtolower($val['Extra']) == 'auto_increment'),
);
}
}
return $info;
}
/**
+----------------------------------------------------------
* 取得数据库的表信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getTables($dbName='') {
$result = $this->query("SELECT name FROM sqlite_master WHERE type='table' "
. "UNION ALL SELECT name FROM sqlite_temp_master "
. "WHERE type='table' ORDER BY name");
$info = array();
foreach ($result as $key => $val) {
$info[$key] = current($val);
}
return $info;
}
/**
+----------------------------------------------------------
* 关闭数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function close() {
if ($this->_linkID){
sqlite_close($this->_linkID);
}
$this->_linkID = null;
}
/**
+----------------------------------------------------------
* 数据库错误信息
* 并显示当前的SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function error() {
$this->error = sqlite_error_string(sqlite_last_error($this->_linkID));
if($this->debug && '' != $this->queryStr){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
return $this->error;
}
/**
+----------------------------------------------------------
* SQL指令安全过滤
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str SQL指令
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function escapeString($str) {
return sqlite_escape_string($str);
}
/**
+----------------------------------------------------------
* limit
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseLimit($limit) {
$limitStr = '';
if(!empty($limit)) {
$limit = explode(',',$limit);
if(count($limit)>1) {
$limitStr .= ' LIMIT '.$limit[1].' OFFSET '.$limit[0].' ';
}else{
$limitStr .= ' LIMIT '.$limit[0].' ';
}
}
return $limitStr;
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Db/DbSqlite.class.php | PHP | asf20 | 13,091 |
<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: DbMongo.class.php 2745 2012-02-18 12:20:36Z liu21st $
/**
+-----------------------------------------------
* Mongo数据库驱动类 需要配合MongoModel使用
+-----------------------------------------------
*/
class DbMongo extends Db{
protected $_mongo = null; // MongoDb Object
protected $_collection = null; // MongoCollection Object
protected $_dbName = ''; // dbName
protected $_collectionName = ''; // collectionName
protected $_cursor = null; // MongoCursor Object
protected $comparison = array('neq'=>'ne','ne'=>'ne','gt'=>'gt','egt'=>'gte','gte'=>'gte','lt'=>'lt','elt'=>'lte','lte'=>'lte','in'=>'in','not in'=>'nin','nin'=>'nin');
/**
+----------------------------------------------------------
* 架构函数 读取数据库配置信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 数据库配置数组
+----------------------------------------------------------
*/
public function __construct($config=''){
if ( !class_exists('mongo') ) {
throw_exception(L('_NOT_SUPPERT_').':mongo');
}
if(!empty($config)) {
$this->config = $config;
if(empty($this->config['params'])) {
$this->config['params'] = array();
}
}
}
/**
+----------------------------------------------------------
* 连接数据库方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function connect($config='',$linkNum=0) {
if ( !isset($this->linkID[$linkNum]) ) {
if(empty($config)) $config = $this->config;
$host = 'mongodb://'.($config['username']?"{$config['username']}":'').($config['password']?":{$config['password']}@":'').$config['hostname'].($config['hostport']?":{$config['hostport']}":'').'/'.($config['database']?"{$config['database']}":'');
try{
$this->linkID[$linkNum] = new mongo( $host,$config['params']);
}catch (MongoConnectionException $e){
throw_exception($e->getmessage());
}
// 标记连接成功
$this->connected = true;
// 注销数据库连接配置信息
if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
}
return $this->linkID[$linkNum];
}
/**
+----------------------------------------------------------
* 切换当前操作的Db和Collection
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $collection collection
* @param string $db db
* @param boolean $master 是否主服务器
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function switchCollection($collection,$db='',$master=true){
// 当前没有连接 则首先进行数据库连接
if ( !$this->_linkID ) $this->initConnect($master);
try{
if(!empty($db)) { // 传人Db则切换数据库
// 当前MongoDb对象
$this->_dbName = $db;
$this->_mongo = $this->_linkID->selectDb($db);
}
// 当前MongoCollection对象
if($this->debug) {
$this->queryStr = $this->_dbName.'.getCollection('.$collection.')';
}
if($this->_collectionName != $collection) {
N('db_read',1);
// 记录开始执行时间
G('queryStartTime');
$this->_collection = $this->_mongo->selectCollection($collection);
$this->debug();
$this->_collectionName = $collection; // 记录当前Collection名称
}
}catch (MongoException $e){
throw_exception($e->getMessage());
}
}
/**
+----------------------------------------------------------
* 释放查询结果
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function free() {
$this->_cursor = null;
}
/**
+----------------------------------------------------------
* 执行命令
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $command 指令
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function command($command=array()) {
N('db_write',1);
$this->queryStr = 'command:'.json_encode($command);
// 记录开始执行时间
G('queryStartTime');
$result = $this->_mongo->command($command);
$this->debug();
if(!$result['ok']) {
throw_exception($result['errmsg']);
}
return $result;
}
/**
+----------------------------------------------------------
* 执行语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $code sql指令
* @param array $args 参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function execute($code,$args=array()) {
N('db_write',1);
$this->queryStr = 'execute:'.$code;
// 记录开始执行时间
G('queryStartTime');
$result = $this->_mongo->execute($code,$args);
$this->debug();
if($result['ok']) {
return $result['retval'];
}else{
throw_exception($result['errmsg']);
}
}
/**
+----------------------------------------------------------
* 关闭数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function close() {
if($this->_linkID) {
$this->_linkID->close();
$this->_linkID = null;
$this->_mongo = null;
$this->_collection = null;
$this->_cursor = null;
}
}
/**
+----------------------------------------------------------
* 数据库错误信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function error() {
$this->error = $this->_mongo->lastError();
return $this->error;
}
/**
+----------------------------------------------------------
* 插入记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 参数表达式
* @param boolean $replace 是否replace
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function insert($data,$options=array(),$replace=false) {
if(isset($options['table'])) {
$this->switchCollection($options['table']);
}
$this->model = $options['model'];
N('db_write',1);
if($this->debug) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.insert(';
$this->queryStr .= $data?json_encode($data):'{}';
$this->queryStr .= ')';
}
try{
// 记录开始执行时间
G('queryStartTime');
$result = $replace? $this->_collection->save($data,true): $this->_collection->insert($data,true);
$this->debug();
if($result) {
$_id = $data['_id'];
if(is_object($_id)) {
$_id = $_id->__toString();
}
$this->lastInsID = $_id;
}
return $result;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
/**
+----------------------------------------------------------
* 插入多条记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $dataList 数据
* @param array $options 参数表达式
+----------------------------------------------------------
* @return bool
+----------------------------------------------------------
*/
public function insertAll($dataList,$options=array()) {
if(isset($options['table'])) {
$this->switchCollection($options['table']);
}
$this->model = $options['model'];
N('db_write',1);
try{
// 记录开始执行时间
G('queryStartTime');
$result = $this->_collection->batchInsert($dataList);
$this->debug();
return $result;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
/**
+----------------------------------------------------------
* 生成下一条记录ID 用于自增非MongoId主键
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $pk 主键名
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
public function mongo_next_id($pk) {
N('db_read',1);
if($this->debug) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.find({},{'.$pk.':1}).sort({'.$pk.':-1}).limit(1)';
}
try{
// 记录开始执行时间
G('queryStartTime');
$result = $this->_collection->find(array(),array($pk=>1))->sort(array($pk=>-1))->limit(1);
$this->debug();
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
$data = $result->getNext();
return isset($data[$pk])?$data[$pk]+1:1;
}
/**
+----------------------------------------------------------
* 更新记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return bool
+----------------------------------------------------------
*/
public function update($data,$options) {
if(isset($options['table'])) {
$this->switchCollection($options['table']);
}
$this->model = $options['model'];
N('db_write',1);
$query = $this->parseWhere($options['where']);
$set = $this->parseSet($data);
if($this->debug) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.update(';
$this->queryStr .= $query?json_encode($query):'{}';
$this->queryStr .= ','.json_encode($set).')';
}
try{
// 记录开始执行时间
G('queryStartTime');
$result = $this->_collection->update($query,$set,array("multiple" => true));
$this->debug();
return $result;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
/**
+----------------------------------------------------------
* 删除记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function delete($options=array()) {
if(isset($options['table'])) {
$this->switchCollection($options['table']);
}
$query = $this->parseWhere($options['where']);
$this->model = $options['model'];
N('db_write',1);
if($this->debug) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.remove('.json_encode($query).')';
}
try{
// 记录开始执行时间
G('queryStartTime');
$result = $this->_collection->remove($query);
$this->debug();
return $result;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
/**
+----------------------------------------------------------
* 清空记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function clear($options=array()){
if(isset($options['table'])) {
$this->switchCollection($options['table']);
}
$this->model = $options['model'];
N('db_write',1);
if($this->debug) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.remove({})';
}
try{
// 记录开始执行时间
G('queryStartTime');
$result = $this->_collection->drop();
$this->debug();
return $result;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
/**
+----------------------------------------------------------
* 查找记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return iterator
+----------------------------------------------------------
*/
public function select($options=array()) {
if(isset($options['table'])) {
$this->switchCollection($options['table'],'',false);
}
$cache = isset($options['cache'])?$options['cache']:false;
if($cache) { // 查询缓存检测
$key = is_string($cache['key'])?$cache['key']:md5(serialize($options));
$value = S($key,'','',$cache['type']);
if(false !== $value) {
return $value;
}
}
$this->model = $options['model'];
N('db_query',1);
$query = $this->parseWhere($options['where']);
$field = $this->parseField($options['field']);
try{
if($this->debug) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.find(';
$this->queryStr .= $query? json_encode($query):'{}';
$this->queryStr .= $field? ','.json_encode($field):'';
$this->queryStr .= ')';
}
// 记录开始执行时间
G('queryStartTime');
$_cursor = $this->_collection->find($query,$field);
if($options['order']) {
$order = $this->parseOrder($options['order']);
if($this->debug) {
$this->queryStr .= '.sort('.json_encode($order).')';
}
$_cursor = $_cursor->sort($order);
}
if(isset($options['page'])) { // 根据页数计算limit
if(strpos($options['page'],',')) {
list($page,$length) = explode(',',$options['page']);
}else{
$page = $options['page'];
}
$page = $page?$page:1;
$length = isset($length)?$length:(is_numeric($options['limit'])?$options['limit']:20);
$offset = $length*((int)$page-1);
$options['limit'] = $offset.','.$length;
}
if(isset($options['limit'])) {
list($offset,$length) = $this->parseLimit($options['limit']);
if(!empty($offset)) {
if($this->debug) {
$this->queryStr .= '.skip('.intval($offset).')';
}
$_cursor = $_cursor->skip(intval($offset));
}
if($this->debug) {
$this->queryStr .= '.limit('.intval($length).')';
}
$_cursor = $_cursor->limit(intval($length));
}
$this->debug();
$this->_cursor = $_cursor;
$resultSet = iterator_to_array($_cursor);
if($cache && $resultSet ) { // 查询缓存写入
S($key,$resultSet,$cache['expire'],$cache['type']);
}
return $resultSet;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
/**
+----------------------------------------------------------
* 查找某个记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function find($options=array()){
if(isset($options['table'])) {
$this->switchCollection($options['table'],'',false);
}
$cache = isset($options['cache'])?$options['cache']:false;
if($cache) { // 查询缓存检测
$key = is_string($cache['key'])?$cache['key']:md5(serialize($options));
$value = S($key,'','',$cache['type']);
if(false !== $value) {
return $value;
}
}
$this->model = $options['model'];
N('db_query',1);
$query = $this->parseWhere($options['where']);
$fields = $this->parseField($options['field']);
if($this->debug) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.fineOne(';
$this->queryStr .= $query?json_encode($query):'{}';
$this->queryStr .= $fields?','.json_encode($fields):'';
$this->queryStr .= ')';
}
try{
// 记录开始执行时间
G('queryStartTime');
$result = $this->_collection->findOne($query,$fields);
$this->debug();
if($cache && $result ) { // 查询缓存写入
S($key,$result,$cache['expire'],$cache['type']);
}
return $result;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
/**
+----------------------------------------------------------
* 统计记录数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return iterator
+----------------------------------------------------------
*/
public function count($options=array()){
if(isset($options['table'])) {
$this->switchCollection($options['table'],'',false);
}
$this->model = $options['model'];
N('db_query',1);
$query = $this->parseWhere($options['where']);
if($this->debug) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName;
$this->queryStr .= $query?'.find('.json_encode($query).')':'';
$this->queryStr .= '.count()';
}
try{
// 记录开始执行时间
G('queryStartTime');
$count = $this->_collection->count($query);
$this->debug();
return $count;
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
}
public function group($keys,$initial,$reduce,$options=array()){
$this->_collection->group($keys,$initial,$reduce,$options);
}
/**
+----------------------------------------------------------
* 取得数据表的字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getFields($collection=''){
if(!empty($collection) && $collection != $this->_collectionName) {
$this->switchCollection($collection,'',false);
}
N('db_query',1);
if($this->debug) {
$this->queryStr = $this->_dbName.'.'.$this->_collectionName.'.findOne()';
}
try{
// 记录开始执行时间
G('queryStartTime');
$result = $this->_collection->findOne();
$this->debug();
} catch (MongoCursorException $e) {
throw_exception($e->getMessage());
}
if($result) { // 存在数据则分析字段
$info = array();
foreach ($result as $key=>$val){
$info[$key] = array(
'name'=>$key,
'type'=>getType($val),
);
}
return $info;
}
// 暂时没有数据 返回false
return false;
}
/**
+----------------------------------------------------------
* 取得当前数据库的collection信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function getTables(){
if($this->debug) {
$this->queryStr = $this->_dbName.'.getCollenctionNames()';
}
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$list = $this->_mongo->listCollections();
$this->debug();
$info = array();
foreach ($list as $collection){
$info[] = $collection->getName();
}
return $info;
}
/**
+----------------------------------------------------------
* set分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseSet($data) {
$result = array();
foreach ($data as $key=>$val){
if(is_array($val)) {
switch($val[0]) {
case 'inc':
$result['$inc'][$key] = (int)$val[1];
break;
case 'set':
case 'unset':
case 'push':
case 'pushall':
case 'addtoset':
case 'pop':
case 'pull':
case 'pullall':
$result['$'.$val[0]][$key] = $val[1];
break;
default:
$result['$set'][$key] = $val;
}
}else{
$result['$set'][$key] = $val;
}
}
return $result;
}
/**
+----------------------------------------------------------
* order分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $order
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function parseOrder($order) {
if(is_string($order)) {
$array = explode(',',$order);
$order = array();
foreach ($array as $key=>$val){
$arr = explode(' ',trim($val));
if(isset($arr[1])) {
$arr[1] = $arr[1]=='asc'?1:-1;
}else{
$arr[1] = 1;
}
$order[$arr[0]] = $arr[1];
}
}
return $order;
}
/**
+----------------------------------------------------------
* limit分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $limit
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function parseLimit($limit) {
if(strpos($limit,',')) {
$array = explode(',',$limit);
}else{
$array = array(0,$limit);
}
return $array;
}
/**
+----------------------------------------------------------
* field分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $fields
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function parseField($fields){
if(empty($fields)) {
$fields = array();
}
if(is_string($fields)) {
$fields = explode(',',$fields);
}
return $fields;
}
/**
+----------------------------------------------------------
* where分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $where
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function parseWhere($where){
$query = array();
foreach ($where as $key=>$val){
if('_id' != $key && 0===strpos($key,'_')) {
// 解析特殊条件表达式
$query = $this->parseThinkWhere($key,$val);
}else{
// 查询字段的安全过滤
if(!preg_match('/^[A-Z_\|\&\-.a-z0-9]+$/',trim($key))){
throw_exception(L('_ERROR_QUERY_').':'.$key);
}
$key = trim($key);
if(strpos($key,'|')) {
$array = explode('|',$key);
$str = array();
foreach ($array as $k){
$str[] = $this->parseWhereItem($k,$val);
}
$query['$or'] = $str;
}elseif(strpos($key,'&')){
$array = explode('&',$key);
$str = array();
foreach ($array as $k){
$str[] = $this->parseWhereItem($k,$val);
}
$query = array_merge($query,$str);
}else{
$str = $this->parseWhereItem($key,$val);
$query = array_merge($query,$str);
}
}
}
return $query;
}
/**
+----------------------------------------------------------
* 特殊条件分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $key
* @param mixed $val
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseThinkWhere($key,$val) {
$query = array();
switch($key) {
case '_query': // 字符串模式查询条件
parse_str($val,$query);
if(isset($query['_logic']) && strtolower($query['_logic']) == 'or' ) {
unset($query['_logic']);
$query['$or'] = $query;
}
break;
case '_string':// MongoCode查询
$query['$where'] = new MongoCode($val);
break;
}
return $query;
}
/**
+----------------------------------------------------------
* where子单元分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $key
* @param mixed $val
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function parseWhereItem($key,$val) {
$query = array();
if(is_array($val)) {
if(is_string($val[0])) {
$con = strtolower($val[0]);
if(in_array($con,array('neq','ne','gt','egt','gte','lt','lte','elt'))) { // 比较运算
$k = '$'.$this->comparison[$con];
$query[$key] = array($k=>$val[1]);
}elseif('like'== $con){ // 模糊查询 采用正则方式
$query[$key] = new MongoRegex("/".$val[1]."/");
}elseif('mod'==$con){ // mod 查询
$query[$key] = array('$mod'=>$val[1]);
}elseif('regex'==$con){ // 正则查询
$query[$key] = new MongoRegex($val[1]);
}elseif(in_array($con,array('in','nin','not in'))){ // IN NIN 运算
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
$k = '$'.$this->comparison[$con];
$query[$key] = array($k=>$data);
}elseif('all'==$con){ // 满足所有指定条件
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
$query[$key] = array('$all'=>$data);
}elseif('between'==$con){ // BETWEEN运算
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
$query[$key] = array('$gte'=>$data[0],'$lte'=>$data[1]);
}elseif('not between'==$con){
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
$query[$key] = array('$lt'=>$data[0],'$gt'=>$data[1]);
}elseif('exp'==$con){ // 表达式查询
$query['$where'] = new MongoCode($val[1]);
}elseif('exists'==$con){ // 字段是否存在
$query[$key] =array('$exists'=>(bool)$val[1]);
}elseif('size'==$con){ // 限制属性大小
$query[$key] =array('$size'=>intval($val[1]));
}elseif('type'==$con){ // 限制字段类型 1 浮点型 2 字符型 3 对象或者MongoDBRef 5 MongoBinData 7 MongoId 8 布尔型 9 MongoDate 10 NULL 15 MongoCode 16 32位整型 17 MongoTimestamp 18 MongoInt64 如果是数组的话判断元素的类型
$query[$key] =array('$type'=>intval($val[1]));
}else{
$query[$key] = $val;
}
return $query;
}
}
$query[$key] = $val;
return $query;
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Db/DbMongo.class.php | PHP | asf20 | 34,784 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: DbPgsql.class.php 2741 2012-02-17 09:00:07Z liu21st $
/**
+---------------------------
* Pgsql数据库驱动类
+---------------------------
*/
class DbPgsql extends Db{
/**
+----------------------------------------------------------
* 架构函数 读取数据库配置信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 数据库配置数组
+----------------------------------------------------------
*/
public function __construct($config='') {
if ( !extension_loaded('pgsql') ) {
throw_exception(L('_NOT_SUPPERT_').':pgsql');
}
if(!empty($config)) {
$this->config = $config;
if(empty($this->config['params'])) {
$this->config['params'] = array();
}
}
}
/**
+----------------------------------------------------------
* 连接数据库方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function connect($config='',$linkNum=0) {
if ( !isset($this->linkID[$linkNum]) ) {
if(empty($config)) $config = $this->config;
$pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;
$conn = $pconnect ? 'pg_pconnect':'pg_connect';
$this->linkID[$linkNum] = $conn('host='.$config['hostname'].' port='.$config['hostport'].' dbname='.$config['database'].' user='.$config['username'].' password='.$config['password']);
if (0 !== pg_connection_status($this->linkID[$linkNum])){
throw_exception($this->error(false));
}
//设置编码
pg_set_client_encoding($this->linkID[$linkNum], C('DB_CHARSET'));
//$pgInfo = pg_version($this->linkID[$linkNum]);
//$dbVersion = $pgInfo['server'];
// 标记连接成功
$this->connected = true;
//注销数据库安全信息
if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
}
return $this->linkID[$linkNum];
}
/**
+----------------------------------------------------------
* 释放查询结果
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function free() {
pg_free_result($this->queryID);
$this->queryID = null;
}
/**
+----------------------------------------------------------
* 执行查询 返回数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function query($str) {
$this->initConnect(false);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID = pg_query($this->_linkID,$str);
$this->debug();
if ( false === $this->queryID ) {
$this->error();
return false;
} else {
$this->numRows = pg_num_rows($this->queryID);
return $this->getAll();
}
}
/**
+----------------------------------------------------------
* 执行语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function execute($str) {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_write',1);
// 记录开始执行时间
G('queryStartTime');
$result = pg_query($this->_linkID,$str);
$this->debug();
if ( false === $result ) {
$this->error();
return false;
} else {
$this->numRows = pg_affected_rows($result);
$this->lastInsID = $this->last_insert_id();
return $this->numRows;
}
}
/**
+----------------------------------------------------------
* 用于获取最后插入的ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
public function last_insert_id() {
$query = "SELECT LASTVAL() AS insert_id";
$result = pg_query($this->_linkID,$query);
list($last_insert_id) = pg_fetch_array($result,null,PGSQL_ASSOC);
pg_free_result($result);
return $last_insert_id;
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function startTrans() {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
//数据rollback 支持
if ($this->transTimes == 0) {
pg_exec($this->_linkID,'begin;');
}
$this->transTimes++;
return ;
}
/**
+----------------------------------------------------------
* 用于非自动提交状态下面的查询提交
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function commit() {
if ($this->transTimes > 0) {
$result = pg_exec($this->_linkID,'end;');
if(!$result){
throw_exception($this->error());
}
$this->transTimes = 0;
}
return true;
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function rollback() {
if ($this->transTimes > 0) {
$result = pg_exec($this->_linkID,'abort;');
if(!$result){
throw_exception($this->error());
}
$this->transTimes = 0;
}
return true;
}
/**
+----------------------------------------------------------
* 获得所有的查询数据
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
private function getAll() {
//返回数据集
$result = pg_fetch_all($this->queryID);
pg_result_seek($this->queryID,0);
return $result;
}
/**
+----------------------------------------------------------
* 取得数据表的字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function getFields($tableName) {
$result = $this->query("select a.attname as \"Field\",
t.typname as \"Type\",
a.attnotnull as \"Null\",
i.indisprimary as \"Key\",
d.adsrc as \"Default\"
from pg_class c
inner join pg_attribute a on a.attrelid = c.oid
inner join pg_type t on a.atttypid = t.oid
left join pg_attrdef d on a.attrelid=d.adrelid and d.adnum=a.attnum
left join pg_index i on a.attnum=ANY(i.indkey) and c.oid = i.indrelid
where (c.relname='{$tableName}' or c.relname = lower('{$tableName}')) AND a.attnum > 0
order by a.attnum asc;");
$info = array();
if($result) {
foreach ($result as $key => $val) {
$info[$val['Field']] = array(
'name' => $val['Field'],
'type' => $val['Type'],
'notnull' => (bool) ($val['Null'] == 't'?1:0), // 't' is 'not null'
'default' => $val['Default'],
'primary' => (strtolower($val['Key']) == 't'),
'autoinc' => (strtolower($val['Default']) == "nextval('{$tableName}_id_seq'::regclass)"),
);
}
}
return $info;
}
/**
+----------------------------------------------------------
* 取得数据库的表信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function getTables($dbName='') {
$result = $this->query("select tablename as Tables_in_test from pg_tables where schemaname ='public'");
$info = array();
foreach ($result as $key => $val) {
$info[$key] = current($val);
}
return $info;
}
/**
+----------------------------------------------------------
* 关闭数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function close() {
if($this->_linkID){
pg_close($this->_linkID);
}
$this->_linkID = null;
}
/**
+----------------------------------------------------------
* 数据库错误信息
* 并显示当前的SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function error($result = true) {
$this->error = $result?pg_result_error($this->queryID): pg_last_error($this->_linkID);
if($this->debug && '' != $this->queryStr){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
return $this->error;
}
/**
+----------------------------------------------------------
* SQL指令安全过滤
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str SQL指令
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function escapeString($str) {
return pg_escape_string($str);
}
/**
+----------------------------------------------------------
* limit
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseLimit($limit) {
$limitStr = '';
if(!empty($limit)) {
$limit = explode(',',$limit);
if(count($limit)>1) {
$limitStr .= ' LIMIT '.$limit[1].' OFFSET '.$limit[0].' ';
}else{
$limitStr .= ' LIMIT '.$limit[0].' ';
}
}
return $limitStr;
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/Db/DbPgsql.class.php | PHP | asf20 | 14,503 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* Html标签库驱动
* @category Extend
* @package Extend
* @subpackage Driver.Taglib
* @author liu21st <liu21st@gmail.com>
*/
class TagLibHtml extends TagLib{
// 标签定义
protected $tags = array(
// 标签定义: attr 属性列表 close 是否闭合(0 或者1 默认1) alias 标签别名 level 嵌套层次
'editor' => array('attr'=>'id,name,style,width,height,type','close'=>1),
'select' => array('attr'=>'name,options,values,output,multiple,id,size,first,change,selected,dblclick','close'=>0),
'grid' => array('attr'=>'id,pk,style,action,actionlist,show,datasource','close'=>0),
'list' => array('attr'=>'id,pk,style,action,actionlist,show,datasource,checkbox','close'=>0),
'imagebtn' => array('attr'=>'id,name,value,type,style,click','close'=>0),
'checkbox' => array('attr'=>'name,checkboxes,checked,separator','close'=>0),
'radio' => array('attr'=>'name,radios,checked,separator','close'=>0)
);
/**
* editor标签解析 插入可视化编辑器
* 格式: <html:editor id="editor" name="remark" type="FCKeditor" style="" >{$vo.remark}</html:editor>
* @access public
* @param string $attr 标签属性
* @return string|void
*/
public function _editor($attr,$content) {
$tag = $this->parseXmlAttr($attr,'editor');
$id = !empty($tag['id'])?$tag['id']: '_editor';
$name = $tag['name'];
$style = !empty($tag['style'])?$tag['style']:'';
$width = !empty($tag['width'])?$tag['width']: '100%';
$height = !empty($tag['height'])?$tag['height'] :'320px';
$type = $tag['type'] ;
switch(strtoupper($type)) {
case 'FCKEDITOR':
$parseStr = '<!-- 编辑器调用开始 --><script type="text/javascript" src="__ROOT__/Public/Js/FCKeditor/fckeditor.js"></script><textarea id="'.$id.'" name="'.$name.'">'.$content.'</textarea><script type="text/javascript"> var oFCKeditor = new FCKeditor( "'.$id.'","'.$width.'","'.$height.'" ) ; oFCKeditor.BasePath = "__ROOT__/Public/Js/FCKeditor/" ; oFCKeditor.ReplaceTextarea() ;function resetEditor(){setContents("'.$id.'",document.getElementById("'.$id.'").value)}; function saveEditor(){document.getElementById("'.$id.'").value = getContents("'.$id.'");} function InsertHTML(html){ var oEditor = FCKeditorAPI.GetInstance("'.$id.'") ;if (oEditor.EditMode == FCK_EDITMODE_WYSIWYG ){oEditor.InsertHtml(html) ;}else alert( "FCK必须处于WYSIWYG模式!" ) ;}</script> <!-- 编辑器调用结束 -->';
break;
case 'FCKMINI':
$parseStr = '<!-- 编辑器调用开始 --><script type="text/javascript" src="__ROOT__/Public/Js/FCKMini/fckeditor.js"></script><textarea id="'.$id.'" name="'.$name.'">'.$content.'</textarea><script type="text/javascript"> var oFCKeditor = new FCKeditor( "'.$id.'","'.$width.'","'.$height.'" ) ; oFCKeditor.BasePath = "__ROOT__/Public/Js/FCKMini/" ; oFCKeditor.ReplaceTextarea() ;function resetEditor(){setContents("'.$id.'",document.getElementById("'.$id.'").value)}; function saveEditor(){document.getElementById("'.$id.'").value = getContents("'.$id.'");} function InsertHTML(html){ var oEditor = FCKeditorAPI.GetInstance("'.$id.'") ;if (oEditor.EditMode == FCK_EDITMODE_WYSIWYG ){oEditor.InsertHtml(html) ;}else alert( "FCK必须处于WYSIWYG模式!" ) ;}</script> <!-- 编辑器调用结束 -->';
break;
case 'EWEBEDITOR':
$parseStr = "<!-- 编辑器调用开始 --><script type='text/javascript' src='__ROOT__/Public/Js/eWebEditor/js/edit.js'></script><input type='hidden' id='{$id}' name='{$name}' value='{$conent}'><iframe src='__ROOT__/Public/Js/eWebEditor/ewebeditor.htm?id={$name}' frameborder=0 scrolling=no width='{$width}' height='{$height}'></iframe><script type='text/javascript'>function saveEditor(){document.getElementById('{$id}').value = getHTML();} </script><!-- 编辑器调用结束 -->";
break;
case 'NETEASE':
$parseStr = '<!-- 编辑器调用开始 --><textarea id="'.$id.'" name="'.$name.'" style="display:none">'.$content.'</textarea><iframe ID="Editor" name="Editor" src="__ROOT__/Public/Js/HtmlEditor/index.html?ID='.$name.'" frameBorder="0" marginHeight="0" marginWidth="0" scrolling="No" style="height:'.$height.';width:'.$width.'"></iframe><!-- 编辑器调用结束 -->';
break;
case 'UBB':
$parseStr = '<script type="text/javascript" src="__ROOT__/Public/Js/UbbEditor.js"></script><div style="padding:1px;width:'.$width.';border:1px solid silver;float:left;"><script LANGUAGE="JavaScript"> showTool(); </script></div><div><TEXTAREA id="UBBEditor" name="'.$name.'" style="clear:both;float:none;width:'.$width.';height:'.$height.'" >'.$content.'</TEXTAREA></div><div style="padding:1px;width:'.$width.';border:1px solid silver;float:left;"><script LANGUAGE="JavaScript">showEmot(); </script></div>';
break;
case 'KINDEDITOR':
$parseStr = '<script type="text/javascript" src="__ROOT__/Public/Js/KindEditor/kindeditor.js"></script><script type="text/javascript"> KE.show({ id : \''.$id.'\' ,urlType : "absolute"});</script><textarea id="'.$id.'" style="'.$style.'" name="'.$name.'" >'.$content.'</textarea>';
break;
default :
$parseStr = '<textarea id="'.$id.'" style="'.$style.'" name="'.$name.'" >'.$content.'</textarea>';
}
return $parseStr;
}
/**
* imageBtn标签解析
* 格式: <html:imageBtn type="" value="" />
* @access public
* @param string $attr 标签属性
* @return string|void
*/
public function _imageBtn($attr) {
$tag = $this->parseXmlAttr($attr,'imageBtn');
$name = $tag['name']; //名称
$value = $tag['value']; //文字
$id = isset($tag['id'])?$tag['id']:''; //ID
$style = isset($tag['style'])?$tag['style']:''; //样式名
$click = isset($tag['click'])?$tag['click']:''; //点击
$type = empty($tag['type'])?'button':$tag['type']; //按钮类型
if(!empty($name)) {
$parseStr = '<div class="'.$style.'" ><input type="'.$type.'" id="'.$id.'" name="'.$name.'" value="'.$value.'" onclick="'.$click.'" class="'.$name.' imgButton"></div>';
}else {
$parseStr = '<div class="'.$style.'" ><input type="'.$type.'" id="'.$id.'" name="'.$name.'" value="'.$value.'" onclick="'.$click.'" class="button"></div>';
}
return $parseStr;
}
/**
* imageLink标签解析
* 格式: <html:imageLink type="" value="" />
* @access public
* @param string $attr 标签属性
* @return string|void
*/
public function _imgLink($attr) {
$tag = $this->parseXmlAttr($attr,'imgLink');
$name = $tag['name']; //名称
$alt = $tag['alt']; //文字
$id = $tag['id']; //ID
$style = $tag['style']; //样式名
$click = $tag['click']; //点击
$type = $tag['type']; //点击
if(empty($type)) {
$type = 'button';
}
$parseStr = '<span class="'.$style.'" ><input title="'.$alt.'" type="'.$type.'" id="'.$id.'" name="'.$name.'" onmouseover="this.style.filter=\'alpha(opacity=100)\'" onmouseout="this.style.filter=\'alpha(opacity=80)\'" onclick="'.$click.'" align="absmiddle" class="'.$name.' imgLink"></span>';
return $parseStr;
}
/**
* select标签解析
* 格式: <html:select options="name" selected="value" />
* @access public
* @param string $attr 标签属性
* @return string|void
*/
public function _select($attr) {
$tag = $this->parseXmlAttr($attr,'select');
$name = $tag['name'];
$options = $tag['options'];
$values = $tag['values'];
$output = $tag['output'];
$multiple = $tag['multiple'];
$id = $tag['id'];
$size = $tag['size'];
$first = $tag['first'];
$selected = $tag['selected'];
$style = $tag['style'];
$ondblclick = $tag['dblclick'];
$onchange = $tag['change'];
if(!empty($multiple)) {
$parseStr = '<select id="'.$id.'" name="'.$name.'" ondblclick="'.$ondblclick.'" onchange="'.$onchange.'" multiple="multiple" class="'.$style.'" size="'.$size.'" >';
}else {
$parseStr = '<select id="'.$id.'" name="'.$name.'" onchange="'.$onchange.'" ondblclick="'.$ondblclick.'" class="'.$style.'" >';
}
if(!empty($first)) {
$parseStr .= '<option value="" >'.$first.'</option>';
}
if(!empty($options)) {
$parseStr .= '<?php foreach($'.$options.' as $key=>$val) { ?>';
if(!empty($selected)) {
$parseStr .= '<?php if(!empty($'.$selected.') && ($'.$selected.' == $key || in_array($key,$'.$selected.'))) { ?>';
$parseStr .= '<option selected="selected" value="<?php echo $key ?>"><?php echo $val ?></option>';
$parseStr .= '<?php }else { ?><option value="<?php echo $key ?>"><?php echo $val ?></option>';
$parseStr .= '<?php } ?>';
}else {
$parseStr .= '<option value="<?php echo $key ?>"><?php echo $val ?></option>';
}
$parseStr .= '<?php } ?>';
}else if(!empty($values)) {
$parseStr .= '<?php for($i=0;$i<count($'.$values.');$i++) { ?>';
if(!empty($selected)) {
$parseStr .= '<?php if(isset($'.$selected.') && ((is_string($'.$selected.') && $'.$selected.' == $'.$values.'[$i]) || (is_array($'.$selected.') && in_array($'.$values.'[$i],$'.$selected.')))) { ?>';
$parseStr .= '<option selected="selected" value="<?php echo $'.$values.'[$i] ?>"><?php echo $'.$output.'[$i] ?></option>';
$parseStr .= '<?php }else { ?><option value="<?php echo $'.$values.'[$i] ?>"><?php echo $'.$output.'[$i] ?></option>';
$parseStr .= '<?php } ?>';
}else {
$parseStr .= '<option value="<?php echo $'.$values.'[$i] ?>"><?php echo $'.$output.'[$i] ?></option>';
}
$parseStr .= '<?php } ?>';
}
$parseStr .= '</select>';
return $parseStr;
}
/**
* checkbox标签解析
* 格式: <html:checkbox checkboxes="" checked="" />
* @access public
* @param string $attr 标签属性
* @return string|void
*/
public function _checkbox($attr) {
$tag = $this->parseXmlAttr($attr,'checkbox');
$name = $tag['name'];
$checkboxes = $tag['checkboxes'];
$checked = $tag['checked'];
$separator = $tag['separator'];
$checkboxes = $this->tpl->get($checkboxes);
$checked = $this->tpl->get($checked)?$this->tpl->get($checked):$checked;
$parseStr = '';
foreach($checkboxes as $key=>$val) {
if($checked == $key || in_array($key,$checked) ) {
$parseStr .= '<label for="'.$name.$key.'"><input type="checkbox" name="'.$name.'[]" id="'.$name.$key.'" value="'.$key.'" checked="checked">'.$val.'</label>'.$separator;
}else {
$parseStr .= '<label for="'.$name.$key.'"><input type="checkbox" name="'.$name.'[]" id="'.$name.$key.'" value="'.$key.'">'.$val.'</label>'.$separator;
}
}
return $parseStr;
}
/**
* radio标签解析
* 格式: <html:radio radios="name" checked="value" />
* @access public
* @param string $attr 标签属性
* @return string|void
*/
public function _radio($attr) {
$tag = $this->parseXmlAttr($attr,'radio');
$name = $tag['name'];
$radios = $tag['radios'];
$checked = $tag['checked'];
$separator = $tag['separator'];
$radios = $this->tpl->get($radios);
$checked = $this->tpl->get($checked)?$this->tpl->get($checked):$checked;
$parseStr = '';
foreach($radios as $key=>$val) {
if($checked == $key ) {
$parseStr .= '<label for="'.$name.$key.'"><input type="radio" name="'.$name.'" id="'.$name.$key.'" value="'.$key.'" checked="checked">'.$val.'</label>'.$separator;
}else {
$parseStr .= '<label for="'.$name.$key.'"><input type="radio" name="'.$name.'" id="'.$name.$key.'" value="'.$key.'">'.$val.'</label>'.$separator;
}
}
return $parseStr;
}
/**
* list标签解析
* 格式: <html:grid datasource="" show="vo" />
* @access public
* @param string $attr 标签属性
* @return string
*/
public function _grid($attr) {
$tag = $this->parseXmlAttr($attr,'grid');
$id = $tag['id']; //表格ID
$datasource = $tag['datasource']; //列表显示的数据源VoList名称
$pk = empty($tag['pk'])?'id':$tag['pk'];//主键名,默认为id
$style = $tag['style']; //样式名
$name = !empty($tag['name'])?$tag['name']:'vo'; //Vo对象名
$action = !empty($tag['action'])?$tag['action']:false; //是否显示功能操作
$key = !empty($tag['key'])?true:false;
if(isset($tag['actionlist'])) {
$actionlist = explode(',',trim($tag['actionlist'])); //指定功能列表
}
if(substr($tag['show'],0,1)=='$') {
$show = $this->tpl->get(substr($tag['show'],1));
}else {
$show = $tag['show'];
}
$show = explode(',',$show); //列表显示字段列表
//计算表格的列数
$colNum = count($show);
if(!empty($action)) $colNum++;
if(!empty($key)) $colNum++;
//显示开始
$parseStr = "<!-- Think 系统列表组件开始 -->\n";
$parseStr .= '<table id="'.$id.'" class="'.$style.'" cellpadding=0 cellspacing=0 >';
$parseStr .= '<tr><td height="5" colspan="'.$colNum.'" class="topTd" ></td></tr>';
$parseStr .= '<tr class="row" >';
//列表需要显示的字段
$fields = array();
foreach($show as $val) {
$fields[] = explode(':',$val);
}
if(!empty($key)) {
$parseStr .= '<th width="12">No</th>';
}
foreach($fields as $field) {//显示指定的字段
$property = explode('|',$field[0]);
$showname = explode('|',$field[1]);
if(isset($showname[1])) {
$parseStr .= '<th width="'.$showname[1].'">';
}else {
$parseStr .= '<th>';
}
$parseStr .= $showname[0].'</th>';
}
if(!empty($action)) {//如果指定显示操作功能列
$parseStr .= '<th >操作</th>';
}
$parseStr .= '</tr>';
$parseStr .= '<volist name="'.$datasource.'" id="'.$name.'" ><tr class="row" >'; //支持鼠标移动单元行颜色变化 具体方法在js中定义
if(!empty($key)) {
$parseStr .= '<td>{$i}</td>';
}
foreach($fields as $field) {
//显示定义的列表字段
$parseStr .= '<td>';
if(!empty($field[2])) {
// 支持列表字段链接功能 具体方法由JS函数实现
$href = explode('|',$field[2]);
if(count($href)>1) {
//指定链接传的字段值
// 支持多个字段传递
$array = explode('^',$href[1]);
if(count($array)>1) {
foreach ($array as $a){
$temp[] = '\'{$'.$name.'.'.$a.'|addslashes}\'';
}
$parseStr .= '<a href="javascript:'.$href[0].'('.implode(',',$temp).')">';
}else{
$parseStr .= '<a href="javascript:'.$href[0].'(\'{$'.$name.'.'.$href[1].'|addslashes}\')">';
}
}else {
//如果没有指定默认传编号值
$parseStr .= '<a href="javascript:'.$field[2].'(\'{$'.$name.'.'.$pk.'|addslashes}\')">';
}
}
if(strpos($field[0],'^')) {
$property = explode('^',$field[0]);
foreach ($property as $p){
$unit = explode('|',$p);
if(count($unit)>1) {
$parseStr .= '{$'.$name.'.'.$unit[0].'|'.$unit[1].'} ';
}else {
$parseStr .= '{$'.$name.'.'.$p.'} ';
}
}
}else{
$property = explode('|',$field[0]);
if(count($property)>1) {
$parseStr .= '{$'.$name.'.'.$property[0].'|'.$property[1].'}';
}else {
$parseStr .= '{$'.$name.'.'.$field[0].'}';
}
}
if(!empty($field[2])) {
$parseStr .= '</a>';
}
$parseStr .= '</td>';
}
if(!empty($action)) {//显示功能操作
if(!empty($actionlist[0])) {//显示指定的功能项
$parseStr .= '<td>';
foreach($actionlist as $val) {
if(strpos($val,':')) {
$a = explode(':',$val);
if(count($a)>2) {
$parseStr .= '<a href="javascript:'.$a[0].'(\'{$'.$name.'.'.$a[2].'}\')">'.$a[1].'</a> ';
}else {
$parseStr .= '<a href="javascript:'.$a[0].'(\'{$'.$name.'.'.$pk.'}\')">'.$a[1].'</a> ';
}
}else{
$array = explode('|',$val);
if(count($array)>2) {
$parseStr .= ' <a href="javascript:'.$array[1].'(\'{$'.$name.'.'.$array[0].'}\')">'.$array[2].'</a> ';
}else{
$parseStr .= ' {$'.$name.'.'.$val.'} ';
}
}
}
$parseStr .= '</td>';
}
}
$parseStr .= '</tr></volist><tr><td height="5" colspan="'.$colNum.'" class="bottomTd"></td></tr></table>';
$parseStr .= "\n<!-- Think 系统列表组件结束 -->\n";
return $parseStr;
}
/**
* list标签解析
* 格式: <html:list datasource="" show="" />
* @access public
* @param string $attr 标签属性
* @return string
*/
public function _list($attr) {
$tag = $this->parseXmlAttr($attr,'list');
$id = $tag['id']; //表格ID
$datasource = $tag['datasource']; //列表显示的数据源VoList名称
$pk = empty($tag['pk'])?'id':$tag['pk'];//主键名,默认为id
$style = $tag['style']; //样式名
$name = !empty($tag['name'])?$tag['name']:'vo'; //Vo对象名
$action = $tag['action']=='true'?true:false; //是否显示功能操作
$key = !empty($tag['key'])?true:false;
$sort = $tag['sort']=='false'?false:true;
$checkbox = $tag['checkbox']; //是否显示Checkbox
if(isset($tag['actionlist'])) {
$actionlist = explode(',',trim($tag['actionlist'])); //指定功能列表
}
if(substr($tag['show'],0,1)=='$') {
$show = $this->tpl->get(substr($tag['show'],1));
}else {
$show = $tag['show'];
}
$show = explode(',',$show); //列表显示字段列表
//计算表格的列数
$colNum = count($show);
if(!empty($checkbox)) $colNum++;
if(!empty($action)) $colNum++;
if(!empty($key)) $colNum++;
//显示开始
$parseStr = "<!-- Think 系统列表组件开始 -->\n";
$parseStr .= '<table id="'.$id.'" class="'.$style.'" cellpadding=0 cellspacing=0 >';
$parseStr .= '<tr><td height="5" colspan="'.$colNum.'" class="topTd" ></td></tr>';
$parseStr .= '<tr class="row" >';
//列表需要显示的字段
$fields = array();
foreach($show as $val) {
$fields[] = explode(':',$val);
}
if(!empty($checkbox) && 'true'==strtolower($checkbox)) {//如果指定需要显示checkbox列
$parseStr .='<th width="8"><input type="checkbox" id="check" onclick="CheckAll(\''.$id.'\')"></th>';
}
if(!empty($key)) {
$parseStr .= '<th width="12">No</th>';
}
foreach($fields as $field) {//显示指定的字段
$property = explode('|',$field[0]);
$showname = explode('|',$field[1]);
if(isset($showname[1])) {
$parseStr .= '<th width="'.$showname[1].'">';
}else {
$parseStr .= '<th>';
}
$showname[2] = isset($showname[2])?$showname[2]:$showname[0];
if($sort) {
$parseStr .= '<a href="javascript:sortBy(\''.$property[0].'\',\'{$sort}\',\''.ACTION_NAME.'\')" title="按照'.$showname[2].'{$sortType} ">'.$showname[0].'<eq name="order" value="'.$property[0].'" ><img src="../Public/images/{$sortImg}.gif" width="12" height="17" border="0" align="absmiddle"></eq></a></th>';
}else{
$parseStr .= $showname[0].'</th>';
}
}
if(!empty($action)) {//如果指定显示操作功能列
$parseStr .= '<th >操作</th>';
}
$parseStr .= '</tr>';
$parseStr .= '<volist name="'.$datasource.'" id="'.$name.'" ><tr class="row" '; //支持鼠标移动单元行颜色变化 具体方法在js中定义
if(!empty($checkbox)) {
$parseStr .= 'onmouseover="over(event)" onmouseout="out(event)" onclick="change(event)" ';
}
$parseStr .= '>';
if(!empty($checkbox)) {//如果需要显示checkbox 则在每行开头显示checkbox
$parseStr .= '<td><input type="checkbox" name="key" value="{$'.$name.'.'.$pk.'}"></td>';
}
if(!empty($key)) {
$parseStr .= '<td>{$i}</td>';
}
foreach($fields as $field) {
//显示定义的列表字段
$parseStr .= '<td>';
if(!empty($field[2])) {
// 支持列表字段链接功能 具体方法由JS函数实现
$href = explode('|',$field[2]);
if(count($href)>1) {
//指定链接传的字段值
// 支持多个字段传递
$array = explode('^',$href[1]);
if(count($array)>1) {
foreach ($array as $a){
$temp[] = '\'{$'.$name.'.'.$a.'|addslashes}\'';
}
$parseStr .= '<a href="javascript:'.$href[0].'('.implode(',',$temp).')">';
}else{
$parseStr .= '<a href="javascript:'.$href[0].'(\'{$'.$name.'.'.$href[1].'|addslashes}\')">';
}
}else {
//如果没有指定默认传编号值
$parseStr .= '<a href="javascript:'.$field[2].'(\'{$'.$name.'.'.$pk.'|addslashes}\')">';
}
}
if(strpos($field[0],'^')) {
$property = explode('^',$field[0]);
foreach ($property as $p){
$unit = explode('|',$p);
if(count($unit)>1) {
$parseStr .= '{$'.$name.'.'.$unit[0].'|'.$unit[1].'} ';
}else {
$parseStr .= '{$'.$name.'.'.$p.'} ';
}
}
}else{
$property = explode('|',$field[0]);
if(count($property)>1) {
$parseStr .= '{$'.$name.'.'.$property[0].'|'.$property[1].'}';
}else {
$parseStr .= '{$'.$name.'.'.$field[0].'}';
}
}
if(!empty($field[2])) {
$parseStr .= '</a>';
}
$parseStr .= '</td>';
}
if(!empty($action)) {//显示功能操作
if(!empty($actionlist[0])) {//显示指定的功能项
$parseStr .= '<td>';
foreach($actionlist as $val) {
if(strpos($val,':')) {
$a = explode(':',$val);
if(count($a)>2) {
$parseStr .= '<a href="javascript:'.$a[0].'(\'{$'.$name.'.'.$a[2].'}\')">'.$a[1].'</a> ';
}else {
$parseStr .= '<a href="javascript:'.$a[0].'(\'{$'.$name.'.'.$pk.'}\')">'.$a[1].'</a> ';
}
}else{
$array = explode('|',$val);
if(count($array)>2) {
$parseStr .= ' <a href="javascript:'.$array[1].'(\'{$'.$name.'.'.$array[0].'}\')">'.$array[2].'</a> ';
}else{
$parseStr .= ' {$'.$name.'.'.$val.'} ';
}
}
}
$parseStr .= '</td>';
}
}
$parseStr .= '</tr></volist><tr><td height="5" colspan="'.$colNum.'" class="bottomTd"></td></tr></table>';
$parseStr .= "\n<!-- Think 系统列表组件结束 -->\n";
return $parseStr;
}
} | 10npsite | trunk/DThinkPHP/Extend/Driver/TagLib/TagLibHtml.class.php | PHP | asf20 | 26,514 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: UploadFile.class.php 2568 2012-01-10 12:15:45Z liu21st $
/**
+------------------------------------------------------------------------------
* 文件上传类
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Net
* @author liu21st <liu21st@gmail.com>
* @version $Id: UploadFile.class.php 2568 2012-01-10 12:15:45Z liu21st $
+------------------------------------------------------------------------------
*/
class UploadFile {//类定义开始
// 上传文件的最大值
public $maxSize = -1;
// 是否支持多文件上传
public $supportMulti = true;
// 允许上传的文件后缀
// 留空不作后缀检查
public $allowExts = array();
// 允许上传的文件类型
// 留空不做检查
public $allowTypes = array();
// 使用对上传图片进行缩略图处理
public $thumb = false;
// 图库类包路径
public $imageClassPath = 'ORG.Util.Image';
// 缩略图最大宽度
public $thumbMaxWidth;
// 缩略图最大高度
public $thumbMaxHeight;
// 缩略图前缀
public $thumbPrefix = 'thumb_';
public $thumbSuffix = '';
// 缩略图保存路径
public $thumbPath = '';
// 缩略图文件名
public $thumbFile = '';
// 是否移除原图
public $thumbRemoveOrigin = false;
// 压缩图片文件上传
public $zipImages = false;
// 启用子目录保存文件
public $autoSub = false;
// 子目录创建方式 可以使用hash date
public $subType = 'hash';
public $dateFormat = 'Ymd';
public $hashLevel = 1; // hash的目录层次
// 上传文件保存路径
public $savePath = '';
public $autoCheck = true; // 是否自动检查附件
// 存在同名是否覆盖
public $uploadReplace = false;
// 上传文件命名规则
// 例如可以是 time uniqid com_create_guid 等
// 必须是一个无需任何参数的函数名 可以使用自定义函数
public $saveRule = '';
// 上传文件Hash规则函数名
// 例如可以是 md5_file sha1_file 等
public $hashType = 'md5_file';
// 错误信息
private $error = '';
// 上传成功的文件信息
private $uploadFileInfo ;
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($maxSize='',$allowExts='',$allowTypes='',$savePath='',$saveRule='') {
if(!empty($maxSize) && is_numeric($maxSize)) {
$this->maxSize = $maxSize;
}
if(!empty($allowExts)) {
if(is_array($allowExts)) {
$this->allowExts = array_map('strtolower',$allowExts);
}else {
$this->allowExts = explode(',',strtolower($allowExts));
}
}
if(!empty($allowTypes)) {
if(is_array($allowTypes)) {
$this->allowTypes = array_map('strtolower',$allowTypes);
}else {
$this->allowTypes = explode(',',strtolower($allowTypes));
}
}
if(!empty($saveRule)) {
$this->saveRule = $saveRule;
}else{
$this->saveRule = C('UPLOAD_FILE_RULE');
}
$this->savePath = $savePath;
}
/**
+----------------------------------------------------------
* 上传一个文件
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $name 数据
* @param string $value 数据表名
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
private function save($file) {
$filename = $file['savepath'].$file['savename'];
if(!$this->uploadReplace && is_file($filename)) {
// 不覆盖同名文件
$this->error = '文件已经存在!'.$filename;
return false;
}
// 如果是图像文件 检测文件格式
if( in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png','swf')) && false === getimagesize($file['tmp_name'])) {
$this->error = '非法图像文件';
return false;
}
if(!move_uploaded_file($file['tmp_name'], $this->autoCharset($filename,'utf-8','gbk'))) {
$this->error = '文件上传保存错误!';
return false;
}
if($this->thumb && in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png'))) {
$image = getimagesize($filename);
if(false !== $image) {
//是图像文件生成缩略图
$thumbWidth = explode(',',$this->thumbMaxWidth);
$thumbHeight = explode(',',$this->thumbMaxHeight);
$thumbPrefix = explode(',',$this->thumbPrefix);
$thumbSuffix = explode(',',$this->thumbSuffix);
$thumbFile = explode(',',$this->thumbFile);
$thumbPath = $this->thumbPath?$this->thumbPath:$file['savepath'];
// 生成图像缩略图
import($this->imageClassPath);
$realFilename = $this->autoSub?basename($file['savename']):$file['savename'];
for($i=0,$len=count($thumbWidth); $i<$len; $i++) {
$thumbname = $thumbPath.$thumbPrefix[$i].substr($realFilename,0,strrpos($realFilename, '.')).$thumbSuffix[$i].'.'.$file['extension'];
Image::thumb($filename,$thumbname,'',$thumbWidth[$i],$thumbHeight[$i],true);
}
if($this->thumbRemoveOrigin) {
// 生成缩略图之后删除原图
unlink($filename);
}
}
}
if($this->zipImags) {
// TODO 对图片压缩包在线解压
}
return true;
}
/**
+----------------------------------------------------------
* 上传所有文件
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $savePath 上传文件保存路径
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function upload($savePath ='') {
//如果不指定保存文件名,则由系统默认
if(empty($savePath))
$savePath = $this->savePath;
// 检查上传目录
if(!is_dir($savePath)) {
// 检查目录是否编码后的
if(is_dir(base64_decode($savePath))) {
$savePath = base64_decode($savePath);
}else{
// 尝试创建目录
if(!mkdir($savePath)){
$this->error = '上传目录'.$savePath.'不存在';
return false;
}
}
}else {
if(!is_writeable($savePath)) {
$this->error = '上传目录'.$savePath.'不可写';
return false;
}
}
$fileInfo = array();
$isUpload = false;
// 获取上传的文件信息
// 对$_FILES数组信息处理
$files = $this->dealFiles($_FILES);
foreach($files as $key => $file) {
//过滤无效的上传
if(!empty($file['name'])) {
//登记上传文件的扩展信息
$file['key'] = $key;
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file);
// 自动检查附件
if($this->autoCheck) {
if(!$this->check($file))
return false;
}
//保存上传文件
if(!$this->save($file)) return false;
if(function_exists($this->hashType)) {
$fun = $this->hashType;
$file['hash'] = $fun($this->autoCharset($file['savepath'].$file['savename'],'utf-8','gbk'));
}
//上传成功后保存文件信息,供其他地方调用
unset($file['tmp_name'],$file['error']);
$fileInfo[] = $file;
$isUpload = true;
}
}
if($isUpload) {
$this->uploadFileInfo = $fileInfo;
return true;
}else {
$this->error = '没有选择上传文件';
return false;
}
}
/**
+----------------------------------------------------------
* 上传单个上传字段中的文件 支持多附件
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $file 上传文件信息
* @param string $savePath 上传文件保存路径
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function uploadOne($file,$savePath=''){
//如果不指定保存文件名,则由系统默认
if(empty($savePath))
$savePath = $this->savePath;
// 检查上传目录
if(!is_dir($savePath)) {
// 尝试创建目录
if(!mk_dir($savePath)){
$this->error = '上传目录'.$savePath.'不存在';
return false;
}
}else {
if(!is_writeable($savePath)) {
$this->error = '上传目录'.$savePath.'不可写';
return false;
}
}
//过滤无效的上传
if(!empty($file['name'])) {
$fileArray = array();
if(is_array($file['name'])) {
$keys = array_keys($file);
$count = count($file['name']);
for ($i=0; $i<$count; $i++) {
foreach ($keys as $key)
$fileArray[$i][$key] = $file[$key][$i];
}
}else{
$fileArray[] = $file;
}
$info = array();
foreach ($fileArray as $key=>$file){
//登记上传文件的扩展信息
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file);
// 自动检查附件
if($this->autoCheck) {
if(!$this->check($file))
return false;
}
//保存上传文件
if(!$this->save($file)) return false;
if(function_exists($this->hashType)) {
$fun = $this->hashType;
$file['hash'] = $fun($this->autoCharset($file['savepath'].$file['savename'],'utf-8','gbk'));
}
unset($file['tmp_name'],$file['error']);
$info[] = $file;
}
// 返回上传的文件信息
return $info;
}else {
$this->error = '没有选择上传文件';
return false;
}
}
/**
+----------------------------------------------------------
* 转换上传文件数组变量为正确的方式
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $files 上传的文件变量
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
private function dealFiles($files) {
$fileArray = array();
$n = 0;
foreach ($files as $file){
if(is_array($file['name'])) {
$keys = array_keys($file);
$count = count($file['name']);
for ($i=0; $i<$count; $i++) {
foreach ($keys as $key)
$fileArray[$n][$key] = $file[$key][$i];
$n++;
}
}else{
$fileArray[$n] = $file;
$n++;
}
}
return $fileArray;
}
/**
+----------------------------------------------------------
* 获取错误代码信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $errorNo 错误号码
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
protected function error($errorNo) {
switch($errorNo) {
case 1:
$this->error = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
break;
case 2:
$this->error = '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
break;
case 3:
$this->error = '文件只有部分被上传';
break;
case 4:
$this->error = '没有文件被上传';
break;
case 6:
$this->error = '找不到临时文件夹';
break;
case 7:
$this->error = '文件写入失败';
break;
default:
$this->error = '未知上传错误!';
}
return ;
}
/**
+----------------------------------------------------------
* 根据上传文件命名规则取得保存文件名
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 数据
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function getSaveName($filename) {
$rule = $this->saveRule;
if(empty($rule)) {//没有定义命名规则,则保持文件名不变
$saveName = $filename['name'];
}else {
if(function_exists($rule)) {
//使用函数生成一个唯一文件标识号
$saveName = $rule().".".$filename['extension'];
}else {
//使用给定的文件名作为标识号
$saveName = $rule.".".$filename['extension'];
}
}
if($this->autoSub) {
// 使用子目录保存文件
$filename['savename'] = $saveName;
$saveName = $this->getSubName($filename).'/'.$saveName;
}
return $saveName;
}
/**
+----------------------------------------------------------
* 获取子目录的名称
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $file 上传的文件信息
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function getSubName($file) {
switch($this->subType) {
case 'date':
$dir = date($this->dateFormat,time());
break;
case 'hash':
default:
$name = md5($file['savename']);
$dir = '';
for($i=0;$i<$this->hashLevel;$i++) {
$dir .= $name{$i}.'/';
}
break;
}
if(!is_dir($file['savepath'].$dir)) {
mk_dir($file['savepath'].$dir);
}
return $dir;
}
/**
+----------------------------------------------------------
* 检查上传的文件
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $file 文件信息
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function check($file) {
if($file['error']!== 0) {
//文件上传失败
//捕获错误代码
$this->error($file['error']);
return false;
}
//文件上传成功,进行自定义规则检查
//检查文件大小
if(!$this->checkSize($file['size'])) {
$this->error = '上传文件大小不符!';
return false;
}
//检查文件Mime类型
if(!$this->checkType($file['type'])) {
$this->error = '上传文件MIME类型不允许!';
return false;
}
//检查文件类型
if(!$this->checkExt($file['extension'])) {
$this->error ='上传文件类型不允许';
return false;
}
//检查是否合法上传
if(!$this->checkUpload($file['tmp_name'])) {
$this->error = '非法上传文件!';
return false;
}
return true;
}
// 自动转换字符集 支持数组转换
private function autoCharset($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 (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($fContents, $to, $from);
} elseif (function_exists('iconv')) {
return iconv($from, $to, $fContents);
} else {
return $fContents;
}
}
/**
+----------------------------------------------------------
* 检查上传的文件类型是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $type 数据
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkType($type) {
if(!empty($this->allowTypes))
return in_array(strtolower($type),$this->allowTypes);
return true;
}
/**
+----------------------------------------------------------
* 检查上传的文件后缀是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $ext 后缀名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkExt($ext) {
if(!empty($this->allowExts))
return in_array(strtolower($ext),$this->allowExts,true);
return true;
}
/**
+----------------------------------------------------------
* 检查文件大小是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param integer $size 数据
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkSize($size) {
return !($size > $this->maxSize) || (-1 == $this->maxSize);
}
/**
+----------------------------------------------------------
* 检查文件是否非法提交
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 文件名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkUpload($filename) {
return is_uploaded_file($filename);
}
/**
+----------------------------------------------------------
* 取得上传文件的后缀
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 文件名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function getExt($filename) {
$pathinfo = pathinfo($filename);
return $pathinfo['extension'];
}
/**
+----------------------------------------------------------
* 取得上传文件的信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getUploadFileInfo() {
return $this->uploadFileInfo;
}
/**
+----------------------------------------------------------
* 取得最后一次错误信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getErrorMsg() {
return $this->error;
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Net/UploadFile.class.php | PHP | asf20 | 24,200 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Http.class.php 2504 2011-12-28 07:35:29Z liu21st $
/**
+------------------------------------------------------------------------------
* Http 工具类
* 提供一系列的Http方法
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Net
* @author liu21st <liu21st@gmail.com>
* @version $Id: Http.class.php 2504 2011-12-28 07:35:29Z liu21st $
+------------------------------------------------------------------------------
*/
class Http {
/**
+----------------------------------------------------------
* 采集远程文件
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $remote 远程文件名
* @param string $local 本地保存文件名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
static public function curlDownload($remote,$local) {
$cp = curl_init($remote);
$fp = fopen($local,"w");
curl_setopt($cp, CURLOPT_FILE, $fp);
curl_setopt($cp, CURLOPT_HEADER, 0);
curl_exec($cp);
curl_close($cp);
fclose($fp);
}
/**
+-----------------------------------------------------------
* 使用 fsockopen 通过 HTTP 协议直接访问(采集)远程文件
* 如果主机或服务器没有开启 CURL 扩展可考虑使用
* fsockopen 比 CURL 稍慢,但性能稳定
+-----------------------------------------------------------
* @static
* @access public
+-----------------------------------------------------------
* @param string $url 远程URL
* @param array $conf 其他配置信息
* int limit 分段读取字符个数
* string post post的内容,字符串或数组,key=value&形式
* string cookie 携带cookie访问,该参数是cookie内容
* string ip 如果该参数传入,$url将不被使用,ip访问优先
* int timeout 采集超时时间
* bool block 是否阻塞访问,默认为true
+-----------------------------------------------------------
* @return mixed
+-----------------------------------------------------------
*/
static public function fsockopenDownload($url, $conf = array()) {
$return = '';
if(!is_array($conf)) return $return;
$matches = parse_url($url);
!isset($matches['host']) && $matches['host'] = '';
!isset($matches['path']) && $matches['path'] = '';
!isset($matches['query']) && $matches['query'] = '';
!isset($matches['port']) && $matches['port'] = '';
$host = $matches['host'];
$path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
$port = !empty($matches['port']) ? $matches['port'] : 80;
$conf_arr = array(
'limit'=>0,
'post'=>'',
'cookie'=>'',
'ip'=>'',
'timeout'=>15,
'block'=>TRUE,
);
foreach (array_merge($conf_arr, $conf) as $k=>$v) ${$k} = $v;
if($post) {
if(is_array($post))
{
$post = http_build_query($post);
}
$out = "POST $path HTTP/1.0\r\n";
$out .= "Accept: */*\r\n";
//$out .= "Referer: $boardurl\r\n";
$out .= "Accept-Language: zh-cn\r\n";
$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
$out .= "Host: $host\r\n";
$out .= 'Content-Length: '.strlen($post)."\r\n";
$out .= "Connection: Close\r\n";
$out .= "Cache-Control: no-cache\r\n";
$out .= "Cookie: $cookie\r\n\r\n";
$out .= $post;
} else {
$out = "GET $path HTTP/1.0\r\n";
$out .= "Accept: */*\r\n";
//$out .= "Referer: $boardurl\r\n";
$out .= "Accept-Language: zh-cn\r\n";
$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
$out .= "Host: $host\r\n";
$out .= "Connection: Close\r\n";
$out .= "Cookie: $cookie\r\n\r\n";
}
$fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
if(!$fp) {
return '';
} else {
stream_set_blocking($fp, $block);
stream_set_timeout($fp, $timeout);
@fwrite($fp, $out);
$status = stream_get_meta_data($fp);
if(!$status['timed_out']) {
while (!feof($fp)) {
if(($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) {
break;
}
}
$stop = false;
while(!feof($fp) && !$stop) {
$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
$return .= $data;
if($limit) {
$limit -= strlen($data);
$stop = $limit <= 0;
}
}
}
@fclose($fp);
return $return;
}
}
/**
+----------------------------------------------------------
* 下载文件
* 可以指定下载显示的文件名,并自动发送相应的Header信息
* 如果指定了content参数,则下载该参数的内容
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $filename 下载文件名
* @param string $showname 下载显示的文件名
* @param string $content 下载的内容
* @param integer $expire 下载内容浏览器缓存时间
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
static public function download ($filename, $showname='',$content='',$expire=180) {
if(is_file($filename)) {
$length = filesize($filename);
}elseif(is_file(UPLOAD_PATH.$filename)) {
$filename = UPLOAD_PATH.$filename;
$length = filesize($filename);
}elseif($content != '') {
$length = strlen($content);
}else {
throw_exception($filename.L('下载文件不存在!'));
}
if(empty($showname)) {
$showname = $filename;
}
$showname = basename($showname);
if(!empty($filename)) {
$type = mime_content_type($filename);
}else{
$type = "application/octet-stream";
}
//发送Http Header信息 开始下载
header("Pragma: public");
header("Cache-control: max-age=".$expire);
//header('Cache-Control: no-store, no-cache, must-revalidate');
header("Expires: " . gmdate("D, d M Y H:i:s",time()+$expire) . "GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s",time()) . "GMT");
header("Content-Disposition: attachment; filename=".$showname);
header("Content-Length: ".$length);
header("Content-type: ".$type);
header('Content-Encoding: none');
header("Content-Transfer-Encoding: binary" );
if($content == '' ) {
readfile($filename);
}else {
echo($content);
}
exit();
}
/**
+----------------------------------------------------------
* 显示HTTP Header 信息
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function getHeaderInfo($header='',$echo=true) {
ob_start();
$headers = getallheaders();
if(!empty($header)) {
$info = $headers[$header];
echo($header.':'.$info."\n"); ;
}else {
foreach($headers as $key=>$val) {
echo("$key:$val\n");
}
}
$output = ob_get_clean();
if ($echo) {
echo (nl2br($output));
}else {
return $output;
}
}
/**
* HTTP Protocol defined status codes
* @param int $num
*/
static function sendHttpStatus($code) {
static $_status = array(
// Informational 1xx
100 => 'Continue',
101 => 'Switching Protocols',
// Success 2xx
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
// Redirection 3xx
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found', // 1.1
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
// 306 is deprecated but reserved
307 => 'Temporary Redirect',
// Client Error 4xx
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',
// Server Error 5xx
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]);
}
}
}//类定义结束
if( !function_exists ('mime_content_type')) {
/**
+----------------------------------------------------------
* 获取文件的mime_content类型
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function mime_content_type($filename) {
static $contentType = array(
'ai' => 'application/postscript',
'aif' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'asc' => 'application/pgp', //changed by skwashd - was text/plain
'asf' => 'video/x-ms-asf',
'asx' => 'video/x-ms-asf',
'au' => 'audio/basic',
'avi' => 'video/x-msvideo',
'bcpio' => 'application/x-bcpio',
'bin' => 'application/octet-stream',
'bmp' => 'image/bmp',
'c' => 'text/plain', // or 'text/x-csrc', //added by skwashd
'cc' => 'text/plain', // or 'text/x-c++src', //added by skwashd
'cs' => 'text/plain', //added by skwashd - for C# src
'cpp' => 'text/x-c++src', //added by skwashd
'cxx' => 'text/x-c++src', //added by skwashd
'cdf' => 'application/x-netcdf',
'class' => 'application/octet-stream',//secure but application/java-class is correct
'com' => 'application/octet-stream',//added by skwashd
'cpio' => 'application/x-cpio',
'cpt' => 'application/mac-compactpro',
'csh' => 'application/x-csh',
'css' => 'text/css',
'csv' => 'text/comma-separated-values',//added by skwashd
'dcr' => 'application/x-director',
'diff' => 'text/diff',
'dir' => 'application/x-director',
'dll' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'doc' => 'application/msword',
'dot' => 'application/msword',//added by skwashd
'dvi' => 'application/x-dvi',
'dxr' => 'application/x-director',
'eps' => 'application/postscript',
'etx' => 'text/x-setext',
'exe' => 'application/octet-stream',
'ez' => 'application/andrew-inset',
'gif' => 'image/gif',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'h' => 'text/plain', // or 'text/x-chdr',//added by skwashd
'h++' => 'text/plain', // or 'text/x-c++hdr', //added by skwashd
'hh' => 'text/plain', // or 'text/x-c++hdr', //added by skwashd
'hpp' => 'text/plain', // or 'text/x-c++hdr', //added by skwashd
'hxx' => 'text/plain', // or 'text/x-c++hdr', //added by skwashd
'hdf' => 'application/x-hdf',
'hqx' => 'application/mac-binhex40',
'htm' => 'text/html',
'html' => 'text/html',
'ice' => 'x-conference/x-cooltalk',
'ics' => 'text/calendar',
'ief' => 'image/ief',
'ifb' => 'text/calendar',
'iges' => 'model/iges',
'igs' => 'model/iges',
'jar' => 'application/x-jar', //added by skwashd - alternative mime type
'java' => 'text/x-java-source', //added by skwashd
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'js' => 'application/x-javascript',
'kar' => 'audio/midi',
'latex' => 'application/x-latex',
'lha' => 'application/octet-stream',
'log' => 'text/plain',
'lzh' => 'application/octet-stream',
'm3u' => 'audio/x-mpegurl',
'man' => 'application/x-troff-man',
'me' => 'application/x-troff-me',
'mesh' => 'model/mesh',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mif' => 'application/vnd.mif',
'mov' => 'video/quicktime',
'movie' => 'video/x-sgi-movie',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpga' => 'audio/mpeg',
'ms' => 'application/x-troff-ms',
'msh' => 'model/mesh',
'mxu' => 'video/vnd.mpegurl',
'nc' => 'application/x-netcdf',
'oda' => 'application/oda',
'patch' => 'text/diff',
'pbm' => 'image/x-portable-bitmap',
'pdb' => 'chemical/x-pdb',
'pdf' => 'application/pdf',
'pgm' => 'image/x-portable-graymap',
'pgn' => 'application/x-chess-pgn',
'pgp' => 'application/pgp',//added by skwashd
'php' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php3',
'pl' => 'application/x-perl',
'pm' => 'application/x-perl',
'png' => 'image/png',
'pnm' => 'image/x-portable-anymap',
'po' => 'text/plain',
'ppm' => 'image/x-portable-pixmap',
'ppt' => 'application/vnd.ms-powerpoint',
'ps' => 'application/postscript',
'qt' => 'video/quicktime',
'ra' => 'audio/x-realaudio',
'rar'=>'application/octet-stream',
'ram' => 'audio/x-pn-realaudio',
'ras' => 'image/x-cmu-raster',
'rgb' => 'image/x-rgb',
'rm' => 'audio/x-pn-realaudio',
'roff' => 'application/x-troff',
'rpm' => 'audio/x-pn-realaudio-plugin',
'rtf' => 'text/rtf',
'rtx' => 'text/richtext',
'sgm' => 'text/sgml',
'sgml' => 'text/sgml',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'shtml' => 'text/html',
'silo' => 'model/mesh',
'sit' => 'application/x-stuffit',
'skd' => 'application/x-koan',
'skm' => 'application/x-koan',
'skp' => 'application/x-koan',
'skt' => 'application/x-koan',
'smi' => 'application/smil',
'smil' => 'application/smil',
'snd' => 'audio/basic',
'so' => 'application/octet-stream',
'spl' => 'application/x-futuresplash',
'src' => 'application/x-wais-source',
'stc' => 'application/vnd.sun.xml.calc.template',
'std' => 'application/vnd.sun.xml.draw.template',
'sti' => 'application/vnd.sun.xml.impress.template',
'stw' => 'application/vnd.sun.xml.writer.template',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'swf' => 'application/x-shockwave-flash',
'sxc' => 'application/vnd.sun.xml.calc',
'sxd' => 'application/vnd.sun.xml.draw',
'sxg' => 'application/vnd.sun.xml.writer.global',
'sxi' => 'application/vnd.sun.xml.impress',
'sxm' => 'application/vnd.sun.xml.math',
'sxw' => 'application/vnd.sun.xml.writer',
't' => 'application/x-troff',
'tar' => 'application/x-tar',
'tcl' => 'application/x-tcl',
'tex' => 'application/x-tex',
'texi' => 'application/x-texinfo',
'texinfo' => 'application/x-texinfo',
'tgz' => 'application/x-gtar',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'tr' => 'application/x-troff',
'tsv' => 'text/tab-separated-values',
'txt' => 'text/plain',
'ustar' => 'application/x-ustar',
'vbs' => 'text/plain', //added by skwashd - for obvious reasons
'vcd' => 'application/x-cdlink',
'vcf' => 'text/x-vcard',
'vcs' => 'text/calendar',
'vfb' => 'text/calendar',
'vrml' => 'model/vrml',
'vsd' => 'application/vnd.visio',
'wav' => 'audio/x-wav',
'wax' => 'audio/x-ms-wax',
'wbmp' => 'image/vnd.wap.wbmp',
'wbxml' => 'application/vnd.wap.wbxml',
'wm' => 'video/x-ms-wm',
'wma' => 'audio/x-ms-wma',
'wmd' => 'application/x-ms-wmd',
'wml' => 'text/vnd.wap.wml',
'wmlc' => 'application/vnd.wap.wmlc',
'wmls' => 'text/vnd.wap.wmlscript',
'wmlsc' => 'application/vnd.wap.wmlscriptc',
'wmv' => 'video/x-ms-wmv',
'wmx' => 'video/x-ms-wmx',
'wmz' => 'application/x-ms-wmz',
'wrl' => 'model/vrml',
'wvx' => 'video/x-ms-wvx',
'xbm' => 'image/x-xbitmap',
'xht' => 'application/xhtml+xml',
'xhtml' => 'application/xhtml+xml',
'xls' => 'application/vnd.ms-excel',
'xlt' => 'application/vnd.ms-excel',
'xml' => 'application/xml',
'xpm' => 'image/x-xpixmap',
'xsl' => 'text/xml',
'xwd' => 'image/x-xwindowdump',
'xyz' => 'chemical/x-xyz',
'z' => 'application/x-compress',
'zip' => 'application/zip',
);
$type = strtolower(substr(strrchr($filename, '.'),1));
if(isset($contentType[$type])) {
$mime = $contentType[$type];
}else {
$mime = 'application/octet-stream';
}
return $mime;
}
}
if(!function_exists('image_type_to_extension')){
function image_type_to_extension($imagetype) {
if(empty($imagetype)) return false;
switch($imagetype) {
case IMAGETYPE_GIF : return '.gif';
case IMAGETYPE_JPEG : return '.jpg';
case IMAGETYPE_PNG : return '.png';
case IMAGETYPE_SWF : return '.swf';
case IMAGETYPE_PSD : return '.psd';
case IMAGETYPE_BMP : return '.bmp';
case IMAGETYPE_TIFF_II : return '.tiff';
case IMAGETYPE_TIFF_MM : return '.tiff';
case IMAGETYPE_JPC : return '.jpc';
case IMAGETYPE_JP2 : return '.jp2';
case IMAGETYPE_JPX : return '.jpf';
case IMAGETYPE_JB2 : return '.jb2';
case IMAGETYPE_SWC : return '.swc';
case IMAGETYPE_IFF : return '.aiff';
case IMAGETYPE_WBMP : return '.wbmp';
case IMAGETYPE_XBM : return '.xbm';
default : return false;
}
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Net/Http.class.php | PHP | asf20 | 20,258 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: IpLocation.class.php 2504 2011-12-28 07:35:29Z liu21st $
/**
+------------------------------------------------------------------------------
* IP 地理位置查询类 修改自 CoolCode.CN
* 由于使用UTF8编码 如果使用纯真IP地址库的话 需要对返回结果进行编码转换
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Net
* @author liu21st <liu21st@gmail.com>
* @version $Id: IpLocation.class.php 2504 2011-12-28 07:35:29Z liu21st $
+------------------------------------------------------------------------------
*/
class IpLocation {
/**
* QQWry.Dat文件指针
*
* @var resource
*/
private $fp;
/**
* 第一条IP记录的偏移地址
*
* @var int
*/
private $firstip;
/**
* 最后一条IP记录的偏移地址
*
* @var int
*/
private $lastip;
/**
* IP记录的总条数(不包含版本信息记录)
*
* @var int
*/
private $totalip;
/**
* 构造函数,打开 QQWry.Dat 文件并初始化类中的信息
*
* @param string $filename
* @return IpLocation
*/
public function __construct($filename = "UTFWry.dat") {
$this->fp = 0;
if (($this->fp = fopen(dirname(__FILE__).'/'.$filename, 'rb')) !== false) {
$this->firstip = $this->getlong();
$this->lastip = $this->getlong();
$this->totalip = ($this->lastip - $this->firstip) / 7;
}
}
/**
* 返回读取的长整型数
*
* @access private
* @return int
*/
private function getlong() {
//将读取的little-endian编码的4个字节转化为长整型数
$result = unpack('Vlong', fread($this->fp, 4));
return $result['long'];
}
/**
* 返回读取的3个字节的长整型数
*
* @access private
* @return int
*/
private function getlong3() {
//将读取的little-endian编码的3个字节转化为长整型数
$result = unpack('Vlong', fread($this->fp, 3).chr(0));
return $result['long'];
}
/**
* 返回压缩后可进行比较的IP地址
*
* @access private
* @param string $ip
* @return string
*/
private function packip($ip) {
// 将IP地址转化为长整型数,如果在PHP5中,IP地址错误,则返回False,
// 这时intval将Flase转化为整数-1,之后压缩成big-endian编码的字符串
return pack('N', intval(ip2long($ip)));
}
/**
* 返回读取的字符串
*
* @access private
* @param string $data
* @return string
*/
private function getstring($data = "") {
$char = fread($this->fp, 1);
while (ord($char) > 0) { // 字符串按照C格式保存,以\0结束
$data .= $char; // 将读取的字符连接到给定字符串之后
$char = fread($this->fp, 1);
}
return $data;
}
/**
* 返回地区信息
*
* @access private
* @return string
*/
private function getarea() {
$byte = fread($this->fp, 1); // 标志字节
switch (ord($byte)) {
case 0: // 没有区域信息
$area = "";
break;
case 1:
case 2: // 标志字节为1或2,表示区域信息被重定向
fseek($this->fp, $this->getlong3());
$area = $this->getstring();
break;
default: // 否则,表示区域信息没有被重定向
$area = $this->getstring($byte);
break;
}
return $area;
}
/**
* 根据所给 IP 地址或域名返回所在地区信息
*
* @access public
* @param string $ip
* @return array
*/
public function getlocation($ip='') {
if (!$this->fp) return null; // 如果数据文件没有被正确打开,则直接返回空
if(empty($ip)) $ip = get_client_ip();
$location['ip'] = gethostbyname($ip); // 将输入的域名转化为IP地址
$ip = $this->packip($location['ip']); // 将输入的IP地址转化为可比较的IP地址
// 不合法的IP地址会被转化为255.255.255.255
// 对分搜索
$l = 0; // 搜索的下边界
$u = $this->totalip; // 搜索的上边界
$findip = $this->lastip; // 如果没有找到就返回最后一条IP记录(QQWry.Dat的版本信息)
while ($l <= $u) { // 当上边界小于下边界时,查找失败
$i = floor(($l + $u) / 2); // 计算近似中间记录
fseek($this->fp, $this->firstip + $i * 7);
$beginip = strrev(fread($this->fp, 4)); // 获取中间记录的开始IP地址
// strrev函数在这里的作用是将little-endian的压缩IP地址转化为big-endian的格式
// 以便用于比较,后面相同。
if ($ip < $beginip) { // 用户的IP小于中间记录的开始IP地址时
$u = $i - 1; // 将搜索的上边界修改为中间记录减一
}
else {
fseek($this->fp, $this->getlong3());
$endip = strrev(fread($this->fp, 4)); // 获取中间记录的结束IP地址
if ($ip > $endip) { // 用户的IP大于中间记录的结束IP地址时
$l = $i + 1; // 将搜索的下边界修改为中间记录加一
}
else { // 用户的IP在中间记录的IP范围内时
$findip = $this->firstip + $i * 7;
break; // 则表示找到结果,退出循环
}
}
}
//获取查找到的IP地理位置信息
fseek($this->fp, $findip);
$location['beginip'] = long2ip($this->getlong()); // 用户IP所在范围的开始地址
$offset = $this->getlong3();
fseek($this->fp, $offset);
$location['endip'] = long2ip($this->getlong()); // 用户IP所在范围的结束地址
$byte = fread($this->fp, 1); // 标志字节
switch (ord($byte)) {
case 1: // 标志字节为1,表示国家和区域信息都被同时重定向
$countryOffset = $this->getlong3(); // 重定向地址
fseek($this->fp, $countryOffset);
$byte = fread($this->fp, 1); // 标志字节
switch (ord($byte)) {
case 2: // 标志字节为2,表示国家信息又被重定向
fseek($this->fp, $this->getlong3());
$location['country'] = $this->getstring();
fseek($this->fp, $countryOffset + 4);
$location['area'] = $this->getarea();
break;
default: // 否则,表示国家信息没有被重定向
$location['country'] = $this->getstring($byte);
$location['area'] = $this->getarea();
break;
}
break;
case 2: // 标志字节为2,表示国家信息被重定向
fseek($this->fp, $this->getlong3());
$location['country'] = $this->getstring();
fseek($this->fp, $offset + 8);
$location['area'] = $this->getarea();
break;
default: // 否则,表示国家信息没有被重定向
$location['country'] = $this->getstring($byte);
$location['area'] = $this->getarea();
break;
}
if ($location['country'] == " CZ88.NET") { // CZ88.NET表示没有有效信息
$location['country'] = "未知";
}
if ($location['area'] == " CZ88.NET") {
$location['area'] = "";
}
return $location;
}
/**
* 析构函数,用于在页面执行结束后自动关闭打开的文件。
*
*/
public function __destruct() {
if ($this->fp) {
fclose($this->fp);
}
$this->fp = 0;
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Net/IpLocation.class.php | PHP | asf20 | 9,442 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Cookie.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* Cookie管理类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id: Cookie.class.php 2702 2012-02-02 12:35:01Z liu21st $
+------------------------------------------------------------------------------
*/
class Cookie {
// 判断Cookie是否存在
static function is_set($name) {
return isset($_COOKIE[C('COOKIE_PREFIX').$name]);
}
// 获取某个Cookie值
static function get($name) {
$value = $_COOKIE[C('COOKIE_PREFIX').$name];
$value = unserialize(base64_decode($value));
return $value;
}
// 设置某个Cookie值
static function set($name,$value,$expire='',$path='',$domain='') {
if($expire=='') {
$expire = C('COOKIE_EXPIRE');
}
if(empty($path)) {
$path = C('COOKIE_PATH');
}
if(empty($domain)) {
$domain = C('COOKIE_DOMAIN');
}
$expire = !empty($expire)? time()+$expire : 0;
$value = base64_encode(serialize($value));
setcookie(C('COOKIE_PREFIX').$name, $value,$expire,$path,$domain);
$_COOKIE[C('COOKIE_PREFIX').$name] = $value;
}
// 删除某个Cookie值
static function delete($name) {
Cookie::set($name,'',-3600);
unset($_COOKIE[C('COOKIE_PREFIX').$name]);
}
// 清空Cookie值
static function clear() {
unset($_COOKIE);
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/Cookie.class.php | PHP | asf20 | 2,356 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CodeSwitch.class.php 2504 2011-12-28 07:35:29Z liu21st $
class CodeSwitch {
// 错误信息
static private $error = array();
// 提示信息
static private $info = array();
// 记录错误
static private function error($msg) {
self::$error[] = $msg;
}
// 记录信息
static private function info($info) {
self::$info[] = $info;
}
/**
+----------------------------------------------------------
* 编码转换函数,对整个文件进行编码转换
* 支持以下转换
* GB2312、UTF-8 WITH BOM转换为UTF-8
* UTF-8、UTF-8 WITH BOM转换为GB2312
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $filename 文件名
* @param string $out_charset 转换后的文件编码,与iconv使用的参数一致
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function DetectAndSwitch($filename,$out_charset) {
$fpr = fopen($filename,"r");
$char1 = fread($fpr,1);
$char2 = fread($fpr,1);
$char3 = fread($fpr,1);
$originEncoding = "";
if($char1==chr(239) && $char2==chr(187) && $char3==chr(191))//UTF-8 WITH BOM
$originEncoding = "UTF-8 WITH BOM";
elseif($char1==chr(255) && $char2==chr(254))//UNICODE LE
{
self::error("不支持从UNICODE LE转换到UTF-8或GB编码");
fclose($fpr);
return;
}
elseif($char1==chr(254) && $char2==chr(255))//UNICODE BE
{
self::error("不支持从UNICODE BE转换到UTF-8或GB编码");
fclose($fpr);
return;
}
else//没有文件头,可能是GB或UTF-8
{
if(rewind($fpr)===false)//回到文件开始部分,准备逐字节读取判断编码
{
self::error($filename."文件指针后移失败");
fclose($fpr);
return;
}
while(!feof($fpr))
{
$char = fread($fpr,1);
//对于英文,GB和UTF-8都是单字节的ASCII码小于128的值
if(ord($char)<128)
continue;
//对于汉字GB编码第一个字节是110*****第二个字节是10******(有特例,比如联字)
//UTF-8编码第一个字节是1110****第二个字节是10******第三个字节是10******
//按位与出来结果要跟上面非星号相同,所以应该先判断UTF-8
//因为使用GB的掩码按位与,UTF-8的111得出来的也是110,所以要先判断UTF-8
if((ord($char)&224)==224)
{
//第一个字节判断通过
$char = fread($fpr,1);
if((ord($char)&128)==128)
{
//第二个字节判断通过
$char = fread($fpr,1);
if((ord($char)&128)==128)
{
$originEncoding = "UTF-8";
break;
}
}
}
if((ord($char)&192)==192)
{
//第一个字节判断通过
$char = fread($fpr,1);
if((ord($char)&128)==128)
{
//第二个字节判断通过
$originEncoding = "GB2312";
break;
}
}
}
}
if(strtoupper($out_charset)==$originEncoding)
{
self::info("文件".$filename."转码检查完成,原始文件编码".$originEncoding);
fclose($fpr);
}
else
{
//文件需要转码
$originContent = "";
if($originEncoding == "UTF-8 WITH BOM")
{
//跳过三个字节,把后面的内容复制一遍得到utf-8的内容
fseek($fpr,3);
$originContent = fread($fpr,filesize($filename)-3);
fclose($fpr);
}
elseif(rewind($fpr)!=false)//不管是UTF-8还是GB2312,回到文件开始部分,读取内容
{
$originContent = fread($fpr,filesize($filename));
fclose($fpr);
}
else
{
self::error("文件编码不正确或指针后移失败");
fclose($fpr);
return;
}
//转码并保存文件
$content = iconv(str_replace(" WITH BOM","",$originEncoding),strtoupper($out_charset),$originContent);
$fpw = fopen($filename,"w");
fwrite($fpw,$content);
fclose($fpw);
if($originEncoding!="")
self::info("对文件".$filename."转码完成,原始文件编码".$originEncoding.",转换后文件编码".strtoupper($out_charset));
elseif($originEncoding=="")
self::info("文件".$filename."中没有出现中文,但是可以断定不是带BOM的UTF-8编码,没有进行编码转换,不影响使用");
}
}
/**
+----------------------------------------------------------
* 目录遍历函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $path 要遍历的目录名
* @param string $mode 遍历模式,一般取FILES,这样只返回带路径的文件名
* @param array $file_types 文件后缀过滤数组
* @param int $maxdepth 遍历深度,-1表示遍历到最底层
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function searchdir($path,$mode = "FULL",$file_types = array(".html",".php"),$maxdepth = -1,$d = 0)
{
if(substr($path,strlen($path)-1) != '/')
$path .= '/';
$dirlist = array();
if($mode != "FILES")
$dirlist[] = $path;
if($handle = @opendir($path))
{
while(false !== ($file = readdir($handle)))
{
if($file != '.' && $file != '..')
{
$file = $path.$file ;
if(!is_dir($file))
{
if($mode != "DIRS")
{
$extension = "";
$extpos = strrpos($file, '.');
if($extpos!==false)
$extension = substr($file,$extpos,strlen($file)-$extpos);
$extension=strtolower($extension);
if(in_array($extension, $file_types))
$dirlist[] = $file;
}
}
elseif($d >= 0 && ($d < $maxdepth || $maxdepth < 0))
{
$result = self::searchdir($file.'/',$mode,$file_types,$maxdepth,$d + 1) ;
$dirlist = array_merge($dirlist,$result);
}
}
}
closedir ( $handle ) ;
}
if($d == 0)
natcasesort($dirlist);
return($dirlist) ;
}
/**
+----------------------------------------------------------
* 对整个项目目录中的PHP和HTML文件行进编码转换
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $app 要遍历的项目路径
* @param string $mode 遍历模式,一般取FILES,这样只返回带路径的文件名
* @param array $file_types 文件后缀过滤数组
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function CodingSwitch($app = "./",$charset='UTF-8',$mode = "FILES",$file_types = array(".html",".php"))
{
self::info("注意: 程序使用的文件编码检测算法可能对某些特殊字符不适用");
$filearr = self::searchdir($app,$mode,$file_types);
foreach($filearr as $file)
self::DetectAndSwitch($file,$charset);
}
static public function getError() {
return self::$error;
}
static public function getInfo() {
return self::$info;
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/CodeSwitch.class.php | PHP | asf20 | 8,093 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <www.3g4k.com>
// +----------------------------------------------------------------------
// $Id: Authority.class.php 2504 2011-12-28 07:35:29Z liu21st $
/**
* 权限认证类
* 功能特性:
* 1,是对规则进行认证,不是对节点进行认证。用户可以把节点当作规则名称实现对节点进行认证。
* $auth=new Authority(); $auth->getAuth('规则名称','用户id')
* 2,可以同时对多条规则进行认证,并设置多条规则的关系(or或者and)
* $auth=new Authority(); $auth->getAuth('规则1,规则2','用户id','and')
* 第三个参数为and时表示,用户需要同时具有规则1和规则2的权限。 当第三个参数为or时,表示用户值需要具备其中一个条件即可。默认为or
* 3,一个用户可以属于多个用户组(think_auth_group_access表 定义了用户所属用户组)。我们需要设置每个用户组拥有哪些规则(think_auth_group 定义了用户组权限)
*
* 4,支持规则表达式。
* 在think_auth_rule 表中定义一条规则时,如果type为1, condition字段就可以定义规则表达式。 如定义{score}>5 and {score}<100 表示用户的分数在5-100之间时这条规则才会通过。
* @category ORG
* @package ORG
* @subpackage Util
* @author luofei614<www.3g4k.com>
*/
//数据库
/*
-- ----------------------------
-- think_auth_rule,规则表,
-- id:主键,name:规则唯一标识, title:规则中文名称 type:类型(0存在规则就通过,1按规则表达时进行认证),condition:规则表达式
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_rule`;
CREATE TABLE `think_auth_rule` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`name` char(10) NOT NULL DEFAULT '',
`title` char(20) NOT NULL DEFAULT '',
`type` tinyint(1) NOT NULL DEFAULT '0',
`condition` char(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- think_auth_group 用户组表,
-- id:主键, title:用户组中文名称, rules:用户组拥有的规则id, 多个规则用“,”隔开
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_group`;
CREATE TABLE `think_auth_group` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`title` char(100) NOT NULL DEFAULT '',
`rules` char(80) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- think_auth_group_access 用户组明细表
-- uid:用户id,group_id:用户组id
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_group_access`;
CREATE TABLE `think_auth_group_access` (
`uid` mediumint(8) unsigned NOT NULL,
`group_id` mediumint(8) unsigned NOT NULL,
UNIQUE KEY `uid_2` (`uid`,`group_id`),
KEY `uid` (`uid`),
KEY `group_id` (`group_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
*/
class Authority {
//默认配置
protected $_config = array(
'AUTH_ON' => true, //认证开关
'AUTH_TYPE' => 1, // 认证方式,1为时时认证;2为登录认证。
'AUTH_GROUP' => 'think_auth_group', //用户组数据表名
'AUTH_GROUP_ACCESS' => 'think_auth_group_access', //用户组明细表
'AUTH_RULE' => 'think_auth_rule', //权限规则表
'AUTH_USER' => 'think_members'//用户信息表
);
public function __construct() {
if (C('AUTH_CONFIG')) {
//可设置配置项 AUTH_CONFIG, 此配置项为数组。
$this->_config = array_merge($this->_config, C('AUTH_CONFIG'));
}
}
//获得权限$name 可以是字符串或数组或逗号分割, uid为 认证的用户id, $or 是否为or关系,为true是, name为数组,只要数组中有一个条件通过则通过,如果为false需要全部条件通过。
public function getAuth($name, $uid, $relation='or') {
if (!$this->_config['AUTH_ON'])
return true;
$authList = $this->getAuthList($uid);
if (is_string($name)) {
if (strpos($name, ',') !== false) {
$name = explode(',', $name);
} else {
$name = array($name);
}
}
$list = array(); //有权限的name
foreach ($authList as $val) {
if (in_array($val, $name))
$list[] = $val;
}
if ($relation=='or' and !empty($list)) {
return true;
}
$diff = array_diff($name, $list);
if ($relation=='and' and empty($diff)) {
return true;
}
return false;
}
//获得用户组,外部也可以调用
public function getGroups($uid) {
static $groups = array();
if (!empty($groups[$uid]))
return $groups[$uid];
$groups[$uid] = M()->table($this->_config['AUTH_GROUP_ACCESS'] . ' a')->where("a.uid='$uid'")->join($this->_config['AUTH_GROUP']." g on a.group_id=g.id")->select();
return $groups[$uid];
}
//获得权限列表
protected function getAuthList($uid) {
static $_authList = array();
if (isset($_authList[$uid])) {
return $_authList[$uid];
}
if(isset($_SESSION['_AUTH_LIST_'.$uid])){
return $_SESSION['_AUTH_LIST_'.$uid];
}
//读取用户所属用户组
$groups = $this->getGroups($uid);
$ids = array();
foreach ($groups as $g) {
$ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
}
$ids = array_unique($ids);
if (empty($ids)) {
$_authList[$uid] = array();
return array();
}
//读取用户组所有权限规则(in)
$map['id'] = array('in', $ids);
$rules = M()->table($this->_config['AUTH_RULE'])->where($map)->select();
//循环规则,判断结果。
$authList = array();
foreach ($rules as $r) {
if ($r['type'] == 1) {
//条件验证
$user = $this->getUserInfo($uid);
$command = preg_replace('/\{(\w*?)\}/e', '$user[\'\\1\']', $r['condition']);
//dump($command);//debug
@(eval('$condition=(' . $command . ');'));
if ($condition) {
$authList[] = $r['name'];
}
} else {
//存在就通过
$authList[] = $r['name'];
}
}
$_authList[$uid] = $authList;
if($this->_config['AUTH_TYPE']==2){
//session结果
$_SESSION['_AUTH_LIST_'.$uid]=$authList;
}
return $authList;
}
//获得用户资料,根据自己的情况读取数据库
protected function getUserInfo($uid) {
return M()->table($this->_config['AUTH_USER'])->find($uid);
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/Authority.class.php | PHP | asf20 | 7,603 |
<?php
/* 海龙挖掘机 2.0正式版
* 正文提取,分析,可自动判断编码,自动转码
* 原理:根据代码块加权的原理,首先将HTML分成若干个小块,然后对每个小块进行评分。
* 取分数在3分以上的代码块中的内容返回
* 加分项 1 含有标点符号
* 2 含有<p>标签
* 3 含有<br>标签
* 减分项 1 含有li标签
* 2 不包含任何标点符号
* 3 含有关键词javascript
* 4 不包含任何中文的,直接删除
* 5 有<li><a这样标签
* 实例:
* $he = new HtmlExtractor();
* $str = $he->text($html);
* 其中$html是某个网页的HTML代码,$str是返回的正文,正文编码是utf-8的
*/
class HtmlExtractor {
/*
* 取得汉字的个数(目前不太精确)
*/
function chineseCount($str){
$count = preg_match_all("/[\xB0-\xF7][\xA1-\xFE]/",$str,$ff);
return $count;
}
/*
* 判断一段文字是否是UTF-8,如果不是,那么要转成UTF-8
*/
function getutf8($str){
if(!$this->is_utf8(substr(strip_tags($str),0,500))){
$str = $this->auto_charset($str,"gbk","utf-8");
}
return $str;
}
function is_utf8($string)
{
if(preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$string) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}$/",$string) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){2,}/",$string) == true){
return true;
}else{
return false;
}
}
/*
* 自动转换字符集,支持数组和字符串
*/
function auto_charset($fContents,$from,$to){
$from = strtoupper($from)=='UTF8'? 'utf-8':$from;
$to = strtoupper($to)=='UTF8'? 'utf-8':$to;
if( strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents)) ){
//如果编码相同或者非字符串标量则不转换
return $fContents;
}
if(is_string($fContents) ) {
if(function_exists('mb_convert_encoding')){
return mb_convert_encoding ($fContents, $to, $from);
}elseif(function_exists('iconv')){
return iconv($from,$to,$fContents);
}else{
return $fContents;
}
}
elseif(is_array($fContents)){
foreach ( $fContents as $key => $val ) {
$_key = $this->auto_charset($key,$from,$to);
$fContents[$_key] = $this->auto_charset($val,$from,$to);
if($key != $_key )
unset($fContents[$key]);
}
return $fContents;
}
else{
return $fContents;
}
}
/*
* 进行正文提取动作
*/
function text($str){
$str = $this->clear($str);
$str = $this->getutf8($str);
$divList = $this->divList($str);
$content = array();
foreach($divList[0] as $k=>$v){
//首先判断,如果这个内容块的汉字数量站总数量的一半还多,那么就直接保留
//还要判断,是不是一个A标签把整个内容都扩上
if($this->chineseCount($v)/(strlen($v)/3) >= 0.4 && $this->checkHref($v)){
array_push($content,strip_tags($v,"<p><br>"));
}else if($this->makeScore($v) >= 3){
//然后根据分数判断,如果大于3分的,保留
array_push($content,strip_tags($v,"<p><br>"));
}else{
//这些就是排除的内容了
}
}
return implode("",$content);
}
/*
* 判断是不是一个A标签把整个内容都扩上
* 判断方法:把A标签和它的内容都去掉后,看是否还含有中文
*/
private function checkHref($str){
if(!preg_match("'<a[^>]*?>(.*)</a>'si",$str)){
//如果不包含A标签,那不用管了,99%是正文
return true;
}
$clear_str = preg_replace("'<a[^>]*?>(.*)</a>'si","",$str);
if($this->chineseCount($clear_str)){
return true;
}else{
return false;
}
}
function makeScore($str){
$score = 0;
//标点分数
$score += $this->score1($str);
//判断含有P标签
$score += $this->score2($str);
//判断是否含有br标签
$score += $this->score3($str);
//判断是否含有li标签
$score -= $this->score4($str);
//判断是否不包含任何标点符号
$score -= $this->score5($str);
//判断javascript关键字
$score -= $this->score6($str);
//判断<li><a这样的标签
$score -= $this->score7($str);
return $score;
}
/*
* 判断是否有标点符号
*/
private function score1($str){
//取得标点符号的个数
$count = preg_match_all("/(,|。|!|(|)|“|”|;|《|》|、)/si",$str,$out);
if($count){
return $count * 2;
}else{
return 0;
}
}
/*
* 判断是否含有P标签
*/
private function score2($str){
$count = preg_match_all("'<p[^>]*?>.*?</p>'si",$str,$out);
return $count * 2;
}
/*
* 判断是否含有BR标签
*/
private function score3($str){
$count = preg_match_all("'<br/>'si",$str,$out) + preg_match_all("'<br>'si",$str,$out);
return $count * 2;
}
/*
* 判断是否含有li标签
*/
private function score4($str){
//有多少,减多少分 * 2
$count = preg_match_all("'<li[^>]*?>.*?</li>'si",$str,$out);
return $count * 2;
}
/*
* 判断是否不包含任何标点符号
*/
private function score5($str){
if(!preg_match_all("/(,|。|!|(|)|“|”|;|《|》|、|【|】)/si",$str,$out)){
return 2;
}else{
return 0;
}
}
/*
* 判断是否包含javascript关键字,有几个,减几分
*/
private function score6($str){
$count = preg_match_all("'javascript'si",$str,$out);
return $count;
}
/*
* 判断<li><a这样的标签,有几个,减几分
*/
private function score7($str){
$count = preg_match_all("'<li[^>]*?>.*?<a'si",$str,$out);
return $count * 2;
}
/*
* 去噪
*/
private function clear($str){
$str = preg_replace("'<script[^>]*?>.*?</script>'si","",$str);
$str = preg_replace("'<style[^>]*?>.*?</style>'si","",$str);
$str = preg_replace("'<!--.*?-->'si","",$str);
return $str;
}
/*
* 取得内容块
*/
private function divList($str){
preg_match_all("'<[^a][^>]*?>.*?</[^>]*?>'si",$str,$divlist);
return $divlist;
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/HtmlExtractor.class.php | PHP | asf20 | 7,388 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Socket.class.php 2504 2011-12-28 07:35:29Z liu21st $
class Socket {
protected $_config = array(
'persistent' => false,
'host' => 'localhost',
'protocol' => 'tcp',
'port' => 80,
'timeout' => 30
);
public $config = array();
public $connection = null;
public $connected = false;
public $error = array();
public function __construct($config = array()) {
$this->config = array_merge($this->_config,$config);
if (!is_numeric($this->config['protocol'])) {
$this->config['protocol'] = getprotobyname($this->config['protocol']);
}
}
public function connect() {
if ($this->connection != null) {
$this->disconnect();
}
if ($this->config['persistent'] == true) {
$tmp = null;
$this->connection = @pfsockopen($this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
} else {
$this->connection = fsockopen($this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
}
if (!empty($errNum) || !empty($errStr)) {
$this->error($errStr, $errNum);
}
$this->connected = is_resource($this->connection);
return $this->connected;
}
public function error() {
}
public function write($data) {
if (!$this->connected) {
if (!$this->connect()) {
return false;
}
}
return fwrite($this->connection, $data, strlen($data));
}
public function read($length=1024) {
if (!$this->connected) {
if (!$this->connect()) {
return false;
}
}
if (!feof($this->connection)) {
return fread($this->connection, $length);
} else {
return false;
}
}
public function disconnect() {
if (!is_resource($this->connection)) {
$this->connected = false;
return true;
}
$this->connected = !fclose($this->connection);
if (!$this->connected) {
$this->connection = null;
}
return !$this->connected;
}
public function __destruct() {
$this->disconnect();
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/Socket.class.php | PHP | asf20 | 2,617 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: RBAC.class.php 2504 2011-12-28 07:35:29Z liu21st $
/**
+------------------------------------------------------------------------------
* 基于角色的数据库方式验证类
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id: RBAC.class.php 2504 2011-12-28 07:35:29Z liu21st $
+------------------------------------------------------------------------------
*/
// 配置文件增加设置
// USER_AUTH_ON 是否需要认证
// USER_AUTH_TYPE 认证类型
// USER_AUTH_KEY 认证识别号
// REQUIRE_AUTH_MODULE 需要认证模块
// NOT_AUTH_MODULE 无需认证模块
// USER_AUTH_GATEWAY 认证网关
// RBAC_DB_DSN 数据库连接DSN
// RBAC_ROLE_TABLE 角色表名称
// RBAC_USER_TABLE 用户表名称
// RBAC_ACCESS_TABLE 权限表名称
// RBAC_NODE_TABLE 节点表名称
/*
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `think_access` (
`role_id` smallint(6) unsigned NOT NULL,
`node_id` smallint(6) unsigned NOT NULL,
`level` tinyint(1) NOT NULL,
`module` varchar(50) DEFAULT NULL,
KEY `groupId` (`role_id`),
KEY `nodeId` (`node_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `think_node` (
`id` smallint(6) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`title` varchar(50) DEFAULT NULL,
`status` tinyint(1) DEFAULT '0',
`remark` varchar(255) DEFAULT NULL,
`sort` smallint(6) unsigned DEFAULT NULL,
`pid` smallint(6) unsigned NOT NULL,
`level` tinyint(1) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `level` (`level`),
KEY `pid` (`pid`),
KEY `status` (`status`),
KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `think_role` (
`id` smallint(6) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`pid` smallint(6) DEFAULT NULL,
`status` tinyint(1) unsigned DEFAULT NULL,
`remark` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `pid` (`pid`),
KEY `status` (`status`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
CREATE TABLE IF NOT EXISTS `think_role_user` (
`role_id` mediumint(9) unsigned DEFAULT NULL,
`user_id` char(32) DEFAULT NULL,
KEY `group_id` (`role_id`),
KEY `user_id` (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
*/
class RBAC {
// 认证方法
static public function authenticate($map,$model='')
{
if(empty($model)) $model = C('USER_AUTH_MODEL');
//使用给定的Map进行认证
return M($model)->where($map)->find();
}
//用于检测用户权限的方法,并保存到Session中
static function saveAccessList($authId=null)
{
if(null===$authId) $authId = $_SESSION[C('USER_AUTH_KEY')];
// 如果使用普通权限模式,保存当前用户的访问权限列表
// 对管理员开发所有权限
if(C('USER_AUTH_TYPE') !=2 && !$_SESSION[C('ADMIN_AUTH_KEY')] )
$_SESSION['_ACCESS_LIST'] = RBAC::getAccessList($authId);
return ;
}
// 取得模块的所属记录访问权限列表 返回有权限的记录ID数组
static function getRecordAccessList($authId=null,$module='') {
if(null===$authId) $authId = $_SESSION[C('USER_AUTH_KEY')];
if(empty($module)) $module = MODULE_NAME;
//获取权限访问列表
$accessList = RBAC::getModuleAccessList($authId,$module);
return $accessList;
}
//检查当前操作是否需要认证
static function checkAccess()
{
//如果项目要求认证,并且当前模块需要认证,则进行权限认证
if( C('USER_AUTH_ON') ){
$_module = array();
$_action = array();
if("" != C('REQUIRE_AUTH_MODULE')) {
//需要认证的模块
$_module['yes'] = explode(',',strtoupper(C('REQUIRE_AUTH_MODULE')));
}else {
//无需认证的模块
$_module['no'] = explode(',',strtoupper(C('NOT_AUTH_MODULE')));
}
//检查当前模块是否需要认证
if((!empty($_module['no']) && !in_array(strtoupper(MODULE_NAME),$_module['no'])) || (!empty($_module['yes']) && in_array(strtoupper(MODULE_NAME),$_module['yes']))) {
if("" != C('REQUIRE_AUTH_ACTION')) {
//需要认证的操作
$_action['yes'] = explode(',',strtoupper(C('REQUIRE_AUTH_ACTION')));
}else {
//无需认证的操作
$_action['no'] = explode(',',strtoupper(C('NOT_AUTH_ACTION')));
}
//检查当前操作是否需要认证
if((!empty($_action['no']) && !in_array(strtoupper(ACTION_NAME),$_action['no'])) || (!empty($_action['yes']) && in_array(strtoupper(ACTION_NAME),$_action['yes']))) {
return true;
}else {
return false;
}
}else {
return false;
}
}
return false;
}
// 登录检查
static public function checkLogin() {
//检查当前操作是否需要认证
if(RBAC::checkAccess()) {
//检查认证识别号
if(!$_SESSION[C('USER_AUTH_KEY')]) {
if(C('GUEST_AUTH_ON')) {
// 开启游客授权访问
if(!isset($_SESSION['_ACCESS_LIST']))
// 保存游客权限
RBAC::saveAccessList(C('GUEST_AUTH_ID'));
}else{
// 禁止游客访问跳转到认证网关
redirect(PHP_FILE.C('USER_AUTH_GATEWAY'));
}
}
}
return true;
}
//权限认证的过滤器方法
static public function AccessDecision($appName=APP_NAME)
{
//检查是否需要认证
if(RBAC::checkAccess()) {
//存在认证识别号,则进行进一步的访问决策
$accessGuid = md5($appName.MODULE_NAME.ACTION_NAME);
if(empty($_SESSION[C('ADMIN_AUTH_KEY')])) {
if(C('USER_AUTH_TYPE')==2) {
//加强验证和即时验证模式 更加安全 后台权限修改可以即时生效
//通过数据库进行访问检查
$accessList = RBAC::getAccessList($_SESSION[C('USER_AUTH_KEY')]);
}else {
// 如果是管理员或者当前操作已经认证过,无需再次认证
if( $_SESSION[$accessGuid]) {
return true;
}
//登录验证模式,比较登录后保存的权限访问列表
$accessList = $_SESSION['_ACCESS_LIST'];
}
//判断是否为组件化模式,如果是,验证其全模块名
$module = defined('P_MODULE_NAME')? P_MODULE_NAME : MODULE_NAME;
if(!isset($accessList[strtoupper($appName)][strtoupper($module)][strtoupper(ACTION_NAME)])) {
$_SESSION[$accessGuid] = false;
return false;
}
else {
$_SESSION[$accessGuid] = true;
}
}else{
//管理员无需认证
return true;
}
}
return true;
}
/**
+----------------------------------------------------------
* 取得当前认证号的所有权限列表
+----------------------------------------------------------
* @param integer $authId 用户ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
static public function getAccessList($authId)
{
// Db方式权限数据
$db = Db::getInstance(C('RBAC_DB_DSN'));
$table = array('role'=>C('RBAC_ROLE_TABLE'),'user'=>C('RBAC_USER_TABLE'),'access'=>C('RBAC_ACCESS_TABLE'),'node'=>C('RBAC_NODE_TABLE'));
$sql = "select node.id,node.name from ".
$table['role']." as role,".
$table['user']." as user,".
$table['access']." as access ,".
$table['node']." as node ".
"where user.user_id='{$authId}' and user.role_id=role.id and ( access.role_id=role.id or (access.role_id=role.pid and role.pid!=0 ) ) and role.status=1 and access.node_id=node.id and node.level=1 and node.status=1";
$apps = $db->query($sql);
$access = array();
foreach($apps as $key=>$app) {
$appId = $app['id'];
$appName = $app['name'];
// 读取项目的模块权限
$access[strtoupper($appName)] = array();
$sql = "select node.id,node.name from ".
$table['role']." as role,".
$table['user']." as user,".
$table['access']." as access ,".
$table['node']." as node ".
"where user.user_id='{$authId}' and user.role_id=role.id and ( access.role_id=role.id or (access.role_id=role.pid and role.pid!=0 ) ) and role.status=1 and access.node_id=node.id and node.level=2 and node.pid={$appId} and node.status=1";
$modules = $db->query($sql);
// 判断是否存在公共模块的权限
$publicAction = array();
foreach($modules as $key=>$module) {
$moduleId = $module['id'];
$moduleName = $module['name'];
if('PUBLIC'== strtoupper($moduleName)) {
$sql = "select node.id,node.name from ".
$table['role']." as role,".
$table['user']." as user,".
$table['access']." as access ,".
$table['node']." as node ".
"where user.user_id='{$authId}' and user.role_id=role.id and ( access.role_id=role.id or (access.role_id=role.pid and role.pid!=0 ) ) and role.status=1 and access.node_id=node.id and node.level=3 and node.pid={$moduleId} and node.status=1";
$rs = $db->query($sql);
foreach ($rs as $a){
$publicAction[$a['name']] = $a['id'];
}
unset($modules[$key]);
break;
}
}
// 依次读取模块的操作权限
foreach($modules as $key=>$module) {
$moduleId = $module['id'];
$moduleName = $module['name'];
$sql = "select node.id,node.name from ".
$table['role']." as role,".
$table['user']." as user,".
$table['access']." as access ,".
$table['node']." as node ".
"where user.user_id='{$authId}' and user.role_id=role.id and ( access.role_id=role.id or (access.role_id=role.pid and role.pid!=0 ) ) and role.status=1 and access.node_id=node.id and node.level=3 and node.pid={$moduleId} and node.status=1";
$rs = $db->query($sql);
$action = array();
foreach ($rs as $a){
$action[$a['name']] = $a['id'];
}
// 和公共模块的操作权限合并
$action += $publicAction;
$access[strtoupper($appName)][strtoupper($moduleName)] = array_change_key_case($action,CASE_UPPER);
}
}
return $access;
}
// 读取模块所属的记录访问权限
static public function getModuleAccessList($authId,$module) {
// Db方式
$db = Db::getInstance(C('RBAC_DB_DSN'));
$table = array('role'=>C('RBAC_ROLE_TABLE'),'user'=>C('RBAC_USER_TABLE'),'access'=>C('RBAC_ACCESS_TABLE'));
$sql = "select access.node_id from ".
$table['role']." as role,".
$table['user']." as user,".
$table['access']." as access ".
"where user.user_id='{$authId}' and user.role_id=role.id and ( access.role_id=role.id or (access.role_id=role.pid and role.pid!=0 ) ) and role.status=1 and access.module='{$module}' and access.status=1";
$rs = $db->query($sql);
$access = array();
foreach ($rs as $node){
$access[] = $node['node_id'];
}
return $access;
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/RBAC.class.php | PHP | asf20 | 13,347 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Debug.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* 系统调试类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id: Debug.class.php 2702 2012-02-02 12:35:01Z liu21st $
+------------------------------------------------------------------------------
*/
class Debug {
static private $marker = array();
/**
+----------------------------------------------------------
* 标记调试位
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 要标记的位置名称
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function mark($name) {
self::$marker['time'][$name] = microtime(TRUE);
if(MEMORY_LIMIT_ON) {
self::$marker['mem'][$name] = memory_get_usage();
self::$marker['peak'][$name] = function_exists('memory_get_peak_usage')?memory_get_peak_usage(): self::$marker['mem'][$name];
}
}
/**
+----------------------------------------------------------
* 区间使用时间查看
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $start 开始标记的名称
* @param string $end 结束标记的名称
* @param integer $decimals 时间的小数位
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
static public function useTime($start,$end,$decimals = 6) {
if ( ! isset(self::$marker['time'][$start]))
return '';
if ( ! isset(self::$marker['time'][$end]))
self::$marker['time'][$end] = microtime(TRUE);
return number_format(self::$marker['time'][$end] - self::$marker['time'][$start], $decimals);
}
/**
+----------------------------------------------------------
* 区间使用内存查看
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $start 开始标记的名称
* @param string $end 结束标记的名称
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
static public function useMemory($start,$end) {
if(!MEMORY_LIMIT_ON)
return '';
if ( ! isset(self::$marker['mem'][$start]))
return '';
if ( ! isset(self::$marker['mem'][$end]))
self::$marker['mem'][$end] = memory_get_usage();
return number_format((self::$marker['mem'][$end] - self::$marker['mem'][$start])/1024);
}
/**
+----------------------------------------------------------
* 区间使用内存峰值查看
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $start 开始标记的名称
* @param string $end 结束标记的名称
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
static function getMemPeak($start,$end) {
if(!MEMORY_LIMIT_ON)
return '';
if ( ! isset(self::$marker['peak'][$start]))
return '';
if ( ! isset(self::$marker['peak'][$end]))
self::$marker['peak'][$end] = function_exists('memory_get_peak_usage')?memory_get_peak_usage(): memory_get_usage();
return number_format(max(self::$marker['peak'][$start],self::$marker['peak'][$end])/1024);
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/Debug.class.php | PHP | asf20 | 4,894 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Input.class.php 2528 2012-01-03 14:58:50Z liu21st $
/** 输入数据管理类
* 使用方法
* $Input = Input::getInstance();
* $Input->get('name','md5','0');
* $Input->session('memberId','','0');
*
* 下面总结了一些常用的数据处理方法。以下方法无需考虑magic_quotes_gpc的设置。
*
* 获取数据:
* 如果从$_POST或者$_GET中获取,使用Input::getVar($_POST['field']);,从数据库或者文件就不需要了。
* 或者直接使用 Input::magicQuotes来消除所有的magic_quotes_gpc转义。
*
* 存储过程:
* 经过Input::getVar($_POST['field'])获得的数据,就是干净的数据,可以直接保存。
* 如果要过滤危险的html,可以使用 $html = Input::safeHtml($data);
*
* 页面显示:
* 纯文本显示在网页中,如文章标题<title>$data</title>: $data = Input::forShow($field);
* HTML 在网页中显示,如文章内容:无需处理。
* 在网页中以源代码方式显示html:$vo = Input::forShow($html);
* 纯文本或者HTML在textarea中进行编辑: $vo = Input::forTarea($value);
* html在标签中使用,如<input value="数据" /> ,使用 $vo = Input::forTag($value); 或者 $vo = Input::hsc($value);
*
* 特殊使用情况:
* 字符串要在数据库进行搜索: $data = Input::forSearch($field);
*/
class Input {
private $filter = null; // 输入过滤
private static $_input = array('get','post','request','env','server','cookie','session','globals','config','lang','call');
//html标签设置
public static $htmlTags = array(
'allow' => 'table|td|th|tr|i|b|u|strong|img|p|br|div|strong|em|ul|ol|li|dl|dd|dt|a',
'ban' => 'html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|script|style|xml',
);
static public function getInstance() {
return get_instance_of(__CLASS__);
}
/**
+----------------------------------------------------------
* 魔术方法 有不存在的操作的时候执行
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $type 输入数据类型
* @param array $args 参数 array(key,filter,default)
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($type,$args=array()) {
$type = strtolower(trim($type));
if(in_array($type,self::$_input,true)) {
switch($type) {
case 'get': $input =& $_GET;break;
case 'post': $input =& $_POST;break;
case 'request': $input =& $_REQUEST;break;
case 'env': $input =& $_ENV;break;
case 'server': $input =& $_SERVER;break;
case 'cookie': $input =& $_COOKIE;break;
case 'session': $input =& $_SESSION;break;
case 'globals': $input =& $GLOBALS;break;
case 'files': $input =& $_FILES;break;
case 'call': $input = 'call';break;
case 'config': $input = C();break;
case 'lang': $input = L();break;
default:return NULL;
}
if('call' === $input) {
// 呼叫其他方式的输入数据
$callback = array_shift($args);
$params = array_shift($args);
$data = call_user_func_array($callback,$params);
if(count($args)===0) {
return $data;
}
$filter = isset($args[0])?$args[0]:$this->filter;
if(!empty($filter)) {
$data = call_user_func_array($filter,$data);
}
}else{
if(0==count($args) || empty($args[0]) ) {
return $input;
}elseif(array_key_exists($args[0],$input)) {
// 系统变量
$data = $input[$args[0]];
$filter = isset($args[1])?$args[1]:$this->filter;
if(!empty($filter)) {
$data = call_user_func_array($filter,$data);
}
}else{
// 不存在指定输入
$data = isset($args[2])?$args[2]:NULL;
}
}
return $data;
}
}
/**
+----------------------------------------------------------
* 设置数据过滤方法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param mixed $filter 过滤方法
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function filter($filter) {
$this->filter = $filter;
return $this;
}
/**
+----------------------------------------------------------
* 字符MagicQuote转义过滤
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function noGPC() {
if ( get_magic_quotes_gpc() ) {
$_POST = stripslashes_deep($_POST);
$_GET = stripslashes_deep($_GET);
$_COOKIE = stripslashes_deep($_COOKIE);
$_REQUEST= stripslashes_deep($_REQUEST);
}
}
/**
+----------------------------------------------------------
* 处理字符串,以便可以正常进行搜索
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function forSearch($string) {
return str_replace( array('%','_'), array('\%','\_'), $string );
}
/**
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function forShow($string) {
return self::nl2Br( self::hsc($string) );
}
/**
+----------------------------------------------------------
* 处理纯文本数据,以便在textarea标签中显示
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function forTarea($string) {
return str_ireplace(array('<textarea>','</textarea>'), array('<textarea>','</textarea>'), $string);
}
/**
+----------------------------------------------------------
* 将数据中的单引号和双引号进行转义
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function forTag($string) {
return str_replace(array('"',"'"), array('"','''), $string);
}
/**
+----------------------------------------------------------
* 转换文字中的超链接为可点击连接
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function makeLink($string) {
$validChars = "a-z0-9\/\-_+=.~!%@?#&;:$\|";
$patterns = array(
"/(^|[^]_a-z0-9-=\"'\/])([a-z]+?):\/\/([{$validChars}]+)/ei",
"/(^|[^]_a-z0-9-=\"'\/])www\.([a-z0-9\-]+)\.([{$validChars}]+)/ei",
"/(^|[^]_a-z0-9-=\"'\/])ftp\.([a-z0-9\-]+)\.([{$validChars}]+)/ei",
"/(^|[^]_a-z0-9-=\"'\/:\.])([a-z0-9\-_\.]+?)@([{$validChars}]+)/ei");
$replacements = array(
"'\\1<a href=\"\\2://\\3\" title=\"\\2://\\3\" rel=\"external\">\\2://'.Input::truncate( '\\3' ).'</a>'",
"'\\1<a href=\"http://www.\\2.\\3\" title=\"www.\\2.\\3\" rel=\"external\">'.Input::truncate( 'www.\\2.\\3' ).'</a>'",
"'\\1<a href=\"ftp://ftp.\\2.\\3\" title=\"ftp.\\2.\\3\" rel=\"external\">'.Input::truncate( 'ftp.\\2.\\3' ).'</a>'",
"'\\1<a href=\"mailto:\\2@\\3\" title=\"\\2@\\3\">'.Input::truncate( '\\2@\\3' ).'</a>'");
return preg_replace($patterns, $replacements, $string);
}
/**
+----------------------------------------------------------
* 缩略显示字符串
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的字符串
* @param int $length 缩略之后的长度
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function truncate($string, $length = '50') {
if ( empty($string) || empty($length) || strlen($string) < $length ) return $string;
$len = floor( $length / 2 );
$ret = substr($string, 0, $len) . " ... ". substr($string, 5 - $len);
return $ret;
}
/**
+----------------------------------------------------------
* 把换行转换为<br />标签
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function nl2Br($string) {
return preg_replace("/(\015\012)|(\015)|(\012)/", "<br />", $string);
}
/**
+----------------------------------------------------------
* 如果 magic_quotes_gpc 为关闭状态,这个函数可以转义字符串
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function addSlashes($string) {
if (!get_magic_quotes_gpc()) {
$string = addslashes($string);
}
return $string;
}
/**
+----------------------------------------------------------
* 从$_POST,$_GET,$_COOKIE,$_REQUEST等数组中获得数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function getVar($string) {
return Input::stripSlashes($string);
}
/**
+----------------------------------------------------------
* 如果 magic_quotes_gpc 为开启状态,这个函数可以反转义字符串
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function stripSlashes($string) {
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return $string;
}
/**
+----------------------------------------------------------
* 用于在textbox表单中显示html代码
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function hsc($string) {
return preg_replace(array("/&/i", "/ /i"), array('&', '&nbsp;'), htmlspecialchars($string, ENT_QUOTES));
}
/**
+----------------------------------------------------------
* 是hsc()方法的逆操作
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function undoHsc($text) {
return preg_replace(array("/>/i", "/</i", "/"/i", "/'/i", '/&nbsp;/i'), array(">", "<", "\"", "'", " "), $text);
}
/**
+----------------------------------------------------------
* 输出安全的html,用于过滤危险代码
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $text 要处理的字符串
* @param mixed $allowTags 允许的标签列表,如 table|td|th|td
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function safeHtml($text, $allowTags = null) {
$text = trim($text);
//完全过滤注释
$text = preg_replace('/<!--?.*-->/','',$text);
//完全过滤动态代码
$text = preg_replace('/<\?|\?'.'>/','',$text);
//完全过滤js
$text = preg_replace('/<script?.*\/script>/','',$text);
$text = str_replace('[','[',$text);
$text = str_replace(']',']',$text);
$text = str_replace('|','|',$text);
//过滤换行符
$text = preg_replace('/\r?\n/','',$text);
//br
$text = preg_replace('/<br(\s\/)?'.'>/i','[br]',$text);
$text = preg_replace('/(\[br\]\s*){10,}/i','[br]',$text);
//过滤危险的属性,如:过滤on事件lang js
while(preg_match('/(<[^><]+)(lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1],$text);
}
while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1].$mat[3],$text);
}
if( empty($allowTags) ) { $allowTags = self::$htmlTags['allow']; }
//允许的HTML标签
$text = preg_replace('/<('.$allowTags.')( [^><\[\]]*)>/i','[\1\2]',$text);
//过滤多余html
if ( empty($banTag) ) { $banTag = self::$htmlTags['ban']; }
$text = preg_replace('/<\/?('.$banTag.')[^><]*>/i','',$text);
//过滤合法的html标签
while(preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i',$text,$mat)){
$text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
}
//转换引号
while(preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2=\[\]]+)\2([^\[\]]*\])/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
}
//空属性转换
$text = str_replace('\'\'','||',$text);
$text = str_replace('""','||',$text);
//过滤错误的单个引号
while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i',$text,$mat)){
$text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
}
//转换其它所有不合法的 < >
$text = str_replace('<','<',$text);
$text = str_replace('>','>',$text);
$text = str_replace('"','"',$text);
//反转换
$text = str_replace('[','<',$text);
$text = str_replace(']','>',$text);
$text = str_replace('|','"',$text);
//过滤多余空格
$text = str_replace(' ',' ',$text);
return $text;
}
/**
+----------------------------------------------------------
* 删除html标签,得到纯文本。可以处理嵌套的标签
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的html
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function deleteHtmlTags($string) {
while(strstr($string, '>')) {
$currentBeg = strpos($string, '<');
$currentEnd = strpos($string, '>');
$tmpStringBeg = @substr($string, 0, $currentBeg);
$tmpStringEnd = @substr($string, $currentEnd + 1, strlen($string));
$string = $tmpStringBeg.$tmpStringEnd;
}
return $string;
}
/**
+----------------------------------------------------------
* 处理文本中的换行
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $string 要处理的字符串
* @param mixed $br 对换行的处理,
* false:去除换行;true:保留原样;string:替换成string
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function nl2($string, $br = '<br />') {
if ($br == false) {
$string = preg_replace("/(\015\012)|(\015)|(\012)/", '', $string);
} elseif ($br != true){
$string = preg_replace("/(\015\012)|(\015)|(\012)/", $br, $string);
}
return $string;
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/Input.class.php | PHP | asf20 | 20,332 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Page.class.php 2712 2012-02-06 10:12:49Z liu21st $
class Page {
// 分页栏每页显示的页数
public $rollPage = 5;
// 页数跳转时要带的参数
public $parameter ;
// 默认列表每页显示行数
public $listRows = 20;
// 起始行数
public $firstRow ;
// 分页总页面数
protected $totalPages ;
// 总行数
protected $totalRows ;
// 当前页数
protected $nowPage ;
// 分页的栏的总页数
protected $coolPages ;
// 分页显示定制
protected $config = array('header'=>'条记录','prev'=>'上一页','next'=>'下一页','first'=>'第一页','last'=>'最后一页','theme'=>' %totalRow% %header% %nowPage%/%totalPage% 页 %upPage% %downPage% %first% %prePage% %linkPage% %nextPage% %end%');
// 默认分页变量名
protected $varPage;
public $lanjief;//url参数的连接符
public $wenhaof;//url参数中的问号符
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $totalRows 总的记录数
* @param array $listRows 每页显示记录数
* @param array $parameter 分页跳转的参数
+----------------------------------------------------------
*/
public function __construct($totalRows,$listRows='',$parameter='') {
$this->totalRows = $totalRows;
$this->parameter = $parameter;
$this->lanjief=C("URL_PATHINFO_DEPR");
$this->wenhaof=C("URL_PATHINFO_DEPR");
$this->varPage = C('VAR_PAGE') ? C('VAR_PAGE') : 'p' ;
if(!empty($listRows)) {
$this->listRows = intval($listRows);
}
$this->totalPages = ceil($this->totalRows/$this->listRows); //总页数
$this->coolPages = ceil($this->totalPages/$this->rollPage);
$this->nowPage = !empty($_GET[$this->varPage])?intval($_GET[$this->varPage]):1;
if(!empty($this->totalPages) && $this->nowPage>$this->totalPages) {
$this->nowPage = $this->totalPages;
}
$this->firstRow = $this->listRows*($this->nowPage-1);
}
public function setConfig($name,$value) {
if(isset($this->config[$name])) {
$this->config[$name] = $value;
}
}
public function replacefenyp($url)
{
}
/**
+----------------------------------------------------------
* 分页显示输出
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function show() {
if(0 == $this->totalRows) return '';
$p = $this->varPage;
$nowCoolPage = ceil($this->nowPage/$this->rollPage);
$te=C("URL_PATHINFO_DEPR");
$tecan=C("URL_PATHINFO_DEPR_CAN");
//die("/".htmlspecialchars("\\").$te."p".htmlspecialchars("\\").$te."[\d]+/");
$REQUEST_URI=preg_replace("/".htmlspecialchars("\\").$tecan."p".htmlspecialchars("\\").$tecan."[\d]+/","",$_SERVER['REQUEST_URI']);
//if($te!=$tecan) $REQUEST_URI=Sys_formaturl($REQUEST_URI,$te,$tecan);
$url = $REQUEST_URI.$this->parameter;
$parse = parse_url($url);
$this->lanjief=$tecan;//由jroam添加,若不用,可以删除
if(isset($parse['query'])) {
parse_str($parse['query'],$params);
unset($params[$p]);
$url = $parse['path'].'".$this->wenhaof."'.http_build_query($params);
}
//上下翻页字符串
$upRow = $this->nowPage-1;
$downRow = $this->nowPage+1;
if ($upRow>0){
$upPage="<a href='".$url.$this->lanjief.$p.$this->lanjief.$upRow."'>".$this->config['prev']."</a>";
}else{
$upPage="";
}
if ($downRow <= $this->totalPages){
$downPage="<a href='".$url.$this->lanjief.$p.$this->lanjief."".$downRow."'>".$this->config['next']."</a>";
}else{
$downPage="";
}
// << < > >>
if($nowCoolPage == 1){
$theFirst = "";
$prePage = "";
}else{
$preRow = $this->nowPage-$this->rollPage;
$prePage = "<a href='".$url.$this->lanjief.$p.$this->lanjief."$preRow' >上".$this->rollPage."页</a>";
$theFirst = "<a href='".$url.$this->lanjief.$p.$this->lanjief."1' >".$this->config['first']."</a>";
}
if($nowCoolPage == $this->coolPages){
$nextPage = "";
$theEnd="";
}else{
$nextRow = $this->nowPage+$this->rollPage;
$theEndRow = $this->totalPages;
$nextPage = "<a href='".$url."".$this->lanjief."".$p."".$this->lanjief.$nextRow."' >下".$this->rollPage."页</a>";
$theEnd = "<a href='".$url.$this->lanjief.$p.$this->lanjief."$theEndRow' >".$this->config['last']."</a>";
}
// 1 2 3 4 5
$linkPage = "";
for($i=1;$i<=$this->rollPage;$i++){
$page=($nowCoolPage-1)*$this->rollPage+$i;
if($page!=$this->nowPage){
if($page<=$this->totalPages){
$linkPage .= " <a href='".$url.$this->lanjief.$p.$this->lanjief."$page'> ".$page." </a>";
}else{
break;
}
}else{
if($this->totalPages != 1){
$linkPage .= " <span class='current'>".$page."</span>";
}
}
}
$pageStr = str_replace(
array('%header%','%nowPage%','%totalRow%','%totalPage%','%upPage%','%downPage%','%first%','%prePage%','%linkPage%','%nextPage%','%end%'),
array($this->config['header'],$this->nowPage,$this->totalRows,$this->totalPages,$upPage,$downPage,$theFirst,$prePage,$linkPage,$nextPage,$theEnd),$this->config['theme']);
return $pageStr;
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/Page.class.php | PHP | asf20 | 6,877 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Image.class.php 2708 2012-02-06 04:10:11Z liu21st $
/**
+------------------------------------------------------------------------------
* 图像操作类库
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id: Image.class.php 2708 2012-02-06 04:10:11Z liu21st $
+------------------------------------------------------------------------------
*/
class Image {
/**
+----------------------------------------------------------
* 取得图像信息
*
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $image 图像文件名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
static function getImageInfo($img) {
$imageInfo = getimagesize($img);
if ($imageInfo !== false) {
$imageType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
$imageSize = filesize($img);
$info = array(
"width" => $imageInfo[0],
"height" => $imageInfo[1],
"type" => $imageType,
"size" => $imageSize,
"mime" => $imageInfo['mime']
);
return $info;
} else {
return false;
}
}
/**
+----------------------------------------------------------
* 为图片添加水印
+----------------------------------------------------------
* @static public
+----------------------------------------------------------
* @param string $source 原文件名
* @param string $water 水印图片
* @param string $$savename 添加水印后的图片名
* @param string $alpha 水印的透明度
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function water($source, $water, $savename=null, $alpha=80) {
//检查文件是否存在
if (!file_exists($source) || !file_exists($water))
return false;
//图片信息
$sInfo = self::getImageInfo($source);
$wInfo = self::getImageInfo($water);
//如果图片小于水印图片,不生成图片
if ($sInfo["width"] < $wInfo["width"] || $sInfo['height'] < $wInfo['height'])
return false;
//建立图像
$sCreateFun = "imagecreatefrom" . $sInfo['type'];
$sImage = $sCreateFun($source);
$wCreateFun = "imagecreatefrom" . $wInfo['type'];
$wImage = $wCreateFun($water);
//设定图像的混色模式
imagealphablending($wImage, true);
//图像位置,默认为右下角右对齐
$posY = $sInfo["height"] - $wInfo["height"];
$posX = $sInfo["width"] - $wInfo["width"];
//生成混合图像
imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo['width'], $wInfo['height'], $alpha);
//输出图像
$ImageFun = 'Image' . $sInfo['type'];
//如果没有给出保存文件名,默认为原图像名
if (!$savename) {
$savename = $source;
@unlink($source);
}
//保存图像
$ImageFun($sImage, $savename);
imagedestroy($sImage);
}
function showImg($imgFile, $text='', $x='10', $y='10', $alpha='50') {
//获取图像文件信息
//2007/6/26 增加图片水印输出,$text为图片的完整路径即可
$info = Image::getImageInfo($imgFile);
if ($info !== false) {
$createFun = str_replace('/', 'createfrom', $info['mime']);
$im = $createFun($imgFile);
if ($im) {
$ImageFun = str_replace('/', '', $info['mime']);
//水印开始
if (!empty($text)) {
$tc = imagecolorallocate($im, 0, 0, 0);
if (is_file($text) && file_exists($text)) {//判断$text是否是图片路径
// 取得水印信息
$textInfo = Image::getImageInfo($text);
$createFun2 = str_replace('/', 'createfrom', $textInfo['mime']);
$waterMark = $createFun2($text);
//$waterMark=imagecolorallocatealpha($text,255,255,0,50);
$imgW = $info["width"];
$imgH = $info["width"] * $textInfo["height"] / $textInfo["width"];
//$y = ($info["height"]-$textInfo["height"])/2;
//设置水印的显示位置和透明度支持各种图片格式
imagecopymerge($im, $waterMark, $x, $y, 0, 0, $textInfo['width'], $textInfo['height'], $alpha);
} else {
imagestring($im, 80, $x, $y, $text, $tc);
}
//ImageDestroy($tc);
}
//水印结束
if ($info['type'] == 'png' || $info['type'] == 'gif') {
imagealphablending($im, FALSE); //取消默认的混色模式
imagesavealpha($im, TRUE); //设定保存完整的 alpha 通道信息
}
Header("Content-type: " . $info['mime']);
$ImageFun($im);
@ImageDestroy($im);
return;
}
//保存图像
$ImageFun($sImage, $savename);
imagedestroy($sImage);
//获取或者创建图像文件失败则生成空白PNG图片
$im = imagecreatetruecolor(80, 30);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
imagestring($im, 4, 5, 5, "no pic", $tc);
Image::output($im);
return;
}
}
/**
+----------------------------------------------------------
* 生成缩略图
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $image 原图
* @param string $type 图像格式
* @param string $thumbname 缩略图文件名
* @param string $maxWidth 宽度
* @param string $maxHeight 高度
* @param string $position 缩略图保存目录
* @param boolean $interlace 启用隔行扫描
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function thumb($image, $thumbname, $type='', $maxWidth=200, $maxHeight=50, $interlace=true) {
// 获取原图信息
$info = Image::getImageInfo($image);
if ($info !== false) {
$srcWidth = $info['width'];
$srcHeight = $info['height'];
$type = empty($type) ? $info['type'] : $type;
$type = strtolower($type);
$interlace = $interlace ? 1 : 0;
unset($info);
$scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight); // 计算缩放比例
if ($scale >= 1) {
// 超过原图大小不再缩略
$width = $srcWidth;
$height = $srcHeight;
} else {
// 缩略图尺寸
$width = (int) ($srcWidth * $scale);
$height = (int) ($srcHeight * $scale);
}
// 载入原图
$createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
$srcImg = $createFun($image);
//创建缩略图
if ($type != 'gif' && function_exists('imagecreatetruecolor'))
$thumbImg = imagecreatetruecolor($width, $height);
else
$thumbImg = imagecreate($width, $height);
// 复制图片
if (function_exists("ImageCopyResampled"))
imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
else
imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
if ('gif' == $type || 'png' == $type) {
//imagealphablending($thumbImg, false);//取消默认的混色模式
//imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息
$background_color = imagecolorallocate($thumbImg, 0, 255, 0); // 指派一个绿色
imagecolortransparent($thumbImg, $background_color); // 设置为透明色,若注释掉该行则输出绿色的图
}
// 对jpeg图形设置隔行扫描
if ('jpg' == $type || 'jpeg' == $type)
imageinterlace($thumbImg, $interlace);
// 生成图片
$imageFun = 'image' . ($type == 'jpg' ? 'jpeg' : $type);
$imageFun($thumbImg, $thumbname);
imagedestroy($thumbImg);
imagedestroy($srcImg);
return $thumbname;
}
return false;
}
/**
+----------------------------------------------------------
* 根据给定的字符串生成图像
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $string 字符串
* @param string $size 图像大小 width,height 或者 array(width,height)
* @param string $font 字体信息 fontface,fontsize 或者 array(fontface,fontsize)
* @param string $type 图像格式 默认PNG
* @param integer $disturb 是否干扰 1 点干扰 2 线干扰 3 复合干扰 0 无干扰
* @param bool $border 是否加边框 array(color)
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function buildString($string, $rgb=array(), $filename='', $type='png', $disturb=1, $border=true) {
if (is_string($size))
$size = explode(',', $size);
$width = $size[0];
$height = $size[1];
if (is_string($font))
$font = explode(',', $font);
$fontface = $font[0];
$fontsize = $font[1];
$length = strlen($string);
$width = ($length * 9 + 10) > $width ? $length * 9 + 10 : $width;
$height = 22;
if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
$im = @imagecreatetruecolor($width, $height);
} else {
$im = @imagecreate($width, $height);
}
if (empty($rgb)) {
$color = imagecolorallocate($im, 102, 104, 104);
} else {
$color = imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]);
}
$backColor = imagecolorallocate($im, 255, 255, 255); //背景色(随机)
$borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
$pointColor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); //点颜色
@imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
@imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
@imagestring($im, 5, 5, 3, $string, $color);
if (!empty($disturb)) {
// 添加干扰
if ($disturb = 1 || $disturb = 3) {
for ($i = 0; $i < 25; $i++) {
imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $pointColor);
}
} elseif ($disturb = 2 || $disturb = 3) {
for ($i = 0; $i < 10; $i++) {
imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $pointColor);
}
}
}
Image::output($im, $type, $filename);
}
/**
+----------------------------------------------------------
* 生成图像验证码
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $length 位数
* @param string $mode 类型
* @param string $type 图像格式
* @param string $width 宽度
* @param string $height 高度
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function buildImageVerify($length=4, $mode=1, $type='png', $width=48, $height=22, $verifyName='verify') {
import('ORG.Util.String');
$randval = String::randString($length, $mode);
$_SESSION[$verifyName] = md5($randval);
$width = ($length * 10 + 10) > $width ? $length * 10 + 10 : $width;
if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
$im = imagecreatetruecolor($width, $height);
} else {
$im = imagecreate($width, $height);
}
$r = Array(225, 255, 255, 223);
$g = Array(225, 236, 237, 255);
$b = Array(225, 236, 166, 125);
$key = mt_rand(0, 3);
$backColor = imagecolorallocate($im, $r[$key], $g[$key], $b[$key]); //背景色(随机)
$borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
$stringColor = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));
// 干扰
for ($i = 0; $i < 10; $i++) {
imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $stringColor);
}
for ($i = 0; $i < 25; $i++) {
imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $stringColor);
}
for ($i = 0; $i < $length; $i++) {
imagestring($im, 5, $i * 10 + 5, mt_rand(1, 8), $randval{$i}, $stringColor);
}
Image::output($im, $type);
}
// 中文验证码
static function GBVerify($length=4, $type='png', $width=180, $height=50, $fontface='simhei.ttf', $verifyName='verify') {
import('ORG.Util.String');
$code = String::randString($length, 4);
$width = ($length * 45) > $width ? $length * 45 : $width;
$_SESSION[$verifyName] = md5($code);
$im = imagecreatetruecolor($width, $height);
$borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
$bkcolor = imagecolorallocate($im, 250, 250, 250);
imagefill($im, 0, 0, $bkcolor);
@imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
// 干扰
for ($i = 0; $i < 15; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $fontcolor);
}
for ($i = 0; $i < 255; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $fontcolor);
}
if (!is_file($fontface)) {
$fontface = dirname(__FILE__) . "/" . $fontface;
}
for ($i = 0; $i < $length; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120)); //这样保证随机出来的颜色较深。
$codex = String::msubstr($code, $i, 1);
imagettftext($im, mt_rand(16, 20), mt_rand(-60, 60), 40 * $i + 20, mt_rand(30, 35), $fontcolor, $fontface, $codex);
}
Image::output($im, $type);
}
/**
+----------------------------------------------------------
* 把图像转换成字符显示
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $image 要显示的图像
* @param string $type 图像类型,默认自动获取
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function showASCIIImg($image, $string='', $type='') {
$info = Image::getImageInfo($image);
if ($info !== false) {
$type = empty($type) ? $info['type'] : $type;
unset($info);
// 载入原图
$createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
$im = $createFun($image);
$dx = imagesx($im);
$dy = imagesy($im);
$i = 0;
$out = '<span style="padding:0px;margin:0;line-height:100%;font-size:1px;">';
set_time_limit(0);
for ($y = 0; $y < $dy; $y++) {
for ($x = 0; $x < $dx; $x++) {
$col = imagecolorat($im, $x, $y);
$rgb = imagecolorsforindex($im, $col);
$str = empty($string) ? '*' : $string[$i++];
$out .= sprintf('<span style="margin:0px;color:#%02x%02x%02x">' . $str . '</span>', $rgb['red'], $rgb['green'], $rgb['blue']);
}
$out .= "<br>\n";
}
$out .= '</span>';
imagedestroy($im);
return $out;
}
return false;
}
/**
+----------------------------------------------------------
* 生成UPC-A条形码
+----------------------------------------------------------
* @static
+----------------------------------------------------------
* @param string $type 图像格式
* @param string $type 图像格式
* @param string $lw 单元宽度
* @param string $hi 条码高度
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function UPCA($code, $type='png', $lw=2, $hi=100) {
static $Lencode = array('0001101', '0011001', '0010011', '0111101', '0100011',
'0110001', '0101111', '0111011', '0110111', '0001011');
static $Rencode = array('1110010', '1100110', '1101100', '1000010', '1011100',
'1001110', '1010000', '1000100', '1001000', '1110100');
$ends = '101';
$center = '01010';
/* UPC-A Must be 11 digits, we compute the checksum. */
if (strlen($code) != 11) {
die("UPC-A Must be 11 digits.");
}
/* Compute the EAN-13 Checksum digit */
$ncode = '0' . $code;
$even = 0;
$odd = 0;
for ($x = 0; $x < 12; $x++) {
if ($x % 2) {
$odd += $ncode[$x];
} else {
$even += $ncode[$x];
}
}
$code.= ( 10 - (($odd * 3 + $even) % 10)) % 10;
/* Create the bar encoding using a binary string */
$bars = $ends;
$bars.=$Lencode[$code[0]];
for ($x = 1; $x < 6; $x++) {
$bars.=$Lencode[$code[$x]];
}
$bars.=$center;
for ($x = 6; $x < 12; $x++) {
$bars.=$Rencode[$code[$x]];
}
$bars.=$ends;
/* Generate the Barcode Image */
if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
$im = imagecreatetruecolor($lw * 95 + 30, $hi + 30);
} else {
$im = imagecreate($lw * 95 + 30, $hi + 30);
}
$fg = ImageColorAllocate($im, 0, 0, 0);
$bg = ImageColorAllocate($im, 255, 255, 255);
ImageFilledRectangle($im, 0, 0, $lw * 95 + 30, $hi + 30, $bg);
$shift = 10;
for ($x = 0; $x < strlen($bars); $x++) {
if (($x < 10) || ($x >= 45 && $x < 50) || ($x >= 85)) {
$sh = 10;
} else {
$sh = 0;
}
if ($bars[$x] == '1') {
$color = $fg;
} else {
$color = $bg;
}
ImageFilledRectangle($im, ($x * $lw) + 15, 5, ($x + 1) * $lw + 14, $hi + 5 + $sh, $color);
}
/* Add the Human Readable Label */
ImageString($im, 4, 5, $hi - 5, $code[0], $fg);
for ($x = 0; $x < 5; $x++) {
ImageString($im, 5, $lw * (13 + $x * 6) + 15, $hi + 5, $code[$x + 1], $fg);
ImageString($im, 5, $lw * (53 + $x * 6) + 15, $hi + 5, $code[$x + 6], $fg);
}
ImageString($im, 4, $lw * 95 + 17, $hi - 5, $code[11], $fg);
/* Output the Header and Content. */
Image::output($im, $type);
}
static function output($im, $type='png', $filename='') {
header("Content-type: image/" . $type);
$ImageFun = 'image' . $type;
if (empty($filename)) {
$ImageFun($im);
} else {
$ImageFun($im, $filename);
}
imagedestroy($im);
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/Image.class.php | PHP | asf20 | 22,698 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: String.class.php 2661 2012-01-26 03:00:18Z liu21st $
class String {
/**
+----------------------------------------------------------
* 生成UUID 单机使用
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function uuid() {
$charid = md5(uniqid(mt_rand(), true));
$hyphen = chr(45);// "-"
$uuid = chr(123)// "{"
.substr($charid, 0, 8).$hyphen
.substr($charid, 8, 4).$hyphen
.substr($charid,12, 4).$hyphen
.substr($charid,16, 4).$hyphen
.substr($charid,20,12)
.chr(125);// "}"
return $uuid;
}
/**
+----------------------------------------------------------
* 生成Guid主键
+----------------------------------------------------------
* @return Boolean
+----------------------------------------------------------
*/
static public function keyGen() {
return str_replace('-','',substr(String::uuid(),1,-1));
}
/**
+----------------------------------------------------------
* 检查字符串是否是UTF8编码
+----------------------------------------------------------
* @param string $string 字符串
+----------------------------------------------------------
* @return Boolean
+----------------------------------------------------------
*/
static public function isUtf8($str) {
$c=0; $b=0;
$bits=0;
$len=strlen($str);
for($i=0; $i<$len; $i++){
$c=ord($str[$i]);
if($c > 128){
if(($c >= 254)) return false;
elseif($c >= 252) $bits=6;
elseif($c >= 248) $bits=5;
elseif($c >= 240) $bits=4;
elseif($c >= 224) $bits=3;
elseif($c >= 192) $bits=2;
else return false;
if(($i+$bits) > $len) return false;
while($bits > 1){
$i++;
$b=ord($str[$i]);
if($b < 128 || $b > 191) return false;
$bits--;
}
}
}
return true;
}
/**
+----------------------------------------------------------
* 字符串截取,支持中文和其他编码
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $str 需要转换的字符串
* @param string $start 开始位置
* @param string $length 截取长度
* @param string $charset 编码格式
* @param string $suffix 截断显示字符
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
if(function_exists("mb_substr"))
$slice = mb_substr($str, $start, $length, $charset);
elseif(function_exists('iconv_substr')) {
$slice = iconv_substr($str,$start,$length,$charset);
}else{
$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
preg_match_all($re[$charset], $str, $match);
$slice = join("",array_slice($match[0], $start, $length));
}
return $suffix ? $slice.'...' : $slice;
}
/**
+----------------------------------------------------------
* 产生随机字串,可用来自动生成密码
* 默认长度6位 字母和数字混合 支持中文
+----------------------------------------------------------
* @param string $len 长度
* @param string $type 字串类型
* 0 字母 1 数字 其它 混合
* @param string $addChars 额外字符
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function randString($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;
case 4:
$chars = "们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩康遵牧遭幅园腔订香肉弟屋敏恢忘编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航衣孙龄岭骗休借".$addChars;
break;
default :
// 默认去掉了容易混淆的字符oOLl和数字01,要添加请使用addChars参数
$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.= self::msubstr($chars, floor(mt_rand(0,mb_strlen($chars,'utf-8')-1)),1,'utf-8',false);
}
}
return $str;
}
/**
+----------------------------------------------------------
* 生成一定数量的随机数,并且不重复
+----------------------------------------------------------
* @param integer $number 数量
* @param string $len 长度
* @param string $type 字串类型
* 0 字母 1 数字 其它 混合
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function buildCountRand ($number,$length=4,$mode=1) {
if($mode==1 && $length<strlen($number) ) {
//不足以生成一定数量的不重复数字
return false;
}
$rand = array();
for($i=0; $i<$number; $i++) {
$rand[] = self::randString($length,$mode);
}
$unqiue = array_unique($rand);
if(count($unqiue)==count($rand)) {
return $rand;
}
$count = count($rand)-count($unqiue);
for($i=0; $i<$count*3; $i++) {
$rand[] = self::randString($length,$mode);
}
$rand = array_slice(array_unique ($rand),0,$number);
return $rand;
}
/**
+----------------------------------------------------------
* 带格式生成随机字符 支持批量生成
* 但可能存在重复
+----------------------------------------------------------
* @param string $format 字符格式
* # 表示数字 * 表示字母和数字 $ 表示字母
* @param integer $number 生成数量
+----------------------------------------------------------
* @return string | array
+----------------------------------------------------------
*/
static public function buildFormatRand($format,$number=1) {
$str = array();
$length = strlen($format);
for($j=0; $j<$number; $j++) {
$strtemp = '';
for($i=0; $i<$length; $i++) {
$char = substr($format,$i,1);
switch($char){
case "*"://字母和数字混合
$strtemp .= String::randString(1);
break;
case "#"://数字
$strtemp .= String::randString(1,1);
break;
case "$"://大写字母
$strtemp .= String::randString(1,2);
break;
default://其他格式均不转换
$strtemp .= $char;
break;
}
}
$str[] = $strtemp;
}
return $number==1? $strtemp : $str ;
}
/**
+----------------------------------------------------------
* 获取一定范围内的随机数字 位数不足补零
+----------------------------------------------------------
* @param integer $min 最小值
* @param integer $max 最大值
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static public function randNumber ($min, $max) {
return sprintf("%0".strlen($max)."d", mt_rand($min,$max));
}
// 自动转换字符集 支持数组转换
static public function autoCharset($string, $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($string) || (is_scalar($string) && !is_string($string))) {
//如果编码相同或者非字符串标量则不转换
return $string;
}
if (is_string($string)) {
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($string, $to, $from);
} elseif (function_exists('iconv')) {
return iconv($from, $to, $string);
} else {
return $string;
}
} elseif (is_array($string)) {
foreach ($string as $key => $val) {
$_key = self::autoCharset($key, $from, $to);
$string[$_key] = self::autoCharset($val, $from, $to);
if ($key != $_key)
unset($string[$key]);
}
return $string;
}
else {
return $string;
}
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/String.class.php | PHP | asf20 | 14,518 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Session.class.php 2702 2012-02-02 12:35:01Z liu21st $
define("HTTP_SESSION_STARTED", 1);
define("HTTP_SESSION_CONTINUED", 2);
/**
+------------------------------------------------------------------------------
* Session管理类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id: Session.class.php 2702 2012-02-02 12:35:01Z liu21st $
+------------------------------------------------------------------------------
*/
class Session {
/**
+----------------------------------------------------------
* 启动Session
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function start() {
session_start();
if (!isset($_SESSION['__HTTP_Session_Info'])) {
$_SESSION['__HTTP_Session_Info'] = HTTP_SESSION_STARTED;
} else {
$_SESSION['__HTTP_Session_Info'] = HTTP_SESSION_CONTINUED;
}
Session::setExpire(C('SESSION_EXPIRE'));
}
/**
+----------------------------------------------------------
* 暂停Session
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function pause() {
session_write_close();
}
/**
+----------------------------------------------------------
* 清空Session
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function clearLocal() {
$local = Session::localName();
unset($_SESSION[$local]);
}
/**
+----------------------------------------------------------
* 清空Session
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function clear() {
$_SESSION = array();
}
/**
+----------------------------------------------------------
* 销毁Session
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function destroy() {
unset($_SESSION);
session_destroy();
}
/**
+----------------------------------------------------------
* 检测SessionID
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function detectID() {
if(session_id()!='') {
return session_id();
}
if (Session::useCookies()) {
if (isset($_COOKIE[Session::name()])) {
return $_COOKIE[Session::name()];
}
} else {
if (isset($_GET[Session::name()])) {
return $_GET[Session::name()];
}
if (isset($_POST[Session::name()])) {
return $_POST[Session::name()];
}
}
return null;
}
/**
+----------------------------------------------------------
* 设置或者获取当前Session name
+----------------------------------------------------------
* @param string $name session名称
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return string 返回之前的Session name
+----------------------------------------------------------
*/
static function name($name = null) {
return isset($name) ? session_name($name) : session_name();
}
/**
+----------------------------------------------------------
* 设置或者获取当前SessionID
+----------------------------------------------------------
* @param string $id sessionID
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return void 返回之前的sessionID
+----------------------------------------------------------
*/
static function id($id = null) {
return isset($id) ? session_id($id) : session_id();
}
/**
+----------------------------------------------------------
* 设置或者获取当前Session保存路径
+----------------------------------------------------------
* @param string $path 保存路径名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function path($path = null) {
return !empty($path)? session_save_path($path):session_save_path();
}
/**
+----------------------------------------------------------
* 设置Session 过期时间
+----------------------------------------------------------
* @param integer $time 过期时间
* @param boolean $add 是否为增加时间
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function setExpire($time, $add = false) {
if ($add) {
if (!isset($_SESSION['__HTTP_Session_Expire_TS'])) {
$_SESSION['__HTTP_Session_Expire_TS'] = time() + $time;
}
// update session.gc_maxlifetime
$currentGcMaxLifetime = Session::setGcMaxLifetime(null);
Session::setGcMaxLifetime($currentGcMaxLifetime + $time);
} elseif (!isset($_SESSION['__HTTP_Session_Expire_TS'])) {
$_SESSION['__HTTP_Session_Expire_TS'] = $time;
}
}
/**
+----------------------------------------------------------
* 设置Session 闲置时间
+----------------------------------------------------------
* @param integer $time 闲置时间
* @param boolean $add 是否为增加时间
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function setIdle($time, $add = false) {
if ($add) {
$_SESSION['__HTTP_Session_Idle'] = $time;
} else {
$_SESSION['__HTTP_Session_Idle'] = $time - time();
}
}
/**
+----------------------------------------------------------
* 取得Session 有效时间
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function sessionValidThru() {
if (!isset($_SESSION['__HTTP_Session_Idle_TS']) || !isset($_SESSION['__HTTP_Session_Idle'])) {
return 0;
} else {
return $_SESSION['__HTTP_Session_Idle_TS'] + $_SESSION['__HTTP_Session_Idle'];
}
}
/**
+----------------------------------------------------------
* 检查Session 是否过期
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
static function isExpired() {
if (isset($_SESSION['__HTTP_Session_Expire_TS']) && $_SESSION['__HTTP_Session_Expire_TS'] < time()) {
return true;
} else {
return false;
}
}
/**
+----------------------------------------------------------
* 检查Session 是否闲置
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function isIdle() {
if (isset($_SESSION['__HTTP_Session_Idle_TS']) && (($_SESSION['__HTTP_Session_Idle_TS'] + $_SESSION['__HTTP_Session_Idle']) < time())) {
return true;
} else {
return false;
}
}
/**
+----------------------------------------------------------
* 更新Session 闲置时间
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function updateIdle() {
$_SESSION['__HTTP_Session_Idle_TS'] = time();
}
/**
+----------------------------------------------------------
* 设置Session 对象反序列化时候的回调函数
* 返回之前设置
+----------------------------------------------------------
* @param string $callback 回调函数方法名
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
static function setCallback($callback = null) {
$return = ini_get('unserialize_callback_func');
if (!empty($callback)) {
ini_set('unserialize_callback_func',$callback);
}
return $return;
}
/**
+----------------------------------------------------------
* 设置Session 是否使用cookie
* 返回之前设置
+----------------------------------------------------------
* @param boolean $useCookies 是否使用cookie
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
static function useCookies($useCookies = null) {
$return = ini_get('session.use_cookies') ? true : false;
if (isset($useCookies)) {
ini_set('session.use_cookies', $useCookies ? 1 : 0);
}
return $return;
}
/**
+----------------------------------------------------------
* 检查Session 是否新建
+----------------------------------------------------------
* @param boolean $useCookies 是否使用cookie
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
static function isNew() {
return !isset($_SESSION['__HTTP_Session_Info']) ||
$_SESSION['__HTTP_Session_Info'] == HTTP_SESSION_STARTED;
}
/**
+----------------------------------------------------------
* 取得当前项目的Session 值
* 返回之前设置
+----------------------------------------------------------
* @param string $name
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
static function getLocal($name) {
$local = Session::localName();
if (!is_array($_SESSION[$local])) {
$_SESSION[$local] = array();
}
return $_SESSION[$local][$name];
}
/**
+----------------------------------------------------------
* 取得当前项目的Session 值
* 返回之前设置
+----------------------------------------------------------
* @param string $name
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
static function get($name) {
if(isset($_SESSION[$name])) {
return $_SESSION[$name];
}else {
return null;
}
}
/**
+----------------------------------------------------------
* 设置当前项目的Session 值
* 返回之前设置
+----------------------------------------------------------
* @param string $name
* @param mixed $value
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
static function setLocal($name, $value) {
$local = Session::localName();
if (!is_array($_SESSION[$local])) {
$_SESSION[$local] = array();
}
if (null === $value) {
unset($_SESSION[$local][$name]);
} else {
$_SESSION[$local][$name] = $value;
}
return;
}
/**
+----------------------------------------------------------
* 设置当前项目的Session 值
* 返回之前设置
+----------------------------------------------------------
* @param string $name
* @param mixed $value
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
static function set($name, $value) {
if (null === $value) {
unset($_SESSION[$name]);
} else {
$_SESSION[$name] = $value;
}
return ;
}
/**
+----------------------------------------------------------
* 检查Session 值是否已经设置
+----------------------------------------------------------
* @param string $name
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
static function is_setLocal($name) {
$local = Session::localName();
return isset($_SESSION[$local][$name]);
}
/**
+----------------------------------------------------------
* 检查Session 值是否已经设置
+----------------------------------------------------------
* @param string $name
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
static function is_set($name) {
return isset($_SESSION[$name]);
}
/**
+----------------------------------------------------------
* 设置或者获取 Session localname
+----------------------------------------------------------
* @param string $name
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function localName($name = null) {
$return = (isset($GLOBALS['__HTTP_Session_Localname'])) ? $GLOBALS['__HTTP_Session_Localname'] : null;
if (!empty($name)) {
$GLOBALS['__HTTP_Session_Localname'] = md5($name);
}
return $return;
}
/**
+----------------------------------------------------------
* Session 初始化
+----------------------------------------------------------
* @static
* @access private
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
static function _init() {
ini_set('session.auto_start', 0);
if (is_null(Session::detectID())) {
Session::id(uniqid(dechex(mt_rand())));
}
// 设置Session有效域名
Session::setCookieDomain(C('COOKIE_DOMAIN'));
//设置当前项目运行脚本作为Session本地名
Session::localName(APP_NAME);
Session::name(C('SESSION_NAME'));
Session::path(C('SESSION_PATH'));
Session::setCallback(C('SESSION_CALLBACK'));
}
/**
+----------------------------------------------------------
* 设置Session use_trans_sid
* 返回之前设置
+----------------------------------------------------------
* @param string $useTransSID
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function useTransSID($useTransSID = null) {
$return = ini_get('session.use_trans_sid') ? true : false;
if (isset($useTransSID)) {
ini_set('session.use_trans_sid', $useTransSID ? 1 : 0);
}
return $return;
}
/**
+----------------------------------------------------------
* 设置Session cookie_domain
* 返回之前设置
+----------------------------------------------------------
* @param string $sessionDomain
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function setCookieDomain($sessionDomain = null) {
$return = ini_get('session.cookie_domain');
if(!empty($sessionDomain)) {
ini_set('session.cookie_domain', $sessionDomain);//跨域访问Session
}
return $return;
}
/**
+----------------------------------------------------------
* 设置Session gc_maxlifetime值
* 返回之前设置
+----------------------------------------------------------
* @param string $gc_maxlifetime
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function setGcMaxLifetime($gcMaxLifetime = null) {
$return = ini_get('session.gc_maxlifetime');
if (isset($gcMaxLifetime) && is_int($gcMaxLifetime) && $gcMaxLifetime >= 1) {
ini_set('session.gc_maxlifetime', $gcMaxLifetime);
}
return $return;
}
/**
+----------------------------------------------------------
* 设置Session gc_probability 值
* 返回之前设置
+----------------------------------------------------------
* @param string $gc_maxlifetime
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function setGcProbability($gcProbability = null) {
$return = ini_get('session.gc_probability');
if (isset($gcProbability) && is_int($gcProbability) && $gcProbability >= 1 && $gcProbability <= 100) {
ini_set('session.gc_probability', $gcProbability);
}
return $return;
}
/**
+----------------------------------------------------------
* 当前Session文件名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function getFilename() {
return Session::path().'/sess_'.session_id();
}
}//类定义结束
Session::_init(); | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/Session.class.php | PHP | asf20 | 22,820 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: ArrayList.class.php 2504 2011-12-28 07:35:29Z liu21st $
/**
+------------------------------------------------------------------------------
* ArrayList实现类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id: ArrayList.class.php 2504 2011-12-28 07:35:29Z liu21st $
+------------------------------------------------------------------------------
*/
class ArrayList implements IteratorAggregate {
/**
+----------------------------------------------------------
* 集合元素
+----------------------------------------------------------
* @var array
* @access protected
+----------------------------------------------------------
*/
protected $_elements = array();
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $elements 初始化数组元素
+----------------------------------------------------------
*/
public function __construct($elements = array()) {
if (!empty($elements)) {
$this->_elements = $elements;
}
}
/**
+----------------------------------------------------------
* 若要获得迭代因子,通过getIterator方法实现
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return ArrayObject
+----------------------------------------------------------
*/
public function getIterator() {
return new ArrayObject($this->_elements);
}
/**
+----------------------------------------------------------
* 增加元素
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $element 要添加的元素
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function add($element) {
return (array_push($this->_elements, $element)) ? true : false;
}
//
public function unshift($element) {
return (array_unshift($this->_elements,$element))?true : false;
}
//
public function pop() {
return array_pop($this->_elements);
}
/**
+----------------------------------------------------------
* 增加元素列表
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param ArrayList $list 元素列表
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function addAll($list) {
$before = $this->size();
foreach( $list as $element) {
$this->add($element);
}
$after = $this->size();
return ($before < $after);
}
/**
+----------------------------------------------------------
* 清除所有元素
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function clear() {
$this->_elements = array();
}
/**
+----------------------------------------------------------
* 是否包含某个元素
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $element 查找元素
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function contains($element) {
return (array_search($element, $this->_elements) !== false );
}
/**
+----------------------------------------------------------
* 根据索引取得元素
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param integer $index 索引
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function get($index) {
return $this->_elements[$index];
}
/**
+----------------------------------------------------------
* 查找匹配元素,并返回第一个元素所在位置
* 注意 可能存在0的索引位置 因此要用===False来判断查找失败
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $element 查找元素
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function indexOf($element) {
return array_search($element, $this->_elements);
}
/**
+----------------------------------------------------------
* 判断元素是否为空
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
public function isEmpty() {
return empty($this->_elements);
}
/**
+----------------------------------------------------------
* 最后一个匹配的元素位置
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $element 查找元素
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
public function lastIndexOf($element) {
for ($i = (count($this->_elements) - 1); $i > 0; $i--) {
if ($element == $this->get($i)) { return $i; }
}
}
public function toJson() {
return json_encode($this->_elements);
}
/**
+----------------------------------------------------------
* 根据索引移除元素
* 返回被移除的元素
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param integer $index 索引
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function remove($index) {
$element = $this->get($index);
if (!is_null($element)) { array_splice($this->_elements, $index, 1); }
return $element;
}
/**
+----------------------------------------------------------
* 移出一定范围的数组列表
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param integer $offset 开始移除位置
* @param integer $length 移除长度
+----------------------------------------------------------
*/
public function removeRange($offset , $length) {
array_splice($this->_elements, $offset , $length);
}
/**
+----------------------------------------------------------
* 移出重复的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function unique() {
$this->_elements = array_unique($this->_elements);
}
/**
+----------------------------------------------------------
* 取出一定范围的数组列表
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param integer $offset 开始位置
* @param integer $length 长度
+----------------------------------------------------------
*/
public function range($offset,$length=null) {
return array_slice($this->_elements,$offset,$length);
}
/**
+----------------------------------------------------------
* 设置列表元素
* 返回修改之前的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param integer $index 索引
* @param mixed $element 元素
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function set($index, $element) {
$previous = $this->get($index);
$this->_elements[$index] = $element;
return $previous;
}
/**
+----------------------------------------------------------
* 获取列表长度
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
public function size() {
return count($this->_elements);
}
/**
+----------------------------------------------------------
* 转换成数组
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function toArray() {
return $this->_elements;
}
// 列表排序
public function ksort() {
ksort($this->_elements);
}
// 列表排序
public function asort() {
asort($this->_elements);
}
// 逆向排序
public function rsort() {
rsort($this->_elements);
}
// 自然排序
public function natsort() {
natsort($this->_elements);
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/ArrayList.class.php | PHP | asf20 | 11,739 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Date.class.php 2662 2012-01-26 06:32:50Z liu21st $
/**
+------------------------------------------------------------------------------
* 日期时间操作类
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Date
* @author liu21st <liu21st@gmail.com>
* @version $Id: Date.class.php 2662 2012-01-26 06:32:50Z liu21st $
+------------------------------------------------------------------------------
*/
class Date {
/**
+----------------------------------------------------------
* 日期的时间戳
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $date;
/**
+----------------------------------------------------------
* 时区
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $timezone;
/**
+----------------------------------------------------------
* 年
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $year;
/**
+----------------------------------------------------------
* 月
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $month;
/**
+----------------------------------------------------------
* 日
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $day;
/**
+----------------------------------------------------------
* 时
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $hour;
/**
+----------------------------------------------------------
* 分
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $minute;
/**
+----------------------------------------------------------
* 秒
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $second;
/**
+----------------------------------------------------------
* 星期的数字表示
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $weekday;
/**
+----------------------------------------------------------
* 星期的完整表示
+----------------------------------------------------------
* @var string
* @access protected
+----------------------------------------------------------
*/
protected $cWeekday;
/**
+----------------------------------------------------------
* 一年中的天数 0-365
+----------------------------------------------------------
* @var integer
* @access protected
+----------------------------------------------------------
*/
protected $yDay;
/**
+----------------------------------------------------------
* 月份的完整表示
+----------------------------------------------------------
* @var string
* @access protected
+----------------------------------------------------------
*/
protected $cMonth;
/**
+----------------------------------------------------------
* 日期CDATE表示
+----------------------------------------------------------
* @var string
* @access protected
+----------------------------------------------------------
*/
protected $CDATE;
/**
+----------------------------------------------------------
* 日期的YMD表示
+----------------------------------------------------------
* @var string
* @access protected
+----------------------------------------------------------
*/
protected $YMD;
/**
+----------------------------------------------------------
* 时间的输出表示
+----------------------------------------------------------
* @var string
* @access protected
+----------------------------------------------------------
*/
protected $CTIME;
// 星期的输出
protected $Week = array("日","一","二","三","四","五","六");
/**
+----------------------------------------------------------
* 架构函数
* 创建一个Date对象
+----------------------------------------------------------
* @param mixed $date 日期
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
*/
public function __construct($date='') {
//分析日期
$this->date = $this->parse($date);
$this->setDate($this->date);
}
/**
+----------------------------------------------------------
* 日期分析
* 返回时间戳
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param mixed $date 日期
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parse($date) {
if (is_string($date)) {
if (($date == "") || strtotime($date) == -1) {
//为空默认取得当前时间戳
$tmpdate = time();
} else {
//把字符串转换成UNIX时间戳
$tmpdate = strtotime($date);
}
} elseif (is_null($date)) {
//为空默认取得当前时间戳
$tmpdate = time();
} elseif (is_numeric($date)) {
//数字格式直接转换为时间戳
$tmpdate = $date;
} else {
if (get_class($date) == "date") {
//如果是Date对象
$tmpdate = $date->date;
} else {
//默认取当前时间戳
$tmpdate = time();
}
}
return $tmpdate;
}
/**
+----------------------------------------------------------
* 验证日期数据是否有效
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $date 日期数据
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function valid($date) {
}
/**
+----------------------------------------------------------
* 日期参数设置
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param integer $date 日期时间戳
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function setDate($date) {
$dateArray = getdate($date);
$this->date = $dateArray[0]; //时间戳
$this->second = $dateArray["seconds"]; //秒
$this->minute = $dateArray["minutes"]; //分
$this->hour = $dateArray["hours"]; //时
$this->day = $dateArray["mday"]; //日
$this->month = $dateArray["mon"]; //月
$this->year = $dateArray["year"]; //年
$this->weekday = $dateArray["wday"]; //星期 0~6
$this->cWeekday = '星期'.$this->Week[$this->weekday];//$dateArray["weekday"]; //星期完整表示
$this->yDay = $dateArray["yday"]; //一年中的天数 0-365
$this->cMonth = $dateArray["month"]; //月份的完整表示
$this->CDATE = $this->format("%Y-%m-%d");//日期表示
$this->YMD = $this->format("%Y%m%d"); //简单日期
$this->CTIME = $this->format("%H:%M:%S");//时间表示
return ;
}
/**
+----------------------------------------------------------
* 日期格式化
* 默认返回 1970-01-01 11:30:45 格式
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $format 格式化参数
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function format($format = "%Y-%m-%d %H:%M:%S") {
return strftime($format, $this->date);
}
/**
+----------------------------------------------------------
* 是否为闰年
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function isLeapYear($year='') {
if(empty($year)) {
$year = $this->year;
}
return ((($year % 4) == 0) && (($year % 100) != 0) || (($year % 400) == 0));
}
/**
+----------------------------------------------------------
* 计算日期差
*
* w - weeks
* d - days
* h - hours
* m - minutes
* s - seconds
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param mixed $date 要比较的日期
* @param string $elaps 比较跨度
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
public function dateDiff($date, $elaps = "d") {
$__DAYS_PER_WEEK__ = (7);
$__DAYS_PER_MONTH__ = (30);
$__DAYS_PER_YEAR__ = (365);
$__HOURS_IN_A_DAY__ = (24);
$__MINUTES_IN_A_DAY__ = (1440);
$__SECONDS_IN_A_DAY__ = (86400);
//计算天数差
$__DAYSELAPS = ($this->parse($date) - $this->date) / $__SECONDS_IN_A_DAY__ ;
switch ($elaps) {
case "y"://转换成年
$__DAYSELAPS = $__DAYSELAPS / $__DAYS_PER_YEAR__;
break;
case "M"://转换成月
$__DAYSELAPS = $__DAYSELAPS / $__DAYS_PER_MONTH__;
break;
case "w"://转换成星期
$__DAYSELAPS = $__DAYSELAPS / $__DAYS_PER_WEEK__;
break;
case "h"://转换成小时
$__DAYSELAPS = $__DAYSELAPS * $__HOURS_IN_A_DAY__;
break;
case "m"://转换成分钟
$__DAYSELAPS = $__DAYSELAPS * $__MINUTES_IN_A_DAY__;
break;
case "s"://转换成秒
$__DAYSELAPS = $__DAYSELAPS * $__SECONDS_IN_A_DAY__;
break;
}
return $__DAYSELAPS;
}
/**
+----------------------------------------------------------
* 人性化的计算日期差
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param mixed $time 要比较的时间
* @param mixed $precision 返回的精度
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function timeDiff( $time ,$precision=false) {
if(!is_numeric($precision) && !is_bool($precision)) {
static $_diff = array('y'=>'年','M'=>'个月','d'=>'天','w'=>'周','s'=>'秒','h'=>'小时','m'=>'分钟');
return ceil($this->dateDiff($time,$precision)).$_diff[$precision].'前';
}
$diff = abs($this->parse($time) - $this->date);
static $chunks = array(array(31536000,'年'),array(2592000,'个月'),array(604800,'周'),array(86400,'天'),array(3600 ,'小时'),array(60,'分钟'),array(1,'秒'));
$count =0;
$since = '';
for($i=0;$i<count($chunks);$i++) {
if($diff>=$chunks[$i][0]) {
$num = floor($diff/$chunks[$i][0]);
$since .= sprintf('%d'.$chunks[$i][1],$num);
$diff = (int)($diff-$chunks[$i][0]*$num);
$count++;
if(!$precision || $count>=$precision) {
break;
}
}
}
return $since.'前';
}
/**
+----------------------------------------------------------
* 计算月份的第一天 返回Date对象
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return Date
+----------------------------------------------------------
*/
public function firstDayOfMonth() {
return (new Date(strftime("%Y-%m-%d", mktime(0, 0, 0,
$this->month,
1,
$this->year ))));
}
/**
+----------------------------------------------------------
* 计算年份的第一天 返回Date对象
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return Date
+----------------------------------------------------------
*/
public function firstDayOfYear() {
return (new Date(strftime("%Y-%m-%d", mktime(0, 0, 0,
1,
1,
$this->year))));
}
/**
+----------------------------------------------------------
* 计算月份的最后一天 返回Date对象
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return Date
+----------------------------------------------------------
*/
public function lastDayOfMonth() {
return (new Date(strftime("%Y-%m-%d", mktime(0, 0, 0,
$this->month + 1,
0,
$this->year ))));
}
/**
+----------------------------------------------------------
* 计算年份的最后一天 返回Date对象
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return Date
+----------------------------------------------------------
*/
public function lastDayOfYear() {
return (new Date(strftime("%Y-%m-%d", mktime(0, 0, 0,
1,
0,
$this->year + 1))));
}
/**
+----------------------------------------------------------
* 计算月份的最大天数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
public function maxDayOfMonth() {
$result = $this->dateDiff(strtotime($this->dateAdd(1,'m')),'d');
return $result;
}
/**
+----------------------------------------------------------
* 取得指定间隔日期
*
* yyyy - 年
* q - 季度
* m - 月
* y - day of year
* d - 日
* w - 周
* ww - week of year
* h - 小时
* n - 分钟
* s - 秒
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param integer $number 间隔数目
* @param string $interval 比较类型
+----------------------------------------------------------
* @return Date
+----------------------------------------------------------
*/
public function dateAdd($number = 0, $interval = "d") {
$hours = $this->hour;
$minutes = $this->minute;
$seconds = $this->second;
$month = $this->month;
$day = $this->day;
$year = $this->year;
switch ($interval) {
case "yyyy":
//---Add $number to year
$year += $number;
break;
case "q":
//---Add $number to quarter
$month += ($number*3);
break;
case "m":
//---Add $number to month
$month += $number;
break;
case "y":
case "d":
case "w":
//---Add $number to day of year, day, day of week
$day += $number;
break;
case "ww":
//---Add $number to week
$day += ($number*7);
break;
case "h":
//---Add $number to hours
$hours += $number;
break;
case "n":
//---Add $number to minutes
$minutes += $number;
break;
case "s":
//---Add $number to seconds
$seconds += $number;
break;
}
return (new Date(mktime($hours,
$minutes,
$seconds,
$month,
$day,
$year)));
}
/**
+----------------------------------------------------------
* 日期数字转中文
* 用于日和月、周
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param integer $number 日期数字
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function numberToCh($number) {
$number = intval($number);
$array = array('一','二','三','四','五','六','七','八','九','十');
$str = '';
if($number ==0) { $str .= "十" ;}
if($number < 10){
$str .= $array[$number-1] ;
}
elseif($number < 20 ){
$str .= "十".$array[$number-11];
}
elseif($number < 30 ){
$str .= "二十".$array[$number-21];
}
else{
$str .= "三十".$array[$number-31];
}
return $str;
}
/**
+----------------------------------------------------------
* 年份数字转中文
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param integer $yearStr 年份数字
* @param boolean $flag 是否显示公元
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function yearToCh( $yearStr ,$flag=false ) {
$array = array('零','一','二','三','四','五','六','七','八','九');
$str = $flag? '公元' : '';
for($i=0;$i<4;$i++){
$str .= $array[substr($yearStr,$i,1)];
}
return $str;
}
/**
+----------------------------------------------------------
* 判断日期 所属 干支 生肖 星座
* type 参数:XZ 星座 GZ 干支 SX 生肖
*
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $type 获取信息类型
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function magicInfo($type) {
$result = '';
$m = $this->month;
$y = $this->year;
$d = $this->day;
switch ($type) {
case 'XZ'://星座
$XZDict = array('摩羯','宝瓶','双鱼','白羊','金牛','双子','巨蟹','狮子','处女','天秤','天蝎','射手');
$Zone = array(1222,122,222,321,421,522,622,722,822,922,1022,1122,1222);
if((100*$m+$d)>=$Zone[0]||(100*$m+$d)<$Zone[1])
$i=0;
else
for($i=1;$i<12;$i++){
if((100*$m+$d)>=$Zone[$i]&&(100*$m+$d)<$Zone[$i+1])
break;
}
$result = $XZDict[$i].'座';
break;
case 'GZ'://干支
$GZDict = array(
array('甲','乙','丙','丁','戊','己','庚','辛','壬','癸'),
array('子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥')
);
$i= $y -1900+36 ;
$result = $GZDict[0][$i%10].$GZDict[1][$i%12];
break;
case 'SX'://生肖
$SXDict = array('鼠','牛','虎','兔','龙','蛇','马','羊','猴','鸡','狗','猪');
$result = $SXDict[($y-4)%12];
break;
}
return $result;
}
public function __toString() {
return $this->format();
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/Date.class.php | PHP | asf20 | 24,196 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Stack.class.php 2662 2012-01-26 06:32:50Z liu21st $
import("ORG.Util.ArrayList");
/**
+------------------------------------------------------------------------------
* Stack实现类
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id: Stack.class.php 2662 2012-01-26 06:32:50Z liu21st $
+------------------------------------------------------------------------------
*/
class Stack extends ArrayList {
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $values 初始化数组元素
+----------------------------------------------------------
*/
public function __construct($values = array()) {
parent::__construct($values);
}
/**
+----------------------------------------------------------
* 将堆栈的内部指针指向第一个单元
*
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function peek() {
return reset($this->toArray());
}
/**
+----------------------------------------------------------
* 元素进栈
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $value
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function push($value) {
$this->add($value);
return $value;
}
}
| 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Util/Stack.class.php | PHP | asf20 | 2,604 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Des.class.php 2504 2011-12-28 07:35:29Z liu21st $
/**
+------------------------------------------------------------------------------
* Des 加密实现类
* Converted from JavaScript to PHP by Jim Gibbs, June 2004 Paul Tero, July 2001
*
* Optimised for performance with large blocks by Michael Hayworth, November 2001
* http://www.netdealing.com
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Crypt
* @author liu21st <liu21st@gmail.com>
* @version $Id: Des.class.php 2504 2011-12-28 07:35:29Z liu21st $
+------------------------------------------------------------------------------
*/
class Des {
/**
+----------------------------------------------------------
* 加密字符串
*
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $str 字符串
* @param string $key 加密key
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
function encrypt($str, $key) {
if ($str == "") {
return "";
}
return self::_des($key,$str,1);
}
/**
+----------------------------------------------------------
* 解密字符串
*
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $str 字符串
* @param string $key 加密key
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
function decrypt($str, $key) {
if ($str == "") {
return "";
}
return self::_des($key,$str,0);
}
/**
+----------------------------------------------------------
* Des算法
*
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $str 字符串
* @param string $key 加密key
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
function _des($key, $message, $encrypt, $mode=0, $iv=null) {
//declaring this locally speeds things up a bit
$spfunction1 = array (0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004);
$spfunction2 = array (-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000);
$spfunction3 = array (0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200);
$spfunction4 = array (0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080);
$spfunction5 = array (0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100);
$spfunction6 = array (0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010);
$spfunction7 = array (0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002);
$spfunction8 = array (0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000);
$masks = array (4294967295,2147483647,1073741823,536870911,268435455,134217727,67108863,33554431,16777215,8388607,4194303,2097151,1048575,524287,262143,131071,65535,32767,16383,8191,4095,2047,1023,511,255,127,63,31,15,7,3,1,0);
//create the 16 or 48 subkeys we will need
$keys = self::_createKeys ($key);
$m=0;
$len = strlen($message);
$chunk = 0;
//set up the loops for single and triple des
$iterations = ((count($keys) == 32) ? 3 : 9); //single or triple des
if ($iterations == 3) {$looping = (($encrypt) ? array (0, 32, 2) : array (30, -2, -2));}
else {$looping = (($encrypt) ? array (0, 32, 2, 62, 30, -2, 64, 96, 2) : array (94, 62, -2, 32, 64, 2, 30, -2, -2));}
$message .= (chr(0) . chr(0) . chr(0) . chr(0) . chr(0) . chr(0) . chr(0) . chr(0)); //pad the message out with null bytes
//store the result here
$result = "";
$tempresult = "";
if ($mode == 1) { //CBC mode
$cbcleft = (ord($iv{$m++}) << 24) | (ord($iv{$m++}) << 16) | (ord($iv{$m++}) << 8) | ord($iv{$m++});
$cbcright = (ord($iv{$m++}) << 24) | (ord($iv{$m++}) << 16) | (ord($iv{$m++}) << 8) | ord($iv{$m++});
$m=0;
}
//loop through each 64 bit chunk of the message
while ($m < $len) {
$left = (ord($message{$m++}) << 24) | (ord($message{$m++}) << 16) | (ord($message{$m++}) << 8) | ord($message{$m++});
$right = (ord($message{$m++}) << 24) | (ord($message{$m++}) << 16) | (ord($message{$m++}) << 8) | ord($message{$m++});
//for Cipher Block Chaining mode, xor the message with the previous result
if ($mode == 1) {if ($encrypt) {$left ^= $cbcleft; $right ^= $cbcright;} else {$cbcleft2 = $cbcleft; $cbcright2 = $cbcright; $cbcleft = $left; $cbcright = $right;}}
//first each 64 but chunk of the message must be permuted according to IP
$temp = (($left >> 4 & $masks[4]) ^ $right) & 0x0f0f0f0f; $right ^= $temp; $left ^= ($temp << 4);
$temp = (($left >> 16 & $masks[16]) ^ $right) & 0x0000ffff; $right ^= $temp; $left ^= ($temp << 16);
$temp = (($right >> 2 & $masks[2]) ^ $left) & 0x33333333; $left ^= $temp; $right ^= ($temp << 2);
$temp = (($right >> 8 & $masks[8]) ^ $left) & 0x00ff00ff; $left ^= $temp; $right ^= ($temp << 8);
$temp = (($left >> 1 & $masks[1]) ^ $right) & 0x55555555; $right ^= $temp; $left ^= ($temp << 1);
$left = (($left << 1) | ($left >> 31 & $masks[31]));
$right = (($right << 1) | ($right >> 31 & $masks[31]));
//do this either 1 or 3 times for each chunk of the message
for ($j=0; $j<$iterations; $j+=3) {
$endloop = $looping[$j+1];
$loopinc = $looping[$j+2];
//now go through and perform the encryption or decryption
for ($i=$looping[$j]; $i!=$endloop; $i+=$loopinc) { //for efficiency
$right1 = $right ^ $keys[$i];
$right2 = (($right >> 4 & $masks[4]) | ($right << 28)) ^ $keys[$i+1];
//the result is attained by passing these bytes through the S selection functions
$temp = $left;
$left = $right;
$right = $temp ^ ($spfunction2[($right1 >> 24 & $masks[24]) & 0x3f] | $spfunction4[($right1 >> 16 & $masks[16]) & 0x3f]
| $spfunction6[($right1 >> 8 & $masks[8]) & 0x3f] | $spfunction8[$right1 & 0x3f]
| $spfunction1[($right2 >> 24 & $masks[24]) & 0x3f] | $spfunction3[($right2 >> 16 & $masks[16]) & 0x3f]
| $spfunction5[($right2 >> 8 & $masks[8]) & 0x3f] | $spfunction7[$right2 & 0x3f]);
}
$temp = $left; $left = $right; $right = $temp; //unreverse left and right
} //for either 1 or 3 iterations
//move then each one bit to the right
$left = (($left >> 1 & $masks[1]) | ($left << 31));
$right = (($right >> 1 & $masks[1]) | ($right << 31));
//now perform IP-1, which is IP in the opposite direction
$temp = (($left >> 1 & $masks[1]) ^ $right) & 0x55555555; $right ^= $temp; $left ^= ($temp << 1);
$temp = (($right >> 8 & $masks[8]) ^ $left) & 0x00ff00ff; $left ^= $temp; $right ^= ($temp << 8);
$temp = (($right >> 2 & $masks[2]) ^ $left) & 0x33333333; $left ^= $temp; $right ^= ($temp << 2);
$temp = (($left >> 16 & $masks[16]) ^ $right) & 0x0000ffff; $right ^= $temp; $left ^= ($temp << 16);
$temp = (($left >> 4 & $masks[4]) ^ $right) & 0x0f0f0f0f; $right ^= $temp; $left ^= ($temp << 4);
//for Cipher Block Chaining mode, xor the message with the previous result
if ($mode == 1) {if ($encrypt) {$cbcleft = $left; $cbcright = $right;} else {$left ^= $cbcleft2; $right ^= $cbcright2;}}
$tempresult .= (chr($left>>24 & $masks[24]) . chr(($left>>16 & $masks[16]) & 0xff) . chr(($left>>8 & $masks[8]) & 0xff) . chr($left & 0xff) . chr($right>>24 & $masks[24]) . chr(($right>>16 & $masks[16]) & 0xff) . chr(($right>>8 & $masks[8]) & 0xff) . chr($right & 0xff));
$chunk += 8;
if ($chunk == 512) {$result .= $tempresult; $tempresult = ""; $chunk = 0;}
} //for every 8 characters, or 64 bits in the message
//return the result as an array
return ($result . $tempresult);
} //end of des
/**
+----------------------------------------------------------
* createKeys
* this takes as input a 64 bit key (even though only 56 bits are used)
* as an array of 2 integers, and returns 16 48 bit keys
*
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $key 加密key
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
function _createKeys ($key) {
//declaring this locally speeds things up a bit
$pc2bytes0 = array (0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204);
$pc2bytes1 = array (0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101);
$pc2bytes2 = array (0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808);
$pc2bytes3 = array (0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000);
$pc2bytes4 = array (0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010);
$pc2bytes5 = array (0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420);
$pc2bytes6 = array (0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002);
$pc2bytes7 = array (0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800);
$pc2bytes8 = array (0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002);
$pc2bytes9 = array (0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408);
$pc2bytes10 = array (0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020);
$pc2bytes11 = array (0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200);
$pc2bytes12 = array (0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010);
$pc2bytes13 = array (0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105);
$masks = array (4294967295,2147483647,1073741823,536870911,268435455,134217727,67108863,33554431,16777215,8388607,4194303,2097151,1048575,524287,262143,131071,65535,32767,16383,8191,4095,2047,1023,511,255,127,63,31,15,7,3,1,0);
//how many iterations (1 for des, 3 for triple des)
$iterations = ((strlen($key) >= 24) ? 3 : 1);
//stores the return keys
$keys = array (); // size = 32 * iterations but you don't specify this in php
//now define the left shifts which need to be done
$shifts = array (0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0);
//other variables
$m=0;
$n=0;
for ($j=0; $j<$iterations; $j++) { //either 1 or 3 iterations
$left = (ord($key{$m++}) << 24) | (ord($key{$m++}) << 16) | (ord($key{$m++}) << 8) | ord($key{$m++});
$right = (ord($key{$m++}) << 24) | (ord($key{$m++}) << 16) | (ord($key{$m++}) << 8) | ord($key{$m++});
$temp = (($left >> 4 & $masks[4]) ^ $right) & 0x0f0f0f0f; $right ^= $temp; $left ^= ($temp << 4);
$temp = (($right >> 16 & $masks[16]) ^ $left) & 0x0000ffff; $left ^= $temp; $right ^= ($temp << -16);
$temp = (($left >> 2 & $masks[2]) ^ $right) & 0x33333333; $right ^= $temp; $left ^= ($temp << 2);
$temp = (($right >> 16 & $masks[16]) ^ $left) & 0x0000ffff; $left ^= $temp; $right ^= ($temp << -16);
$temp = (($left >> 1 & $masks[1]) ^ $right) & 0x55555555; $right ^= $temp; $left ^= ($temp << 1);
$temp = (($right >> 8 & $masks[8]) ^ $left) & 0x00ff00ff; $left ^= $temp; $right ^= ($temp << 8);
$temp = (($left >> 1 & $masks[1]) ^ $right) & 0x55555555; $right ^= $temp; $left ^= ($temp << 1);
//the right side needs to be shifted and to get the last four bits of the left side
$temp = ($left << 8) | (($right >> 20 & $masks[20]) & 0x000000f0);
//left needs to be put upside down
$left = ($right << 24) | (($right << 8) & 0xff0000) | (($right >> 8 & $masks[8]) & 0xff00) | (($right >> 24 & $masks[24]) & 0xf0);
$right = $temp;
//now go through and perform these shifts on the left and right keys
for ($i=0; $i < count($shifts); $i++) {
//shift the keys either one or two bits to the left
if ($shifts[$i] > 0) {
$left = (($left << 2) | ($left >> 26 & $masks[26]));
$right = (($right << 2) | ($right >> 26 & $masks[26]));
} else {
$left = (($left << 1) | ($left >> 27 & $masks[27]));
$right = (($right << 1) | ($right >> 27 & $masks[27]));
}
$left = $left & -0xf;
$right = $right & -0xf;
//now apply PC-2, in such a way that E is easier when encrypting or decrypting
//this conversion will look like PC-2 except only the last 6 bits of each byte are used
//rather than 48 consecutive bits and the order of lines will be according to
//how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7
$lefttemp = $pc2bytes0[$left >> 28 & $masks[28]] | $pc2bytes1[($left >> 24 & $masks[24]) & 0xf]
| $pc2bytes2[($left >> 20 & $masks[20]) & 0xf] | $pc2bytes3[($left >> 16 & $masks[16]) & 0xf]
| $pc2bytes4[($left >> 12 & $masks[12]) & 0xf] | $pc2bytes5[($left >> 8 & $masks[8]) & 0xf]
| $pc2bytes6[($left >> 4 & $masks[4]) & 0xf];
$righttemp = $pc2bytes7[$right >> 28 & $masks[28]] | $pc2bytes8[($right >> 24 & $masks[24]) & 0xf]
| $pc2bytes9[($right >> 20 & $masks[20]) & 0xf] | $pc2bytes10[($right >> 16 & $masks[16]) & 0xf]
| $pc2bytes11[($right >> 12 & $masks[12]) & 0xf] | $pc2bytes12[($right >> 8 & $masks[8]) & 0xf]
| $pc2bytes13[($right >> 4 & $masks[4]) & 0xf];
$temp = (($righttemp >> 16 & $masks[16]) ^ $lefttemp) & 0x0000ffff;
$keys[$n++] = $lefttemp ^ $temp; $keys[$n++] = $righttemp ^ ($temp << 16);
}
} //for each iterations
//return the keys we've created
return $keys;
} //end of des_createKeys
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Crypt/Des.class.php | PHP | asf20 | 20,655 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Xxtea.class.php 2504 2011-12-28 07:35:29Z liu21st $
/**
+------------------------------------------------------------------------------
* Xxtea 加密实现类
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Crypt
* @author liu21st <liu21st@gmail.com>
* @version $Id: Xxtea.class.php 2504 2011-12-28 07:35:29Z liu21st $
+------------------------------------------------------------------------------
*/
class Xxtea {
/**
+----------------------------------------------------------
* 加密字符串
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $str 字符串
* @param string $key 加密key
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
function encrypt($str, $key) {
if ($str == "") {
return "";
}
$v = self::str2long($str, true);
$k = self::str2long($key, false);
$n = count($v) - 1;
$z = $v[$n];
$y = $v[0];
$delta = 0x9E3779B9;
$q = floor(6 + 52 / ($n + 1));
$sum = 0;
while (0 < $q--) {
$sum = self::int32($sum + $delta);
$e = $sum >> 2 & 3;
for ($p = 0; $p < $n; $p++) {
$y = $v[$p + 1];
$mx = self::int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ self::int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$z = $v[$p] = self::int32($v[$p] + $mx);
}
$y = $v[0];
$mx = self::int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ self::int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$z = $v[$n] = self::int32($v[$n] + $mx);
}
return self::long2str($v, false);
}
/**
+----------------------------------------------------------
* 解密字符串
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $str 字符串
* @param string $key 加密key
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
function decrypt($str, $key) {
if ($str == "") {
return "";
}
$v = self::str2long($str, false);
$k = self::str2long($key, false);
$n = count($v) - 1;
$z = $v[$n];
$y = $v[0];
$delta = 0x9E3779B9;
$q = floor(6 + 52 / ($n + 1));
$sum = self::int32($q * $delta);
while ($sum != 0) {
$e = $sum >> 2 & 3;
for ($p = $n; $p > 0; $p--) {
$z = $v[$p - 1];
$mx = self::int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ self::int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$y = $v[$p] = self::int32($v[$p] - $mx);
}
$z = $v[$n];
$mx = self::int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ self::int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$y = $v[0] = self::int32($v[0] - $mx);
$sum = self::int32($sum - $delta);
}
return self::long2str($v, true);
}
/**
+----------------------------------------------------------
* 解密字符串
*
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $str 字符串
* @param string $key 加密key
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
function long2str($v, $w) {
$len = count($v);
$s = array();
for ($i = 0; $i < $len; $i++) {
$s[$i] = pack("V", $v[$i]);
}
if ($w) {
return substr(join('', $s), 0, $v[$len - 1]);
}else{
return join('', $s);
}
}
function str2long($s, $w) {
$v = unpack("V*", $s. str_repeat("\0", (4 - strlen($s) % 4) & 3));
$v = array_values($v);
if ($w) {
$v[count($v)] = strlen($s);
}
return $v;
}
function int32($n) {
while ($n >= 2147483648) $n -= 4294967296;
while ($n <= -2147483649) $n += 4294967296;
return (int)$n;
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Crypt/Xxtea.class.php | PHP | asf20 | 5,799 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Base64.class.php 2504 2011-12-28 07:35:29Z liu21st $
/**
+------------------------------------------------------------------------------
* Base64 加密实现类
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Crypt
* @author liu21st <liu21st@gmail.com>
* @version $Id: Base64.class.php 2504 2011-12-28 07:35:29Z liu21st $
+------------------------------------------------------------------------------
*/
class Base64 {
/**
+----------------------------------------------------------
* 加密字符串
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $str 字符串
* @param string $key 加密key
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public static function encrypt($data,$key) {
$key = md5($key);
$data = base64_encode($data);
$x=0;
$len = strlen($data);
$l = strlen($key);
for ($i=0;$i< $len;$i++) {
if ($x== $l) $x=0;
$char .=substr($key,$x,1);
$x++;
}
for ($i=0;$i< $len;$i++) {
$str .=chr(ord(substr($data,$i,1))+(ord(substr($char,$i,1)))%256);
}
return $str;
}
/**
+----------------------------------------------------------
* 解密字符串
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $str 字符串
* @param string $key 加密key
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public static function decrypt($data,$key) {
$key = md5($key);
$x=0;
$len = strlen($data);
$l = strlen($key);
for ($i=0;$i< $len;$i++) {
if ($x== $l) $x=0;
$char .=substr($key,$x,1);
$x++;
}
for ($i=0;$i< $len;$i++) {
if (ord(substr($data,$i,1))<ord(substr($char,$i,1))) {
$str .=chr((ord(substr($data,$i,1))+256)-ord(substr($char,$i,1)));
}else{
$str .=chr(ord(substr($data,$i,1))-ord(substr($char,$i,1)));
}
}
return base64_decode($str);
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Crypt/Base64.class.php | PHP | asf20 | 3,457 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: cevin <cevin1991@gmail.com>
// +----------------------------------------------------------------------
// $Id: Hmac.class.php 2504 2011-12-28 07:35:29Z liu21st $
/**
+------------------------------------------------------------------------------
* HMAC 加密实现类
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Crypt
* @author cevin <cevin1991@gmail.com>
* @version $Id: Hmac.class.php 2504 2011-12-28 07:35:29Z liu21st $
+------------------------------------------------------------------------------
*/
class Hmac {
/**
+----------------------------------------------------------
* SHA1加密
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $key 加密key
* @param string $str 字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public static function sha1($key,$str) {
$blocksize=64;
$hashfunc='sha1';
if (strlen($key)>$blocksize)
$key=pack('H*', $hashfunc($key));
$key=str_pad($key,$blocksize,chr(0x00));
$ipad=str_repeat(chr(0x36),$blocksize);
$opad=str_repeat(chr(0x5c),$blocksize);
$hmac = pack(
'H*',$hashfunc(
($key^$opad).pack(
'H*',$hashfunc(
($key^$ipad).$str
)
)
)
);
return $hmac;
}
/**
+----------------------------------------------------------
* MD5加密
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $key 加密key
* @param string $str 字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public static function md5($key, $str) {
$b = 64;
if (strlen($key) > $b) {
$key = pack("H*",md5($key));
}
$key = str_pad($key, $b, chr(0x00));
$ipad = str_pad('', $b, chr(0x36));
$opad = str_pad('', $b, chr(0x5c));
$k_ipad = $key ^ $ipad ;
$k_opad = $key ^ $opad;
return md5($k_opad . pack("H*",md5($k_ipad . $str)));
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Crypt/Hmac.class.php | PHP | asf20 | 3,391 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Crypt.class.php 2504 2011-12-28 07:35:29Z liu21st $
/**
+------------------------------------------------------------------------------
* Crypt 加密实现类
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Crypt
* @author liu21st <liu21st@gmail.com>
* @version $Id: Crypt.class.php 2504 2011-12-28 07:35:29Z liu21st $
+------------------------------------------------------------------------------
*/
class Crypt {
/**
+----------------------------------------------------------
* 加密字符串
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $str 字符串
* @param string $key 加密key
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
function encrypt($str,$key,$toBase64=false){
$r = md5($key);
$c=0;
$v = "";
$len = strlen($str);
$l = strlen($r);
for ($i=0;$i<$len;$i++){
if ($c== $l) $c=0;
$v.= substr($r,$c,1) .
(substr($str,$i,1) ^ substr($r,$c,1));
$c++;
}
if($toBase64) {
return base64_encode(self::ed($v,$key));
}else {
return self::ed($v,$key);
}
}
/**
+----------------------------------------------------------
* 解密字符串
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $str 字符串
* @param string $key 加密key
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
function decrypt($str,$key,$toBase64=false) {
if($toBase64) {
$str = self::ed(base64_decode($str),$key);
}else {
$str = self::ed($str,$key);
}
$v = "";
$len = strlen($str);
for ($i=0;$i<$len;$i++){
$md5 = substr($str,$i,1);
$i++;
$v.= (substr($str,$i,1) ^ $md5);
}
return $v;
}
function ed($str,$key) {
$r = md5($key);
$c=0;
$v = "";
$len = strlen($str);
$l = strlen($r);
for ($i=0;$i<$len;$i++) {
if ($c==$l) $c=0;
$v.= substr($str,$i,1) ^ substr($r,$c,1);
$c++;
}
return $v;
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Crypt/Crypt.class.php | PHP | asf20 | 3,509 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Rsa.class.php 2504 2011-12-28 07:35:29Z liu21st $
define("BCCOMP_LARGER", 1);
/**
+------------------------------------------------------------------------------
* Rsa 加密实现类
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Crypt
* @author liu21st <liu21st@gmail.com>
* @version $Id: Rsa.class.php 2504 2011-12-28 07:35:29Z liu21st $
+------------------------------------------------------------------------------
*/
class Rsa {
/**
+----------------------------------------------------------
* 加密字符串
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $str 字符串
* @param string $key 加密key
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
function encrypt($message, $public_key, $modulus, $keylength)
{
$padded = self::add_PKCS1_padding($message, true, $keylength / 8);
$number = self::binary_to_number($padded);
$encrypted = self::pow_mod($number, $public_key, $modulus);
$result = self::number_to_binary($encrypted, $keylength / 8);
return $result;
}
/**
+----------------------------------------------------------
* 解密字符串
+----------------------------------------------------------
* @access static
+----------------------------------------------------------
* @param string $str 字符串
* @param string $key 加密key
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
function decrypt($message, $private_key, $modulus, $keylength)
{
$number = self::binary_to_number($message);
$decrypted = self::pow_mod($number, $private_key, $modulus);
$result = self::number_to_binary($decrypted, $keylength / 8);
return self::remove_PKCS1_padding($result, $keylength / 8);
}
function sign($message, $private_key, $modulus, $keylength)
{
$padded = self::add_PKCS1_padding($message, false, $keylength / 8);
$number = self::binary_to_number($padded);
$signed = self::pow_mod($number, $private_key, $modulus);
$result = self::number_to_binary($signed, $keylength / 8);
return $result;
}
function verify($message, $public_key, $modulus, $keylength)
{
return decrypt($message, $public_key, $modulus, $keylength);
}
function pow_mod($p, $q, $r)
{
// Extract powers of 2 from $q
$factors = array();
$div = $q;
$power_of_two = 0;
while(bccomp($div, "0") == BCCOMP_LARGER)
{
$rem = bcmod($div, 2);
$div = bcdiv($div, 2);
if($rem) array_push($factors, $power_of_two);
$power_of_two++;
}
// Calculate partial results for each factor, using each partial result as a
// starting point for the next. This depends of the factors of two being
// generated in increasing order.
$partial_results = array();
$part_res = $p;
$idx = 0;
foreach($factors as $factor)
{
while($idx < $factor)
{
$part_res = bcpow($part_res, "2");
$part_res = bcmod($part_res, $r);
$idx++;
}
array_pus($partial_results, $part_res);
}
// Calculate final result
$result = "1";
foreach($partial_results as $part_res)
{
$result = bcmul($result, $part_res);
$result = bcmod($result, $r);
}
return $result;
}
//--
// Function to add padding to a decrypted string
// We need to know if this is a private or a public key operation [4]
//--
function add_PKCS1_padding($data, $isPublicKey, $blocksize)
{
$pad_length = $blocksize - 3 - strlen($data);
if($isPublicKey)
{
$block_type = "\x02";
$padding = "";
for($i = 0; $i < $pad_length; $i++)
{
$rnd = mt_rand(1, 255);
$padding .= chr($rnd);
}
}
else
{
$block_type = "\x01";
$padding = str_repeat("\xFF", $pad_length);
}
return "\x00" . $block_type . $padding . "\x00" . $data;
}
//--
// Remove padding from a decrypted string
// See [4] for more details.
//--
function remove_PKCS1_padding($data, $blocksize)
{
assert(strlen($data) == $blocksize);
$data = substr($data, 1);
// We cannot deal with block type 0
if($data{0} == '\0')
die("Block type 0 not implemented.");
// Then the block type must be 1 or 2
assert(($data{0} == "\x01") || ($data{0} == "\x02"));
// Remove the padding
$offset = strpos($data, "\0", 1);
return substr($data, $offset + 1);
}
//--
// Convert binary data to a decimal number
//--
function binary_to_number($data)
{
$base = "256";
$radix = "1";
$result = "0";
for($i = strlen($data) - 1; $i >= 0; $i--)
{
$digit = ord($data{$i});
$part_res = bcmul($digit, $radix);
$result = bcadd($result, $part_res);
$radix = bcmul($radix, $base);
}
return $result;
}
//--
// Convert a number back into binary form
//--
function number_to_binary($number, $blocksize)
{
$base = "256";
$result = "";
$div = $number;
while($div > 0)
{
$mod = bcmod($div, $base);
$div = bcdiv($div, $base);
$result = chr($mod) . $result;
}
return str_pad($result, $blocksize, "\x00", STR_PAD_LEFT);
}
} | 10npsite | trunk/DThinkPHP/Extend/Library/ORG/Crypt/Rsa.class.php | PHP | asf20 | 6,326 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: extend.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* Think扩展函数库 需要手动加载后调用或者放入项目函数库
+------------------------------------------------------------------------------
* @category Think
* @package Common
* @author liu21st <liu21st@gmail.com>
* @version $Id: extend.php 2702 2012-02-02 12:35:01Z liu21st $
+------------------------------------------------------------------------------
*/
/**
+----------------------------------------------------------
* 字符串截取,支持中文和其他编码
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $str 需要转换的字符串
* @param string $start 开始位置
* @param string $length 截取长度
* @param string $charset 编码格式
* @param string $suffix 截断显示字符
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
if(function_exists("mb_substr"))
$slice = mb_substr($str, $start, $length, $charset);
elseif(function_exists('iconv_substr')) {
$slice = iconv_substr($str,$start,$length,$charset);
if(false === $slice) {
$slice = '';
}
}else{
$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
preg_match_all($re[$charset], $str, $match);
$slice = join("",array_slice($match[0], $start, $length));
}
return $suffix ? $slice.'...' : $slice;
}
/**
+----------------------------------------------------------
* 产生随机字串,可用来自动生成密码 默认长度6位 字母和数字混合
+----------------------------------------------------------
* @param string $len 长度
* @param string $type 字串类型
* 0 字母 1 数字 其它 混合
* @param string $addChars 额外字符
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
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;
case 4:
$chars = "们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩康遵牧遭幅园腔订香肉弟屋敏恢忘编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航衣孙龄岭骗休借".$addChars;
break;
default :
// 默认去掉了容易混淆的字符oOLl和数字01,要添加请使用addChars参数
$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;
}
/**
+----------------------------------------------------------
* 获取登录验证码 默认为4位数字
+----------------------------------------------------------
* @param string $fmode 文件名
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function build_verify ($length=4,$mode=1) {
return rand_string($length,$mode);
}
/**
+----------------------------------------------------------
* 字节格式化 把字节数格式为 B K M G T 描述的大小
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function byte_format($size, $dec=2) {
$a = array("B", "KB", "MB", "GB", "TB", "PB");
$pos = 0;
while ($size >= 1024) {
$size /= 1024;
$pos++;
}
return round($size,$dec)." ".$a[$pos];
}
/**
+----------------------------------------------------------
* 检查字符串是否是UTF8编码
+----------------------------------------------------------
* @param string $string 字符串
+----------------------------------------------------------
* @return Boolean
+----------------------------------------------------------
*/
function is_utf8($string) {
return preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $string);
}
/**
+----------------------------------------------------------
* 代码加亮
+----------------------------------------------------------
* @param String $str 要高亮显示的字符串 或者 文件名
* @param Boolean $show 是否输出
+----------------------------------------------------------
* @return String
+----------------------------------------------------------
*/
function highlight_code($str,$show=false) {
if(file_exists($str)) {
$str = file_get_contents($str);
}
$str = stripslashes(trim($str));
// The highlight string function encodes and highlights
// brackets so we need them to start raw
$str = str_replace(array('<', '>'), array('<', '>'), $str);
// Replace any existing PHP tags to temporary markers so they don't accidentally
// break the string out of PHP, and thus, thwart the highlighting.
$str = str_replace(array('<?php', '?>', '\\'), array('phptagopen', 'phptagclose', 'backslashtmp'), $str);
// The highlight_string function requires that the text be surrounded
// by PHP tags. Since we don't know if A) the submitted text has PHP tags,
// or B) whether the PHP tags enclose the entire string, we will add our
// own PHP tags around the string along with some markers to make replacement easier later
$str = '<?php //tempstart'."\n".$str.'//tempend ?>'; // <?
// All the magic happens here, baby!
$str = highlight_string($str, TRUE);
// Prior to PHP 5, the highlight function used icky font tags
// so we'll replace them with span tags.
if (abs(phpversion()) < 5) {
$str = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $str);
$str = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str);
}
// Remove our artificially added PHP
$str = preg_replace("#\<code\>.+?//tempstart\<br />\</span\>#is", "<code>\n", $str);
$str = preg_replace("#\<code\>.+?//tempstart\<br />#is", "<code>\n", $str);
$str = preg_replace("#//tempend.+#is", "</span>\n</code>", $str);
// Replace our markers back to PHP tags.
$str = str_replace(array('phptagopen', 'phptagclose', 'backslashtmp'), array('<?php', '?>', '\\'), $str); //<?
$line = explode("<br />", rtrim(ltrim($str,'<code>'),'</code>'));
$result = '<div class="code"><ol>';
foreach($line as $key=>$val) {
$result .= '<li>'.$val.'</li>';
}
$result .= '</ol></div>';
$result = str_replace("\n", "", $result);
if( $show!== false) {
echo($result);
}else {
return $result;
}
}
//输出安全的html
function h($text, $tags = null) {
$text = trim($text);
//完全过滤注释
$text = preg_replace('/<!--?.*-->/','',$text);
//完全过滤动态代码
$text = preg_replace('/<\?|\?'.'>/','',$text);
//完全过滤js
$text = preg_replace('/<script?.*\/script>/','',$text);
$text = str_replace('[','[',$text);
$text = str_replace(']',']',$text);
$text = str_replace('|','|',$text);
//过滤换行符
$text = preg_replace('/\r?\n/','',$text);
//br
$text = preg_replace('/<br(\s\/)?'.'>/i','[br]',$text);
$text = preg_replace('/(\[br\]\s*){10,}/i','[br]',$text);
//过滤危险的属性,如:过滤on事件lang js
while(preg_match('/(<[^><]+)( lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1],$text);
}
while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1].$mat[3],$text);
}
if(empty($tags)) {
$tags = 'table|td|th|tr|i|b|u|strong|img|p|br|div|strong|em|ul|ol|li|dl|dd|dt|a';
}
//允许的HTML标签
$text = preg_replace('/<('.$tags.')( [^><\[\]]*)>/i','[\1\2]',$text);
//过滤多余html
$text = preg_replace('/<\/?(html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|script|style|xml)[^><]*>/i','',$text);
//过滤合法的html标签
while(preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i',$text,$mat)){
$text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
}
//转换引号
while(preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2=\[\]]+)\2([^\[\]]*\])/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
}
//过滤错误的单个引号
while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i',$text,$mat)){
$text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
}
//转换其它所有不合法的 < >
$text = str_replace('<','<',$text);
$text = str_replace('>','>',$text);
$text = str_replace('"','"',$text);
//反转换
$text = str_replace('[','<',$text);
$text = str_replace(']','>',$text);
$text = str_replace('|','"',$text);
//过滤多余空格
$text = str_replace(' ',' ',$text);
return $text;
}
function ubb($Text) {
$Text=trim($Text);
//$Text=htmlspecialchars($Text);
$Text=preg_replace("/\\t/is"," ",$Text);
$Text=preg_replace("/\[h1\](.+?)\[\/h1\]/is","<h1>\\1</h1>",$Text);
$Text=preg_replace("/\[h2\](.+?)\[\/h2\]/is","<h2>\\1</h2>",$Text);
$Text=preg_replace("/\[h3\](.+?)\[\/h3\]/is","<h3>\\1</h3>",$Text);
$Text=preg_replace("/\[h4\](.+?)\[\/h4\]/is","<h4>\\1</h4>",$Text);
$Text=preg_replace("/\[h5\](.+?)\[\/h5\]/is","<h5>\\1</h5>",$Text);
$Text=preg_replace("/\[h6\](.+?)\[\/h6\]/is","<h6>\\1</h6>",$Text);
$Text=preg_replace("/\[separator\]/is","",$Text);
$Text=preg_replace("/\[center\](.+?)\[\/center\]/is","<center>\\1</center>",$Text);
$Text=preg_replace("/\[url=http:\/\/([^\[]*)\](.+?)\[\/url\]/is","<a href=\"http://\\1\" target=_blank>\\2</a>",$Text);
$Text=preg_replace("/\[url=([^\[]*)\](.+?)\[\/url\]/is","<a href=\"http://\\1\" target=_blank>\\2</a>",$Text);
$Text=preg_replace("/\[url\]http:\/\/([^\[]*)\[\/url\]/is","<a href=\"http://\\1\" target=_blank>\\1</a>",$Text);
$Text=preg_replace("/\[url\]([^\[]*)\[\/url\]/is","<a href=\"\\1\" target=_blank>\\1</a>",$Text);
$Text=preg_replace("/\[img\](.+?)\[\/img\]/is","<img src=\\1>",$Text);
$Text=preg_replace("/\[color=(.+?)\](.+?)\[\/color\]/is","<font color=\\1>\\2</font>",$Text);
$Text=preg_replace("/\[size=(.+?)\](.+?)\[\/size\]/is","<font size=\\1>\\2</font>",$Text);
$Text=preg_replace("/\[sup\](.+?)\[\/sup\]/is","<sup>\\1</sup>",$Text);
$Text=preg_replace("/\[sub\](.+?)\[\/sub\]/is","<sub>\\1</sub>",$Text);
$Text=preg_replace("/\[pre\](.+?)\[\/pre\]/is","<pre>\\1</pre>",$Text);
$Text=preg_replace("/\[email\](.+?)\[\/email\]/is","<a href='mailto:\\1'>\\1</a>",$Text);
$Text=preg_replace("/\[colorTxt\](.+?)\[\/colorTxt\]/eis","color_txt('\\1')",$Text);
$Text=preg_replace("/\[emot\](.+?)\[\/emot\]/eis","emot('\\1')",$Text);
$Text=preg_replace("/\[i\](.+?)\[\/i\]/is","<i>\\1</i>",$Text);
$Text=preg_replace("/\[u\](.+?)\[\/u\]/is","<u>\\1</u>",$Text);
$Text=preg_replace("/\[b\](.+?)\[\/b\]/is","<b>\\1</b>",$Text);
$Text=preg_replace("/\[quote\](.+?)\[\/quote\]/is"," <div class='quote'><h5>引用:</h5><blockquote>\\1</blockquote></div>", $Text);
$Text=preg_replace("/\[code\](.+?)\[\/code\]/eis","highlight_code('\\1')", $Text);
$Text=preg_replace("/\[php\](.+?)\[\/php\]/eis","highlight_code('\\1')", $Text);
$Text=preg_replace("/\[sig\](.+?)\[\/sig\]/is","<div class='sign'>\\1</div>", $Text);
$Text=preg_replace("/\\n/is","<br/>",$Text);
return $Text;
}
// 随机生成一组字符串
function build_count_rand ($number,$length=4,$mode=1) {
if($mode==1 && $length<strlen($number) ) {
//不足以生成一定数量的不重复数字
return false;
}
$rand = array();
for($i=0; $i<$number; $i++) {
$rand[] = rand_string($length,$mode);
}
$unqiue = array_unique($rand);
if(count($unqiue)==count($rand)) {
return $rand;
}
$count = count($rand)-count($unqiue);
for($i=0; $i<$count*3; $i++) {
$rand[] = rand_string($length,$mode);
}
$rand = array_slice(array_unique ($rand),0,$number);
return $rand;
}
function remove_xss($val) {
// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
// this prevents some character re-spacing such as <java\0script>
// note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
$val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
// straight replacements, the user should never need these since they're normal characters
// this prevents like <IMG SRC=@avascript:alert('XSS')>
$search = 'abcdefghijklmnopqrstuvwxyz';
$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$search .= '1234567890!@#$%^&*()';
$search .= '~`";:?+/={}[]-_|\'\\';
for ($i = 0; $i < strlen($search); $i++) {
// ;? matches the ;, which is optional
// 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
// @ @ search for the hex values
$val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
// @ @ 0{0,7} matches '0' zero to seven times
$val = preg_replace('/(�{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
}
// now the only remaining whitespace attacks are \t, \n, and \r
$ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
$ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
$ra = array_merge($ra1, $ra2);
$found = true; // keep replacing as long as the previous round replaced something
while ($found == true) {
$val_before = $val;
for ($i = 0; $i < sizeof($ra); $i++) {
$pattern = '/';
for ($j = 0; $j < strlen($ra[$i]); $j++) {
if ($j > 0) {
$pattern .= '(';
$pattern .= '(&#[xX]0{0,8}([9ab]);)';
$pattern .= '|';
$pattern .= '|(�{0,8}([9|10|13]);)';
$pattern .= ')*';
}
$pattern .= $ra[$i][$j];
}
$pattern .= '/i';
$replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
$val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
if ($val_before == $val) {
// no replacements were made, so exit the loop
$found = false;
}
}
}
return $val;
}
/**
+----------------------------------------------------------
* 把返回的数据集转换成Tree
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $list 要转换的数据集
* @param string $pid parent标记字段
* @param string $level level标记字段
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0) {
// 创建Tree
$tree = array();
if(is_array($list)) {
// 创建基于主键的数组引用
$refer = array();
foreach ($list as $key => $data) {
$refer[$data[$pk]] =& $list[$key];
}
foreach ($list as $key => $data) {
// 判断是否存在parent
$parentId = $data[$pid];
if ($root == $parentId) {
$tree[] =& $list[$key];
}else{
if (isset($refer[$parentId])) {
$parent =& $refer[$parentId];
$parent[$child][] =& $list[$key];
}
}
}
}
return $tree;
}
/**
+----------------------------------------------------------
* 对查询结果集进行排序
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $list 查询结果
* @param string $field 排序的字段名
* @param array $sortby 排序类型
* asc正向排序 desc逆向排序 nat自然排序
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
function list_sort_by($list,$field, $sortby='asc') {
if(is_array($list)){
$refer = $resultSet = array();
foreach ($list as $i => $data)
$refer[$i] = &$data[$field];
switch ($sortby) {
case 'asc': // 正向排序
asort($refer);
break;
case 'desc':// 逆向排序
arsort($refer);
break;
case 'nat': // 自然排序
natcasesort($refer);
break;
}
foreach ( $refer as $key=> $val)
$resultSet[] = &$list[$key];
return $resultSet;
}
return false;
}
/**
+----------------------------------------------------------
* 在数据列表中搜索
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $list 数据列表
* @param mixed $condition 查询条件
* 支持 array('name'=>$value) 或者 name=$value
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
function list_search($list,$condition) {
if(is_string($condition))
parse_str($condition,$condition);
// 返回的结果集合
$resultSet = array();
foreach ($list as $key=>$data){
$find = false;
foreach ($condition as $field=>$value){
if(isset($data[$field])) {
if(0 === strpos($value,'/')) {
$find = preg_match($value,$data[$field]);
}elseif($data[$field]==$value){
$find = true;
}
}
}
if($find)
$resultSet[] = &$list[$key];
}
return $resultSet;
}
// 自动转换字符集 支持数组转换
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;
}
} | 10npsite | trunk/DThinkPHP/Extend/Function/extend.php | PHP | asf20 | 27,518 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: RobotCheckBehavior.class.php 2616 2012-01-16 08:36:46Z liu21st $
class RobotCheckBehavior extends Behavior {
protected $options = array(
'LIMIT_ROBOT_VISIT'=>true,
);
public function run(&$params) {
// 机器人访问检测
if(C('LIMIT_ROBOT_VISIT') && self::isRobot()) {
// 禁止机器人访问
exit('Access Denied');
}
}
static private function isRobot() {
static $_robot = null;
if(is_null($_robot)) {
$spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
$browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
if(preg_match("/($browsers)/", $_SERVER['HTTP_USER_AGENT'])) {
$_robot = false ;
} elseif(preg_match("/($spiders)/", $_SERVER['HTTP_USER_AGENT'])) {
$_robot = true;
} else {
$_robot = false;
}
}
return $_robot;
}
} | 10npsite | trunk/DThinkPHP/Extend/Behavior/RobotCheckBehavior.class.php | PHP | asf20 | 1,631 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CheckLangBehavior.class.php 2735 2012-02-15 03:11:13Z liu21st $
/**
+------------------------------------------------------------------------------
* 系统行为扩展 语言检测 并自动加载语言包
+------------------------------------------------------------------------------
*/
class CheckLangBehavior extends Behavior {
// 行为参数定义(默认值) 可在项目配置中覆盖
protected $options = array(
'LANG_SWITCH_ON' => false, // 默认关闭语言包功能
'LANG_AUTO_DETECT' => true, // 自动侦测语言 开启多语言功能后有效
'LANG_LIST' => 'zh-cn', // 允许切换的语言列表 用逗号分隔
'VAR_LANGUAGE' => 'l', // 默认语言切换变量
);
// 行为扩展的执行入口必须是run
public function run(&$params){
// 开启静态缓存
$this->checkLanguage();
}
/**
+----------------------------------------------------------
* 语言检查
* 检查浏览器支持语言,并自动加载语言包
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
private function checkLanguage() {
// 不开启语言包功能,仅仅加载框架语言文件直接返回
if (!C('LANG_SWITCH_ON')){
return;
}
$langSet = C('DEFAULT_LANG');
// 启用了语言包功能
// 根据是否启用自动侦测设置获取语言选择
if (C('LANG_AUTO_DETECT')){
if(isset($_GET[C('VAR_LANGUAGE')])){
$langSet = $_GET[C('VAR_LANGUAGE')];// url中设置了语言变量
cookie('think_language',$langSet,3600);
}elseif(cookie('think_language')){// 获取上次用户的选择
$langSet = cookie('think_language');
}elseif(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){// 自动侦测浏览器语言
preg_match('/^([a-z\-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches);
$langSet = $matches[1];
cookie('think_language',$langSet,3600);
}
if(false === stripos(C('LANG_LIST'),$langSet)) { // 非法语言参数
$langSet = C('DEFAULT_LANG');
}
}
// 定义当前语言
define('LANG_SET',strtolower($langSet));
// 读取项目公共语言包
if (is_file(LANG_PATH.LANG_SET.'/common.php'))
L(include LANG_PATH.LANG_SET.'/common.php');
$group = '';
// 读取当前分组公共语言包
if (defined('GROUP_NAME')){
if (is_file(LANG_PATH.LANG_SET.'/'.GROUP_NAME.'.php'))
L(include LANG_PATH.LANG_SET.'/'.GROUP_NAME.'.php');
$group = GROUP_NAME.C('TMPL_FILE_DEPR');
}
// 读取当前模块语言包
if (is_file(LANG_PATH.LANG_SET.'/'.$group.strtolower(MODULE_NAME).'.php'))
L(include LANG_PATH.LANG_SET.'/'.$group.strtolower(MODULE_NAME).'.php');
}
} | 10npsite | trunk/DThinkPHP/Extend/Behavior/CheckLangBehavior.class.php | PHP | asf20 | 3,896 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <www.3g4k.com>
// +----------------------------------------------------------------------
// $Id$
/**
+------------------------------------------------------------------------------
* 将Trace信息输出到火狐的firebug,从而不影响ajax效果和页面的布局。
+------------------------------------------------------------------------------
* 使用前,你需要先在火狐浏览器上安装firebug和firePHP两个插件。
* 定义项目的tags.php文件,
* <code>
* <?php return array(
* 'view_end'=>array(
* '_overlay'=>true,
* 'FireShowPageTrace'
* )
* );
* </code>
* 再将此文件放到项目的Behavior文件夹中即可
* 如果trace信息没有正常输出,请查看您的日志。
* firePHP,是通过http headers和firebug通讯的,所以要保证在输出trace信息之前不能有
* headers输出,你可以在入口文件第一个加入代码 ob_start(); 或者配置output_buffering
*
*/
class FireShowPageTraceBehavior extends Behavior {
// 行为参数定义
protected $options = array(
'FIRE_SHOW_PAGE_TRACE' => true, // 显示页面Trace信息
);
// 行为扩展的执行入口必须是run
public function run(&$params){
if(C('FIRE_SHOW_PAGE_TRACE')) {
$this->showTrace();
}
}
/**
+----------------------------------------------------------
* 显示页面Trace信息
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
*/
private function showTrace() {
// 系统默认显示信息
$log = Log::$log;
$files = get_included_files();
$trace = array(
'请求时间'=> date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']),
'当前页面'=> __SELF__,
'请求协议'=> $_SERVER['SERVER_PROTOCOL'].' '.$_SERVER['REQUEST_METHOD'],
'运行信息'=> $this->showTime(),
'会话ID' => session_id(),
'日志记录'=> !empty($log)?$log:'无日志记录',
'加载文件'=>$files,
);
// 读取项目定义的Trace文件
$traceFile = CONF_PATH.'trace.php';
if(is_file($traceFile)) {
// 定义格式 return array('当前页面'=>$_SERVER['PHP_SELF'],'通信协议'=>$_SERVER['SERVER_PROTOCOL'],...);
$trace = array_merge(include $traceFile,$trace);
}
// 设置trace信息
trace($trace);
$fire=array(
array('','')
);
foreach(trace() as $key=>$value){
$fire[]=array($key,$value);
}
if(headers_sent($filename, $linenum)){
$fileInfo=!empty($filename)?"(在{$filename}文件的第{$linenum}行)":'';
Log::record("已经有Http Header信息头输出{$fileInfo},请在你的入口文件加入ob_start() 或通过配置output_buffering,已确保headers不被提前输出");
}else{
fb(array('页面Trace信息',$fire),FirePHP::TABLE);
}
}
/**
+----------------------------------------------------------
* 显示运行时间、数据库操作、缓存次数、内存使用信息
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function showTime() {
// 显示运行时间
G('beginTime',$GLOBALS['_beginTime']);
G('viewEndTime');
$showTime = 'Process: '.G('beginTime','viewEndTime').'s ';
// 显示详细运行时间
$showTime .= '( Load:'.G('beginTime','loadTime').'s Init:'.G('loadTime','initTime').'s Exec:'.G('initTime','viewStartTime').'s Template:'.G('viewStartTime','viewEndTime').'s )';
// 显示数据库操作次数
if(class_exists('Db',false) ) {
$showTime .= ' | DB :'.N('db_query').' queries '.N('db_write').' writes ';
}
// 显示缓存读写次数
if( class_exists('Cache',false)) {
$showTime .= ' | Cache :'.N('cache_read').' gets '.N('cache_write').' writes ';
}
// 显示内存开销
if(MEMORY_LIMIT_ON ) {
$showTime .= ' | UseMem:'. number_format((memory_get_usage() - $GLOBALS['_startUseMems'])/1024).' kb';
}
// 显示文件加载数
$showTime .= ' | LoadFile:'.count(get_included_files());
// 显示函数调用次数 自定义函数,内置函数
$fun = get_defined_functions();
$showTime .= ' | CallFun:'.count($fun['user']).','.count($fun['internal']);
return $showTime;
}
}
function fb()
{
$instance = FirePHP::getInstance(true);
$args = func_get_args();
return call_user_func_array(array($instance,'fb'),$args);
}
class FB
{
/**
* Enable and disable logging to Firebug
*
* @see FirePHP->setEnabled()
* @param boolean $Enabled TRUE to enable, FALSE to disable
* @return void
*/
public static function setEnabled($Enabled)
{
$instance = FirePHP::getInstance(true);
$instance->setEnabled($Enabled);
}
/**
* Check if logging is enabled
*
* @see FirePHP->getEnabled()
* @return boolean TRUE if enabled
*/
public static function getEnabled()
{
$instance = FirePHP::getInstance(true);
return $instance->getEnabled();
}
/**
* Specify a filter to be used when encoding an object
*
* Filters are used to exclude object members.
*
* @see FirePHP->setObjectFilter()
* @param string $Class The class name of the object
* @param array $Filter An array or members to exclude
* @return void
*/
public static function setObjectFilter($Class, $Filter)
{
$instance = FirePHP::getInstance(true);
$instance->setObjectFilter($Class, $Filter);
}
/**
* Set some options for the library
*
* @see FirePHP->setOptions()
* @param array $Options The options to be set
* @return void
*/
public static function setOptions($Options)
{
$instance = FirePHP::getInstance(true);
$instance->setOptions($Options);
}
/**
* Get options for the library
*
* @see FirePHP->getOptions()
* @return array The options
*/
public static function getOptions()
{
$instance = FirePHP::getInstance(true);
return $instance->getOptions();
}
/**
* Log object to firebug
*
* @see http://www.firephp.org/Wiki/Reference/Fb
* @param mixed $Object
* @return true
* @throws Exception
*/
public static function send()
{
$instance = FirePHP::getInstance(true);
$args = func_get_args();
return call_user_func_array(array($instance,'fb'),$args);
}
/**
* Start a group for following messages
*
* Options:
* Collapsed: [true|false]
* Color: [#RRGGBB|ColorName]
*
* @param string $Name
* @param array $Options OPTIONAL Instructions on how to log the group
* @return true
*/
public static function group($Name, $Options=null)
{
$instance = FirePHP::getInstance(true);
return $instance->group($Name, $Options);
}
/**
* Ends a group you have started before
*
* @return true
* @throws Exception
*/
public static function groupEnd()
{
return self::send(null, null, FirePHP::GROUP_END);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::LOG
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public static function log($Object, $Label=null)
{
return self::send($Object, $Label, FirePHP::LOG);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::INFO
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public static function info($Object, $Label=null)
{
return self::send($Object, $Label, FirePHP::INFO);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::WARN
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public static function warn($Object, $Label=null)
{
return self::send($Object, $Label, FirePHP::WARN);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::ERROR
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public static function error($Object, $Label=null)
{
return self::send($Object, $Label, FirePHP::ERROR);
}
/**
* Dumps key and variable to firebug server panel
*
* @see FirePHP::DUMP
* @param string $Key
* @param mixed $Variable
* @return true
* @throws Exception
*/
public static function dump($Key, $Variable)
{
return self::send($Variable, $Key, FirePHP::DUMP);
}
/**
* Log a trace in the firebug console
*
* @see FirePHP::TRACE
* @param string $Label
* @return true
* @throws Exception
*/
public static function trace($Label)
{
return self::send($Label, FirePHP::TRACE);
}
/**
* Log a table in the firebug console
*
* @see FirePHP::TABLE
* @param string $Label
* @param string $Table
* @return true
* @throws Exception
*/
public static function table($Label, $Table)
{
return self::send($Table, $Label, FirePHP::TABLE);
}
}
if (!defined('E_STRICT')) {
define('E_STRICT', 2048);
}
if (!defined('E_RECOVERABLE_ERROR')) {
define('E_RECOVERABLE_ERROR', 4096);
}
if (!defined('E_DEPRECATED')) {
define('E_DEPRECATED', 8192);
}
if (!defined('E_USER_DEPRECATED')) {
define('E_USER_DEPRECATED', 16384);
}
/**
* Sends the given data to the FirePHP Firefox Extension.
* The data can be displayed in the Firebug Console or in the
* "Server" request tab.
*
* For more information see: http://www.firephp.org/
*
* @copyright Copyright (C) 2007-2009 Christoph Dorn
* @author Christoph Dorn <christoph@christophdorn.com>
* @license http://www.opensource.org/licenses/bsd-license.php
* @package FirePHPCore
*/
class FirePHP {
/**
* FirePHP version
*
* @var string
*/
const VERSION = '0.3'; // @pinf replace '0.3' with '%%package.version%%'
/**
* Firebug LOG level
*
* Logs a message to firebug console.
*
* @var string
*/
const LOG = 'LOG';
/**
* Firebug INFO level
*
* Logs a message to firebug console and displays an info icon before the message.
*
* @var string
*/
const INFO = 'INFO';
/**
* Firebug WARN level
*
* Logs a message to firebug console, displays an warning icon before the message and colors the line turquoise.
*
* @var string
*/
const WARN = 'WARN';
/**
* Firebug ERROR level
*
* Logs a message to firebug console, displays an error icon before the message and colors the line yellow. Also increments the firebug error count.
*
* @var string
*/
const ERROR = 'ERROR';
/**
* Dumps a variable to firebug's server panel
*
* @var string
*/
const DUMP = 'DUMP';
/**
* Displays a stack trace in firebug console
*
* @var string
*/
const TRACE = 'TRACE';
/**
* Displays an exception in firebug console
*
* Increments the firebug error count.
*
* @var string
*/
const EXCEPTION = 'EXCEPTION';
/**
* Displays an table in firebug console
*
* @var string
*/
const TABLE = 'TABLE';
/**
* Starts a group in firebug console
*
* @var string
*/
const GROUP_START = 'GROUP_START';
/**
* Ends a group in firebug console
*
* @var string
*/
const GROUP_END = 'GROUP_END';
/**
* Singleton instance of FirePHP
*
* @var FirePHP
*/
protected static $instance = null;
/**
* Flag whether we are logging from within the exception handler
*
* @var boolean
*/
protected $inExceptionHandler = false;
/**
* Flag whether to throw PHP errors that have been converted to ErrorExceptions
*
* @var boolean
*/
protected $throwErrorExceptions = true;
/**
* Flag whether to convert PHP assertion errors to Exceptions
*
* @var boolean
*/
protected $convertAssertionErrorsToExceptions = true;
/**
* Flag whether to throw PHP assertion errors that have been converted to Exceptions
*
* @var boolean
*/
protected $throwAssertionExceptions = false;
/**
* Wildfire protocol message index
*
* @var int
*/
protected $messageIndex = 1;
/**
* Options for the library
*
* @var array
*/
protected $options = array('maxDepth' => 10,
'maxObjectDepth' => 5,
'maxArrayDepth' => 5,
'useNativeJsonEncode' => true,
'includeLineNumbers' => true);
/**
* Filters used to exclude object members when encoding
*
* @var array
*/
protected $objectFilters = array(
'firephp' => array('objectStack', 'instance', 'json_objectStack'),
'firephp_test_class' => array('objectStack', 'instance', 'json_objectStack')
);
/**
* A stack of objects used to detect recursion during object encoding
*
* @var object
*/
protected $objectStack = array();
/**
* Flag to enable/disable logging
*
* @var boolean
*/
protected $enabled = true;
/**
* The insight console to log to if applicable
*
* @var object
*/
protected $logToInsightConsole = null;
/**
* When the object gets serialized only include specific object members.
*
* @return array
*/
public function __sleep()
{
return array('options','objectFilters','enabled');
}
/**
* Gets singleton instance of FirePHP
*
* @param boolean $AutoCreate
* @return FirePHP
*/
public static function getInstance($AutoCreate = false)
{
if ($AutoCreate===true && !self::$instance) {
self::init();
}
return self::$instance;
}
/**
* Creates FirePHP object and stores it for singleton access
*
* @return FirePHP
*/
public static function init()
{
return self::setInstance(new self());
}
/**
* Set the instance of the FirePHP singleton
*
* @param FirePHP $instance The FirePHP object instance
* @return FirePHP
*/
public static function setInstance($instance)
{
return self::$instance = $instance;
}
/**
* Set an Insight console to direct all logging calls to
*
* @param object $console The console object to log to
* @return void
*/
public function setLogToInsightConsole($console)
{
if(is_string($console)) {
if(get_class($this)!='FirePHP_Insight' && !is_subclass_of($this, 'FirePHP_Insight')) {
throw new Exception('FirePHP instance not an instance or subclass of FirePHP_Insight!');
}
$this->logToInsightConsole = $this->to('request')->console($console);
} else {
$this->logToInsightConsole = $console;
}
}
/**
* Enable and disable logging to Firebug
*
* @param boolean $Enabled TRUE to enable, FALSE to disable
* @return void
*/
public function setEnabled($Enabled)
{
$this->enabled = $Enabled;
}
/**
* Check if logging is enabled
*
* @return boolean TRUE if enabled
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Specify a filter to be used when encoding an object
*
* Filters are used to exclude object members.
*
* @param string $Class The class name of the object
* @param array $Filter An array of members to exclude
* @return void
*/
public function setObjectFilter($Class, $Filter)
{
$this->objectFilters[strtolower($Class)] = $Filter;
}
/**
* Set some options for the library
*
* Options:
* - maxDepth: The maximum depth to traverse (default: 10)
* - maxObjectDepth: The maximum depth to traverse objects (default: 5)
* - maxArrayDepth: The maximum depth to traverse arrays (default: 5)
* - useNativeJsonEncode: If true will use json_encode() (default: true)
* - includeLineNumbers: If true will include line numbers and filenames (default: true)
*
* @param array $Options The options to be set
* @return void
*/
public function setOptions($Options)
{
$this->options = array_merge($this->options,$Options);
}
/**
* Get options from the library
*
* @return array The currently set options
*/
public function getOptions()
{
return $this->options;
}
/**
* Set an option for the library
*
* @param string $Name
* @param mixed $Value
* @throws Exception
* @return void
*/
public function setOption($Name, $Value)
{
if (!isset($this->options[$Name])) {
throw $this->newException('Unknown option: ' . $Name);
}
$this->options[$Name] = $Value;
}
/**
* Get an option from the library
*
* @param string $Name
* @throws Exception
* @return mixed
*/
public function getOption($Name)
{
if (!isset($this->options[$Name])) {
throw $this->newException('Unknown option: ' . $Name);
}
return $this->options[$Name];
}
/**
* Register FirePHP as your error handler
*
* Will throw exceptions for each php error.
*
* @return mixed Returns a string containing the previously defined error handler (if any)
*/
public function registerErrorHandler($throwErrorExceptions = false)
{
//NOTE: The following errors will not be caught by this error handler:
// E_ERROR, E_PARSE, E_CORE_ERROR,
// E_CORE_WARNING, E_COMPILE_ERROR,
// E_COMPILE_WARNING, E_STRICT
$this->throwErrorExceptions = $throwErrorExceptions;
return set_error_handler(array($this,'errorHandler'));
}
/**
* FirePHP's error handler
*
* Throws exception for each php error that will occur.
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param array $errcontext
*/
public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext)
{
// Don't throw exception if error reporting is switched off
if (error_reporting() == 0) {
return;
}
// Only throw exceptions for errors we are asking for
if (error_reporting() & $errno) {
$exception = new ErrorException($errstr, 0, $errno, $errfile, $errline);
if ($this->throwErrorExceptions) {
throw $exception;
} else {
$this->fb($exception);
}
}
}
/**
* Register FirePHP as your exception handler
*
* @return mixed Returns the name of the previously defined exception handler,
* or NULL on error.
* If no previous handler was defined, NULL is also returned.
*/
public function registerExceptionHandler()
{
return set_exception_handler(array($this,'exceptionHandler'));
}
/**
* FirePHP's exception handler
*
* Logs all exceptions to your firebug console and then stops the script.
*
* @param Exception $Exception
* @throws Exception
*/
function exceptionHandler($Exception)
{
$this->inExceptionHandler = true;
header('HTTP/1.1 500 Internal Server Error');
try {
$this->fb($Exception);
} catch (Exception $e) {
echo 'We had an exception: ' . $e;
}
$this->inExceptionHandler = false;
}
/**
* Register FirePHP driver as your assert callback
*
* @param boolean $convertAssertionErrorsToExceptions
* @param boolean $throwAssertionExceptions
* @return mixed Returns the original setting or FALSE on errors
*/
public function registerAssertionHandler($convertAssertionErrorsToExceptions = true, $throwAssertionExceptions = false)
{
$this->convertAssertionErrorsToExceptions = $convertAssertionErrorsToExceptions;
$this->throwAssertionExceptions = $throwAssertionExceptions;
if ($throwAssertionExceptions && !$convertAssertionErrorsToExceptions) {
throw $this->newException('Cannot throw assertion exceptions as assertion errors are not being converted to exceptions!');
}
return assert_options(ASSERT_CALLBACK, array($this, 'assertionHandler'));
}
/**
* FirePHP's assertion handler
*
* Logs all assertions to your firebug console and then stops the script.
*
* @param string $file File source of assertion
* @param int $line Line source of assertion
* @param mixed $code Assertion code
*/
public function assertionHandler($file, $line, $code)
{
if ($this->convertAssertionErrorsToExceptions) {
$exception = new ErrorException('Assertion Failed - Code[ '.$code.' ]', 0, null, $file, $line);
if ($this->throwAssertionExceptions) {
throw $exception;
} else {
$this->fb($exception);
}
} else {
$this->fb($code, 'Assertion Failed', FirePHP::ERROR, array('File'=>$file,'Line'=>$line));
}
}
/**
* Start a group for following messages.
*
* Options:
* Collapsed: [true|false]
* Color: [#RRGGBB|ColorName]
*
* @param string $Name
* @param array $Options OPTIONAL Instructions on how to log the group
* @return true
* @throws Exception
*/
public function group($Name, $Options = null)
{
if (!$Name) {
throw $this->newException('You must specify a label for the group!');
}
if ($Options) {
if (!is_array($Options)) {
throw $this->newException('Options must be defined as an array!');
}
if (array_key_exists('Collapsed', $Options)) {
$Options['Collapsed'] = ($Options['Collapsed'])?'true':'false';
}
}
return $this->fb(null, $Name, FirePHP::GROUP_START, $Options);
}
/**
* Ends a group you have started before
*
* @return true
* @throws Exception
*/
public function groupEnd()
{
return $this->fb(null, null, FirePHP::GROUP_END);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::LOG
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public function log($Object, $Label = null, $Options = array())
{
return $this->fb($Object, $Label, FirePHP::LOG, $Options);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::INFO
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public function info($Object, $Label = null, $Options = array())
{
return $this->fb($Object, $Label, FirePHP::INFO, $Options);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::WARN
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public function warn($Object, $Label = null, $Options = array())
{
return $this->fb($Object, $Label, FirePHP::WARN, $Options);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::ERROR
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public function error($Object, $Label = null, $Options = array())
{
return $this->fb($Object, $Label, FirePHP::ERROR, $Options);
}
/**
* Dumps key and variable to firebug server panel
*
* @see FirePHP::DUMP
* @param string $Key
* @param mixed $Variable
* @return true
* @throws Exception
*/
public function dump($Key, $Variable, $Options = array())
{
if (!is_string($Key)) {
throw $this->newException('Key passed to dump() is not a string');
}
if (strlen($Key)>100) {
throw $this->newException('Key passed to dump() is longer than 100 characters');
}
if (!preg_match_all('/^[a-zA-Z0-9-_\.:]*$/', $Key, $m)) {
throw $this->newException('Key passed to dump() contains invalid characters [a-zA-Z0-9-_\.:]');
}
return $this->fb($Variable, $Key, FirePHP::DUMP, $Options);
}
/**
* Log a trace in the firebug console
*
* @see FirePHP::TRACE
* @param string $Label
* @return true
* @throws Exception
*/
public function trace($Label)
{
return $this->fb($Label, FirePHP::TRACE);
}
/**
* Log a table in the firebug console
*
* @see FirePHP::TABLE
* @param string $Label
* @param string $Table
* @return true
* @throws Exception
*/
public function table($Label, $Table, $Options = array())
{
return $this->fb($Table, $Label, FirePHP::TABLE, $Options);
}
/**
* Insight API wrapper
*
* @see Insight_Helper::to()
*/
public static function to()
{
$instance = self::getInstance();
if (!method_exists($instance, "_to")) {
throw new Exception("FirePHP::to() implementation not loaded");
}
$args = func_get_args();
return call_user_func_array(array($instance, '_to'), $args);
}
/**
* Insight API wrapper
*
* @see Insight_Helper::plugin()
*/
public static function plugin()
{
$instance = self::getInstance();
if (!method_exists($instance, "_plugin")) {
throw new Exception("FirePHP::plugin() implementation not loaded");
}
$args = func_get_args();
return call_user_func_array(array($instance, '_plugin'), $args);
}
/**
* Check if FirePHP is installed on client
*
* @return boolean
*/
public function detectClientExtension()
{
// Check if FirePHP is installed on client via User-Agent header
if (@preg_match_all('/\sFirePHP\/([\.\d]*)\s?/si',$this->getUserAgent(),$m) &&
version_compare($m[1][0],'0.0.6','>=')) {
return true;
} else
// Check if FirePHP is installed on client via X-FirePHP-Version header
if (@preg_match_all('/^([\.\d]*)$/si',$this->getRequestHeader("X-FirePHP-Version"),$m) &&
version_compare($m[1][0],'0.0.6','>=')) {
return true;
}
return false;
}
/**
* Log varible to Firebug
*
* @see http://www.firephp.org/Wiki/Reference/Fb
* @param mixed $Object The variable to be logged
* @return true Return TRUE if message was added to headers, FALSE otherwise
* @throws Exception
*/
public function fb($Object)
{
if($this instanceof FirePHP_Insight && method_exists($this, '_logUpgradeClientMessage')) {
if(!FirePHP_Insight::$upgradeClientMessageLogged) { // avoid infinite recursion as _logUpgradeClientMessage() logs a message
$this->_logUpgradeClientMessage();
}
}
static $insightGroupStack = array();
if (!$this->getEnabled()) {
return false;
}
if ($this->headersSent($filename, $linenum)) {
// If we are logging from within the exception handler we cannot throw another exception
if ($this->inExceptionHandler) {
// Simply echo the error out to the page
echo '<div style="border: 2px solid red; font-family: Arial; font-size: 12px; background-color: lightgray; padding: 5px;"><span style="color: red; font-weight: bold;">FirePHP ERROR:</span> Headers already sent in <b>'.$filename.'</b> on line <b>'.$linenum.'</b>. Cannot send log data to FirePHP. You must have Output Buffering enabled via ob_start() or output_buffering ini directive.</div>';
} else {
throw $this->newException('Headers already sent in '.$filename.' on line '.$linenum.'. Cannot send log data to FirePHP. You must have Output Buffering enabled via ob_start() or output_buffering ini directive.');
}
}
$Type = null;
$Label = null;
$Options = array();
if (func_num_args()==1) {
} else
if (func_num_args()==2) {
switch(func_get_arg(1)) {
case self::LOG:
case self::INFO:
case self::WARN:
case self::ERROR:
case self::DUMP:
case self::TRACE:
case self::EXCEPTION:
case self::TABLE:
case self::GROUP_START:
case self::GROUP_END:
$Type = func_get_arg(1);
break;
default:
$Label = func_get_arg(1);
break;
}
} else
if (func_num_args()==3) {
$Type = func_get_arg(2);
$Label = func_get_arg(1);
} else
if (func_num_args()==4) {
$Type = func_get_arg(2);
$Label = func_get_arg(1);
$Options = func_get_arg(3);
} else {
throw $this->newException('Wrong number of arguments to fb() function!');
}
if($this->logToInsightConsole!==null && (get_class($this)=='FirePHP_Insight' || is_subclass_of($this, 'FirePHP_Insight'))) {
$msg = $this->logToInsightConsole;
if ($Object instanceof Exception) {
$Type = self::EXCEPTION;
}
if($Label && $Type!=self::TABLE && $Type!=self::GROUP_START) {
$msg = $msg->label($Label);
}
switch($Type) {
case self::DUMP:
case self::LOG:
return $msg->log($Object);
case self::INFO:
return $msg->info($Object);
case self::WARN:
return $msg->warn($Object);
case self::ERROR:
return $msg->error($Object);
case self::TRACE:
return $msg->trace($Object);
case self::EXCEPTION:
return $this->plugin('engine')->handleException($Object, $msg);
case self::TABLE:
if (isset($Object[0]) && !is_string($Object[0]) && $Label) {
$Object = array($Label, $Object);
}
return $msg->table($Object[0], array_slice($Object[1],1), $Object[1][0]);
case self::GROUP_START:
$insightGroupStack[] = $msg->group(md5($Label))->open();
return $msg->log($Label);
case self::GROUP_END:
if(count($insightGroupStack)==0) {
throw new Error('Too many groupEnd() as opposed to group() calls!');
}
$group = array_pop($insightGroupStack);
return $group->close();
default:
return $msg->log($Object);
}
}
if (!$this->detectClientExtension()) {
return false;
}
$meta = array();
$skipFinalObjectEncode = false;
if ($Object instanceof Exception) {
$meta['file'] = $this->_escapeTraceFile($Object->getFile());
$meta['line'] = $Object->getLine();
$trace = $Object->getTrace();
if ($Object instanceof ErrorException
&& isset($trace[0]['function'])
&& $trace[0]['function']=='errorHandler'
&& isset($trace[0]['class'])
&& $trace[0]['class']=='FirePHP') {
$severity = false;
switch($Object->getSeverity()) {
case E_WARNING: $severity = 'E_WARNING'; break;
case E_NOTICE: $severity = 'E_NOTICE'; break;
case E_USER_ERROR: $severity = 'E_USER_ERROR'; break;
case E_USER_WARNING: $severity = 'E_USER_WARNING'; break;
case E_USER_NOTICE: $severity = 'E_USER_NOTICE'; break;
case E_STRICT: $severity = 'E_STRICT'; break;
case E_RECOVERABLE_ERROR: $severity = 'E_RECOVERABLE_ERROR'; break;
case E_DEPRECATED: $severity = 'E_DEPRECATED'; break;
case E_USER_DEPRECATED: $severity = 'E_USER_DEPRECATED'; break;
}
$Object = array('Class'=>get_class($Object),
'Message'=>$severity.': '.$Object->getMessage(),
'File'=>$this->_escapeTraceFile($Object->getFile()),
'Line'=>$Object->getLine(),
'Type'=>'trigger',
'Trace'=>$this->_escapeTrace(array_splice($trace,2)));
$skipFinalObjectEncode = true;
} else {
$Object = array('Class'=>get_class($Object),
'Message'=>$Object->getMessage(),
'File'=>$this->_escapeTraceFile($Object->getFile()),
'Line'=>$Object->getLine(),
'Type'=>'throw',
'Trace'=>$this->_escapeTrace($trace));
$skipFinalObjectEncode = true;
}
$Type = self::EXCEPTION;
} else
if ($Type==self::TRACE) {
$trace = debug_backtrace();
if (!$trace) return false;
for( $i=0 ; $i<sizeof($trace) ; $i++ ) {
if (isset($trace[$i]['class'])
&& isset($trace[$i]['file'])
&& ($trace[$i]['class']=='FirePHP'
|| $trace[$i]['class']=='FB')
&& (substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php'
|| substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) {
/* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */
} else
if (isset($trace[$i]['class'])
&& isset($trace[$i+1]['file'])
&& $trace[$i]['class']=='FirePHP'
&& substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') {
/* Skip fb() */
} else
if ($trace[$i]['function']=='fb'
|| $trace[$i]['function']=='trace'
|| $trace[$i]['function']=='send') {
$Object = array('Class'=>isset($trace[$i]['class'])?$trace[$i]['class']:'',
'Type'=>isset($trace[$i]['type'])?$trace[$i]['type']:'',
'Function'=>isset($trace[$i]['function'])?$trace[$i]['function']:'',
'Message'=>$trace[$i]['args'][0],
'File'=>isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'',
'Line'=>isset($trace[$i]['line'])?$trace[$i]['line']:'',
'Args'=>isset($trace[$i]['args'])?$this->encodeObject($trace[$i]['args']):'',
'Trace'=>$this->_escapeTrace(array_splice($trace,$i+1)));
$skipFinalObjectEncode = true;
$meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'';
$meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:'';
break;
}
}
} else
if ($Type==self::TABLE) {
if (isset($Object[0]) && is_string($Object[0])) {
$Object[1] = $this->encodeTable($Object[1]);
} else {
$Object = $this->encodeTable($Object);
}
$skipFinalObjectEncode = true;
} else
if ($Type==self::GROUP_START) {
if (!$Label) {
throw $this->newException('You must specify a label for the group!');
}
} else {
if ($Type===null) {
$Type = self::LOG;
}
}
if ($this->options['includeLineNumbers']) {
if (!isset($meta['file']) || !isset($meta['line'])) {
$trace = debug_backtrace();
for( $i=0 ; $trace && $i<sizeof($trace) ; $i++ ) {
if (isset($trace[$i]['class'])
&& isset($trace[$i]['file'])
&& ($trace[$i]['class']=='FirePHP'
|| $trace[$i]['class']=='FB')
&& (substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php'
|| substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) {
/* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */
} else
if (isset($trace[$i]['class'])
&& isset($trace[$i+1]['file'])
&& $trace[$i]['class']=='FirePHP'
&& substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') {
/* Skip fb() */
} else
if (isset($trace[$i]['file'])
&& substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php') {
/* Skip FB::fb() */
} else {
$meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'';
$meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:'';
break;
}
}
}
} else {
unset($meta['file']);
unset($meta['line']);
}
$this->setHeader('X-Wf-Protocol-1','http://meta.wildfirehq.org/Protocol/JsonStream/0.2');
$this->setHeader('X-Wf-1-Plugin-1','http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/'.self::VERSION);
$structure_index = 1;
if ($Type==self::DUMP) {
$structure_index = 2;
$this->setHeader('X-Wf-1-Structure-2','http://meta.firephp.org/Wildfire/Structure/FirePHP/Dump/0.1');
} else {
$this->setHeader('X-Wf-1-Structure-1','http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1');
}
if ($Type==self::DUMP) {
$msg = '{"'.$Label.'":'.$this->jsonEncode($Object, $skipFinalObjectEncode).'}';
} else {
$msg_meta = $Options;
$msg_meta['Type'] = $Type;
if ($Label!==null) {
$msg_meta['Label'] = $Label;
}
if (isset($meta['file']) && !isset($msg_meta['File'])) {
$msg_meta['File'] = $meta['file'];
}
if (isset($meta['line']) && !isset($msg_meta['Line'])) {
$msg_meta['Line'] = $meta['line'];
}
$msg = '['.$this->jsonEncode($msg_meta).','.$this->jsonEncode($Object, $skipFinalObjectEncode).']';
}
$parts = explode("\n",chunk_split($msg, 5000, "\n"));
for( $i=0 ; $i<count($parts) ; $i++) {
$part = $parts[$i];
if ($part) {
if (count($parts)>2) {
// Message needs to be split into multiple parts
$this->setHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex,
(($i==0)?strlen($msg):'')
. '|' . $part . '|'
. (($i<count($parts)-2)?'\\':''));
} else {
$this->setHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex,
strlen($part) . '|' . $part . '|');
}
$this->messageIndex++;
if ($this->messageIndex > 99999) {
throw $this->newException('Maximum number (99,999) of messages reached!');
}
}
}
$this->setHeader('X-Wf-1-Index',$this->messageIndex-1);
return true;
}
/**
* Standardizes path for windows systems.
*
* @param string $Path
* @return string
*/
protected function _standardizePath($Path)
{
return preg_replace('/\\\\+/','/',$Path);
}
/**
* Escape trace path for windows systems
*
* @param array $Trace
* @return array
*/
protected function _escapeTrace($Trace)
{
if (!$Trace) return $Trace;
for( $i=0 ; $i<sizeof($Trace) ; $i++ ) {
if (isset($Trace[$i]['file'])) {
$Trace[$i]['file'] = $this->_escapeTraceFile($Trace[$i]['file']);
}
if (isset($Trace[$i]['args'])) {
$Trace[$i]['args'] = $this->encodeObject($Trace[$i]['args']);
}
}
return $Trace;
}
/**
* Escape file information of trace for windows systems
*
* @param string $File
* @return string
*/
protected function _escapeTraceFile($File)
{
/* Check if we have a windows filepath */
if (strpos($File,'\\')) {
/* First strip down to single \ */
$file = preg_replace('/\\\\+/','\\',$File);
return $file;
}
return $File;
}
/**
* Check if headers have already been sent
*
* @param string $Filename
* @param integer $Linenum
*/
protected function headersSent(&$Filename, &$Linenum)
{
return headers_sent($Filename, $Linenum);
}
/**
* Send header
*
* @param string $Name
* @param string $Value
*/
protected function setHeader($Name, $Value)
{
return header($Name.': '.$Value);
}
/**
* Get user agent
*
* @return string|false
*/
protected function getUserAgent()
{
if (!isset($_SERVER['HTTP_USER_AGENT'])) return false;
return $_SERVER['HTTP_USER_AGENT'];
}
/**
* Get all request headers
*
* @return array
*/
public static function getAllRequestHeaders() {
static $_cached_headers = false;
if($_cached_headers!==false) {
return $_cached_headers;
}
$headers = array();
if(function_exists('getallheaders')) {
foreach( getallheaders() as $name => $value ) {
$headers[strtolower($name)] = $value;
}
} else {
foreach($_SERVER as $name => $value) {
if(substr($name, 0, 5) == 'HTTP_') {
$headers[strtolower(str_replace(' ', '-', str_replace('_', ' ', substr($name, 5))))] = $value;
}
}
}
return $_cached_headers = $headers;
}
/**
* Get a request header
*
* @return string|false
*/
protected function getRequestHeader($Name)
{
$headers = self::getAllRequestHeaders();
if (isset($headers[strtolower($Name)])) {
return $headers[strtolower($Name)];
}
return false;
}
/**
* Returns a new exception
*
* @param string $Message
* @return Exception
*/
protected function newException($Message)
{
return new Exception($Message);
}
/**
* Encode an object into a JSON string
*
* Uses PHP's jeson_encode() if available
*
* @param object $Object The object to be encoded
* @return string The JSON string
*/
public function jsonEncode($Object, $skipObjectEncode = false)
{
if (!$skipObjectEncode) {
$Object = $this->encodeObject($Object);
}
if (function_exists('json_encode')
&& $this->options['useNativeJsonEncode']!=false) {
return json_encode($Object);
} else {
return $this->json_encode($Object);
}
}
/**
* Encodes a table by encoding each row and column with encodeObject()
*
* @param array $Table The table to be encoded
* @return array
*/
protected function encodeTable($Table)
{
if (!$Table) return $Table;
$new_table = array();
foreach($Table as $row) {
if (is_array($row)) {
$new_row = array();
foreach($row as $item) {
$new_row[] = $this->encodeObject($item);
}
$new_table[] = $new_row;
}
}
return $new_table;
}
/**
* Encodes an object including members with
* protected and private visibility
*
* @param Object $Object The object to be encoded
* @param int $Depth The current traversal depth
* @return array All members of the object
*/
protected function encodeObject($Object, $ObjectDepth = 1, $ArrayDepth = 1, $MaxDepth = 1)
{
if ($MaxDepth > $this->options['maxDepth']) {
return '** Max Depth ('.$this->options['maxDepth'].') **';
}
$return = array();
if (is_resource($Object)) {
return '** '.(string)$Object.' **';
} else
if (is_object($Object)) {
if ($ObjectDepth > $this->options['maxObjectDepth']) {
return '** Max Object Depth ('.$this->options['maxObjectDepth'].') **';
}
foreach ($this->objectStack as $refVal) {
if ($refVal === $Object) {
return '** Recursion ('.get_class($Object).') **';
}
}
array_push($this->objectStack, $Object);
$return['__className'] = $class = get_class($Object);
$class_lower = strtolower($class);
$reflectionClass = new ReflectionClass($class);
$properties = array();
foreach( $reflectionClass->getProperties() as $property) {
$properties[$property->getName()] = $property;
}
$members = (array)$Object;
foreach( $properties as $plain_name => $property ) {
$name = $raw_name = $plain_name;
if ($property->isStatic()) {
$name = 'static:'.$name;
}
if ($property->isPublic()) {
$name = 'public:'.$name;
} else
if ($property->isPrivate()) {
$name = 'private:'.$name;
$raw_name = "\0".$class."\0".$raw_name;
} else
if ($property->isProtected()) {
$name = 'protected:'.$name;
$raw_name = "\0".'*'."\0".$raw_name;
}
if (!(isset($this->objectFilters[$class_lower])
&& is_array($this->objectFilters[$class_lower])
&& in_array($plain_name,$this->objectFilters[$class_lower]))) {
if (array_key_exists($raw_name,$members)
&& !$property->isStatic()) {
$return[$name] = $this->encodeObject($members[$raw_name], $ObjectDepth + 1, 1, $MaxDepth + 1);
} else {
if (method_exists($property,'setAccessible')) {
$property->setAccessible(true);
$return[$name] = $this->encodeObject($property->getValue($Object), $ObjectDepth + 1, 1, $MaxDepth + 1);
} else
if ($property->isPublic()) {
$return[$name] = $this->encodeObject($property->getValue($Object), $ObjectDepth + 1, 1, $MaxDepth + 1);
} else {
$return[$name] = '** Need PHP 5.3 to get value **';
}
}
} else {
$return[$name] = '** Excluded by Filter **';
}
}
// Include all members that are not defined in the class
// but exist in the object
foreach( $members as $raw_name => $value ) {
$name = $raw_name;
if ($name{0} == "\0") {
$parts = explode("\0", $name);
$name = $parts[2];
}
$plain_name = $name;
if (!isset($properties[$name])) {
$name = 'undeclared:'.$name;
if (!(isset($this->objectFilters[$class_lower])
&& is_array($this->objectFilters[$class_lower])
&& in_array($plain_name,$this->objectFilters[$class_lower]))) {
$return[$name] = $this->encodeObject($value, $ObjectDepth + 1, 1, $MaxDepth + 1);
} else {
$return[$name] = '** Excluded by Filter **';
}
}
}
array_pop($this->objectStack);
} elseif (is_array($Object)) {
if ($ArrayDepth > $this->options['maxArrayDepth']) {
return '** Max Array Depth ('.$this->options['maxArrayDepth'].') **';
}
foreach ($Object as $key => $val) {
// Encoding the $GLOBALS PHP array causes an infinite loop
// if the recursion is not reset here as it contains
// a reference to itself. This is the only way I have come up
// with to stop infinite recursion in this case.
if ($key=='GLOBALS'
&& is_array($val)
&& array_key_exists('GLOBALS',$val)) {
$val['GLOBALS'] = '** Recursion (GLOBALS) **';
}
$return[$key] = $this->encodeObject($val, 1, $ArrayDepth + 1, $MaxDepth + 1);
}
} else {
if (self::is_utf8($Object)) {
return $Object;
} else {
return utf8_encode($Object);
}
}
return $return;
}
/**
* Returns true if $string is valid UTF-8 and false otherwise.
*
* @param mixed $str String to be tested
* @return boolean
*/
protected static function is_utf8($str)
{
if(function_exists('mb_detect_encoding')) {
return (mb_detect_encoding($str) == 'UTF-8');
}
$c=0; $b=0;
$bits=0;
$len=strlen($str);
for($i=0; $i<$len; $i++){
$c=ord($str[$i]);
if ($c > 128){
if (($c >= 254)) return false;
elseif ($c >= 252) $bits=6;
elseif ($c >= 248) $bits=5;
elseif ($c >= 240) $bits=4;
elseif ($c >= 224) $bits=3;
elseif ($c >= 192) $bits=2;
else return false;
if (($i+$bits) > $len) return false;
while($bits > 1){
$i++;
$b=ord($str[$i]);
if ($b < 128 || $b > 191) return false;
$bits--;
}
}
}
return true;
}
/**
* Converts to and from JSON format.
*
* JSON (JavaScript Object Notation) is a lightweight data-interchange
* format. It is easy for humans to read and write. It is easy for machines
* to parse and generate. It is based on a subset of the JavaScript
* Programming Language, Standard ECMA-262 3rd Edition - December 1999.
* This feature can also be found in Python. JSON is a text format that is
* completely language independent but uses conventions that are familiar
* to programmers of the C-family of languages, including C, C++, C#, Java,
* JavaScript, Perl, TCL, and many others. These properties make JSON an
* ideal data-interchange language.
*
* This package provides a simple encoder and decoder for JSON notation. It
* is intended for use with client-side Javascript applications that make
* use of HTTPRequest to perform server communication functions - data can
* be encoded into JSON notation for use in a client-side javascript, or
* decoded from incoming Javascript requests. JSON format is native to
* Javascript, and can be directly eval()'ed with no further parsing
* overhead
*
* All strings should be in ASCII or UTF-8 format!
*
* LICENSE: Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met: Redistributions of source code must retain the
* above copyright notice, this list of conditions and the following
* disclaimer. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* @category
* @package Services_JSON
* @author Michal Migurski <mike-json@teczno.com>
* @author Matt Knapp <mdknapp[at]gmail[dot]com>
* @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
* @author Christoph Dorn <christoph@christophdorn.com>
* @copyright 2005 Michal Migurski
* @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
* @license http://www.opensource.org/licenses/bsd-license.php
* @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
*/
/**
* Keep a list of objects as we descend into the array so we can detect recursion.
*/
private $json_objectStack = array();
/**
* convert a string from one UTF-8 char to one UTF-16 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf8 UTF-8 character
* @return string UTF-16 character
* @access private
*/
private function json_utf82utf16($utf8)
{
// oh please oh please oh please oh please oh please
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
}
switch(strlen($utf8)) {
case 1:
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return $utf8;
case 2:
// return a UTF-16 character from a 2-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x07 & (ord($utf8{0}) >> 2))
. chr((0xC0 & (ord($utf8{0}) << 6))
| (0x3F & ord($utf8{1})));
case 3:
// return a UTF-16 character from a 3-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr((0xF0 & (ord($utf8{0}) << 4))
| (0x0F & (ord($utf8{1}) >> 2)))
. chr((0xC0 & (ord($utf8{1}) << 6))
| (0x7F & ord($utf8{2})));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* encodes an arbitrary variable into JSON format
*
* @param mixed $var any number, boolean, string, array, or object to be encoded.
* see argument 1 to Services_JSON() above for array-parsing behavior.
* if var is a strng, note that encode() always expects it
* to be in ASCII or UTF-8 format!
*
* @return mixed JSON string representation of input var or an error if a problem occurs
* @access public
*/
private function json_encode($var)
{
if (is_object($var)) {
if (in_array($var,$this->json_objectStack)) {
return '"** Recursion **"';
}
}
switch (gettype($var)) {
case 'boolean':
return $var ? 'true' : 'false';
case 'NULL':
return 'null';
case 'integer':
return (int) $var;
case 'double':
case 'float':
return (float) $var;
case 'string':
// STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
$ascii = '';
$strlen_var = strlen($var);
/*
* Iterate over every character in the string,
* escaping with a slash or encoding to UTF-8 where necessary
*/
for ($c = 0; $c < $strlen_var; ++$c) {
$ord_var_c = ord($var{$c});
switch (true) {
case $ord_var_c == 0x08:
$ascii .= '\b';
break;
case $ord_var_c == 0x09:
$ascii .= '\t';
break;
case $ord_var_c == 0x0A:
$ascii .= '\n';
break;
case $ord_var_c == 0x0C:
$ascii .= '\f';
break;
case $ord_var_c == 0x0D:
$ascii .= '\r';
break;
case $ord_var_c == 0x22:
case $ord_var_c == 0x2F:
case $ord_var_c == 0x5C:
// double quote, slash, slosh
$ascii .= '\\'.$var{$c};
break;
case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ascii .= $var{$c};
break;
case (($ord_var_c & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110XXXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c, ord($var{$c + 1}));
$c += 1;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}));
$c += 2;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}));
$c += 3;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}));
$c += 4;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}),
ord($var{$c + 5}));
$c += 5;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
}
}
return '"'.$ascii.'"';
case 'array':
/*
* As per JSON spec if any array key is not an integer
* we must treat the the whole array as an object. We
* also try to catch a sparsely populated associative
* array with numeric keys here because some JS engines
* will create an array with empty indexes up to
* max_index which can cause memory issues and because
* the keys, which may be relevant, will be remapped
* otherwise.
*
* As per the ECMA and JSON specification an object may
* have any string as a property. Unfortunately due to
* a hole in the ECMA specification if the key is a
* ECMA reserved word or starts with a digit the
* parameter is only accessible using ECMAScript's
* bracket notation.
*/
// treat as a JSON object
if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
$this->json_objectStack[] = $var;
$properties = array_map(array($this, 'json_name_value'),
array_keys($var),
array_values($var));
array_pop($this->json_objectStack);
foreach($properties as $property) {
if ($property instanceof Exception) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
}
$this->json_objectStack[] = $var;
// treat it like a regular array
$elements = array_map(array($this, 'json_encode'), $var);
array_pop($this->json_objectStack);
foreach($elements as $element) {
if ($element instanceof Exception) {
return $element;
}
}
return '[' . join(',', $elements) . ']';
case 'object':
$vars = self::encodeObject($var);
$this->json_objectStack[] = $var;
$properties = array_map(array($this, 'json_name_value'),
array_keys($vars),
array_values($vars));
array_pop($this->json_objectStack);
foreach($properties as $property) {
if ($property instanceof Exception) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
default:
return null;
}
}
/**
* array-walking function for use in generating JSON-formatted name-value pairs
*
* @param string $name name of key to use
* @param mixed $value reference to an array element to be encoded
*
* @return string JSON-formatted name-value pair, like '"name":value'
* @access private
*/
private function json_name_value($name, $value)
{
// Encoding the $GLOBALS PHP array causes an infinite loop
// if the recursion is not reset here as it contains
// a reference to itself. This is the only way I have come up
// with to stop infinite recursion in this case.
if ($name=='GLOBALS'
&& is_array($value)
&& array_key_exists('GLOBALS',$value)) {
$value['GLOBALS'] = '** Recursion **';
}
$encoded_value = $this->json_encode($value);
if ($encoded_value instanceof Exception) {
return $encoded_value;
}
return $this->json_encode(strval($name)) . ':' . $encoded_value;
}
/**
* @deprecated
*/
public function setProcessorUrl($URL)
{
trigger_error("The FirePHP::setProcessorUrl() method is no longer supported", E_USER_DEPRECATED);
}
/**
* @deprecated
*/
public function setRendererUrl($URL)
{
trigger_error("The FirePHP::setRendererUrl() method is no longer supported", E_USER_DEPRECATED);
}
} | 10npsite | trunk/DThinkPHP/Extend/Behavior/FireShowPageTraceBehavior.class.php | PHP | asf20 | 72,118 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CronRunBehavior.class.php 2616 2012-01-16 08:36:46Z liu21st $
class CronRunBehavior extends Behavior {
protected $options = array(
'CRON_MAX_TIME'=>60,
);
public function run(&$params) {
// 锁定自动执行
$lockfile = RUNTIME_PATH.'cron.lock';
if(is_writable($lockfile) && filemtime($lockfile) > $_SERVER['REQUEST_TIME'] - C('CRON_MAX_TIME')) {
return ;
} else {
touch($lockfile);
}
set_time_limit(1000);
ignore_user_abort(true);
// 载入cron配置文件
// 格式 return array(
// 'cronname'=>array('filename',intervals,nextruntime),...
// );
if(is_file(RUNTIME_PATH.'~crons.php')) {
$crons = include RUNTIME_PATH.'~crons.php';
}elseif(is_file(CONF_PATH.'crons.php')){
$crons = include CONF_PATH.'crons.php';
}
if(isset($crons) && is_array($crons)) {
$update = false;
$log = array();
foreach ($crons as $key=>$cron){
if(empty($cron[2]) || $_SERVER['REQUEST_TIME']>=$cron[2]) {
// 到达时间 执行cron文件
G('cronStart');
include LIB_PATH.'Cron/'.$cron[0].'.php';
$_useTime = G('cronStart','cronEnd', 6);
// 更新cron记录
$cron[2] = $_SERVER['REQUEST_TIME']+$cron[1];
$crons[$key] = $cron;
$log[] = "Cron:$key Runat ".date('Y-m-d H:i:s')." Use $_useTime s\n";
$update = true;
}
}
if($update) {
// 记录Cron执行日志
Log::write(implode('',$log));
// 更新cron文件
$content = "<?php\nreturn ".var_export($crons,true).";\n?>";
file_put_contents(RUNTIME_PATH.'~crons.php',$content);
}
}
// 解除锁定
unlink($lockfile);
return ;
}
} | 10npsite | trunk/DThinkPHP/Extend/Behavior/CronRunBehavior.class.php | PHP | asf20 | 2,723 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: BrowserCheckBehavior.class.php 2616 2012-01-16 08:36:46Z liu21st $
class BrowserCheckBehavior extends Behavior {
protected $options = array(
'LIMIT_REFLESH_TIMES'=>10,
);
public function run(&$params) {
if($_SERVER['REQUEST_METHOD'] == 'GET') {
// 启用页面防刷新机制
$guid = md5($_SERVER['PHP_SELF']);
// 检查页面刷新间隔
if(Cookie::is_set('_last_visit_time_'.$guid) && Cookie::get('_last_visit_time_'.$guid)>time()-C('LIMIT_REFLESH_TIMES')) {
// 页面刷新读取浏览器缓存
header('HTTP/1.1 304 Not Modified');
exit;
}else{
// 缓存当前地址访问时间
Cookie::set('_last_visit_time_'.$guid, $_SERVER['REQUEST_TIME'],$_SERVER['REQUEST_TIME']+3600);
//header('Last-Modified:'.(date('D,d M Y H:i:s',$_SERVER['REQUEST_TIME']-C('LIMIT_REFLESH_TIMES'))).' GMT');
}
}
}
} | 10npsite | trunk/DThinkPHP/Extend/Behavior/BrowserCheckBehavior.class.php | PHP | asf20 | 1,646 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: AgentCheckBehavior.class.php 2616 2012-01-16 08:36:46Z liu21st $
class AgentCheckBehavior extends Behavior {
protected $options = array(
'LIMIT_PROXY_VISIT'=>true,
);
public function run(&$params) {
// 代理访问检测
if(C('LIMIT_PROXY_VISIT') && ($_SERVER['HTTP_X_FORWARDED_FOR'] || $_SERVER['HTTP_VIA'] || $_SERVER['HTTP_PROXY_CONNECTION'] || $_SERVER['HTTP_USER_AGENT_VIA'])) {
// 禁止代理访问
exit('Access Denied');
}
}
}
?> | 10npsite | trunk/DThinkPHP/Extend/Behavior/AgentCheckBehavior.class.php | PHP | asf20 | 1,145 |
.te_main{
border:#b1bab7 1px solid;
background:#FFF;
}
.te_toolbar_box {
padding-bottom:5px;
border-bottom:#b1bab7 1px solid;
background:#f5f5f5;
}
.te_toolbar{
margin-left:10px;
margin-right:8px;
overflow:hidden;
_zoom: 1;
}
.te_toolbar:after {
content: "\0020";
display: block;
height: 0;
clear: both;
}
*+html .te_toolbar{
overflow:hidden;
}
.te_main iframe{
}
/*textarea样式, 注意设置resize:none,不然火狐能拖动*/
.te_main textarea{
border:none;
resize:none;
overflow-y:scroll;
}
.te_dialog{
position:absolute;
display:none;
}
.te_group{
float:left;
margin:1px;
height:17px;
overflow-y:hidden;
margin-top:5px;
margin-left:-2px;
margin-right:2px;
}
.te_btn{
float:left;
margin-right:5px;
width:27px;
height:17px;
cursor:pointer;
font-size:8px;
background-image:url(img/bg_img.png);
background-repeat:no-repeat;
}
.te_line{
width:0;
height:17px;
border-left:1px solid #fff;
border-right:1px solid #b0baba;
float:left;
overflow:hidden;
zoom:1;
margin-right:5px;
}
.te_btn_source{
background-position: 2px -4px ;
}
.te_btn_undo{
background-position: 6px -29px;
}
.te_btn_redo{
background-position: 6px -54px;
}
.te_btn_cut{
background-position: 6px -79px;
}
.te_btn_copy{
background-position: 6px -104px;
}
.te_btn_paste{
background-position: 6px -129px;
}
.te_btn_pastetext{
background-position: 6px -154px;
}
.te_btn_pastefromword{
background-position: 6px -179px;
}
.te_btn_selectAll{
background-position: 6px -204px;
}
.te_btn_blockquote{
background-position: 6px -229px;
}
.te_btn_find{
background-position: 6px -254px;
}
.te_btn_image{
background-position: 6px -279px;
}
.te_btn_flash{
background-position: 6px -304px;
}
.te_btn_media{
background-position: 6px -329px;
}
.te_btn_table{
background-position: 6px -354px;
}
.te_btn_hr{
background-position: 6px -379px;
}
.te_btn_pagebreak{
background-position: 6px -404px;
}
.te_btn_face{
background-position: 6px -429px;
}
.te_btn_code{
background-position: 6px -454px;
}
.te_btn_link{
background-position: 6px -479px;
}
.te_btn_unlink{
background-position: 6px -504px;
}
.te_btn_print{
background-position: 6px -529px;
}
.te_btn_fullscreen{
background-position: 6px -554px;
}
.te_btn_style{
background-position: 6px -579px;
}
.te_btn_font{
background-position: 6px -604px;
}
.te_btn_fontsize{
background-position: 6px -629px;
}
.te_btn_fontcolor{
background-position: 6px -654px;
}
.te_btn_backcolor{
background-position: 6px -679px;
}
.te_btn_bold{
background-position: 6px -704px;
}
.te_btn_italic{
background-position: 6px -729px;
}
.te_btn_underline{
background-position: 6px -754px;
}
.te_btn_strikethrough{
background-position: 6px -779px;
}
.te_btn_unformat{
background-position: 6px -804px;
}
.te_btn_leftalign{
background-position: 6px -829px;
}
.te_btn_centeralign{
background-position: 6px -854px;
}
.te_btn_rightalign{
background-position: 6px -879px;
}
.te_btn_blockjustify{
background-position: 6px -904px;
}
.te_btn_orderedlist{
background-position: 6px -929px;
}
.te_btn_unorderedlist{
background-position: 6px -954px;
}
.te_btn_indent{
background-position: 6px -979px;
}
.te_btn_outdent{
background-position: 6px -1004px;
}
.te_btn_subscript{
background-position: 6px -1029px;
}
.te_btn_superscript{
background-position: 6px -1054px;
}
.te_btn_about{
background-position: 6px -1079px;
}
.te_bottom{
border-top:#b1bab7 1px solid;
position:relative;
top:-1px;
height:12px;
overflow:hidden;
zoom:1;
}
.te_resize_center{
height:12px;
overflow:hidden;
cursor:n-resize;
zoom:1;
background:#f5f5f5 url(img/resize_center.jpg) center center no-repeat;
}
.te_resize_left{
width:10px;
height:10px;
cursor:nw-resize;
background:url(img/resize_leftjpg.jpg) no-repeat;
position:absolute;
bottom:0;
right:0;
overflow:hidden;
zoom:1;
}
| 10npsite | trunk/DThinkPHP/Extend/Tool/thinkeditor/skins/default/style.css | CSS | asf20 | 4,065 |
.te_main {
background: none repeat scroll 0 0 #FFFFFF;
border: 1px solid #B1BAB7;
}
.te_toolbar_box {
background: none repeat scroll 0 0 #F5F5F5;
border-bottom: 1px solid #B1BAB7;
padding-bottom: 12px;
}
.te_toolbar {
margin-left: 10px;
margin-right: 8px;
overflow: hidden;
}
.te_toolbar:after {
clear: both;
content: " ";
display: block;
height: 0;
}
* + html .te_toolbar {
overflow: hidden;
}
.te_main iframe {
}
.te_main textarea {
border: medium none;
overflow-y: scroll;
resize: none;
}
.te_dialog {
display: none;
position: absolute;
}
.te_group {
float: left;
height: 22px;
margin: 8px 2px 1px -2px;
overflow-y: hidden;
}
.te_btn {
background-image: url("img/bg_img.png");
background-repeat: no-repeat;
border: 1px solid #F5F5F5;
cursor: pointer;
float: left;
font-size: 8px;
height: 20px;
margin-right: 5px;
width: 20px;
}
.te_line {
border-left: 1px solid #FFFFFF;
border-right: 1px solid #B0BABA;
float: left;
height: 20px;
margin-right: 5px;
overflow: hidden;
width: 0;
}
.te_mouseover {
border: 1px solid #C0C0C0;
}
.te_btn_source {
background-position: 2px -4px;
}
.te_btn_undo {
background-position: 3px -28px;
}
.te_btn_redo {
background-position: 3px -53px;
}
.te_btn_cut {
background-position: 2px -78px;
}
.te_btn_copy {
background-position: 3px -103px;
}
.te_btn_paste {
background-position: 2px -128px;
}
.te_btn_pastetext {
background-position: 2px -153px;
}
.te_btn_pastefromword {
background-position: 3px -177px;
}
.te_btn_selectAll {
background-position: 2px -203px;
}
.te_btn_blockquote {
background-position: 2px -228px;
}
.te_btn_find {
background-position: 3px -254px;
}
.te_btn_image {
background-position: 2px -278px;
}
.te_btn_flash {
background-position: 2px -303px;
}
.te_btn_media {
background-position: 3px -329px;
}
.te_btn_table {
background-position: 2px -353px;
}
.te_btn_hr {
background-position: 3px -377px;
}
.te_btn_pagebreak {
background-position: 2px -403px;
}
.te_btn_face {
background-position: 2px -428px;
}
.te_btn_code {
background-position: 1px -452px;
}
.te_btn_link {
background-position: 3px -478px;
}
.te_btn_unlink {
background-position: 3px -503px;
}
.te_btn_print {
background-position: 2px -528px;
}
.te_btn_fullscreen {
background-position: 2px -553px;
}
.te_btn_style {
background-position: 3px -579px;
}
.te_btn_font {
background-position: 2px -604px;
}
.te_btn_fontsize {
background-position: 2px -629px;
}
.te_btn_fontcolor {
background-position: 3px -652px;
}
.te_btn_backcolor {
background-position: 2px -678px;
}
.te_btn_bold {
background-position: 3px -702px;
}
.te_btn_italic {
background-position: 4px -727px;
}
.te_btn_underline {
background-position: 3px -752px;
}
.te_btn_strikethrough {
background-position: 2px -779px;
}
.te_btn_unformat {
background-position: 3px -803px;
}
.te_btn_leftalign {
background-position: 3px -828px;
}
.te_btn_centeralign {
background-position: 3px -853px;
}
.te_btn_rightalign {
background-position: 3px -878px;
}
.te_btn_blockjustify {
background-position: 3px -903px;
}
.te_btn_orderedlist {
background-position: 3px -929px;
}
.te_btn_unorderedlist {
background-position: 3px -953px;
}
.te_btn_indent {
background-position: 4px -978px;
}
.te_btn_outdent {
background-position: 4px -1003px;
}
.te_btn_subscript {
background-position: 2px -1028px;
}
.te_btn_superscript {
background-position: 3px -1053px;
}
.te_btn_about {
background-position: 4px -1079px;
}
.te_bottom {
border-top: 1px solid #B1BAB7;
height: 12px;
overflow: hidden;
position: relative;
top: -1px;
}
.te_resize_center {
background: url("img/resize_center.jpg") no-repeat scroll center center #F5F5F5;
cursor: n-resize;
height: 12px;
overflow: hidden;
}
.te_resize_left {
background: url("img/resize_leftjpg.jpg") no-repeat scroll 0 0 transparent;
bottom: 0;
cursor: nw-resize;
height: 10px;
overflow: hidden;
position: absolute;
right: 0;
width: 10px;
}
| 10npsite | trunk/DThinkPHP/Extend/Tool/thinkeditor/skins/default/styles.css | CSS | asf20 | 4,446 |
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title></title>
<link media="all" rel="stylesheet" href="css/base.css" type="text/css" />
<link media="all" rel="stylesheet" href="css/te_dialog.css" type="text/css" />
<style>
.filebox {
cursor: pointer;
height: 22px;
overflow: hidden;
position: absolute;
width: 70px;
}
.filebox .upinput {
border-width: 5px;
cursor: pointer;
left: -12px;
margin: 0;
opacity: 0.01;
padding: 0;
position: absolute;
z-index: 3;
}
.filebox .upbtn {
border: 1px solid #CCCCCC;
color: #666666;
display: block;
font-size: 12px;
height: 20px;
line-height: 20px;
text-align: center;
width: 68px;
}
</style>
<script src="js/jquery-1.6.2.min.js" type="text/javascript"></script>
</head>
<body>
<!--插入图片弹出框 开始-->
<div class="te_dialog Lmt10 Lml10 Ldib Lvat">
<div class="te_dialog_image">
<div class="seltab">
<div class="links Lovh">
<a href="###" class="cstyle">插入图片</a>
</div>
<div class="bdb"> </div>
</div>
<div class="centbox">
<div class="insertimage Lmt20 Lpb10">
<div class="item Lovh">
<span class="ltext Lfll">图片地址:</span>
<div class="Lfll Lovh">
<input type="text" class="imageurl input1 Lfll Lmr5" />
</div>
</div>
<div class="item Lovh">
<span class="ltext Lfll">上传图片:</span>
<div class="Lfll Lovh">
<form enctype="multipart/form-data" action="__SELF__" method="POST">
<div class="filebox">
<input id="teupload" name="teupload" size="1" onchange="te_contact('change', this.value)" class="upinput" type="file" hidefocus="true" />
<input id="tefiletype" name="tefiletype" type="hidden" value="*" />
<input id="temaxsize" name="temaxsize" type="hidden" value="0" />
<span class="upbtn">上传</span>
</div>
</form>
</div>
</div>
<div class="item Lovh">
<span class="ltext Lfll">宽度:</span>
<div class="Lfll">
<input id="" name="" type="text" class="input2" />
</div>
<span class="ltext Lfll">高度:</span>
<div class="Lfll">
<input id="" name="" type="text" class="input2" />
</div>
</div>
</div>
</div>
<div class="btnarea">
<input type="button" value="确定" class="te_ok" />
<input type="button" value="取消" class="te_close" />
</div>
</div>
</div>
<!--插入图片弹出框 结束-->
<!--粘贴文本对话框 开始-->
<div class="te_dialog Lmt10 Lml10 Ldib Lvat">
<div class="te_dialog_pasteText">
<div class="seltab">
<div class="links Lovh">
<a href="###" class="cstyle">贴粘文本</a>
</div>
<div class="bdb"> </div>
</div>
<div class="centbox">
<div class="pasteText">
<span class="tips Lmt5">请使用键盘快捷键(Ctrl/Cmd+V)把内容粘贴到下面的方框里。</span>
<textarea id="" name="" class="tarea1 Lmt5" rows="10" cols="30"></textarea>
</div>
</div>
<div class="btnarea">
<input type="button" value="确定" class="te_ok" />
<input type="button" value="取消" class="te_close" />
</div>
</div>
</div>
<!--粘贴文本对话框 结束-->
<!--插入flash动画 开始-->
<div class="te_dialog Lmt10 Lml10 Ldib Lvat">
<div class="te_dialog_flash">
<div class="seltab">
<div class="links Lovh">
<a href="###" class="cstyle">插入flash动画</a>
</div>
<div class="bdb"> </div>
</div>
<div class="centbox">
<div class="insertflash Lmt20 Lpb10">
<div class="item Lovh">
<span class="ltext Lfll">flash地址:</span>
<div class="Lfll Lovh">
<input type="text" class="imageurl input1 Lfll Lmr5" />
</div>
</div>
<div class="item Lovh">
<span class="ltext Lfll">上传flash:</span>
<div class="Lfll Lovh">
<iframe src="upload.html" width="70" height="22" class="Lfll" scrolling="no" frameborder="0"></iframe>
</div>
</div>
<div class="item Lovh">
<span class="ltext Lfll">宽度:</span>
<div class="Lfll">
<input id="" name="" type="text" class="input2" />
</div>
<span class="ltext Lfll">高度:</span>
<div class="Lfll">
<input id="" name="" type="text" class="input2" />
</div>
</div>
<div class="item Lovh">
<span class="ltext Lfll"> </span>
<div class="Lfll">
<input id="" name="" type="checkbox" class="input3" />
<label for="" class="labeltext">开启背景透明</label>
</div>
</div>
</div>
</div>
<div class="btnarea">
<input type="button" value="确定" class="te_ok" />
<input type="button" value="取消" class="te_close" />
</div>
</div>
</div>
<!--插入flash动画 结束-->
<!--插入表格 开始-->
<div class="te_dialog Lmt10 Lml10 Ldib Lvat">
<div class="te_dialog_table">
<div class="seltab">
<div class="links Lovh">
<a href="###" class="cstyle">插入表格</a>
</div>
<div class="bdb"> </div>
</div>
<div class="centbox">
<div class="insertTable">
<div class="item Lovh">
<span class="ltext Lfll">行数:</span>
<input type="text" class="input1 Lfll" value="3" />
<span class="ltext Lfll">列数:</span>
<input type="text" class="input1 Lfll" value="2" />
</div>
<div class="item Lovh">
<span class="ltext Lfll">宽度:</span>
<input type="text" class="input1 Lfll" value="500" />
<span class="ltext Lfll">高度:</span>
<input type="text" class="input1 Lfll" />
</div>
<div class="item Lovh">
<span class="ltext Lfll">边框:</span>
<input type="text" class="input1 Lfll" value="1" />
</div>
</div>
</div>
<div class="btnarea">
<input type="button" value="确定" class="te_ok" />
<input type="button" value="取消" class="te_close" />
</div>
</div>
</div>
<!--插入表格 结束-->
<!--插入表情 开始-->
<div class="te_dialog Lmt10 Lml10 Ldib Lvat">
<div class="te_dialog_face Lovh">
<div class="seltab">
<div class="links Lovh">
<a href="###" class="cstyle">插入表格</a>
</div>
<div class="bdb"> </div>
</div>
<div class="centbox">
<div class="insertFace" style="background-image:url(../../qq_face/qq_face.gif);">
<span face_num="0"> </span>
<span face_num="1"> </span>
<span face_num="2"> </span>
<span face_num="3"> </span>
<span face_num="4"> </span>
<span face_num="5"> </span>
<span face_num="6"> </span>
<span face_num="7"> </span>
<span face_num="8"> </span>
<span face_num="9"> </span>
<span face_num="10"> </span>
<span face_num="11"> </span>
<span face_num="12"> </span>
<span face_num="13"> </span>
<span face_num="14"> </span>
<span face_num="15"> </span>
<span face_num="16"> </span>
<span face_num="17"> </span>
<span face_num="18"> </span>
<span face_num="19"> </span>
<span face_num="20"> </span>
<span face_num="21"> </span>
<span face_num="22"> </span>
<span face_num="23"> </span>
<span face_num="24"> </span>
<span face_num="25"> </span>
<span face_num="26"> </span>
<span face_num="27"> </span>
<span face_num="28"> </span>
<span face_num="29"> </span>
<span face_num="30"> </span>
<span face_num="31"> </span>
<span face_num="32"> </span>
<span face_num="33"> </span>
<span face_num="34"> </span>
<span face_num="35"> </span>
<span face_num="36"> </span>
<span face_num="37"> </span>
<span face_num="38"> </span>
<span face_num="39"> </span>
<span face_num="40"> </span>
<span face_num="41"> </span>
<span face_num="42"> </span>
<span face_num="43"> </span>
<span face_num="44"> </span>
<span face_num="45"> </span>
<span face_num="46"> </span>
<span face_num="47"> </span>
<span face_num="48"> </span>
<span face_num="49"> </span>
<span face_num="50"> </span>
<span face_num="51"> </span>
<span face_num="52"> </span>
<span face_num="53"> </span>
<span face_num="54"> </span>
<span face_num="55"> </span>
<span face_num="56"> </span>
<span face_num="57"> </span>
<span face_num="58"> </span>
<span face_num="59"> </span>
<span face_num="60"> </span>
<span face_num="61"> </span>
<span face_num="62"> </span>
<span face_num="63"> </span>
<span face_num="64"> </span>
<span face_num="65"> </span>
<span face_num="66"> </span>
<span face_num="67"> </span>
<span face_num="68"> </span>
<span face_num="69"> </span>
<span face_num="70"> </span>
<span face_num="71"> </span>
<span face_num="72"> </span>
<span face_num="73"> </span>
<span face_num="74"> </span>
<span face_num="75"> </span>
<span face_num="76"> </span>
<span face_num="77"> </span>
<span face_num="78"> </span>
<span face_num="79"> </span>
<span face_num="80"> </span>
<span face_num="81"> </span>
<span face_num="82"> </span>
<span face_num="83"> </span>
<span face_num="84"> </span>
<span face_num="85"> </span>
<span face_num="86"> </span>
<span face_num="87"> </span>
<span face_num="88"> </span>
<span face_num="89"> </span>
<span face_num="90"> </span>
<span face_num="91"> </span>
<span face_num="92"> </span>
<span face_num="93"> </span>
<span face_num="94"> </span>
<span face_num="95"> </span>
<span face_num="96"> </span>
<span face_num="97"> </span>
<span face_num="98"> </span>
<span face_num="99"> </span>
<span face_num="100"> </span>
<span face_num="101"> </span>
<span face_num="102"> </span>
<span face_num="103"> </span>
<span face_num="104"> </span>
</div>
</div>
<div class="btnarea">
<input type="button" value="确定" class="te_ok" />
<input type="button" value="取消" class="te_close" />
</div>
</div>
</div>
<!--插入表情 结束-->
<!--插入代码 开始-->
<div class="te_dialog Lmt10 Lml10 Ldib Lvat">
<div class="te_dialog_code Lovh">
<div class="seltab">
<div class="links Lovh">
<a href="###" class="cstyle">插入代码</a>
</div>
<div class="bdb"> </div>
</div>
<div class="centbox">
<div class="Lmt10 Lml10">
<span>选择语言:</span>
<select id="langType" name="">
<option value="-1">-请选择-</option>
<option value="1">HTML</option>
<option value="2">JS</option>
<option value="3">CSS</option>
<option value="4">SQL</option>
<option value="5">C#</option>
<option value="6">JAVA</option>
<option value="7">VBS</option>
<option value="8">VB</option>
<option value="9">XML</option>
<option value="0">其它类型</option>
</select>
</div>
<textarea id="insertCode" name="" rows="10" class="tarea1 Lmt10" cols="30"></textarea>
</div>
<div class="btnarea">
<input type="button" value="确定" class="te_ok" />
<input type="button" value="取消" class="te_close" />
</div>
</div>
</div>
<!--插入代码 结束-->
<!--选择段落样式 开始-->
<div class="te_dialog Lmt10 Lml10 Ldib Lvat">
<div class="te_dialog_style Lovh">
<div class="centbox">
<h1 title="设置当前内容为一级标题"><a href="###">一级标题</a></h1>
<h2 title="设置当前内容为二级标题"><a href="###">二级标题</a></h2>
<h3 title="设置当前内容为三级标题"><a href="###">三级标题</a></h3>
<h4 title="设置当前内容为四级标题"><a href="###">四级标题</a></h4>
<h5 title="设置当前内容为五级标题"><a href="###">五级标题</a></h5>
<h6 title="设置当前内容为六级标题"><a href="###">六级标题</a></h6>
</div>
</div>
</div>
<!--选择段落样式 结束-->
<!--设置字体 开始-->
<div class="te_dialog Lmt10 Lml10 Ldib Lvat">
<div class="te_dialog_font Lovh">
<div class="centbox">
<div><a href="###" style="font-family:"宋体","SimSun"">宋体</a></div>
<div><a href="###" style="font-family:"楷体","楷体_GB2312","SimKai"">楷体</a></div>
<div><a href="###" style="font-family:"隶书","SimLi"">隶书</a></div>
<div><a href="###" style="font-family:"黑体","SimHei"">黑体</a></div>
<div><a href="###" style="font-family:"微软雅黑"">微软雅黑</a></div>
<div><a href="###" style="">微软雅黑</a></div>
<span>------</span>
<div><a href="###" style="font-family:arial,helvetica,sans-serif;">Arial</a></div>
<div><a href="###" style="font-family:comic sans ms,cursive;">Comic Sans Ms</a></div>
<div><a href="###" style="font-family:courier new,courier,monospace;">Courier New</a></div>
<div><a href="###" style="font-family:georgia,serif;">Georgia</a></div>
<div><a href="###" style="font-family:lucida sans unicode,lucida grande,sans-serif;">Lucida Sans Unicode</a></div>
<div><a href="###" style="font-family:tahoma,geneva,sans-serif;">Tahoma</a></div>
<div><a href="###" style="font-family:times new roman,times,serif;">Times New Roman</a></div>
<div><a href="###" style="font-family:trebuchet ms,helvetica,sans-serif;">Trebuchet Ms</a></div>
<div><a href="###" style="font-family:verdana,geneva,sans-serif;">Verdana</a></div>
</div>
</div>
</div>
<!--设置字体 结束-->
<!--设置字号 开始-->
<div class="te_dialog Lmt10 Lml10 Ldib Lvat">
<div class="te_dialog_fontsize Lovh">
<div class="centbox">
<div><a href="#" style="font-size:10px">10</a></div>
<div><a href="#" style="font-size:12px">12</a></div>
<div><a href="#" style="font-size:14px">14</a></div>
<div><a href="#" style="font-size:16px">16</a></div>
<div><a href="#" style="font-size:18px">18</a></div>
<div><a href="#" style="font-size:20px">20</a></div>
<div><a href="#" style="font-size:22px">22</a></div>
<div><a href="#" style="font-size:24px">24</a></div>
<div><a href="#" style="font-size:36px">36</a></div>
<div><a href="#" style="font-size:48px">48</a></div>
<div><a href="#" style="font-size:60px">60</a></div>
<div><a href="#" style="font-size:72px">72</a></div>
</div>
</div>
</div>
<!--设置字号 结束-->
<!--背景色设置 开始-->
<div class="te_dialog Lmt10 Lml10 Ldib Lvat">
<div class="te_dialog_fontcolor Lovh">
<div class="colorsel">
<!--第一列-->
<a href="###" style="background-color:#FF0000"> </a>
<a href="###" style="background-color:#FFA900"> </a>
<a href="###" style="background-color:#FFFF00"> </a>
<a href="###" style="background-color:#99E600"> </a>
<a href="###" style="background-color:#99E600"> </a>
<a href="###" style="background-color:#00FFFF"> </a>
<a href="###" style="background-color:#00AAFF"> </a>
<a href="###" style="background-color:#0055FF"> </a>
<a href="###" style="background-color:#5500FF"> </a>
<a href="###" style="background-color:#AA00FF"> </a>
<a href="###" style="background-color:#FF007F"> </a>
<a href="###" style="background-color:#FFFFFF"> </a>
<!--第二列-->
<a href="###" style="background-color:#FFE5E5"> </a>
<a href="###" style="background-color:#FFF2D9"> </a>
<a href="###" style="background-color:#FFFFCC"> </a>
<a href="###" style="background-color:#EEFFCC"> </a>
<a href="###" style="background-color:#D9FFE0"> </a>
<a href="###" style="background-color:#D9FFFF"> </a>
<a href="###" style="background-color:#D9F2FF"> </a>
<a href="###" style="background-color:#D9E6FF"> </a>
<a href="###" style="background-color:#E6D9FF"> </a>
<a href="###" style="background-color:#F2D9FF"> </a>
<a href="###" style="background-color:#FFD9ED"> </a>
<a href="###" style="background-color:#D9D9D9"> </a>
<!--第三列-->
<a href="###" style="background-color:#E68A8A"> </a>
<a href="###" style="background-color:#E6C78A"> </a>
<a href="###" style="background-color:#FFFF99"> </a>
<a href="###" style="background-color:#BFE673"> </a>
<a href="###" style="background-color:#99EEA0"> </a>
<a href="###" style="background-color:#A1E6E6"> </a>
<a href="###" style="background-color:#99DDFF"> </a>
<a href="###" style="background-color:#8AA8E6"> </a>
<a href="###" style="background-color:#998AE6"> </a>
<a href="###" style="background-color:#C78AE6"> </a>
<a href="###" style="background-color:#E68AB9"> </a>
<a href="###" style="background-color:#B3B3B3"> </a>
<!--第四列-->
<a href="###" style="background-color:#CC5252"> </a>
<a href="###" style="background-color:#CCA352"> </a>
<a href="###" style="background-color:#D9D957"> </a>
<a href="###" style="background-color:#A7CC39"> </a>
<a href="###" style="background-color:#57CE6D"> </a>
<a href="###" style="background-color:#52CCCC"> </a>
<a href="###" style="background-color:#52A3CC"> </a>
<a href="###" style="background-color:#527ACC"> </a>
<a href="###" style="background-color:#6652CC"> </a>
<a href="###" style="background-color:#A352CC"> </a>
<a href="###" style="background-color:#CC5291"> </a>
<a href="###" style="background-color:#B3B3B3"> </a>
<!--第五列-->
<a href="###" style="background-color:#991F1F"> </a>
<a href="###" style="background-color:#99701F"> </a>
<a href="###" style="background-color:#99991F"> </a>
<a href="###" style="background-color:#59800D"> </a>
<a href="###" style="background-color:#0F9932"> </a>
<a href="###" style="background-color:#1F9999"> </a>
<a href="###" style="background-color:#1F7099"> </a>
<a href="###" style="background-color:#1F4799"> </a>
<a href="###" style="background-color:#471F99"> </a>
<a href="###" style="background-color:#701F99"> </a>
<a href="###" style="background-color:#991F5E"> </a>
<a href="###" style="background-color:#404040"> </a>
<!--第六列-->
<a href="###" style="background-color:#660000"> </a>
<a href="###" style="background-color:#664B14"> </a>
<a href="###" style="background-color:#666600"> </a>
<a href="###" style="background-color:#3B5900"> </a>
<a href="###" style="background-color:#005916"> </a>
<a href="###" style="background-color:#146666"> </a>
<a href="###" style="background-color:#144B66"> </a>
<a href="###" style="background-color:#143066"> </a>
<a href="###" style="background-color:#220066"> </a>
<a href="###" style="background-color:#301466"> </a>
<a href="###" style="background-color:#66143F"> </a>
<a href="###" style="background-color:#000000"> </a>
</div>
</div>
</div>
<!--背景色设置 结束-->
<!--关于 开始-->
<div class="te_dialog Lmt10 Lml10 Ldib Lvat">
<div class="te_dialog_about Lovh">
<div class="seltab">
<div class="links Lovh">
<a href="###" class="cstyle">关于ThinkEditor</a>
</div>
<div class="bdb"> </div>
</div>
<div class="centbox">
<div class="aboutcontent">
<p>ThinkPHP是一个免费开源的,快速、简单的面向对象的轻量级PHP开发框架,遵循Apache2开源协议发布,是为了敏捷WEB应用开发和简化企业级应用开发而诞生的。拥有众多的优秀功能和特性,经历了三年多发展的同时,在社区团队的积极参与下,在易用性、扩展性和性能方面不断优化和改进,众多的典型案例确保可以稳定用于商业以及门户级的开发。</p>
<p>ThinkPHP借鉴了国外很多优秀的框架和模式,使用面向对象的开发结构和MVC模式,采用单一入口模式等,融合了Struts的Action思想和JSP的TagLib(标签库)、RoR的ORM映射和ActiveRecord模式,封装了CURD和一些常用操作,在项目配置、类库导入、模版引擎、查询语言、自动验证、视图模型、项目编译、缓存机制、SEO支持、分布式数据库、多数据库连接和切换、认证机制和扩展性方面均有独特的表现。</p>
<p>使用ThinkPHP,你可以更方便和快捷的开发和部署应用。当然不仅仅是企业级应用,任何PHP应用开发都可以从ThinkPHP的简单和快速的特性中受益。ThinkPHP本身具有很多的原创特性,并且倡导大道至简,开发由我的开发理念,用最少的代码完成更多的功能,宗旨就是让WEB应用开发更简单、更快速。为此ThinkPHP会不断吸收和融入更好的技术以保证其新鲜和活力,提供WEB应用开发的最佳实践!</p>
<p>ThinkPHP遵循Apache2开源许可协议发布,意味着你可以免费使用ThinkPHP,甚至允许把你基于ThinkPHP开发的应用开源或商业产品发布/销售。 </p>
</div>
</div>
<div class="btnarea">
<input type="button" value="关闭" class="te_close" />
</div>
</div>
</div>
<!--关于 结束-->
<!--链接 开始-->
<div class="te_dialog Lmt10 Lml10 Ldib Lvat">
<div class="te_dialog_link Lovh">
<div class="seltab">
<div class="links Lovh">
<a href="###" class="cstyle">创建链接</a>
</div>
<div class="bdb"> </div>
</div>
<div class="centbox">
<div class="item Lovh">
<span class="ltext Lfll">链接地址:</span>
<div class="Lfll">
<input id="" name="" type="text" class="Lfll input1" />
</div>
</div>
</div>
<div class="btnarea">
<input type="button" value="确定" class="te_ok" />
<input type="button" value="取消" class="te_close" />
</div>
</div>
</div>
<!--链接 结束-->
</body>
</html>
| 10npsite | trunk/DThinkPHP/Extend/Tool/thinkeditor/skins/default/dialog/dialog.html | HTML | asf20 | 23,159 |
/* --------------------------------------------------
* FileName: base.css
* Desc: CSS基础样式库
* Author: leftcold
* Email: leftcold@topthink.com
* Version: 0.1.07262011
* LastChange: 09/06/2011 10:46
* History: 参见history.txt
* -------------------------------------------------- */
/* 全局样式重置 */
body, div, span, small, p, em,
th, td, dl, dt, dd, ul, ol, li,
h1, h2, h3, h4, h5, h6, form, textarea { padding:0; margin:0; }
a { cursor:pointer; text-decoration:none; }
a img { border:none; }
ul, ol { list-style:none; }
table { border-spacing:0; border-collapse:collapse; }
input:focus, select:focus, textarea:focus { outline:0; }
/* 常用样式缩写 */
/* float */
.Lfll { float:left; }
.Lflr { float:right; }
.Lcfl { clear:left; }
.Lcfr { clear:right; }
.Lcfb { clear:both; }
/* font */
.Lfz10 { font-size:10px; }
.Lfz12 { font-size:12px; }
.Lfz14 { font-size:14px; }
.Lfz16 { font-size:16px; }
.Lfz18 { font-size:18px; }
.Lfz20 { font-size:20px; }
/* color */
.Lcf60 { color:#F60; }
.Lcc00 { color:#C00; }
.Lc390 { color:#390; }
.Lc333 { color:#333; }
.Lc666 { color:#666; }
.Lc999 { color:#999; }
.Ltal { text-align:left; }
.Ltac { text-align:center; }
.Ltar { text-align:right; }
.Lvat { vertical-align:top; }
.Lvam { vertical-align:middle; }
.Lvab { vertical-align:bottom; }
.Lva3r { vertical-align:-3px; }
.Lva2r { vertical-align:-2px; }
.Lfwb { font-weight:bold; }
.Lffar { font-family:Arial; }
.Lfftm { font-family:Tahoma; }
.Lffst { font-family:\5B8B\4F53; }
.Lffyh { font-family:\5FAE\8F6F\96C5\9ED1; }
/* indent */
.Lti5 { text-indent:5px; }
.Lti10 { text-indent:10px; }
.Lti15 { text-indent:15px; }
.Lti20 { text-indent:20px; }
.Lti25 { text-indent:25px; }
.Lti30 { text-indent:30px; }
.Lti35 { text-indent:35px; }
.Lti40 { text-indent:40px; }
.Lti1000r { text-indent:-1000px; }
/* margin */
.Lmt5 { margin-top:5px; }
.Lmt10 { margin-top:10px; }
.Lmt15 { margin-top:15px; }
.Lmt20 { margin-top:20px; }
.Lmt25 { margin-top:25px; }
.Lmt30 { margin-top:30px; }
.Lmt35 { margin-top:35px; }
.Lmt40 { margin-top:40px; }
.Lmr5 { margin-right:5px; }
.Lmr10 { margin-right:10px; }
.Lmr15 { margin-right:15px; }
.Lmr20 { margin-right:20px; }
.Lmr25 { margin-right:25px; }
.Lmr30 { margin-right:30px; }
.Lmr35 { margin-right:35px; }
.Lmr40 { margin-right:40px; }
.Lmb5 { margin-bottom:5px; }
.Lmb10 { margin-bottom:10px; }
.Lmb15 { margin-bottom:15px; }
.Lmb20 { margin-bottom:20px; }
.Lmb25 { margin-bottom:25px; }
.Lmb30 { margin-bottom:30px; }
.Lmb35 { margin-bottom:35px; }
.Lmb40 { margin-bottom:40px; }
.Lml5 { margin-left:5px; }
.Lml10 { margin-left:10px; }
.Lml15 { margin-left:15px; }
.Lml20 { margin-left:20px; }
.Lml25 { margin-left:25px; }
.Lml30 { margin-left:30px; }
.Lml35 { margin-left:35px; }
.Lml40 { margin-left:40px; }
/* padding */
.Lpt5 { padding-top:5px; }
.Lpt10 { padding-top:10px; }
.Lpt15 { padding-top:15px }
.Lpt20 { padding-top:20px; }
.Lpt25 { padding-top:25px; }
.Lpt30 { padding-top:30px; }
.Lpt35 { padding-top:35px; }
.Lpt40 { padding-top:40px; }
.Lpr5 { padding-right:5px; }
.Lpr10 { padding-right:10px; }
.Lpr15 { padding-right:15px; }
.Lpr20 { padding-right:20px; }
.Lpr25 { padding-right:25px; }
.Lpr30 { padding-right:30px; }
.Lpr35 { padding-right:35px; }
.Lpr40 { padding-right:40px; }
.Lpb5 { padding-bottom:5px; }
.Lpb10 { padding-bottom:10px; }
.Lpb15 { padding-bottom:15px; }
.Lpb20 { padding-bottom:20px; }
.Lpb25 { padding-bottom:25px; }
.Lpb30 { padding-bottom:30px; }
.Lpb35 { padding-bottom:35px; }
.Lpb40 { padding-bottom:40px; }
.Lpl5 { padding-left:5px; }
.Lpl10 { padding-left:10px; }
.Lpl15 { padding-left:15px; }
.Lpl20 { padding-left:20px; }
.Lpl25 { padding-left:25px; }
.Lpl30 { padding-left:30px; }
.Lpl35 { padding-left:35px; }
.Lpl40 { padding-left:40px; }
/* position */
.Lposa { position:absolute; }
.Lposr { position:relative; }
.Lposf { position:fixed; }
/* display */
.Ldb { display:block; }
.Ldn { display:none; }
.Ldib { display:inline-block; }
/* overflow */
.Lovh { overflow:hidden; zoom:1; }
.Lovv { overflow:visible; }
/* background */
.Lbgcr { background-color:Red; }
.Lbgcw { background-color:#FFF; }
.Lbgcb { background-color:blue; }
/* other */
.Lon { outline:none; }
.Lcurp { cursor:pointer; }
| 10npsite | trunk/DThinkPHP/Extend/Tool/thinkeditor/skins/default/dialog/css/base.css | CSS | asf20 | 4,392 |
/* 选项卡/标题 */
.te_dialog .seltab { position:relative; }
.te_dialog .seltab .bdb { height:30px; border-bottom:2px solid #CCC; }
.te_dialog .seltab .links { font-size:12px; line-height:24px; position:absolute; top:5px; padding-left:10px; }
.te_dialog .seltab .links a { display:inline-block; padding:0 8px; color:#999; border:1px solid #FFF; border-bottom:none; float:left; }
.te_dialog .seltab .links a:hover { color:#333; }
.te_dialog .seltab .links a.cstyle { color:#333; border-color:#CCC; border-bottom-color:#FFF; border-bottom:2px solid #FFF; }
/* 内容盒子 */
.te_dialog .te_centbox { }
/* 按钮区域 */
.te_dialog .btnarea { margin-top:10px; text-align:right; padding-right:10px; padding-bottom:10px; }
/* 颜色区块 */
.te_dialog .colorsel { width:276px; padding-left:5px; overflow:hidden; padding-top:5px; zoom:1; }
.te_dialog .colorsel a { zoom:1; width:16px; height:16px; float:left; margin-right:5px; margin-bottom:5px; overflow:hidden; display:inline-block; border:1px solid #333; }
.te_dialog .colorsel a:hover { width:20px; height:20px; margin:-2px; margin-left:-2px; margin-right:3px; margin-bottom:3px; }
/* 插入图片区域 */
.te_dialog_image { width:360px; border:1px solid #999; background-color:#FFF; font-size:12px; }
.te_dialog_image .item { margin-top:10px; }
.te_dialog_image .ltext { width:80px; text-align:right; display:inline-block; line-height:22px; }
.te_dialog_image .input1 { border:1px solid #AAA; padding:0 5px; width:220px; line-height:20px; height:20px; }
.te_dialog_image .input2 { width:40px; padding:0 5px; margin:0; border:1px solid #AAA; line-height:20px; height:20px; }
/* 粘贴为文本格式 */
.te_dialog_pasteText { width:360px; border:1px solid #999; background-color:#FFF; font-size:12px; }
.te_dialog_pasteText .tips { color:#666; line-height:22px; margin-left:10px; margin-right:10px; display:inline-block; }
.te_dialog_pasteText .tarea1 { width:336px; height:120px; margin-left:10px; border:1px solid #AAA; }
/* 插入flash */
.te_dialog_flash { width:360px; border:1px solid #999; background-color:#FFF; font-size:12px; }
.te_dialog_flash .item { margin-top:10px; }
.te_dialog_flash .ltext { width:80px; text-align:right; display:inline-block; line-height:22px; }
.te_dialog_flash .input1 { border:1px solid #AAA; padding:0 5px; width:220px; line-height:20px; height:20px; }
.te_dialog_flash .input2 { width:40px; padding:0 5px; margin:0; border:1px solid #AAA; line-height:20px; height:20px; }
.te_dialog_flash .input3 { vertical-align:-3px; margin:0; line-height:20px; }
.te_dialog_flash .labeltext { line-height:20px; }
/* 插入表格 */
.te_dialog_table { width:360px; border:1px solid #999; background-color:#FFF; font-size:12px; }
.te_dialog_table .insertTable { margin:10px; }
.te_dialog_table .item { margin-top:10px; }
.te_dialog_table .ltext { width:80px; text-align:right; display:inline-block; line-height:22px; }
.te_dialog_table .input1 { width:40px; padding:0 5px; height:20px; line-height:20px; border:1px solid #AAA; }
.te_dialog_table .input2 { width:170px; padding:0 5px; height:20px; line-height:20px; border:1px solid #AAA; }
/* 插入表情 */
.te_dialog_face { width:434px; border:1px solid #999; background-color:#FFF; font-size:12px; }
.te_dialog_face .insertFace { width:436px; height:203px; background-color:#FFF; background-position:-1px -1px; cursor:pointer; }
.te_dialog_face .insertFace span { float:left; width:29px; height:29px; display:block; }
/* 插入代码 */
.te_dialog_code { width:360px; border:1px solid #999; background-color:#FFF; font-size:12px; }
/* .te_dialog_code .tips { color:#666; line-height:22px; margin-left:10px; margin-right:10px; display:inline-block; } */
.te_dialog_code .tarea1 { width:336px; height:120px; margin-left:10px; border:1px solid #AAA; }
/* 选择标题样式 */
.te_dialog_style { border:1px solid #999; background-color:#FFF; padding:10px; height:180px; overflow-y:scroll; width:154px; }
.te_dialog_style a { border:1px solid #FFF; color:#333; margin:5px 0; padding:2px; display:inline-block; }
.te_dialog_style a:hover { border:1px dotted #59CB55; background-color:#ECFFEC; }
/* 选择字体样式 */
.te_dialog_font { border:1px solid #999; background-color:#FFF; padding:10px; height:180px; overflow-y:scroll; width:159px; }
.te_dialog_font .centbox a { color:#333; font-size:12px; line-height:16px; border:1px solid #FFF; padding:2px; display:inline-block; }
.te_dialog_font .centbox a:hover { border:1px dotted #59CB55; background-color:#ECFFEC; }
.te_dialog_font .centbox span { color:#999; }
/* 选择字号 */
.te_dialog_fontsize { border:1px solid #999; background-color:#FFF; padding:10px; height:180px; overflow-y:scroll; width:94px; }
.te_dialog_fontsize .centbox a { color:#333; font-size:12px; border:1px solid #FFF; padding:2px; display:inline-block; }
.te_dialog_fontsize .centbox a:hover { border:1px dotted #59CB55; background-color:#ECFFEC; }
.te_dialog_fontcolor { border:1px solid #999; background-color:#FFF; width:281px; }
.te_dialog_about { width:360px; border:1px solid #999; background-color:#FFF; }
.te_dialog_about .aboutcontent { color:#333; margin:10px; height:140px; font-size:12px; overflow-y:scroll; line-height:1.6em; }
/* 插入表格 */
.te_dialog_link { width:360px; border:1px solid #999; background-color:#FFF; font-size:12px; }
.te_dialog_link .item { margin-top:10px; }
.te_dialog_link .ltext { width:80px; text-align:right; display:inline-block; line-height:22px; }
.te_dialog_link .input1 { width:190px; padding:0 5px; height:20px; line-height:20px; border:1px solid #AAA; }
.te_dialog_link .centbox { margin:10px; }
.filebox {cursor: pointer;height: 22px;overflow: hidden;position: absolute;width: 70px;}
.filebox .upinput {border-width: 5px;cursor: pointer;left: -12px; margin: 0;opacity: 0.01;padding: 0;position: absolute;z-index: 3;}
.filebox .upbtn {border: 1px solid #CCCCCC;color: #666666;display: block;font-size: 12px;height: 20px;line-height: 20px;text-align: center;width: 68px;} | 10npsite | trunk/DThinkPHP/Extend/Tool/thinkeditor/skins/default/dialog/css/te_dialog.css | CSS | asf20 | 6,060 |
$.TE.plugin("bold",{
title:"标题",
cmd:"bold",
click:function(){
this.editor.pasteHTML("sdfdf");
},
bold:function(){
alert('sdfsdf');
},
noRight:function(e){
if(e.type=="click"){
alert('noright');
}
},
init:function(){
},
event:"click mouseover mouseout",
mouseover:function(e){
this.$btn.css("color","red");
},
mouseout:function(e){
this.$btn.css("color","#000")
}
});
| 10npsite | trunk/DThinkPHP/Extend/Tool/thinkeditor/plugins/myplugins.js | JavaScript | asf20 | 521 |
function te_upload_interface() {
//初始化参数
var _args = arguments,
_fn = _args.callee,
_data = '';
if( _args[0] == 'reg' ) {
//注册回调
_data = _args[1];
_fn.curr = _data['callid'];
_fn.data = _data;
jQuery('#temaxsize').val(_data['maxsize']);
} else if( _args[0] == 'get' ) {
//获取配置
return _fn.data || false;
} else if( _args[0] == 'call' ) {
//处理回调与实例不一致
if( _args[1] != _fn.curr ) {
alert( '上传出错,请不要同时打开多个上传弹窗' );
return false;
}
//上传成功
if( _args[2] == 'success' ) {
_fn.data['callback']( _args[3] );
}
//上传失败
else if( _args[2] == 'failure' ) {
alert( '[上传失败]\n错误信息:'+_args[3] );
}
//文件类型检测错误
else if( _args[2] == 'filetype' ) {
alert( '[上传失败]\n错误信息:您上传的文件类型有误' );
}
//处理状态改变
else if( _args[2] == 'change' ) {
// TODO 更细致的回调实现,此处返回true自动提交
return true;
}
}
}
//用户选择文件时
function checkTypes(id){
//校验文件类型
var filename = document.getElementById( 'teupload' ).value,
filetype = document.getElementById( 'tefiletype' ).value.split( ',' );
currtype = filename.split( '.' ).pop(),
checktype = false;
if( filetype[0] == '*' ) {
checktype = true;
} else {
for(var i=0; i<filetype.length; i++) {
if( currtype == filetype[i] ) {
checktype = true;
break;
}
}
}
if( !checktype ) {
alert( '[上传失败]\n错误信息:您上传的文件类型有误' );
return false;
} else {
//校验通过,提交
jQuery('#'+id).submit()
}
} | 10npsite | trunk/DThinkPHP/Extend/Tool/thinkeditor/plugins/upload_interface.js | JavaScript | asf20 | 2,075 |
// 系统自带插件
( function ( $ ) {
//全屏
$.TE.plugin( "fullscreen", {
fullscreen:function(e){
var $btn = this.$btn,
opt = this.editor.opt;
if($btn.is("."+opt.cssname.fulled)){
//取消全屏
this.editor.$main.removeAttr("style");
this.editor.$bottom.find("div").show();
this.editor.resize(opt.width,opt.height);
$("html,body").css("overflow","auto");
$btn.removeClass(opt.cssname.fulled);
$(window).scrollTop(this.scrolltop);
}else{
//全屏
this.scrolltop=$(window).scrollTop();
this.editor.$main.attr("style","z-index:900000;position:absolute;left:0;top:0px");
$(window).scrollTop(0);
$("html,body").css("overflow","hidden");//隐藏滚蛋条
this.editor.$bottom.find("div").hide();//隐藏底部的调整大小控制块
this.editor.resize($(window).width(),$(window).height());
$btn.addClass(opt.cssname.fulled);
}
}
} );
//切换源码
$.TE.plugin( "source", {
source:function(e){
var $btn = this.$btn,
$area = this.editor.$area,
$frame = this.editor.$frame,
opt = this.editor.opt,
_self = this;
if($btn.is("."+opt.cssname.sourceMode)){
//切换到可视化
_self.editor.core.updateFrame();
$area.hide();
$frame.show();
$btn.removeClass(opt.cssname.sourceMode);
}else{
//切换到源码
_self.editor.core.updateTextArea();
$area.show();
$frame.hide();
$btn.addClass(opt.cssname.sourceMode);
}
setTimeout(function(){_self.editor.refreshBtn()},100);
}
} );
//剪切
$.TE.plugin( 'cut', {
click: function() {
if( $.browser.mozilla ) {
alert('您的浏览器安全设置不支持该操作,请使用Ctrl/Cmd+X快捷键完成操作。');
} else {
this.exec();
}
}
});
//复制
$.TE.plugin( 'copy', {
click: function() {
if( $.browser.mozilla ) {
alert('您的浏览器安全设置不支持该操作,请使用Ctrl/Cmd+C快捷键完成操作。');
} else {
this.exec();
}
}
});
//粘贴
$.TE.plugin( 'paste', {
click: function() {
if( $.browser.mozilla ) {
alert('您的浏览器安全设置不支持该操作,请使用Ctrl/Cmd+V快捷键完成操作。');
} else {
this.exec();
}
}
});
//创建链接
$.TE.plugin( "link", {
click:function(e){
var _self = this;
var $html = $(
'<div class="te_dialog_link Lovh">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="###" class="cstyle">创建链接</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="centbox">'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">链接地址:</span>'+
' <div class="Lfll">'+
' <input id="te_dialog_url" name="" type="text" class="Lfll input1" />'+
' </div>'+
' </div>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="确定" class="te_ok" />'+
' <input type="button" value="取消" class="te_close" />'+
' </div>'+
'</div>'
);
if( _self.isie6() ) {
window.selectionCache = [
/* 暂存选区对象 */
_self.editor.doc.selection.createRange(),
/* 选区html内容 */
_self.editor.doc.selection.createRange().htmlText,
/* 选区文本用来计算差值 */
_self.editor.doc.selection.createRange().text
];
}
this.createDialog({
body:$html,
ok:function(){
_self.value=$html.find("#te_dialog_url").val();
if( _self.isie6() ) {
var _sCache = window.selectionCache,
str1 = '<a href="'+_self.value+'">'+_sCache[1]+'</a>',
str2 = '<a href="'+_self.value+'">'+_sCache[2]+'</a>';
_sCache[0].pasteHTML( str1 );
_sCache[0].moveStart( 'character', -_self.strlen( str2 ) + ( str2.length - _sCache[2].length ) );
_sCache[0].moveEnd( 'character', -0 );
_sCache[0].select();
//置空暂存对象
window.selectionCache = _sCache = null;
} else {
_self.exec();
}
_self.hideDialog();
}
});
},
strlen : function ( str ) {
return window.ActiveXObject && str.indexOf("\n") != -1 ? str.replace(/\r?\n/g, "_").length : str.length;
},
isie6 : function () {
return $.browser.msie && $.browser.version == '6.0' ? true : false;
}
} );
$.TE.plugin( 'print', {
click: function(e) {
var _win = this.editor.core.$frame[0].contentWindow;
if($.browser.msie) {
this.exec();
} else if(_win.print) {
_win.print();
} else {
alert('您的系统不支持打印接口');
}
}
} );
$.TE.plugin( 'pagebreak', {
exec: function() {
var _self = this;
_self.editor.pasteHTML('<div style="page-break-after: always;zoom:1; height:0px; clear:both; display:block; overflow:hidden; border-top:2px dotted #CCC;"> </div><p> </p>');
}
} );
$.TE.plugin( 'pastetext', {
exec: function() {
var _self = this,
_html = '';
clipData = window.clipboardData ? window.clipboardData.getData('text') : false;
if( clipData ) {
_self.editor.pasteHTML( clipData.replace( /\r\n/g, '<br />' ) );
} else {
_html = $(
'<div class="te_dialog_pasteText">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="###" class="cstyle">贴粘文本</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="centbox">'+
' <div class="pasteText">'+
' <span class="tips Lmt5">请使用键盘快捷键(Ctrl/Cmd+V)把内容粘贴到下面的方框里。</span>'+
' <textarea id="pasteText" name="" class="tarea1 Lmt5" rows="10" cols="30"></textarea>'+
' </div>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="确定" class="te_ok" />'+
' <input type="button" value="取消" class="te_close" />'+
' </div>'+
'</div>'
);
this.createDialog({
body : _html,
ok : function(){
_self.editor.pasteHTML(_html.find('#pasteText').val().replace(/\n/g, '<br />'));
_self.hideDialog();
}
});
}
}
} );
$.TE.plugin( 'table', {
exec : function (e) {
var _self = this,
_html = '';
_html = $(
'<div class="te_dialog_table">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="###" class="cstyle">插入表格</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="centbox">'+
' <div class="insertTable">'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">行数:</span>'+
' <input type="text" id="te_tab_rows" class="input1 Lfll" value="3" />'+
' <span class="ltext Lfll">列数:</span>'+
' <input type="text" id="te_tab_cols" class="input1 Lfll" value="2" />'+
' </div>'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">宽度:</span>'+
' <input type="text" id="te_tab_width" class="input1 Lfll" value="500" />'+
' <span class="ltext Lfll">高度:</span>'+
' <input type="text" id="te_tab_height" class="input1 Lfll" />'+
' </div>'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">边框:</span>'+
' <input type="text" id="te_tab_border" class="input1 Lfll" value="1" />'+
' </div>'+
' </div>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="确定" class="te_ok" />'+
' <input type="button" value="取消" class="te_close" />'+
' </div>'+
'</div>'
);
this.createDialog({
body : _html,
ok : function () {
//获取参数
var rows = parseInt(_html.find('#te_tab_rows').val()),
cols = parseInt(_html.find('#te_tab_cols').val()),
width = parseInt(_html.find('#te_tab_width').val()),
height = parseInt(_html.find('#te_tab_height').val()),
border = parseInt(_html.find('#te_tab_border').val()),
tab_html = '<table width="'+width+'" border="'+border+'"';
if(height) tab_html += ' height="'+height+'"';
tab_html += '>';
for(var i=0; i<rows; i++) {
tab_html += '<tr>';
for(var j=0; j<cols; j++) {
tab_html += '<td> </td>';
}
tab_html += '</tr>';
}
tab_html += '</table>';
_self.editor.pasteHTML( tab_html );
_self.hideDialog();
}
});
}
} );
$.TE.plugin( 'blockquote', {
exec : function () {
var _self = this,
_doc = _self.editor.doc,
elem = '', //当前对象
isquote = false, //是否已被引用
node = '',
child = false; //找到的引用对象
//取得当前对象
node = elem = this.getElement();
//判断是否已被引用
while( node !== _doc.body ) {
if( node.nodeName.toLowerCase() == 'blockquote' ){
isquote = true;
break;
}
node = node.parentNode;
}
if( isquote ) {
//如果存在引用,则清理
if( node === _doc.body ) {
node.innerHTML = elem.parentNode.innerHTML;
} else {
while (child = node.firstChild) {
node.parentNode.insertBefore(child, node);
}
node.parentNode.removeChild(node);
}
} else {
//不存在引用,创建引用
if( $.browser.msie ) {
if( elem === _doc.body ) {
elem.innerHTML = '<blockquote>' + elem.innerHTML + '</blockquote>';
} else {
elem.outerHTML = '<blockquote>' + elem.outerHTML + '</blockquote>';
}
} else {
_doc.execCommand( 'formatblock', false, '<blockquote>' )
}
}
},
getElement : function () {
var ret = false;
if( $.browser.msie ) {
ret = this.editor.doc.selection.createRange().parentElement();
} else {
ret = this.editor.$frame.get( 0 ).contentWindow.getSelection().getRangeAt( 0 ).startContainer;
}
return ret;
}
} );
$.TE.plugin( 'image', {
upid : 'te_image_upload',
uptype : [ 'jpg', 'jpeg', 'gif', 'png', 'bmp' ],
//文件大小
maxsize : 1024*1024*1024*2, // 2MB
exec : function() {
var _self = this,
//上传地址
updir = _self.editor.opt.uploadURL,
//传给上传页的参数
parame = 'callback='+this.upid+this.editor.guid+'&rands='+(+new Date());
if(updir && updir!='about:blank'){
if( updir.indexOf('?') > -1 ) {
updir += '&' + parame;
} else {
updir += '?' + parame;
}
//弹出窗内容
var $html = $(
'<div class="te_dialog_image">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="#" class="cstyle">插入图片</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="centbox">'+
' <div class="insertimage Lmt20 Lpb10">'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">图片地址:</span>'+
' <div class="Lfll Lovh">'+
' <input type="text" id="te_image_url" class="imageurl input1 Lfll Lmr5" />'+
' </div>'+
' </div>'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">上传图片:</span>'+
' <div class="Lfll Lovh">'+
' <form id="form_img" enctype="multipart/form-data" action="'+updir+'" method="POST" target="upifrem">'+
' <div class="filebox">'+
' <input id="teupload" name="teupload" size="1" onchange="checkTypes(\'form_img\');" class="upinput" type="file" hidefocus="true" />'+
' <input id="tefiletype" name="tefiletype" type="hidden" value="'+this.uptype+'" />'+
' <input id="temaxsize" name="temaxsize" type="hidden" value="'+this.maxsize+'" />'+
' <span class="upbtn">上传</span>'+
' </div>'+
' </form>'+
' <iframe name="upifrem" id="upifrem" width="70" height="22" class="Lfll" scrolling="no" frameborder="0"></iframe>'+
' </div>'+
' </div>'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">图片宽度:</span>'+
' <div class="Lfll">'+
' <input id="te_image_width" name="" type="text" class="input2" />'+
' </div>'+
' <span class="ltext Lfll">图片高度:</span>'+
' <div class="Lfll">'+
' <input id="te_image_height" name="" type="text" class="input2" />'+
' </div>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="确定" class="te_ok" />'+
' <input type="button" value="取消" class="te_close" />'+
' </div>'+
'</div>'
),
_upcall = function(path) {
//获取上传的值
$html.find( '#te_image_url' ).val(path);
// 刷新iframe上传页
//var _url = $html.find( 'iframe' ).attr( 'src' );
//_url = _url.replace( /rands=[^&]+/, 'rands=' + (+ new Date()) );
$html.find( 'iframe' ).attr( 'src', 'about:blank' );
}
//注册通信
te_upload_interface( 'reg', {
'callid' : this.upid+this.editor.guid,
'filetype': this.uptype,
'maxsize' : this.maxsize,
'callback': _upcall
} );
//创建对话框
this.createDialog( {
body : $html,
ok : function() {
var _src = $html.find('#te_image_url').val(),
_width = parseInt($html.find('#te_image_width').val()),
_height = parseInt($html.find('#te_image_height').val());
_src = _APP+_src;
var _insertHTML = '<img src="'+(_src||'http://www.baidu.com/img/baidu_sylogo1.gif')+'" ';
if( _width ) _insertHTML += 'width="'+_width+'" ';
if( _height ) _insertHTML += 'height="'+_height+'" ';
_insertHTML += '/>';
_self.editor.pasteHTML( _insertHTML );
_self.hideDialog();
}
} );
}else{
alert('请配置上传处理路径!');
}
}
} );
$.TE.plugin( 'flash', {
upid : 'te_flash_upload',
uptype : [ 'swf' ],
//文件大小
maxsize : 1024*1024*1024*2, // 2MB
exec : function() {
var _self = this,
//上传地址
updir = _self.editor.opt.uploadURL,
//传给上传页的参数
parame = 'callback='+this.upid+this.editor.guid+'&rands='+(+new Date());
if(updir && updir!='about:blank'){
if( updir.indexOf('?') > -1 ) {
updir += '&' + parame;
} else {
updir += '?' + parame;
}
//弹出窗内容
var $html = $(
'<div class="te_dialog_flash">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="###" class="cstyle">插入flash动画</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="insertflash Lmt20 Lpb10">'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">flash地址:</span>'+
' <div class="Lfll Lovh">'+
' <input id="te_flash_url" type="text" class="imageurl input1 Lfll Lmr5" />'+
' </div>'+
' </div>'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">上传flash:</span>'+
' <div class="Lfll Lovh">'+
' <form id="form_swf" enctype="multipart/form-data" action="'+updir+'" method="POST" target="upifrem">'+
' <div class="filebox">'+
' <input id="teupload" name="teupload" size="1" onchange="checkTypes(\'form_swf\');" class="upinput" type="file" hidefocus="true" />'+
' <input id="tefiletype" name="tefiletype" type="hidden" value="'+this.uptype+'" />'+
' <input id="temaxsize" name="temaxsize" type="hidden" value="'+this.maxsize+'" />'+
' <span class="upbtn">上传</span>'+
' </div>'+
' </form>'+
' <iframe name="upifrem" id="upifrem" width="70" height="22" class="Lfll" scrolling="no" frameborder="0"></iframe>'+
' </div>'+
' </div>'+
' <div class="item Lovh">'+
' <span class="ltext Lfll">宽度:</span>'+
' <div class="Lfll">'+
' <input id="te_flash_width" name="" type="text" class="input2" value="200" />'+
' </div>'+
' <span class="ltext Lfll">高度:</span>'+
' <div class="Lfll">'+
' <input id="te_flash_height" name="" type="text" class="input2" value="60" />'+
' </div>'+
' </div>'+
' <div class="item Lovh">'+
' <span class="ltext Lfll"> </span>'+
' <div class="Lfll">'+
' <input id="te_flash_wmode" name="" type="checkbox" class="input3" />'+
' <label for="te_flash_wmode" class="labeltext">开启背景透明</label>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="确定" class="te_ok" />'+
' <input type="button" value="取消" class="te_close" />'+
' </div>'+
'</div>'
),
_upcall = function(path) {
//获取上传的值
$html.find( '#te_flash_url' ).val(path);
// 刷新iframe上传页
//var _url = $html.find( 'iframe' ).attr( 'src' );
//_url = _url.replace( /rands=[^&]+/, 'rands=' + (+ new Date()) );
$html.find( 'iframe' ).attr( 'src', 'about:blank' );
}
//注册通信
te_upload_interface( 'reg', {
'callid' : this.upid+this.editor.guid,
'filetype': this.uptype,
'maxsize' : this.maxsize,
'callback': _upcall
} );
//创建对话框
this.createDialog( {
body : $html,
ok : function() {
var _src = $html.find('#te_flash_url').val(),
_width = parseInt($html.find('#te_flash_width').val()),
_height = parseInt($html.find('#te_flash_height').val());
_wmode = !!$html.find('#te_flash_wmode').attr('checked');
if( _src == '' ) {
alert('请输入flash地址,或者从本地选择文件上传');
return true;
}
if( isNaN(_width) || isNaN(_height) ) {
alert('请输入宽高');
return true;
}
_src = _APP+_src;
var _data = "{'src':'"+_src+"','width':'"+_width+"','height':'"+_height+"','wmode':"+(_wmode)+"}";
var _insertHTML = '<img src="'+$.TE.basePath()+'skins/'+_self.editor.opt.skins+'/img/spacer.gif" class="_flash_position" style="';
if( _width ) _insertHTML += 'width:'+_width+'px;';
if( _height ) _insertHTML += 'height:'+_height+'px;';
_insertHTML += 'border:1px solid #DDD; display:inline-block;text-align:center;line-height:'+_height+'px;" ';
_insertHTML += '_data="'+_data+'"';
_insertHTML += ' alt="flash占位符" />';
_self.editor.pasteHTML( _insertHTML );
_self.hideDialog();
}
} )
}else{
alert('请配置上传处理路径!');
}
}
} );
$.TE.plugin( 'face', {
exec: function() {
var _self = this,
//表情路径
_fp = _self.editor.opt.face_path,
//弹出窗同容
$html = $(
'<div class="te_dialog_face Lovh">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="###" class="cstyle">插入表情</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="centbox">'+
' <div class="insertFace" style="background-image:url('+$.TE.basePath()+'skins/'+_fp[1]+'/'+_fp[0]+'.gif'+');">'+
'<span face_num="0"> </span>'+
'<span face_num="1"> </span>'+
'<span face_num="2"> </span>'+
'<span face_num="3"> </span>'+
'<span face_num="4"> </span>'+
'<span face_num="5"> </span>'+
'<span face_num="6"> </span>'+
'<span face_num="7"> </span>'+
'<span face_num="8"> </span>'+
'<span face_num="9"> </span>'+
'<span face_num="10"> </span>'+
'<span face_num="11"> </span>'+
'<span face_num="12"> </span>'+
'<span face_num="13"> </span>'+
'<span face_num="14"> </span>'+
'<span face_num="15"> </span>'+
'<span face_num="16"> </span>'+
'<span face_num="17"> </span>'+
'<span face_num="18"> </span>'+
'<span face_num="19"> </span>'+
'<span face_num="20"> </span>'+
'<span face_num="21"> </span>'+
'<span face_num="22"> </span>'+
'<span face_num="23"> </span>'+
'<span face_num="24"> </span>'+
'<span face_num="25"> </span>'+
'<span face_num="26"> </span>'+
'<span face_num="27"> </span>'+
'<span face_num="28"> </span>'+
'<span face_num="29"> </span>'+
'<span face_num="30"> </span>'+
'<span face_num="31"> </span>'+
'<span face_num="32"> </span>'+
'<span face_num="33"> </span>'+
'<span face_num="34"> </span>'+
'<span face_num="35"> </span>'+
'<span face_num="36"> </span>'+
'<span face_num="37"> </span>'+
'<span face_num="38"> </span>'+
'<span face_num="39"> </span>'+
'<span face_num="40"> </span>'+
'<span face_num="41"> </span>'+
'<span face_num="42"> </span>'+
'<span face_num="43"> </span>'+
'<span face_num="44"> </span>'+
'<span face_num="45"> </span>'+
'<span face_num="46"> </span>'+
'<span face_num="47"> </span>'+
'<span face_num="48"> </span>'+
'<span face_num="49"> </span>'+
'<span face_num="50"> </span>'+
'<span face_num="51"> </span>'+
'<span face_num="52"> </span>'+
'<span face_num="53"> </span>'+
'<span face_num="54"> </span>'+
'<span face_num="55"> </span>'+
'<span face_num="56"> </span>'+
'<span face_num="57"> </span>'+
'<span face_num="58"> </span>'+
'<span face_num="59"> </span>'+
'<span face_num="60"> </span>'+
'<span face_num="61"> </span>'+
'<span face_num="62"> </span>'+
'<span face_num="63"> </span>'+
'<span face_num="64"> </span>'+
'<span face_num="65"> </span>'+
'<span face_num="66"> </span>'+
'<span face_num="67"> </span>'+
'<span face_num="68"> </span>'+
'<span face_num="69"> </span>'+
'<span face_num="70"> </span>'+
'<span face_num="71"> </span>'+
'<span face_num="72"> </span>'+
'<span face_num="73"> </span>'+
'<span face_num="74"> </span>'+
'<span face_num="75"> </span>'+
'<span face_num="76"> </span>'+
'<span face_num="77"> </span>'+
'<span face_num="78"> </span>'+
'<span face_num="79"> </span>'+
'<span face_num="80"> </span>'+
'<span face_num="81"> </span>'+
'<span face_num="82"> </span>'+
'<span face_num="83"> </span>'+
'<span face_num="84"> </span>'+
'<span face_num="85"> </span>'+
'<span face_num="86"> </span>'+
'<span face_num="87"> </span>'+
'<span face_num="88"> </span>'+
'<span face_num="89"> </span>'+
'<span face_num="90"> </span>'+
'<span face_num="91"> </span>'+
'<span face_num="92"> </span>'+
'<span face_num="93"> </span>'+
'<span face_num="94"> </span>'+
'<span face_num="95"> </span>'+
'<span face_num="96"> </span>'+
'<span face_num="97"> </span>'+
'<span face_num="98"> </span>'+
'<span face_num="99"> </span>'+
'<span face_num="100"> </span>'+
'<span face_num="101"> </span>'+
'<span face_num="102"> </span>'+
'<span face_num="103"> </span>'+
'<span face_num="104"> </span>'+
'</div>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="取消" class="te_close" />'+
' </div>'+
'</div>'
);
$html.find('.insertFace span').click(function( e ) {
var _url = $.TE.basePath()+'skins/'+_fp[1]+'/'+_fp[0]+'_'+$( this ).attr( 'face_num' )+'.gif',
_insertHtml = '<img src="'+_url+'" />';
_self.editor.pasteHTML( _insertHtml );
_self.hideDialog();
});
this.createDialog( {
body : $html
} );
}
} );
$.TE.plugin( 'code', {
exec: function() {
var _self = this,
$html = $(
'<div class="te_dialog_code Lovh">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="###" class="cstyle">插入代码</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="centbox">'+
' <div class="Lmt10 Lml10">'+
' <span>选择语言:</span>'+
' <select id="langType" name="">'+
' <option value="None">其它类型</option>'+
' <option value="PHP">PHP</option>'+
' <option value="HTML">HTML</option>'+
' <option value="JS">JS</option>'+
' <option value="CSS">CSS</option>'+
' <option value="SQL">SQL</option>'+
' <option value="C#">C#</option>'+
' <option value="JAVA">JAVA</option>'+
' <option value="VBS">VBS</option>'+
' <option value="VB">VB</option>'+
' <option value="XML">XML</option>'+
' </select>'+
' </div>'+
' <textarea id="insertCode" name="" rows="10" class="tarea1 Lmt10" cols="30"></textarea>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="确定" class="te_ok" />'+
' <input type="button" value="取消" class="te_close" />'+
' </div>'+
'</div>'
);
this.createDialog({
body : $html,
ok : function(){
var _code = $html.find('#insertCode').val(),
_type = $html.find('#langType').val(),
_html = '';
_code = _code.replace( /</g, '<' );
_code = _code.replace( />/g, '>' );
_code = _code.split('\n');
_html += '<pre style="overflow-x:auto; padding:10px; color:blue; border:1px dotted #2BC1FF; background-color:#EEFAFF;" _syntax="'+_type+'">'
_html += '语言类型:'+_type;
_html += '<ol style="list-stype-type:decimal;">';
for(var i=0; i<_code.length; i++) {
_html += '<li>'+_code[i].replace( /^(\t+)/g, function( $1 ) {return $1.replace(/\t/g, ' ');} );+'</li>';
}
_html += '</ol></pre><p> </p>';
_self.editor.pasteHTML( _html );
_self.hideDialog();
}
});
}
} );
$.TE.plugin( 'style', {
click: function() {
var _self = this,
$html = $(
'<div class="te_dialog_style Lovh">'+
' <div class="centbox">'+
' <h1 title="设置当前内容为一级标题"><a href="###">一级标题</a></h1>'+
' <h2 title="设置当前内容为二级标题"><a href="###">二级标题</a></h2>'+
' <h3 title="设置当前内容为三级标题"><a href="###">三级标题</a></h3>'+
' <h4 title="设置当前内容为四级标题"><a href="###">四级标题</a></h4>'+
' <h5 title="设置当前内容为五级标题"><a href="###">五级标题</a></h5>'+
' <h6 title="设置当前内容为六级标题"><a href="###">六级标题</a></h6>'+
' </div>'+
'</div>'
),
_call = function(e) {
var _value = this.nodeName;
_self.value= _value;
_self.exec();
//_self.hideDialog();
};
$html.find( '>.centbox>*' ).click( _call );
this.createDialog( {
body: $html
} );
},
exec: function() {
var _self = this,
_html = '<'+_self.value+'>'+_self.editor.selectedHTML()+'</'+_self.value+'>';
_self.editor.pasteHTML( _html );
}
} );
$.TE.plugin( 'font', {
click: function() {
var _self = this;
$html = $(
'<div class="te_dialog_font Lovh">'+
' <div class="centbox">'+
' <div><a href="###" style="font-family:\'宋体\',\'SimSun\'">宋体</a></div>'+
' <div><a href="###" style="font-family:\'楷体\',\'楷体_GB2312\',\'SimKai\'">楷体</a></div>'+
' <div><a href="###" style="font-family:\'隶书\',\'SimLi\'">隶书</a></div>'+
' <div><a href="###" style="font-family:\'黑体\',\'SimHei\'">黑体</a></div>'+
' <div><a href="###" style="font-family:\'微软雅黑\'">微软雅黑</a></div>'+
' <span>------</span>'+
' <div><a href="###" style="font-family:arial,helvetica,sans-serif;">Arial</a></div>'+
' <div><a href="###" style="font-family:comic sans ms,cursive;">Comic Sans Ms</a></div>'+
' <div><a href="###" style="font-family:courier new,courier,monospace;">Courier New</a></div>'+
' <div><a href="###" style="font-family:georgia,serif;">Georgia</a></div>'+
' <div><a href="###" style="font-family:lucida sans unicode,lucida grande,sans-serif;">Lucida Sans Unicode</a></div>'+
' <div><a href="###" style="font-family:tahoma,geneva,sans-serif;">Tahoma</a></div>'+
' <div><a href="###" style="font-family:times new roman,times,serif;">Times New Roman</a></div>'+
' <div><a href="###" style="font-family:trebuchet ms,helvetica,sans-serif;">Trebuchet Ms</a></div>'+
' <div><a href="###" style="font-family:verdana,geneva,sans-serif;">Verdana</a></div>'+
' </div>'+
'</div>'
),
_call = function(e) {
var _value = this.style.fontFamily;
_self.value= _value;
_self.exec();
};
$html.find( '>.centbox a' ).click( _call );
this.createDialog( {
body: $html
} );
}
} );
$.TE.plugin( 'fontsize', {
click: function() {
var _self = this,
$html = $(
'<div class="te_dialog_fontsize Lovh">'+
' <div class="centbox">'+
' <div><a href="#" style="font-size:10px">10</a></div>'+
' <div><a href="#" style="font-size:12px">12</a></div>'+
' <div><a href="#" style="font-size:14px">14</a></div>'+
' <div><a href="#" style="font-size:16px">16</a></div>'+
' <div><a href="#" style="font-size:18px">18</a></div>'+
' <div><a href="#" style="font-size:20px">20</a></div>'+
' <div><a href="#" style="font-size:22px">22</a></div>'+
' <div><a href="#" style="font-size:24px">24</a></div>'+
' <div><a href="#" style="font-size:36px">36</a></div>'+
' <div><a href="#" style="font-size:48px">48</a></div>'+
' <div><a href="#" style="font-size:60px">60</a></div>'+
' <div><a href="#" style="font-size:72px">72</a></div>'+
' </div>'+
'</div>'
),
_call = function(e) {
var _value = this.style.fontSize;
_self.value= _value;
_self.exec();
};
$html.find( '>.centbox a' ).click( _call );
this.createDialog( {
body: $html
} );
},
exec: function() {
var _self = this,
_html = '<span style="font-size:'+_self.value+'">'+_self.editor.selectedText()+'</span>';
_self.editor.pasteHTML( _html );
}
} );
$.TE.plugin( 'fontcolor', {
click: function() {
var _self = this,
$html = $(
'<div class="te_dialog_fontcolor Lovh">'+
' <div class="colorsel">'+
' <!--第一列-->'+
' <a href="###" style="background-color:#FF0000"> </a>'+
' <a href="###" style="background-color:#FFA900"> </a>'+
' <a href="###" style="background-color:#FFFF00"> </a>'+
' <a href="###" style="background-color:#99E600"> </a>'+
' <a href="###" style="background-color:#99E600"> </a>'+
' <a href="###" style="background-color:#00FFFF"> </a>'+
' <a href="###" style="background-color:#00AAFF"> </a>'+
' <a href="###" style="background-color:#0055FF"> </a>'+
' <a href="###" style="background-color:#5500FF"> </a>'+
' <a href="###" style="background-color:#AA00FF"> </a>'+
' <a href="###" style="background-color:#FF007F"> </a>'+
' <a href="###" style="background-color:#FFFFFF"> </a>'+
' <!--第二列-->'+
' <a href="###" style="background-color:#FFE5E5"> </a>'+
' <a href="###" style="background-color:#FFF2D9"> </a>'+
' <a href="###" style="background-color:#FFFFCC"> </a>'+
' <a href="###" style="background-color:#EEFFCC"> </a>'+
' <a href="###" style="background-color:#D9FFE0"> </a>'+
' <a href="###" style="background-color:#D9FFFF"> </a>'+
' <a href="###" style="background-color:#D9F2FF"> </a>'+
' <a href="###" style="background-color:#D9E6FF"> </a>'+
' <a href="###" style="background-color:#E6D9FF"> </a>'+
' <a href="###" style="background-color:#F2D9FF"> </a>'+
' <a href="###" style="background-color:#FFD9ED"> </a>'+
' <a href="###" style="background-color:#D9D9D9"> </a>'+
' <!--第三列-->'+
' <a href="###" style="background-color:#E68A8A"> </a>'+
' <a href="###" style="background-color:#E6C78A"> </a>'+
' <a href="###" style="background-color:#FFFF99"> </a>'+
' <a href="###" style="background-color:#BFE673"> </a>'+
' <a href="###" style="background-color:#99EEA0"> </a>'+
' <a href="###" style="background-color:#A1E6E6"> </a>'+
' <a href="###" style="background-color:#99DDFF"> </a>'+
' <a href="###" style="background-color:#8AA8E6"> </a>'+
' <a href="###" style="background-color:#998AE6"> </a>'+
' <a href="###" style="background-color:#C78AE6"> </a>'+
' <a href="###" style="background-color:#E68AB9"> </a>'+
' <a href="###" style="background-color:#B3B3B3"> </a>'+
' <!--第四列-->'+
' <a href="###" style="background-color:#CC5252"> </a>'+
' <a href="###" style="background-color:#CCA352"> </a>'+
' <a href="###" style="background-color:#D9D957"> </a>'+
' <a href="###" style="background-color:#A7CC39"> </a>'+
' <a href="###" style="background-color:#57CE6D"> </a>'+
' <a href="###" style="background-color:#52CCCC"> </a>'+
' <a href="###" style="background-color:#52A3CC"> </a>'+
' <a href="###" style="background-color:#527ACC"> </a>'+
' <a href="###" style="background-color:#6652CC"> </a>'+
' <a href="###" style="background-color:#A352CC"> </a>'+
' <a href="###" style="background-color:#CC5291"> </a>'+
' <a href="###" style="background-color:#B3B3B3"> </a>'+
' <!--第五列-->'+
' <a href="###" style="background-color:#991F1F"> </a>'+
' <a href="###" style="background-color:#99701F"> </a>'+
' <a href="###" style="background-color:#99991F"> </a>'+
' <a href="###" style="background-color:#59800D"> </a>'+
' <a href="###" style="background-color:#0F9932"> </a>'+
' <a href="###" style="background-color:#1F9999"> </a>'+
' <a href="###" style="background-color:#1F7099"> </a>'+
' <a href="###" style="background-color:#1F4799"> </a>'+
' <a href="###" style="background-color:#471F99"> </a>'+
' <a href="###" style="background-color:#701F99"> </a>'+
' <a href="###" style="background-color:#991F5E"> </a>'+
' <a href="###" style="background-color:#404040"> </a>'+
' <!--第六列-->'+
' <a href="###" style="background-color:#660000"> </a>'+
' <a href="###" style="background-color:#664B14"> </a>'+
' <a href="###" style="background-color:#666600"> </a>'+
' <a href="###" style="background-color:#3B5900"> </a>'+
' <a href="###" style="background-color:#005916"> </a>'+
' <a href="###" style="background-color:#146666"> </a>'+
' <a href="###" style="background-color:#144B66"> </a>'+
' <a href="###" style="background-color:#143066"> </a>'+
' <a href="###" style="background-color:#220066"> </a>'+
' <a href="###" style="background-color:#301466"> </a>'+
' <a href="###" style="background-color:#66143F"> </a>'+
' <a href="###" style="background-color:#000000"> </a>'+
' </div>'+
'</div>'
),
_call = function(e) {
var _value = this.style.backgroundColor;
_self.value= _value;
_self.exec();
};
$html.find( '>.colorsel a' ).click( _call );
this.createDialog( {
body: $html
} );
}
} );
$.TE.plugin( 'backcolor', {
click: function() {
var _self = this,
$html = $(
'<div class="te_dialog_fontcolor Lovh">'+
' <div class="colorsel">'+
' <!--第一列-->'+
' <a href="###" style="background-color:#FF0000"> </a>'+
' <a href="###" style="background-color:#FFA900"> </a>'+
' <a href="###" style="background-color:#FFFF00"> </a>'+
' <a href="###" style="background-color:#99E600"> </a>'+
' <a href="###" style="background-color:#99E600"> </a>'+
' <a href="###" style="background-color:#00FFFF"> </a>'+
' <a href="###" style="background-color:#00AAFF"> </a>'+
' <a href="###" style="background-color:#0055FF"> </a>'+
' <a href="###" style="background-color:#5500FF"> </a>'+
' <a href="###" style="background-color:#AA00FF"> </a>'+
' <a href="###" style="background-color:#FF007F"> </a>'+
' <a href="###" style="background-color:#FFFFFF"> </a>'+
' <!--第二列-->'+
' <a href="###" style="background-color:#FFE5E5"> </a>'+
' <a href="###" style="background-color:#FFF2D9"> </a>'+
' <a href="###" style="background-color:#FFFFCC"> </a>'+
' <a href="###" style="background-color:#EEFFCC"> </a>'+
' <a href="###" style="background-color:#D9FFE0"> </a>'+
' <a href="###" style="background-color:#D9FFFF"> </a>'+
' <a href="###" style="background-color:#D9F2FF"> </a>'+
' <a href="###" style="background-color:#D9E6FF"> </a>'+
' <a href="###" style="background-color:#E6D9FF"> </a>'+
' <a href="###" style="background-color:#F2D9FF"> </a>'+
' <a href="###" style="background-color:#FFD9ED"> </a>'+
' <a href="###" style="background-color:#D9D9D9"> </a>'+
' <!--第三列-->'+
' <a href="###" style="background-color:#E68A8A"> </a>'+
' <a href="###" style="background-color:#E6C78A"> </a>'+
' <a href="###" style="background-color:#FFFF99"> </a>'+
' <a href="###" style="background-color:#BFE673"> </a>'+
' <a href="###" style="background-color:#99EEA0"> </a>'+
' <a href="###" style="background-color:#A1E6E6"> </a>'+
' <a href="###" style="background-color:#99DDFF"> </a>'+
' <a href="###" style="background-color:#8AA8E6"> </a>'+
' <a href="###" style="background-color:#998AE6"> </a>'+
' <a href="###" style="background-color:#C78AE6"> </a>'+
' <a href="###" style="background-color:#E68AB9"> </a>'+
' <a href="###" style="background-color:#B3B3B3"> </a>'+
' <!--第四列-->'+
' <a href="###" style="background-color:#CC5252"> </a>'+
' <a href="###" style="background-color:#CCA352"> </a>'+
' <a href="###" style="background-color:#D9D957"> </a>'+
' <a href="###" style="background-color:#A7CC39"> </a>'+
' <a href="###" style="background-color:#57CE6D"> </a>'+
' <a href="###" style="background-color:#52CCCC"> </a>'+
' <a href="###" style="background-color:#52A3CC"> </a>'+
' <a href="###" style="background-color:#527ACC"> </a>'+
' <a href="###" style="background-color:#6652CC"> </a>'+
' <a href="###" style="background-color:#A352CC"> </a>'+
' <a href="###" style="background-color:#CC5291"> </a>'+
' <a href="###" style="background-color:#B3B3B3"> </a>'+
' <!--第五列-->'+
' <a href="###" style="background-color:#991F1F"> </a>'+
' <a href="###" style="background-color:#99701F"> </a>'+
' <a href="###" style="background-color:#99991F"> </a>'+
' <a href="###" style="background-color:#59800D"> </a>'+
' <a href="###" style="background-color:#0F9932"> </a>'+
' <a href="###" style="background-color:#1F9999"> </a>'+
' <a href="###" style="background-color:#1F7099"> </a>'+
' <a href="###" style="background-color:#1F4799"> </a>'+
' <a href="###" style="background-color:#471F99"> </a>'+
' <a href="###" style="background-color:#701F99"> </a>'+
' <a href="###" style="background-color:#991F5E"> </a>'+
' <a href="###" style="background-color:#404040"> </a>'+
' <!--第六列-->'+
' <a href="###" style="background-color:#660000"> </a>'+
' <a href="###" style="background-color:#664B14"> </a>'+
' <a href="###" style="background-color:#666600"> </a>'+
' <a href="###" style="background-color:#3B5900"> </a>'+
' <a href="###" style="background-color:#005916"> </a>'+
' <a href="###" style="background-color:#146666"> </a>'+
' <a href="###" style="background-color:#144B66"> </a>'+
' <a href="###" style="background-color:#143066"> </a>'+
' <a href="###" style="background-color:#220066"> </a>'+
' <a href="###" style="background-color:#301466"> </a>'+
' <a href="###" style="background-color:#66143F"> </a>'+
' <a href="###" style="background-color:#000000"> </a>'+
' </div>'+
'</div>'
),
_call = function(e) {
var _value = this.style.backgroundColor;
_self.value= _value;
_self.exec();
};
$html.find( '>.colorsel a' ).click( _call );
this.createDialog( {
body: $html
} );
}
} );
$.TE.plugin( 'about', {
'click': function() {
var _self = this,
$html = $(
'<div class="te_dialog_about Lovh">'+
' <div class="seltab">'+
' <div class="links Lovh">'+
' <a href="###" class="cstyle">关于ThinkEditor</a>'+
' </div>'+
' <div class="bdb"> </div>'+
' </div>'+
' <div class="centbox">'+
' <div class="aboutcontent">'+
' <p>ThinkPHP是一个免费开源的,快速、简单的面向对象的轻量级PHP开发框架,遵循Apache2开源协议发布,是为了敏捷WEB应用开发和简化企业级应用开发而诞生的。拥有众多的优秀功能和特性,经历了三年多发展的同时,在社区团队的积极参与下,在易用性、扩展性和性能方面不断优化和改进,众多的典型案例确保可以稳定用于商业以及门户级的开发。</p>'+
' <p>ThinkPHP借鉴了国外很多优秀的框架和模式,使用面向对象的开发结构和MVC模式,采用单一入口模式等,融合了Struts的Action思想和JSP的TagLib(标签库)、RoR的ORM映射和ActiveRecord模式,封装了CURD和一些常用操作,在项目配置、类库导入、模版引擎、查询语言、自动验证、视图模型、项目编译、缓存机制、SEO支持、分布式数据库、多数据库连接和切换、认证机制和扩展性方面均有独特的表现。</p>'+
' <p>使用ThinkPHP,你可以更方便和快捷的开发和部署应用。当然不仅仅是企业级应用,任何PHP应用开发都可以从ThinkPHP的简单和快速的特性中受益。ThinkPHP本身具有很多的原创特性,并且倡导大道至简,开发由我的开发理念,用最少的代码完成更多的功能,宗旨就是让WEB应用开发更简单、更快速。为此ThinkPHP会不断吸收和融入更好的技术以保证其新鲜和活力,提供WEB应用开发的最佳实践!</p>'+
' <p>ThinkPHP遵循Apache2开源许可协议发布,意味着你可以免费使用ThinkPHP,甚至允许把你基于ThinkPHP开发的应用开源或商业产品发布/销售。 </p>'+
' </div>'+
' </div>'+
' <div class="btnarea">'+
' <input type="button" value="关闭" class="te_close" />'+
' </div>'+
'</div>'
);
_self.createDialog( {
body: $html
} );
}
} );
//$.TE.plugin( 'eq', {
// 'click': function() {
// var _self = this,
// $html = $(
// '<div class="te_dialog_about Lovh">'+
// ' <div class="seltab">'+
// ' <div class="links Lovh">'+
// ' <a href="###" class="cstyle">关于ThinkEditor</a>'+
// ' </div>'+
// ' <div class="bdb"> </div>'+
// ' </div>'+
// ' <div class="centbox">'+
// ' <div class="eqcontent">'+
// ' <label for="eq_name">名称</label>'+
// ' <input type="text" name="eq_name" id="eq_name"/></br>'+
// ' <label for="eq_name">值</label>'+
// ' <input type="text" name="eq_val" id="eq_val"/></br>'+
// ' <textarea name="eq_content" id="eq_content" cols="30" rows="2"></textarea>'+
// ' </div>'+
// ' </div>'+
// ' <div class="btnarea">'+
// ' <input type="button" value="确定" class="te_ok" />'+
// ' <input type="button" value="关闭" class="te_close" />'+
// ' </div>'+
// '</div>'
// );
//
// _self.createDialog({
// body: $html,
// ok : function(){
// var _name = $html.find('#eq_name').val(),
// _val = $html.find('#eq_val').val(),
// _content = $html.find('#eq_content').val(),
// _html = '';
// _html += '<eq name="' + _name +'" value="' + _val +'">'+
// _content +
// '</eq>';
// _self.editor.pasteHTML( _html );
// _self.hideDialog();
// }
// });
//
// }
//});
} )( jQuery );
| 10npsite | trunk/DThinkPHP/Extend/Tool/thinkeditor/plugins/system.js | JavaScript | asf20 | 46,285 |
(function ($) {
var ie = $.browser.msie,
iOS = /iphone|ipad|ipod/i.test(navigator.userAgent);
$.TE = {
version:'1.0', // 版本号
debug: 1, //调试开关
timeOut: 3000, //加载单个文件超时时间,单位为毫秒。
defaults: {
//默认参数controls,noRigths,plugins,定义加载插件
controls: "source,|,undo,redo,|,cut,copy,paste,pastetext,selectAll,blockquote,|,image,flash,table,hr,pagebreak,face,code,|,link,unlink,|,print,fullscreen,|,eq,|,style,font,fontsize,|,fontcolor,backcolor,|,bold,italic,underline,strikethrough,unformat,|,leftalign,centeralign,rightalign,blockjustify,|,orderedlist,unorderedlist,indent,outdent,|,subscript,superscript",
//noRights:"underline,strikethrough,superscript",
width: 740,
height: 500,
skins: "default",
resizeType: 2,
face_path: ['qq_face', 'qq_face'],
minHeight: 200,
minWidth: 500,
uploadURL: 'about:blank',
theme: 'default'
},
buttons: {
//按钮属性
//eq: {title: '等于',cmd: 'bold'},
bold: { title: "加粗", cmd: "bold" },
pastetext: { title: "粘贴无格式", cmd: "bold" },
pastefromword: { title: "粘贴word格式", cmd: "bold" },
selectAll: { title: "全选", cmd: "selectall" },
blockquote: { title: "引用" },
find: { title: "查找", cmd: "bold" },
flash: { title: "插入flash", cmd: "bold" },
media: { title: "插入多媒体", cmd: "bold" },
table: { title: "插入表格" },
pagebreak: { title: "插入分页符" },
face: { title: "插入表情", cmd: "bold" },
code: { title: "插入源码", cmd: "bold" },
print: { title: "打印", cmd: "print" },
about: { title: "关于", cmd: "bold" },
fullscreen: { title: "全屏", cmd: "fullscreen" },
source: { title: "HTML代码", cmd: "source" },
undo: { title: "后退", cmd: "undo" },
redo: { title: "前进", cmd: "redo" },
cut: { title: "剪贴", cmd: "cut" },
copy: { title: "复制", cmd: "copy" },
paste: { title: "粘贴", cmd: "paste" },
hr: { title: "插入横线", cmd: "inserthorizontalrule" },
link: { title: "创建链接", cmd: "createlink" },
unlink: { title: "删除链接", cmd: "unlink" },
italic: { title: "斜体", cmd: "italic" },
underline: { title: "下划线", cmd: "underline" },
strikethrough: { title: "删除线", cmd: "strikethrough" },
unformat: { title: "清除格式", cmd: "removeformat" },
subscript: { title: "下标", cmd: "subscript" },
superscript: { title: "上标", cmd: "superscript" },
orderedlist: { title: "有序列表", cmd: "insertorderedlist" },
unorderedlist: { title: "无序列表", cmd: "insertunorderedlist" },
indent: { title: "增加缩进", cmd: "indent" },
outdent: { title: "减少缩进", cmd: "outdent" },
leftalign: { title: "左对齐", cmd: "justifyleft" },
centeralign: { title: "居中对齐", cmd: "justifycenter" },
rightalign: { title: "右对齐", cmd: "justifyright" },
blockjustify: { title: "两端对齐", cmd: "justifyfull" },
font: { title: "字体", cmd: "fontname", value: "微软雅黑" },
fontsize: { title: "字号", cmd: "fontsize", value: "4" },
style: { title: "段落标题", cmd: "formatblock", value: "" },
fontcolor: { title: "前景颜色", cmd: "forecolor", value: "#ff6600" },
backcolor: { title: "背景颜色", cmd: "hilitecolor", value: "#ff6600" },
image: { title: "插入图片", cmd: "insertimage", value: "" }
},
defaultEvent: {
event: "click mouseover mouseout",
click: function (e) {
this.exec(e);
},
mouseover: function (e) {
var opt = this.editor.opt;
this.$btn.addClass(opt.cssname.mouseover);
},
mouseout: function (e) { },
noRight: function (e) { },
init: function (e) { },
exec: function () {
this.editor.restoreRange();
//执行命令
if ($.isFunction(this[this.cmd])) {
this[this.cmd](); //如果有已当前cmd为名的方法,则执行
} else {
this.editor.doc.execCommand(this.cmd, 0, this.value || null);
}
this.editor.focus();
this.editor.refreshBtn();
this.editor.hideDialog();
},
createDialog: function (v) {
//创建对话框
var editor = this.editor,
opt = editor.opt,
$btn = this.$btn,
_self = this;
var defaults = {
body: "", //对话框内容
closeBtn: opt.cssname.dialogCloseBtn,
okBtn: opt.cssname.dialogOkBtn,
ok: function () {
//点击ok按钮后执行函数
},
setDialog: function ($dialog) {
//设置对话框(位置)
var y = $btn.offset().top + $btn.outerHeight();
var x = $btn.offset().left;
$dialog.offset({
top: y,
left: x
});
}
};
var options = $.extend(defaults, v);
//初始化对话框
editor.$dialog.empty();
//加入内容
$body = $.type(options.body) == "string" ? $(options.body) : options.body;
$dialog = $body.appendTo(editor.$dialog);
$dialog.find("." + options.closeBtn).click(function () { _self.hideDialog(); });
$dialog.find("." + options.okBtn).click(options.ok);
//设置对话框
editor.$dialog.show();
options.setDialog(editor.$dialog);
},
hideDialog: function () {
this.editor.hideDialog();
}
//getEnable:function(){return false},
//disable:function(e){alert('disable')}
},
plugin: function (name, v) {
//新增或修改插件。
$.TE.buttons[name] = $.extend($.TE.buttons[name], v);
},
config: function (name, value) {
var _fn = arguments.callee;
if (!_fn.conf) _fn.conf = {};
if (value) {
_fn.conf[name] = value;
return true;
} else {
return name == 'default' ? $.TE.defaults : _fn.conf[name];
}
},
systemPlugins: ['system', 'upload_interface'], //系统自带插件
basePath: function () {
var jsFile = "ThinkEditor.js";
var src = $("script[src$='" + jsFile + "']").attr("src");
return src.substr(0, src.length - jsFile.length);
}
};
$.fn.extend({
//调用插件
ThinkEditor: function (v) {
//配置处理
var conf = '',
temp = '';
conf = v ? $.extend($.TE.config(v.theme ? v.theme : 'default'), v) : $.TE.config('default');
v = conf;
//配置处理完成
//载入皮肤
var skins = v.skins || $.TE.defaults.skins; //获得皮肤参数
var skinsDir = $.TE.basePath() + "skins/" + skins + "/",
jsFile = "@" + skinsDir + "config.js",
cssFile = "@" + skinsDir + "style.css";
var _self = this;
//加载插件
if ($.defined(v.plugins)) {
var myPlugins = $.type(v.plugins) == "string" ? [v.plugins] : v.plugins;
var files = $.merge($.merge([], $.TE.systemPlugins), myPlugins);
} else {
var files = $.TE.systemPlugins;
}
$.each(files, function (i, v) {
files[i] = v + ".js";
})
files.push(jsFile, cssFile);
files.push("@" + skinsDir + "dialog/css/base.css");
files.push("@" + skinsDir + "dialog/css/te_dialog.css");
$.loadFile(files, function () {
//设置css参数
v.cssname = $.extend({}, TECSS, v.cssname);
//创建编辑器,存储对象
$(_self).each(function (idx, elem) {
var data = $(elem).data("editorData");
if (!data) {
data = new ThinkEditor(elem, v);
$(elem).data("editorData", data);
}
});
});
}
});
//编辑器对象。
function ThinkEditor(area, v) {
//添加随机序列数防冲突
var _fn = arguments.callee;
this.guid = !_fn.guid ? _fn.guid = 1 : _fn.guid += 1;
//生成参数
var opt = this.opt = $.extend({}, $.TE.defaults, v);
var _self = this;
//结构:主层,工具层,分组层,按钮层,底部,dialog层
var $main = this.$main = $("<div></div>").addClass(opt.cssname.main),
$toolbar_box = $('<div></div>').addClass(opt.cssname.toolbar_box).appendTo($main),
$toolbar = this.$toolbar = $("<div></div>").addClass(opt.cssname.toolbar).appendTo($toolbar_box),
/*$toolbar=this.$toolbar=$("<div></div>").addClass(opt.cssname.toolbar).appendTo($main),*/
$group = $("<div></div>").addClass(opt.cssname.group).appendTo($toolbar),
$bottom = this.$bottom = $("<div></div>").addClass(opt.cssname.bottom),
$dialog = this.$dialog = $("<div></div>").addClass(opt.cssname.dialog),
$area = $(area).hide(),
$frame = $('<iframe frameborder="0"></iframe>');
opt.noRights = opt.noRights || "";
var noRights = opt.noRights.split(",");
//调整结构
$main.insertBefore($area)
.append($area);
//加入frame
$frame.appendTo($main);
//加入bottom
if (opt.resizeType != 0) {
//拖动改变编辑器高度
$("<div></div>").addClass(opt.cssname.resizeCenter).mousedown(function (e) {
var y = e.pageY,
x = e.pageX,
height = _self.$main.height(),
width = _self.$main.width();
$(document).add(_self.doc).mousemove(function (e) {
var mh = e.pageY - y;
_self.resize(width, height + mh);
});
$(document).add(_self.doc).mouseup(function (e) {
$(document).add(_self.doc).unbind("mousemove");
$(document).add(_self.doc).unbind("mousemup");
});
}).appendTo($bottom);
}
if (opt.resizeType == 2) {
//拖动改变编辑器高度和宽度
$("<div></div>").addClass(opt.cssname.resizeLeft).mousedown(function (e) {
var y = e.pageY,
x = e.pageX,
height = _self.$main.height(),
width = _self.$main.width();
$(document).add(_self.doc).mousemove(function (e) {
var mh = e.pageY - y,
mw = e.pageX - x;
_self.resize(width + mw, height + mh);
});
$(document).add(_self.doc).mouseup(function (e) {
$(document).add(_self.doc).unbind("mousemove");
$(document).add(_self.doc).unbind("mousemup");
});
}).appendTo($bottom);
}
$bottom.appendTo($main);
$dialog.appendTo($main);
//循环按钮处理。
//TODO 默认参数处理
$.each(opt.controls.split(","), function (idx, bname) {
var _fn = arguments.callee;
if (_fn.count == undefined) {
_fn.count = 0;
}
//处理分组
if (bname == "|") {
//设定分组宽
if (_fn.count) {
$toolbar.find('.' + opt.cssname.group + ':last').css('width', (opt.cssname.btnWidth * _fn.count + opt.cssname.lineWidth) + 'px');
_fn.count = 0;
}
//分组宽结束
$group = $("<div></div>").addClass(opt.cssname.group).appendTo($toolbar);
$("<div> </div>").addClass(opt.cssname.line).appendTo($group);
} else {
//更新统计数
_fn.count += 1;
//获取按钮属性
var btn = $.extend({}, $.TE.defaultEvent, $.TE.buttons[bname]);
//标记无权限
var noRightCss = "", noRightTitle = "";
if ($.inArray(bname, noRights) != -1) {
noRightCss = " " + opt.cssname.noRight;
noRightTitle = "(无权限)";
}
$btn = $("<div></div>").addClass(opt.cssname.btn + " " + opt.cssname.btnpre + bname + noRightCss)
.data("bname", bname)
.attr("title", btn.title + noRightTitle)
.appendTo($group)
.bind(btn.event, function (e) {
//不可用触发
if ($(this).is("." + opt.cssname.disable)) {
if ($.isFunction(btn.disable)) btn.disable.call(btn, e);
return false;
}
//判断权限和是否可用
if ($(this).is("." + opt.cssname.noRight)) {
//点击时触发无权限说明
btn['noRight'].call(btn, e);
return false;
}
if ($.isFunction(btn[e.type])) {
//触发事件
btn[e.type].call(btn, e);
//TODO 刷新按钮
}
});
if ($.isFunction(btn.init)) btn.init.call(btn); //初始化
if (ie) $btn.attr("unselectable", "on");
btn.editor = _self;
btn.$btn = $btn;
}
});
//调用核心
this.core = new editorCore($frame, $area);
this.doc = this.core.doc;
this.$frame = this.core.$frame;
this.$area = this.core.$area;
this.restoreRange = this.core.restoreRange;
this.selectedHTML = function () { return this.core.selectedHTML(); }
this.selectedText = function () { return this.core.selectedText(); }
this.pasteHTML = function (v) { this.core.pasteHTML(v); }
this.sourceMode = this.core.sourceMode;
this.focus = this.core.focus;
//监控变化
$(this.core.doc).click(function () {
//隐藏对话框
_self.hideDialog();
}).bind("keyup mouseup", function () {
_self.refreshBtn();
})
this.refreshBtn();
//调整大小
this.resize(opt.width, opt.height);
//获取DOM层级
this.core.focus();
}
//end ThinkEditor
ThinkEditor.prototype.resize = function (w, h) {
//最小高度和宽度
var opt = this.opt,
h = h < opt.minHeight ? opt.minHeight : h,
w = w < opt.minWidth ? opt.minWidth : w;
this.$main.width(w).height(h);
var height = h - (this.$toolbar.parent().outerHeight() + this.$bottom.height());
this.$frame.height(height).width("100%");
this.$area.height(height).width("100%");
};
//隐藏对话框
ThinkEditor.prototype.hideDialog = function () {
var opt = this.opt;
$("." + opt.cssname.dialog).hide();
};
//刷新按钮
ThinkEditor.prototype.refreshBtn = function () {
var sourceMode = this.sourceMode(); // 标记状态。
var opt = this.opt;
if (!iOS && $.browser.webkit && !this.focused) {
this.$frame[0].contentWindow.focus();
window.focus();
this.focused = true;
}
var queryObj = this.doc;
if (ie) queryObj = this.core.getRange();
//循环按钮
//TODO undo,redo等判断
this.$toolbar.find("." + opt.cssname.btn + ":not(." + opt.cssname.noRight + ")").each(function () {
var enabled = true,
btnName = $(this).data("bname"),
btn = $.extend({}, $.TE.defaultEvent, $.TE.buttons[btnName]),
command = btn.cmd;
if (sourceMode && btnName != "source") {
enabled = false;
} else if ($.isFunction(btn.getEnable)) {
enabled = btn.getEnable.call(btn);
} else if ($.isFunction(btn[command])) {
enabled = true; //如果命令为自定义命令,默认为可用
} else {
if (!ie || btn.cmd != "inserthtml") {
try {
enabled = queryObj.queryCommandEnabled(command);
$.debug(enabled.toString(), "命令:" + command);
}
catch (err) {
enabled = false;
}
}
//判断该功能是否有实现 @TODO 代码胶着
if ($.TE.buttons[btnName]) enabled = true;
}
if (enabled) {
$(this).removeClass(opt.cssname.disable);
} else {
$(this).addClass(opt.cssname.disable);
}
});
};
//core code start
function editorCore($frame, $area, v) {
//TODO 参数改为全局的。
var defaults = {
docType: '<!DOCTYPE HTML>',
docCss: "",
bodyStyle: "margin:4px; font:10pt Arial,Verdana; cursor:text",
focusExt: function (editor) {
//触发编辑器获得焦点时执行,比如刷新按钮
},
//textarea内容更新到iframe的处理函数
updateFrame: function (code) {
//翻转flash为占位符
code = code.replace(/(<embed[^>]*?type="application\/x-shockwave-flash" [^>]*?>)/ig, function ($1) {
var ret = '<img class="_flash_position" src="' + $.TE.basePath() + 'skins/default/img/spacer.gif" style="',
_width = $1.match(/width="(\d+)"/),
_height = $1.match(/height="(\d+)"/),
_src = $1.match(/src="([^"]+)"/),
_wmode = $1.match(/wmode="(\w+)"/),
_data = '';
_width = _width && _width[1] ? parseInt(_width[1]) : 0;
_height = _height && _height[1] ? parseInt(_height[1]) : 0;
_src = _src && _src[1] ? _src[1] : '';
_wmode = _wmode && _wmode[1] ? true : false;
_data = "{'src':'" + _src + "','width':'" + _width + "','height':'" + _height + "','wmode':" + (_wmode) + "}";
if (_width) ret += 'width:' + _width + 'px;';
if (_height) ret += 'height:' + _height + 'px;';
ret += 'border:1px solid #DDD; display:inline-block;text-align:center;line-height:' + _height + 'px;" ';
ret += '_data="' + _data + '"';
ret += ' alt="flash占位符" />';
return ret;
});
return code;
},
//iframe更新到text的, TODO 去掉
updateTextArea: function (html) {
//翻转占位符为flash
html = html.replace(/(<img[^>]*?class=(?:"|)_flash_position(?:"|)[^>]*?>)/ig, function ($1) {
var ret = '',
data = $1.match(/_data="([^"]*)"/);
if (data && data[1]) {
data = eval('(' + data + ')');
}
ret += '<embed type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" ';
ret += 'src="' + data.src + '" ';
ret += 'width="' + data.width + '" ';
ret += 'height="' + data.height + '" ';
if (data.wmode) ret += 'wmode="transparent" ';
ret += '/>';
return ret;
});
return html;
}
};
options = $.extend({}, defaults, v);
//存储属性
this.opt = options;
this.$frame = $frame;
this.$area = $area;
var contentWindow = $frame[0].contentWindow,
doc = this.doc = contentWindow.document,
$doc = $(doc);
var _self = this;
//初始化
doc.open();
doc.write(
options.docType +
'<html>' +
((options.docCss === '') ? '' : '<head><link rel="stylesheet" type="text/css" href="' + options.docCss + '" /></head>') +
'<body style="' + options.bodyStyle + '"></body></html>'
);
doc.close();
//设置frame编辑模式
try {
if (ie) {
doc.body.contentEditable = true;
}
else {
doc.designMode = "on";
}
} catch (err) {
$.debug(err, "创建编辑模式错误");
}
//统一 IE FF 等的 execCommand 行为
try {
this.e.execCommand("styleWithCSS", 0, 0)
}
catch (e) {
try {
this.e.execCommand("useCSS", 0, 1);
} catch (e) { }
}
//监听
if (ie)
$doc.click(function () {
_self.focus();
});
this.updateFrame(); //更新内容
if (ie) {
$doc.bind("beforedeactivate beforeactivate selectionchange keypress", function (e) {
if (e.type == "beforedeactivate")
_self.inactive = true;
else if (e.type == "beforeactivate") {
if (!_self.inactive && _self.range && _self.range.length > 1)
_self.range.shift();
delete _self.inactive;
}
else if (!_self.inactive) {
if (!_self.range)
_self.range = [];
_self.range.unshift(_self.getRange());
while (_self.range.length > 2)
_self.range.pop();
}
});
// Restore the text range when the iframe gains focus
$frame.focus(function () {
_self.restoreRange();
});
}
($.browser.mozilla ? $doc : $(contentWindow)).blur(function () {
_self.updateTextArea(true);
});
this.$area.blur(function () {
// Update the iframe when the textarea loses focus
_self.updateFrame(true);
});
/*
* //自动添加p标签
* $doc.keydown(function(e){
* if(e.keyCode == 13){
* //_self.pasteHTML('<p> </p>');
* //this.execCommand( 'formatblock', false, '<p>' );
* }
* });
*/
}
//是否为源码模式
editorCore.prototype.sourceMode = function () {
return this.$area.is(":visible");
};
//编辑器获得焦点
editorCore.prototype.focus = function () {
var opt = this.opt;
if (this.sourceMode()) {
this.$area.focus();
}
else {
this.$frame[0].contentWindow.focus();
}
if ($.isFunction(opt.focusExt)) opt.focusExt(this);
};
//textarea内容更新到iframe
editorCore.prototype.updateFrame = function (checkForChange) {
var code = this.$area.val(),
options = this.opt,
updateFrameCallback = options.updateFrame,
$body = $(this.doc.body);
//判断是否已经修改
if (updateFrameCallback) {
var sum = checksum(code);
if (checkForChange && this.areaChecksum == sum)
return;
this.areaChecksum = sum;
}
//回调函数处理
var html = updateFrameCallback ? updateFrameCallback(code) : code;
// 禁止script标签
html = html.replace(/<(?=\/?script)/ig, "<");
// TODO,判断是否有作用
if (options.updateTextArea)
this.frameChecksum = checksum(html);
if (html != $body.html()) {
$body.html(html);
}
};
editorCore.prototype.getRange = function () {
if (ie) return this.getSelection().createRange();
return this.getSelection().getRangeAt(0);
};
editorCore.prototype.getSelection = function () {
if (ie) return this.doc.selection;
return this.$frame[0].contentWindow.getSelection();
};
editorCore.prototype.restoreRange = function () {
if (ie && this.range)
this.range[0].select();
};
editorCore.prototype.selectedHTML = function () {
this.restoreRange();
var range = this.getRange();
if (ie)
return range.htmlText;
var layer = $("<layer>")[0];
layer.appendChild(range.cloneContents());
var html = layer.innerHTML;
layer = null;
return html;
};
editorCore.prototype.selectedText = function () {
this.restoreRange();
if (ie) return this.getRange().text;
return this.getSelection().toString();
};
editorCore.prototype.pasteHTML = function (value) {
this.restoreRange();
if (ie) {
this.getRange().pasteHTML(value);
} else {
this.doc.execCommand("inserthtml", 0, value || null);
}
//获得焦点
this.$frame[0].contentWindow.focus();
}
editorCore.prototype.updateTextArea = function (checkForChange) {
var html = $(this.doc.body).html(),
options = this.opt,
updateTextAreaCallback = options.updateTextArea,
$area = this.$area;
if (updateTextAreaCallback) {
var sum = checksum(html);
if (checkForChange && this.frameChecksum == sum)
return;
this.frameChecksum = sum;
}
var code = updateTextAreaCallback ? updateTextAreaCallback(html) : html;
// TODO 判断是否有必要
if (options.updateFrame)
this.areaChecksum = checksum(code);
if (code != $area.val()) {
$area.val(code);
}
};
function checksum(text) {
var a = 1, b = 0;
for (var index = 0; index < text.length; ++index) {
a = (a + text.charCodeAt(index)) % 65521;
b = (b + a) % 65521;
}
return (b << 16) | a;
}
$.extend({
teExt: {
//扩展配置
},
debug: function (msg, group) {
//判断是否有console对象
if ($.TE.debug && window.console !== undefined) {
//分组开始
if (group) console.group(group);
if ($.type(msg) == "string") {
//是否为执行特殊函数,用双冒号隔开
if (msg.indexOf("::") != -1) {
var arr = msg.split("::");
eval("console." + arr[0] + "('" + arr[1] + "')");
} else {
console.debug(msg);
}
} else {
if ($(msg).html() == null) {
console.dir(msg); //输出对象或数组
} else {
console.dirxml($(msg)[0]); //输出dom对象
}
}
//记录trace信息
if ($.TE.debug == 2) {
console.group("trace 信息:");
console.trace();
console.groupEnd();
}
//分组结束
if (group) console.groupEnd();
}
},
//end debug
defined: function (variable) {
return $.type(variable) == "undefined" ? false : true;
},
isTag: function (tn) {
if (!tn) return false;
return $(this)[0].tagName.toLowerCase() == tn ? true : false;
},
//end istag
include: function (file) {
if (!$.defined($.TE.loadUrl)) $.TE.loadUrl = {};
//定义皮肤路径和插件路径。
var basePath = $.TE.basePath(),
skinsDir = basePath + "skins/",
pluginDir = basePath + "plugins/";
var files = $.type(file) == "string" ? [file] : file;
for (var i = 0; i < files.length; i++) {
var loadurl = name = $.trim(files[i]);
//判断是否已经加载过
if ($.TE.loadUrl[loadurl]) {
continue;
}
//判断是否有@
var at = false;
if (name.indexOf("@") != -1) {
at = true;
name = name.substr(1);
}
var att = name.split('.');
var ext = att[att.length - 1].toLowerCase();
if (ext == "css") {
//加载css
var filepath = at ? name : skinsDir + name;
var newNode = document.createElement("link");
newNode.setAttribute('type', 'text/css');
newNode.setAttribute('rel', 'stylesheet');
newNode.setAttribute('href', filepath);
$.TE.loadUrl[loadurl] = 1;
} else {
var filepath = at ? name : pluginDir + name;
//$("<scri"+"pt>"+"</scr"+"ipt>").attr({src:filepath,type:'text/javascript'}).appendTo('head');
var newNode = document.createElement("script");
newNode.type = "text/javascript";
newNode.src = filepath;
newNode.id = loadurl; //实现批量加载
newNode.onload = function () {
$.TE.loadUrl[this.id] = 1;
};
newNode.onreadystatechange = function () {
//针对ie
if ((newNode.readyState == 'loaded' || newNode.readyState == 'complete')) {
$.TE.loadUrl[this.id] = 1;
}
};
}
$("head")[0].appendChild(newNode);
}
},
//end include
loadedFile: function (file) {
//判断是否加载
if (!$.defined($.TE.loadUrl)) return false;
var files = $.type(file) == "string" ? [file] : file,
result = true;
$.each(files, function (i, name) {
if (!$.TE.loadUrl[name]) result = false;
//alert(name+':'+result);
});
return result;
},
//end loaded
loadFile: function (file, fun) {
//加载文件,加载完毕后执行fun函数。
$.include(file);
var time = 0;
var check = function () {
//alert($.loadedFile(file));
if ($.loadedFile(file)) {
if ($.isFunction(fun)) fun();
} else {
//alert(time);
if (time >= $.TE.timeOut) {
// TODO 细化哪些文件加载失败。
$.debug(file, "文件加载失败");
} else {
//alert('time:'+time);
setTimeout(check, 50);
time += 50;
}
}
};
check();
}
//end loadFile
});
})(jQuery);
jQuery.TE.config( 'mini', {
'controls' : 'font,fontsize,fontcolor,backcolor,bold,italic,underline,unformat,leftalign,centeralign,rightalign,orderedlist,unorderedlist',
'width':498,
'height':400,
'resizeType':1
} ); | 10npsite | trunk/DThinkPHP/Extend/Tool/thinkeditor/ThinkEditor.js | JavaScript | asf20 | 32,537 |
#! php -d safe_mode=Off
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: phpunit.php 2504 2011-12-28 07:35:29Z liu21st $
require_once 'PHPUnit/Util/Filter.php';
PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT');
require_once 'PHPUnit/TextUI/Command.php';
?> | 10npsite | trunk/DThinkPHP/Extend/Tool/phpunit.php | PHP | asf20 | 819 |
#! php -d safe_mode=Off
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: phpunit.php 2504 2011-12-28 07:35:29Z liu21st $
require_once 'PHPUnit/Util/Filter.php';
PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT');
require_once 'PHPUnit/TextUI/Command.php';
?> | 10npsite | trunk/DThinkPHP/Extend/Tool/.svn/text-base/phpunit.php.svn-base | PHP | asf20 | 819 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: RestAction.class.php 2795 2012-03-02 15:34:18Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP RESTFul 控制器扩展类
+------------------------------------------------------------------------------
*/
abstract class RestAction {
// 当前Action名称
private $name = '';
// 视图实例
protected $view = null;
protected $_method = ''; // 当前请求类型
protected $_type = ''; // 当前资源类型
// 输出类型
protected $_types = array();
/**
+----------------------------------------------------------
* 架构函数 取得模板对象实例
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct() {
//实例化视图类
$this->view = Think::instance('View');
if(!defined('__EXT__')) define('__EXT__','');
// 资源类型检测
if(''==__EXT__) { // 自动检测资源类型
$this->_type = $this->getAcceptType();
}elseif(false === stripos(C('REST_CONTENT_TYPE_LIST'),__EXT__)) {
// 资源类型非法 则用默认资源类型访问
$this->_type = C('REST_DEFAULT_TYPE');
}else{
// 检测实际资源类型
if($this->getAcceptType() == __EXT__) {
$this->_type = __EXT__;
}else{
$this->_type = C('REST_DEFAULT_TYPE');
}
}
// 请求方式检测
$method = strtolower($_SERVER['REQUEST_METHOD']);
if(false === stripos(C('REST_METHOD_LIST'),$method)) {
// 请求方式非法 则用默认请求方法
$method = C('REST_DEFAULT_METHOD');
}
$this->_method = $method;
// 允许输出的资源类型
$this->_types = C('REST_OUTPUT_TYPE');
//控制器初始化
if(method_exists($this,'_initialize'))
$this->_initialize();
}
/**
+----------------------------------------------------------
* 获取当前Action名称
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
*/
protected function getActionName() {
if(empty($this->name)) {
// 获取Action名称
$this->name = substr(get_class($this),0,-6);
}
return $this->name;
}
/**
+----------------------------------------------------------
* 是否AJAX请求
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return bool
+----------------------------------------------------------
*/
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')]))
// 判断Ajax方式提交
return true;
return false;
}
/**
+----------------------------------------------------------
* 魔术方法 有不存在的操作的时候执行
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名
* @param array $args 参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$args) {
if( 0 === strcasecmp($method,ACTION_NAME)) {
if(method_exists($this,$method.'_'.$this->_method.'_'.$this->_type)) { // RESTFul方法支持
$fun = $method.'_'.$this->_method.'_'.$this->_type;
$this->$fun();
}elseif($this->_method == C('REST_DEFAULT_METHOD') && method_exists($this,$method.'_'.$this->_type) ){
$fun = $method.'_'.$this->_type;
$this->$fun();
}elseif($this->_type == C('REST_DEFAULT_TYPE') && method_exists($this,$method.'_'.$this->_method) ){
$fun = $method.'_'.$this->_method;
$this->$fun();
}elseif(method_exists($this,'_empty')) {
// 如果定义了_empty操作 则调用
$this->_empty($method,$args);
}elseif(file_exists_case(C('TMPL_FILE_NAME'))){
// 检查是否存在默认模版 如果有直接输出模版
$this->display();
}else{
// 抛出异常
throw_exception(L('_ERROR_ACTION_').ACTION_NAME);
}
}else{
switch(strtolower($method)) {
// 获取变量 支持过滤和默认值 调用方式 $this->_post($key,$filter,$default);
case '_get': $input =& $_GET;break;
case '_post':$input =& $_POST;break;
case '_put':
case '_delete':parse_str(file_get_contents('php://input'), $input);break;
case '_request': $input =& $_REQUEST;break;
case '_session': $input =& $_SESSION;break;
case '_cookie': $input =& $_COOKIE;break;
case '_server': $input =& $_SERVER;break;
default:
throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
}
if(isset($input[$args[0]])) { // 取值操作
$data = $input[$args[0]];
$fun = $args[1]?$args[1]:C('DEFAULT_FILTER');
$data = $fun($data); // 参数过滤
}else{ // 变量默认值
$data = isset($args[2])?$args[2]:NULL;
}
return $data;
}
}
/**
+----------------------------------------------------------
* 模板显示
* 调用内置的模板引擎显示方法,
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $templateFile 指定要调用的模板文件
* 默认为空 由系统自动定位模板文件
* @param string $charset 输出编码
* @param string $contentType 输出类型
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function display($templateFile='',$charset='',$contentType='') {
$this->view->display($templateFile,$charset,$contentType);
}
/**
+----------------------------------------------------------
* 模板变量赋值
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $name 要显示的模板变量
* @param mixed $value 变量的值
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function assign($name,$value='') {
$this->view->assign($name,$value);
}
public function __set($name,$value) {
$this->view->assign($name,$value);
}
/**
+----------------------------------------------------------
* 设置页面输出的CONTENT_TYPE和编码
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $type content_type 类型对应的扩展名
* @param string $charset 页面输出编码
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function setContentType($type, $charset=''){
if(headers_sent()) return;
if(empty($charset)) $charset = C('DEFAULT_CHARSET');
$type = strtolower($type);
if(isset($this->_types[$type])) //过滤content_type
header('Content-Type: '.$this->_types[$type].'; charset='.$charset);
}
/**
+----------------------------------------------------------
* 输出返回数据
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 要返回的数据
* @param String $type 返回类型 JSON XML
* @param integer $code HTTP状态
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function response($data,$type='',$code=200) {
// 保存日志
if(C('LOG_RECORD')) Log::save();
$this->sendHttpStatus($code);
exit($this->encodeData($data,strtolower($type)));
}
/**
+----------------------------------------------------------
* 编码数据
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 要返回的数据
* @param String $type 返回类型 JSON XML
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function encodeData($data,$type='') {
if(empty($data)) return '';
if('json' == $type) {
// 返回JSON数据格式到客户端 包含状态信息
$data = json_encode($data);
}elseif('xml' == $type){
// 返回xml格式数据
$data = xml_encode($data);
}elseif('php'==$type){
$data = serialize($data);
}// 默认直接输出
$this->setContentType($type);
header('Content-Length: ' . strlen($data));
return $data;
}
// 发送Http状态信息
protected function sendHttpStatus($status) {
static $_status = array(
// Informational 1xx
100 => 'Continue',
101 => 'Switching Protocols',
// Success 2xx
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
// Redirection 3xx
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Moved Temporarily ', // 1.1
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
// 306 is deprecated but reserved
307 => 'Temporary Redirect',
// Client Error 4xx
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',
// Server Error 5xx
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]);
// 确保FastCGI模式下正常
header('Status:'.$code.' '.$_status[$code]);
}
}
/**
+----------------------------------------------------------
* 获取当前请求的Accept头信息
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function getAcceptType(){
$type = array(
'html'=>'text/html,application/xhtml+xml,*/*',
'xml'=>'application/xml,text/xml,application/x-xml',
'json'=>'application/json,text/x-json,application/jsonrequest,text/json',
'js'=>'text/javascript,application/javascript,application/x-javascript',
'css'=>'text/css',
'rss'=>'application/rss+xml',
'yaml'=>'application/x-yaml,text/yaml',
'atom'=>'application/atom+xml',
'pdf'=>'application/pdf',
'text'=>'text/plain',
'png'=>'image/png',
'jpg'=>'image/jpg,image/jpeg,image/pjpeg',
'gif'=>'image/gif',
'csv'=>'text/csv'
);
foreach($type as $key=>$val){
$array = explode(',',$val);
foreach($array as $k=>$v){
if(stristr($_SERVER['HTTP_ACCEPT'], $v)) {
return $key;
}
}
}
return false;
}
} | 10npsite | trunk/DThinkPHP/Extend/Action/RestAction.class.php | PHP | asf20 | 14,751 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2008 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: alias.php 2504 2011-12-28 07:35:29Z liu21st $
// 导入别名定义
alias_import(array(
'Model' => MODE_PATH.'Amf/Model.class.php',
'Db' => MODE_PATH.'Phprpc/Db.class.php',
'Debug' => CORE_PATH.'Util/Debug.class.php',
'Session' => CORE_PATH.'Util/Session.class.php',
)
); | 10npsite | trunk/DThinkPHP/Extend/Mode/Phprpc/alias.php | PHP | asf20 | 971 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: App.class.php 2504 2011-12-28 07:35:29Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP AMF模式应用程序类
+------------------------------------------------------------------------------
*/
class App {
/**
+----------------------------------------------------------
* 应用程序初始化
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function run() {
//导入类库
Vendor('phpRPC.phprpc_server');
//实例化phprpc
$server = new PHPRPC_Server();
$actions = explode(',',C('APP_PHPRPC_ACTIONS'));
foreach ($actions as $action){
//$server -> setClass($action.'Action');
$temp = $action.'Action';
$methods = get_class_methods($temp);
$server->add($methods,new $temp);
}
if(APP_DEBUG) {
$server->setDebugMode(true);
}
$server->setEnableGZIP(true);
$server->start();
//C('PHPRPC_COMMENT',$server->comment());
echo $server->comment();
// 保存日志记录
if(C('LOG_RECORD')) Log::save();
return ;
}
}; | 10npsite | trunk/DThinkPHP/Extend/Mode/Phprpc/App.class.php | PHP | asf20 | 1,985 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Db.class.php 2657 2012-01-23 13:23:09Z liu21st $
define('CLIENT_MULTI_RESULTS', 131072);
/**
+------------------------------------------------------------------------------
* ThinkPHP AMF模式数据库中间层实现类 只支持Mysql
+------------------------------------------------------------------------------
*/
class Db {
static private $_instance = null;
// 是否自动释放查询结果
protected $autoFree = false;
// 是否显示调试信息 如果启用会在日志文件记录sql语句
public $debug = false;
// 是否使用永久连接
protected $pconnect = false;
// 当前SQL指令
protected $queryStr = '';
// 最后插入ID
protected $lastInsID = null;
// 返回或者影响记录数
protected $numRows = 0;
// 返回字段数
protected $numCols = 0;
// 事务指令数
protected $transTimes = 0;
// 错误信息
protected $error = '';
// 当前连接ID
protected $linkID = null;
// 当前查询ID
protected $queryID = null;
// 是否已经连接数据库
protected $connected = false;
// 数据库连接参数配置
protected $config = '';
// 数据库表达式
protected $comparison = array('eq'=>'=','neq'=>'!=','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE');
// 查询表达式
protected $selectSql = 'SELECT%DISTINCT% %FIELDS% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT%';
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 数据库配置数组
+----------------------------------------------------------
*/
public function __construct($config=''){
if ( !extension_loaded('mysql') ) {
throw_exception(L('_NOT_SUPPERT_').':mysql');
}
$this->config = $this->parseConfig($config);
}
/**
+----------------------------------------------------------
* 连接数据库方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function connect() {
if(!$this->connected) {
$config = $this->config;
// 处理不带端口号的socket连接情况
$host = $config['hostname'].($config['hostport']?":{$config['hostport']}":'');
if($this->pconnect) {
$this->linkID = mysql_pconnect( $host, $config['username'], $config['password'],CLIENT_MULTI_RESULTS);
}else{
$this->linkID = mysql_connect( $host, $config['username'], $config['password'],true,CLIENT_MULTI_RESULTS);
}
if ( !$this->linkID || (!empty($config['database']) && !mysql_select_db($config['database'], $this->linkID)) ) {
throw_exception(mysql_error());
}
$dbVersion = mysql_get_server_info($this->linkID);
if ($dbVersion >= "4.1") {
//使用UTF8存取数据库 需要mysql 4.1.0以上支持
mysql_query("SET NAMES '".C('DB_CHARSET')."'", $this->linkID);
}
//设置 sql_model
if($dbVersion >'5.0.1'){
mysql_query("SET sql_mode=''",$this->linkID);
}
// 标记连接成功
$this->connected = true;
// 注销数据库连接配置信息
unset($this->config);
}
}
/**
+----------------------------------------------------------
* 释放查询结果
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function free() {
mysql_free_result($this->queryID);
$this->queryID = 0;
}
/**
+----------------------------------------------------------
* 执行查询 主要针对 SELECT, SHOW 等指令
* 返回数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function query($str='') {
$this->connect();
if ( !$this->linkID ) return false;
if ( $str != '' ) $this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) { $this->free(); }
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID = mysql_query($this->queryStr, $this->linkID);
$this->debug();
if ( !$this->queryID ) {
if ( $this->debug )
throw_exception($this->error());
else
return false;
} else {
$this->numRows = mysql_num_rows($this->queryID);
return $this->getAll();
}
}
/**
+----------------------------------------------------------
* 执行语句 针对 INSERT, UPDATE 以及DELETE
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function execute($str='') {
$this->connect();
if ( !$this->linkID ) return false;
if ( $str != '' ) $this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) { $this->free(); }
N('db_write',1);
// 记录开始执行时间
G('queryStartTime');
$result = mysql_query($this->queryStr, $this->linkID) ;
$this->debug();
if ( false === $result) {
if ( $this->debug )
throw_exception($this->error());
else
return false;
} else {
$this->numRows = mysql_affected_rows($this->linkID);
$this->lastInsID = mysql_insert_id($this->linkID);
return $this->numRows;
}
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function startTrans() {
$this->connect(true);
if ( !$this->linkID ) return false;
//数据rollback 支持
if ($this->transTimes == 0) {
mysql_query('START TRANSACTION', $this->linkID);
}
$this->transTimes++;
return ;
}
/**
+----------------------------------------------------------
* 用于非自动提交状态下面的查询提交
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function commit() {
if ($this->transTimes > 0) {
$result = mysql_query('COMMIT', $this->linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
return false;
}
}
return true;
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function rollback() {
if ($this->transTimes > 0) {
$result = mysql_query('ROLLBACK', $this->linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
return false;
}
}
return true;
}
/**
+----------------------------------------------------------
* 获得所有的查询数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function getAll() {
if ( !$this->queryID ) {
throw_exception($this->error());
return false;
}
//返回数据集
$result = array();
if($this->numRows >0) {
while($row = mysql_fetch_assoc($this->queryID)){
$result[] = $row;
}
mysql_data_seek($this->queryID,0);
}
return $result;
}
/**
+----------------------------------------------------------
* 取得数据表的字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function getFields($tableName) {
$result = $this->query('SHOW COLUMNS FROM '.$tableName);
$info = array();
foreach ($result as $key => $val) {
$info[$val['Field']] = array(
'name' => $val['Field'],
'type' => $val['Type'],
'notnull' => (bool) ($val['Null'] === ''), // not null is empty, null is yes
'default' => $val['Default'],
'primary' => (strtolower($val['Key']) == 'pri'),
'autoinc' => (strtolower($val['Extra']) == 'auto_increment'),
);
}
return $info;
}
/**
+----------------------------------------------------------
* 取得数据库的表信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function getTables($dbName='') {
if(!empty($dbName)) {
$sql = 'SHOW TABLES FROM '.$dbName;
}else{
$sql = 'SHOW TABLES ';
}
$result = $this->query($sql);
$info = array();
foreach ($result as $key => $val) {
$info[$key] = current($val);
}
return $info;
}
/**
+----------------------------------------------------------
* 关闭数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function close() {
if (!empty($this->queryID))
mysql_free_result($this->queryID);
if ($this->linkID && !mysql_close($this->linkID)){
throw_exception($this->error());
}
$this->linkID = 0;
}
/**
+----------------------------------------------------------
* 数据库错误信息
* 并显示当前的SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function error() {
$this->error = mysql_error($this->linkID);
if($this->queryStr!=''){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
return $this->error;
}
/**
+----------------------------------------------------------
* SQL指令安全过滤
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str SQL字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function escape_string($str) {
return mysql_escape_string($str);
}
/**
+----------------------------------------------------------
* 析构方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __destruct() {
// 关闭连接
$this->close();
}
/**
+----------------------------------------------------------
* 取得数据库类实例
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return mixed 返回数据库驱动类
+----------------------------------------------------------
*/
public static function getInstance($db_config='') {
if ( self::$_instance==null ){
self::$_instance = new Db($db_config);
}
return self::$_instance;
}
/**
+----------------------------------------------------------
* 分析数据库配置信息,支持数组和DSN
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param mixed $db_config 数据库配置信息
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function parseConfig($db_config='') {
if ( !empty($db_config) && is_string($db_config)) {
// 如果DSN字符串则进行解析
$db_config = $this->parseDSN($db_config);
}else if(empty($db_config)){
// 如果配置为空,读取配置文件设置
$db_config = array (
'dbms' => C('DB_TYPE'),
'username' => C('DB_USER'),
'password' => C('DB_PWD'),
'hostname' => C('DB_HOST'),
'hostport' => C('DB_PORT'),
'database' => C('DB_NAME'),
'dsn' => C('DB_DSN'),
'params' => C('DB_PARAMS'),
);
}
return $db_config;
}
/**
+----------------------------------------------------------
* DSN解析
* 格式: mysql://username:passwd@localhost:3306/DbName
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $dsnStr
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function parseDSN($dsnStr) {
if( empty($dsnStr) ){return false;}
$info = parse_url($dsnStr);
if($info['scheme']){
$dsn = array(
'dbms' => $info['scheme'],
'username' => isset($info['user']) ? $info['user'] : '',
'password' => isset($info['pass']) ? $info['pass'] : '',
'hostname' => isset($info['host']) ? $info['host'] : '',
'hostport' => isset($info['port']) ? $info['port'] : '',
'database' => isset($info['path']) ? substr($info['path'],1) : ''
);
}else {
preg_match('/^(.*?)\:\/\/(.*?)\:(.*?)\@(.*?)\:([0-9]{1, 6})\/(.*?)$/',trim($dsnStr),$matches);
$dsn = array (
'dbms' => $matches[1],
'username' => $matches[2],
'password' => $matches[3],
'hostname' => $matches[4],
'hostport' => $matches[5],
'database' => $matches[6]
);
}
return $dsn;
}
/**
+----------------------------------------------------------
* 数据库调试 记录当前SQL
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
*/
protected function debug() {
// 记录操作结束时间
if ( $this->debug ) {
G('queryEndTime');
Log::record($this->queryStr." [ RunTime:".G('queryStartTime','queryEndTime',6)."s ]",Log::SQL);
}
}
/**
+----------------------------------------------------------
* 设置锁机制
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseLock($lock=false) {
if(!$lock) return '';
if('ORACLE' == $this->dbType) {
return ' FOR UPDATE NOWAIT ';
}
return ' FOR UPDATE ';
}
/**
+----------------------------------------------------------
* set分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseSet($data) {
foreach ($data as $key=>$val){
$value = $this->parseValue($val);
if(is_scalar($value)) // 过滤非标量数据
$set[] = $this->parseKey($key).'='.$value;
}
return ' SET '.implode(',',$set);
}
/**
+----------------------------------------------------------
* value分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $value
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseValue($value) {
if(is_string($value)) {
$value = '\''.$this->escape_string($value).'\'';
}elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){
$value = $this->escape_string($value[1]);
}elseif(is_null($value)){
$value = 'null';
}
return $value;
}
/**
+----------------------------------------------------------
* field分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $fields
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseField($fields) {
if(is_array($fields)) {
// 完善数组方式传字段名的支持
// 支持 'field1'=>'field2' 这样的字段别名定义
$array = array();
foreach ($fields as $key=>$field){
if(!is_numeric($key))
$array[] = $this->parseKey($key).' AS '.$this->parseKey($field);
else
$array[] = $this->parseKey($field);
}
$fieldsStr = implode(',', $array);
}elseif(is_string($fields) && !empty($fields)) {
$fieldsStr = $this->parseKey($fields);
}else{
$fieldsStr = '*';
}
return $fieldsStr;
}
/**
+----------------------------------------------------------
* table分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $table
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseTable($tables) {
if(is_string($tables))
$tables = explode(',',$tables);
array_walk($tables, array(&$this, 'parseKey'));
return implode(',',$tables);
}
/**
+----------------------------------------------------------
* where分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $where
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseWhere($where) {
$whereStr = '';
if(is_string($where)) {
// 直接使用字符串条件
$whereStr = $where;
}else{ // 使用数组条件表达式
if(isset($where['_logic'])) {
// 定义逻辑运算规则 例如 OR XOR AND NOT
$operate = ' '.strtoupper($where['_logic']).' ';
unset($where['_logic']);
}else{
// 默认进行 AND 运算
$operate = ' AND ';
}
foreach ($where as $key=>$val){
$whereStr .= "( ";
if(0===strpos($key,'_')) {
// 解析特殊条件表达式
$whereStr .= $this->parseThinkWhere($key,$val);
}else{
$key = $this->parseKey($key);
if(is_array($val)) {
if(is_string($val[0])) {
if(preg_match('/^(EQ|NEQ|GT|EGT|LT|ELT|NOTLIKE|LIKE)$/i',$val[0])) { // 比较运算
$whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' '.$this->parseValue($val[1]);
}elseif('exp'==strtolower($val[0])){ // 使用表达式
$whereStr .= ' ('.$key.' '.$val[1].') ';
}elseif(preg_match('/IN/i',$val[0])){ // IN 运算
$zone = is_array($val[1])? implode(',',$this->parseValue($val[1])):$val[1];
$whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')';
}elseif(preg_match('/BETWEEN/i',$val[0])){ // BETWEEN运算
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
$whereStr .= ' ('.$key.' BETWEEN '.$data[0].' AND '.$data[1].' )';
}else{
throw_exception(L('_EXPRESS_ERROR_').':'.$val[0]);
}
}else {
$count = count($val);
if(in_array(strtoupper(trim($val[$count-1])),array('AND','OR','XOR'))) {
$rule = strtoupper(trim($val[$count-1]));
$count = $count -1;
}else{
$rule = 'AND';
}
for($i=0;$i<$count;$i++) {
$data = is_array($val[$i])?$val[$i][1]:$val[$i];
if('exp'==strtolower($val[$i][0])) {
$whereStr .= '('.$key.' '.$data.') '.$rule.' ';
}else{
$op = is_array($val[$i])?$this->comparison[strtolower($val[$i][0])]:'=';
$whereStr .= '('.$key.' '.$op.' '.$this->parseValue($data).') '.$rule.' ';
}
}
$whereStr = substr($whereStr,0,-4);
}
}else {
//对字符串类型字段采用模糊匹配
if(C('LIKE_MATCH_FIELDS') && preg_match('/('.C('LIKE_MATCH_FIELDS').')/i',$key)) {
$val = '%'.$val.'%';
$whereStr .= $key." LIKE ".$this->parseValue($val);
}else {
$whereStr .= $key." = ".$this->parseValue($val);
}
}
}
$whereStr .= ' )'.$operate;
}
$whereStr = substr($whereStr,0,-strlen($operate));
}
return empty($whereStr)?'':' WHERE '.$whereStr;
}
/**
+----------------------------------------------------------
* 特殊条件分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $key
* @param mixed $val
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseThinkWhere($key,$val) {
$whereStr = '';
switch($key) {
case '_string':
// 字符串模式查询条件
$whereStr = $val;
break;
case '_complex':
// 复合查询条件
$whereStr = substr($this->parseWhere($val),6);
break;
case '_query':
// 字符串模式查询条件
parse_str($val,$where);
if(isset($where['_logic'])) {
$op = ' '.strtoupper($where['_logic']).' ';
unset($where['_logic']);
}else{
$op = ' AND ';
}
$array = array();
foreach ($where as $field=>$data)
$array[] = $this->parseKey($field).' = '.$this->parseValue($data);
$whereStr = implode($op,$array);
break;
}
return $whereStr;
}
/**
+----------------------------------------------------------
* limit分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $lmit
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseLimit($limit) {
return !empty($limit)? ' LIMIT '.$limit.' ':'';
}
/**
+----------------------------------------------------------
* join分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $join
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseJoin($join) {
$joinStr = '';
if(!empty($join)) {
if(is_array($join)) {
foreach ($join as $key=>$_join){
if(false !== stripos($_join,'JOIN'))
$joinStr .= ' '.$_join;
else
$joinStr .= ' LEFT JOIN ' .$_join;
}
}else{
$joinStr .= ' LEFT JOIN ' .$join;
}
}
return $joinStr;
}
/**
+----------------------------------------------------------
* order分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $order
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseOrder($order) {
return !empty($order)? ' ORDER BY '.$order:'';
}
/**
+----------------------------------------------------------
* group分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $group
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseGroup($group) {
return !empty($group)? ' GROUP BY '.$group:'';
}
/**
+----------------------------------------------------------
* having分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $having
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseHaving($having) {
return !empty($having)? ' HAVING '.$having:'';
}
/**
+----------------------------------------------------------
* distinct分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $distinct
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseDistinct($distinct) {
return !empty($distinct)? ' DISTINCT ' :'';
}
/**
+----------------------------------------------------------
* 插入记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 参数表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function insert($data,$options=array()) {
foreach ($data as $key=>$val){
$value = $this->parseValue($val);
if(is_scalar($value)) { // 过滤非标量数据
$values[] = $value;
$fields[] = $this->parseKey($key);
}
}
$sql = 'INSERT INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')';
$sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 更新记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function update($data,$options) {
$sql = 'UPDATE '
.$this->parseTable($options['table'])
.$this->parseSet($data)
.$this->parseWhere(isset($options['where'])?$options['where']:'')
.$this->parseOrder(isset($options['order'])?$options['order']:'')
.$this->parseLimit(isset($options['limit'])?$options['limit']:'')
.$this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 删除记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function delete($options=array()) {
$sql = 'DELETE FROM '
.$this->parseTable($options['table'])
.$this->parseWhere(isset($options['where'])?$options['where']:'')
.$this->parseOrder(isset($options['order'])?$options['order']:'')
.$this->parseLimit(isset($options['limit'])?$options['limit']:'')
.$this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 查找记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function select($options=array()) {
if(isset($options['page'])) {
// 根据页数计算limit
list($page,$listRows) = explode(',',$options['page']);
$listRows = $listRows?$listRows:($options['limit']?$options['limit']:20);
$offset = $listRows*((int)$page-1);
$options['limit'] = $offset.','.$listRows;
}
$sql = str_replace(
array('%TABLE%','%DISTINCT%','%FIELDS%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%'),
array(
$this->parseTable($options['table']),
$this->parseDistinct(isset($options['distinct'])?$options['distinct']:false),
$this->parseField(isset($options['field'])?$options['field']:'*'),
$this->parseJoin(isset($options['join'])?$options['join']:''),
$this->parseWhere(isset($options['where'])?$options['where']:''),
$this->parseGroup(isset($options['group'])?$options['group']:''),
$this->parseHaving(isset($options['having'])?$options['having']:''),
$this->parseOrder(isset($options['order'])?$options['order']:''),
$this->parseLimit(isset($options['limit'])?$options['limit']:'')
),$this->selectSql);
$sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->query($sql);
}
/**
+----------------------------------------------------------
* 字段和表名添加`
* 保证指令中使用关键字不出错 针对mysql
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $value
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
protected function parseKey(&$value) {
$value = trim($value);
if( false !== strpos($value,' ') || false !== strpos($value,',') || false !== strpos($value,'*') || false !== strpos($value,'(') || false !== strpos($value,'.') || false !== strpos($value,'`')) {
//如果包含* 或者 使用了sql方法 则不作处理
}else{
$value = '`'.$value.'`';
}
return $value;
}
/**
+----------------------------------------------------------
* 获取最近一次查询的sql语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastSql() {
return $this->queryStr;
}
/**
+----------------------------------------------------------
* 获取最近插入的ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastInsID(){
return $this->lastInsID;
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Phprpc/Db.class.php | PHP | asf20 | 39,438 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Model.class.php 2779 2012-02-24 02:56:57Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP AMF模式Model模型类
* 只支持CURD和连贯操作 以及常用查询 去掉回调接口
+------------------------------------------------------------------------------
*/
class Model {
// 当前数据库操作对象
protected $db = null;
// 主键名称
protected $pk = 'id';
// 数据表前缀
protected $tablePrefix = '';
// 模型名称
protected $name = '';
// 数据库名称
protected $dbName = '';
// 数据表名(不包含表前缀)
protected $tableName = '';
// 实际数据表名(包含表前缀)
protected $trueTableName ='';
// 数据信息
protected $data = array();
// 查询表达式参数
protected $options = array();
// 最近错误信息
protected $error = '';
/**
+----------------------------------------------------------
* 架构函数
* 取得DB类的实例对象
+----------------------------------------------------------
* @param string $name 模型名称
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($name='') {
// 模型初始化
$this->_initialize();
// 获取模型名称
if(!empty($name)) {
$this->name = $name;
}elseif(empty($this->name)){
$this->name = $this->getModelName();
}
// 数据库初始化操作
$this->db = Db::getInstance(empty($this->connection)?'':$this->connection);
// 设置表前缀
$this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX');
// 字段检测
if(!empty($this->name)) $this->_checkTableInfo();
}
/**
+----------------------------------------------------------
* 自动检测数据表信息
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function _checkTableInfo() {
// 如果不是Model类 自动记录数据表信息
// 只在第一次执行记录
if(empty($this->fields)) {
// 如果数据表字段没有定义则自动获取
if(C('DB_FIELDS_CACHE')) {
$this->fields = F('_fields/'.$this->name);
if(!$this->fields) $this->flush();
}else{
// 每次都会读取数据表信息
$this->flush();
}
}
}
/**
+----------------------------------------------------------
* 获取字段信息并缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function flush() {
// 缓存不存在则查询数据表信息
$fields = $this->db->getFields($this->getTableName());
$this->fields = array_keys($fields);
$this->fields['_autoinc'] = false;
foreach ($fields as $key=>$val){
// 记录字段类型
$type[$key] = $val['type'];
if($val['primary']) {
$this->fields['_pk'] = $key;
if($val['autoinc']) $this->fields['_autoinc'] = true;
}
}
// 记录字段类型信息
if(C('DB_FIELDTYPE_CHECK')) $this->fields['_type'] = $type;
// 2008-3-7 增加缓存开关控制
if(C('DB_FIELDS_CACHE'))
// 永久缓存数据表信息
F('_fields/'.$this->name,$this->fields);
}
// 回调方法 初始化模型
protected function _initialize() {}
/**
+----------------------------------------------------------
* 利用__call方法实现一些特殊的Model方法 (魔术方法)
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名称
* @param array $args 调用参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$args) {
if(in_array(strtolower($method),array('field','table','where','order','limit','page','having','group','lock','distinct'),true)) {
// 连贯操作的实现
$this->options[strtolower($method)] = $args[0];
return $this;
}elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){
// 统计查询的实现
$field = isset($args[0])?$args[0]:'*';
return $this->getField(strtoupper($method).'('.$field.') AS tp_'.$method);
}elseif(strtolower(substr($method,0,5))=='getby') {
// 根据某个字段获取记录
$field = parse_name(substr($method,5));
$options['where'] = $field.'=\''.$args[0].'\'';
return $this->find($options);
}else{
throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
return;
}
}
/**
+----------------------------------------------------------
* 设置数据对象的值 (魔术方法)
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
* @param mixed $value 值
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function __set($name,$value) {
// 设置数据对象属性
$this->data[$name] = $value;
}
/**
+----------------------------------------------------------
* 获取数据对象的值 (魔术方法)
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __get($name) {
return isset($this->data[$name])?$this->data[$name]:null;
}
/**
+----------------------------------------------------------
* 新增数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function add($data='',$options=array()) {
if(empty($data)) {
// 没有传递数据,获取当前数据对象的值
if(!empty($this->data)) {
$data = $this->data;
}else{
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
}
// 分析表达式
$options = $this->_parseOptions($options);
// 写入数据到数据库
$result = $this->db->insert($data,$options);
$insertId = $this->getLastInsID();
if($insertId) {
return $insertId;
}
//成功后返回插入ID
return $result;
}
/**
+----------------------------------------------------------
* 保存数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function save($data='',$options=array()) {
if(empty($data)) {
// 没有传递数据,获取当前数据对象的值
if(!empty($this->data)) {
$data = $this->data;
}else{
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
}
// 分析表达式
$options = $this->_parseOptions($options);
if(!isset($options['where']) ) {
// 如果存在主键数据 则自动作为更新条件
if(isset($data[$this->getPk()])) {
$pk = $this->getPk();
$options['where'] = $pk.'=\''.$data[$pk].'\'';
$pkValue = $data[$pk];
unset($data[$pk]);
}else{
// 如果没有任何更新条件则不执行
$this->error = L('_OPERATION_WRONG_');
return false;
}
}
return $this->db->update($data,$options);
}
/**
+----------------------------------------------------------
* 删除数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $options 表达式
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function delete($options=array()) {
if(empty($options) && empty($this->options['where'])) {
// 如果删除条件为空 则删除当前数据对象所对应的记录
if(!empty($this->data) && isset($this->data[$this->getPk()]))
return $this->delete($this->data[$this->getPk()]);
else
return false;
}
if(is_numeric($options) || is_string($options)) {
// 根据主键删除记录
$pk = $this->getPk();
$where = $pk.'=\''.$options.'\'';
$pkValue = $options;
$options = array();
$options['where'] = $where;
}
// 分析表达式
$options = $this->_parseOptions($options);
return $this->db->delete($options);
}
/**
+----------------------------------------------------------
* 查询数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function select($options=array()) {
// 分析表达式
$options = $this->_parseOptions($options);
$resultSet = $this->db->select($options);
if(empty($resultSet)) { // 查询结果为空
return false;
}
return $resultSet;
}
/**
+----------------------------------------------------------
* 查询数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $options 表达式参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function find($options=array()) {
if(is_numeric($options) || is_string($options)) {
$where = $this->getPk().'=\''.$options.'\'';
$options = array();
$options['where'] = $where;
}
// 总是查找一条记录
$options['limit'] = 1;
// 分析表达式
$options = $this->_parseOptions($options);
$resultSet = $this->db->select($options);
if(empty($resultSet)) {// 查询结果为空
return false;
}
$this->data = $resultSet[0];
return $this->data;
}
/**
+----------------------------------------------------------
* 分析表达式
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $options 表达式参数
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
private function _parseOptions($options) {
if(is_array($options))
$options = array_merge($this->options,$options);
// 查询过后清空sql表达式组装 避免影响下次查询
$this->options = array();
if(!isset($options['table']))
// 自动获取表名
$options['table'] =$this->getTableName();
return $options;
}
/**
+----------------------------------------------------------
* 创建数据对象 但不保存到数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 创建数据
* @param string $type 状态
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function create($data='',$type='') {
// 如果没有传值默认取POST数据
if(empty($data)) {
$data = $_POST;
}elseif(is_object($data)){
$data = get_object_vars($data);
}elseif(!is_array($data)){
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
// 生成数据对象
$vo = array();
foreach ($this->fields as $key=>$name){
if(substr($key,0,1)=='_') continue;
$val = isset($data[$name])?$data[$name]:null;
//保证赋值有效
if(!is_null($val)){
$vo[$name] = (MAGIC_QUOTES_GPC && is_string($val))? stripslashes($val) : $val;
if(C('DB_FIELDTYPE_CHECK')) {
// 字段类型检查
$fieldType = strtolower($this->fields['_type'][$name]);
if(false !== strpos($fieldType,'int')) {
$vo[$name] = intval($vo[$name]);
}elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){
$vo[$name] = floatval($vo[$name]);
}
}
}
}
// 赋值当前数据对象
$this->data = $vo;
// 返回创建的数据以供其他调用
return $vo;
}
/**
+----------------------------------------------------------
* SQL查询
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $sql SQL指令
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function query($sql) {
if(!empty($sql)) {
if(strpos($sql,'__TABLE__'))
$sql = str_replace('__TABLE__',$this->getTableName(),$sql);
return $this->db->query($sql);
}else{
return false;
}
}
/**
+----------------------------------------------------------
* 执行SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $sql SQL指令
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function execute($sql='') {
if(!empty($sql)) {
if(strpos($sql,'__TABLE__'))
$sql = str_replace('__TABLE__',$this->getTableName(),$sql);
return $this->db->execute($sql);
}else {
return false;
}
}
/**
+----------------------------------------------------------
* 得到当前的数据对象名称
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getModelName() {
if(empty($this->name)) {
$this->name = substr(get_class($this),0,-5);
}
return $this->name;
}
/**
+----------------------------------------------------------
* 得到完整的数据表名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getTableName() {
if(empty($this->trueTableName)) {
$tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
if(!empty($this->tableName)) {
$tableName .= $this->tableName;
}else{
$tableName .= parse_name($this->name);
}
if(!empty($this->dbName)) {
$tableName = $this->dbName.'.'.$tableName;
}
$this->trueTableName = strtolower($tableName);
}
return $this->trueTableName;
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function startTrans() {
$this->commit();
$this->db->startTrans();
return ;
}
/**
+----------------------------------------------------------
* 提交事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function commit() {
return $this->db->commit();
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function rollback() {
return $this->db->rollback();
}
/**
+----------------------------------------------------------
* 获取主键名称
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getPk() {
return isset($this->fields['_pk'])?$this->fields['_pk']:$this->pk;
}
/**
+----------------------------------------------------------
* 返回最后执行的sql语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastSql() {
return $this->db->getLastSql();
}
/**
+----------------------------------------------------------
* 返回最后插入的ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastInsID() {
return $this->db->getLastInsID();
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Phprpc/Model.class.php | PHP | asf20 | 22,044 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Action.class.php 2504 2011-12-28 07:35:29Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP AMF模式Action控制器基类
+------------------------------------------------------------------------------
*/
abstract class Action {
/**
+----------------------------------------------------------
* 魔术方法 有不存在的操作的时候执行
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名
* @param array $parms 参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$parms) {
// 如果定义了_empty操作 则调用
if(method_exists($this,'_empty')) {
$this->_empty($method,$parms);
}
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Phprpc/Action.class.php | PHP | asf20 | 1,643 |