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 class XmlAction extends BaseAction{ // 资源列表 public function show(){ $this->assign('jumpurl',F('_xml/xucai')); $this->display('./Public/system/xml_show_list.html'); } // FeiFei备用库 public function feifei(){ $cai = D('Cai'); $xml = $cai->xml_httpurl('feifei'); if ($xml) { $this->xmlmdb($xml); }else{ $this->error("采集失败请多试几次,如一直失败通常为网络不稳定或禁用了采集!"); } } // 资源站A型 public function caijia(){ $cai = D('Cai'); $xml = $cai->xml_httpurl('caijia'); if ($xml) { $this->xmlmdb($xml); }else{ $this->error("采集失败请多试几次,如一直失败通常为网络不稳定或禁用了采集!"); } } // 断点续采 public function xuncai(){ $jumpurl = F('_xml/xucai'); redirect($jumpurl); } // 分解数据 public function xmlmdb($xml){ $cai = D('Cai'); $array_url = $xml['url']; $array_tpl = $xml['tpl']; $xml_page = $xml['page']; $list_class = $xml['listclass']; $list_vod = $xml['listvod']; //是否采集入库 if($array_url['action']){ $page = $array_url['page']; echo '<style type="text/css">div{font-size:12px;color: #333333}span{font-weight:bold;color:#FF0000}</style>'; echo'<div id="show"><div>当前采集任务<strong class="green">'.$page.'</strong>/<span class="green">'.$xml_page['pagecount'].'</span>页,共需要采集数据<span>'.$xml_page['recordcount'].'</span>个</div>'; foreach($list_vod as $key=>$vod){ //判断地址入库 $vod['vod_inputer'] = 'xml_'.$array_url['fid']; $vod_play = explode('$$$',$vod['vod_play']); $vod_url = explode('$$$',$vod['vod_url']); echo '<div style="line-height:22px"><span>'.(($page-1)*$xml_page['pagesize']+$key+1).'</span> ['.getlistname($vod['vod_cid']).'] '.$vod['vod_name'].' 需采集<span>'.count($vod_play).'</span>组播放地址 <font color=green>'; foreach($vod_play as $ii=>$value){ $vod['vod_play'] = $value; $vod['vod_url'] = trim($vod_url[$ii]); echo $cai->xml_insert($vod,$array_url['pic']); } echo '</font></div>'; ob_flush();flush(); } if('all' == $array_url['action'] || 'day' == $array_url['action']){ if($page < $xml_page['pagecount']){ $jumpurl = str_replace('{!page!}',($page+1),$array_tpl['pageurl']); //缓存断点续采 F('_xml/xucai',$jumpurl); //跳转到下一页 echo C('play_collect_time').'秒后将自动采集下一页!'; echo '<meta http-equiv="refresh" content='.C('play_collect_time').';url='.$jumpurl.'>'; }else{ //清除断点续采 F('_xml/xucai',NULL); echo '<div>所有采集任务已经完成,返回[<a href="?s=Admin-Vod-Show">视频管理中心</a>],查看[<a href="?s=Admin-Vod-Show-vod_cid-0">相似未入库影片</a>]!</div>'; } } }else{ $array_url['vodids'] = ''; $this->assign($array_url); $this->assign($array_tpl); $this->assign('list_class',$list_class); $this->assign('list_vod',$list_vod); $this->display('./Public/system/xml_show.html'); } } // 检测第三方资源分类是否绑定 public function setbind(){ $rs = M("List"); $list = $rs->field('list_id,list_pid,list_sid,list_name')->where('list_sid = 1')->order('list_id asc')->select(); foreach($list as $key=>$value){ if(!getlistson($list[$key]['list_id'])){ unset($list[$key]); } } $array_bind = F('_xml/bind'); $this->assign('vod_cid',$array_bind[$_GET['bind']]);//绑定后的系统分类 $this->assign('vod_list',$list); $this->display('./Public/system/xml_setbind.html'); } // 存储第三方资源分类绑定 public function insertbind(){ $bindcache = F('_xml/bind'); if (!is_array($bindcache)) { $bindcache = array(); $bindcache['1_1'] = 0; } $bindkey = trim($_GET['bind']); $bindinsert[$bindkey] = intval($_GET['cid']); $bindarray = array_merge($bindcache,$bindinsert); F('_xml/bind',$bindarray); exit('ok'); } } ?>
0321hy
trunk/Lib/Lib/Action/Admin/XmlAction.class.php
PHP
asf20
4,118
<?php class TagAction extends BaseAction{ // 显示标签列表 public function show(){ //生成查询参数 $admin['p'] = ''; //组合分页信息 $limit = C('url_num_admin'); $rs = new Model() ; $count = $rs->query("select count(1) as count from (select * from ".C('db_prefix')."tag group by tag_sid,tag_name ) aa"); $count = $count[0]['count']; $totalpages = ceil($count/$limit); $currentpage = !empty($_GET['p'])?intval($_GET['p']):1; $currentpage = get_maxpage($currentpage,$totalpages);//$admin['page'] = $currentpage; $pageurl = U('Admin-Tag/Show',$admin,false,false).'{!page!}'.C('url_html_suffix'); $admin['p'] = $currentpage; $pages = '共'.$count.'个标签&nbsp;当前:'.$currentpage.'/'.$totalpages.'页&nbsp;'.getpage($currentpage,$totalpages,8,$pageurl,'pagego(\''.$pageurl.'\','.$totalpages.')'); $admin['pages'] = $pages; //查询数据 $rs = D("Tag"); $array = $rs->field('*,count(tag_name) as tag_count')->limit($limit)->page($currentpage)->group('tag_sid,tag_name')->order('tag_sid asc,tag_count desc')->select(); foreach($array as $key=>$val){ $array[$key]['tag_url'] = U('Admin-'.ucfirst(getsidname($array[$key]['tag_sid'])).'/Show',array('tag'=>urlencode($array[$key]['tag_name'])),'',false,true); } $this->assign($admin); $this->assign('list_tag',$array); $this->display('./Public/system/tag_show.html'); } // 显示标签AJAX方式 public function showajax(){ $rs = D("Tag"); $array = $rs->field('*,count(tag_name) as tag_count')->limit('100')->group('tag_name,tag_sid')->order('tag_count desc')->select(); foreach($array as $key=>$val){ if($array[$key]['tag_sid']==2){ $array[$key]['tag_url']=UU('Admin-News/Show',array('tag_name'=>urlencode($array[$key]['tag_name']),'tag_type'=>1),'',false,true); }else{ $array[$key]['tag_url']=UU('Admin-Vod/Show',array('tag_name'=>urlencode($array[$key]['tag_name']),'tag_type'=>1),'',false,true); } } $this->assign('tag_list',$array); $this->display('./Public/system/tag_ajax.html'); } // 删除标签 public function del(){ $rs = D("Tag"); $where['tag_name'] = trim($_GET['id']); $rs->where($where)->delete(); $this->success('标签:'.$tag.'删除成功!'); } } ?>
0321hy
trunk/Lib/Lib/Action/Admin/TagAction.class.php
PHP
asf20
2,311
<?php class PicAction extends BaseAction{ //下载远程图片 public function down(){ C('upload_http',1); $img = D('Img'); $rs = D("Vod"); if('fail'==trim($_GET['id'])){ $rs->execute('update '.C('db_prefix').'vod set vod_pic=REPLACE(vod_pic,"httpf://", "http://")'); } $count = $rs->where('Left(vod_pic,7)="http://"')->count('vod_id'); $list = $rs->where('Left(vod_pic,7)="http://"')->order('vod_addtime desc')->limit(C('upload_http_down'))->select(); if($list){ echo '<style type="text/css">div{font-size:13px;color: #333333;line-height:21px;}span{font-weight:bold;color:#FF0000}</style>'; echo'<div>共有<span>'.$count.'</span>张远程图片,每次批量下载<span>'.C('upload_http_down').'</span>张,<span>'.C('play_collect_time').'</span>秒后执行下一次操作。<br />'; foreach($list as $key=>$value){ $imgnew = $img->down_load($value['vod_pic'],'vod'); if($value['vod_pic'] == $imgnew){ $rs->where('vod_id='.$value['vod_id'])->setField('vod_pic',str_replace("http://","httpf://",$value['vod_pic'])); echo(($key+1).' <a href="'.$value['vod_pic'].'" target="_blank">'.$value['vod_pic'].'</a> <font color=red>下载失败!</font><br/>'); }else{ $rs->where('vod_id = '.$value['vod_id'])->setField('vod_pic',$imgnew); echo(($key+1).' <a href="'.$value['vod_pic'].'" target="_blank">'.$value['vod_pic'].'</a> 下载成功!<br />'); } ob_flush();flush(); } echo'请稍等一会,正在释放服务器资源...<meta http-equiv="refresh" content='.C('play_collect_time').';url=?s=Admin-Pic-Down>'; echo'</div>'; }else{ $count = $rs->where('Left(vod_pic,8)="httpf://"')->count('vod_id'); if($count){ echo'<div style="font-size:14px;">共有<span>'.$count.'</span>张远程图片保存失败,如果需要重新下载,请点击<a href="?s=Admin-Pic-Down-id-fail">[这里]</a>!</div>'; }else{ $this->assign("jumpUrl","?s=Admin-Vod-Show"); $this->success('恭喜您,所有远程图片已经下载完成!'); } } } // 本地附件展示 public function show(){ $id = trim($_GET['id']); if ($id) { $dirpath = admin_ff_url_repalce(str_replace('*','-',$id)); }else{ $dirpath = './'.C('upload_path'); } if (!strpos($dirpath,C('upload_path'))) { $this->error('不在上传文件夹范围内!'); } $dirlast = $this->dirlast(); import("ORG.Io.Dir"); $dir = new Dir($dirpath); $list_dir = $dir->toArray(); foreach($list_dir as $key=>$value){ $list_dir[$key]['pathfile'] = admin_ff_url_repalce($value['path'],'desc').'|'.str_replace('-','*',$value['filename']); } if (empty($list_dir)){ $this->error('还没有上传任何附件,无需管理!'); } if($dirlast && $dirlast != '.'){ $this->assign('dirlast',admin_ff_url_repalce($dirlast,'desc')); } $this->assign('dirpath',$dirpath); $this->assign('list_dir',$list_dir); $this->display('./Public/system/pic_show.html'); } //获取上一层路径 public function dirlast(){ $id = admin_ff_url_repalce(trim($_GET['id'])); if ($id) { return substr($id,0,strrpos($id, '/')); }else{ return false; } } // 删除单个本地附件 public function del(){ $path = trim(str_replace('*','-',$_GET['id'])); @unlink($path); @unlink(str_replace(C('upload_path').'/',C('upload_path').'-s/',$path)); $this->success('删除附件成功!'); } // 清理无效图片 public function ajaxpic(){ $path = trim(str_replace('*','-',$_GET['id'])); //根据参数组合生成当前目录下的图片数组 $list = glob($path.'/*'); if(empty($list)){ exit('无图片'); } foreach ($list as $i=>$file){ $dir[] = str_replace('./'.C('upload_path').'/','',$path.'/'.basename($file)); } //根据条件查询数据库并将图片保存为数组 if(stristr($path,'/vod')){ $rs = M("Vod"); $array = $rs->field('vod_pic')->where('Left(vod_pic,4)!="http"')->order('vod_addtime desc')->select(); foreach ($array as $value){ $dir2[] = $value['vod_pic']; } }elseif(stristr($path,'/news')){ $rs = M("News"); $array = $rs->field('news_pic')->where('Left(news_pic,4)!="http"')->order('news_addtime desc')->select(); foreach ($array as $value){ $dir2[] = $value['news_pic']; } }elseif(stristr($path,'/slide')){ $rs = D("Slide"); $array = $rs->field('slide_pic')->where('Left(slide_pic,4)!="http"')->order('slide_id desc')->select(); foreach ($array as $value){ $dir2[] = $value['slide_pic']; } }elseif(stristr($path,'/link')){ $rs = M("Link"); $array = $rs->field('link_logo')->where('Left(link_logo,4)!="http"')->order('link_id desc')->select(); foreach ($array as $value){ $dir2[] = $value['link_logo']; } } //筛选出当前目录下的无效图片 $del = array_diff($dir,$dir2); foreach ($del as $key=>$value){ @unlink('./'.C('upload_path').'/'.$value); }; exit('清理完成'); } } ?>
0321hy
trunk/Lib/Lib/Action/Admin/PicAction.class.php
PHP
asf20
5,081
<?php class ListAction extends BaseAction{ // 显示分类 public function show(){ $sid = $_GET['sid']; if ($sid) { $where['list_sid'] = $sid; } $rs = D("Admin.List"); $list = $rs->where($where)->order('list_oid asc')->select(); if($list){ $this->assign('listtree',list_to_tree($list,'list_id','list_pid','son',0)); $this->display('./Public/system/list_show.html'); }else{ $this->assign("jumpUrl",'?s=Admin-List-Add'); $this->success('暂无分类数据请先添加!'); } } // 添加编辑分类 public function add(){ $cid = intval($_GET['id']); $rs = D("Admin.List"); if ($cid>0) { $where['list_id'] = $cid; $list = $rs->where($where)->find(); $list['tpltitle'] = '编辑'; }else{ $list['list_id'] = 0; $list['list_pid'] = intval($_GET['pid']); $list['list_sid'] = intval($_GET['sid']); $list['list_oid'] = $rs->max('list_oid')+1; $list['list_status'] = 1; $list['tpltitle'] = '添加'; } $this->assign($list); $this->assign('list_tree',F('_ppvod/listtree')); $this->display('./Public/system/list_add.html'); } // 写入数据 public function _before_insert(){//写入前置 if($_POST['list_sid'] == 9){ $_POST['list_dir'] = uniqid(); } } public function insert(){ $rs = D("Admin.List"); if ($rs->create()) { if ( false !== $rs->add() ) { $this->ppvod_list(); $this->assign("jumpUrl",'?s=Admin-List-Show'); $this->success('添加栏目分类成功!'); }else{ $this->error('添加栏目分类错误'); } }else{ $this->error($rs->getError()); } } // 更新数据 public function _before_update(){//前置 $where['list_dir'] = trim($_POST['list_dir']); $rs = D("Admin.List"); $list = $rs->field('id,cfile')->where($where)->find(); if(!empty($list)){ if(intval($_POST['list_id']) != $list['list_id']){ $this->error('栏目英文别名已经存在,请重新填写!'); } } } public function update(){ $rs = D("Admin.List"); if ($rs->create()) { $list = $rs->save(); if ($list !== false) { $this->ppvod_list(); $this->assign("jumpUrl",'?s=Admin-List-Show'); $this->success('栏目分类更新成功!'); }else{ $this->error("栏目分类更新失败!"); } }else{ $this->error($rs->getError()); } } // 批量更新数据 public function updateall(){ if(empty($_POST['ids'])){ $this->error('请选择需要修改的栏目!'); } $rs = D("Admin.List"); $array = $_POST; foreach($array['ids'] as $key=>$value){ $data['list_oid'] = intval($array['list_oid'][$value]); $data['list_name'] = $array['list_name'][$value]; $data['list_skin'] = $array['list_skin'][$value]; if(empty($array['list_dir'][$value])){ $data['list_dir'] = ff_pinyin($array['list_name'][$value]); }else{ $data['list_dir'] = $array['list_dir'][$value]; } $rs->where('list_id = '.intval($value))->save($data); } $this->ppvod_list(); $this->redirect('Admin-List/Show'); } // 隐藏与显示栏目 public function status(){ $where['list_id'] = intval($_GET['id']); if (!getlistson($where['list_id'])) { $this->error("该栏目有子类,不可以隐藏!"); } $rs = D("Admin.List"); if (intval($_GET['sid'])) { $rs->where($where)->setField('list_status',1); }else{ $rs->where($where)->setField('list_status',0); } $this->ppvod_list(); $this->redirect('Admin-List/Show'); } // 删除数据 public function del(){ $rs = D("Admin.List"); $where['list_id'] = $_GET['id']; if (!getlistson($_GET['id'])) { $this->error("请先删除本类下面的子栏目!"); } $rs->where($where)->delete(); $sid = getlistname($id,'list_id'); $this->deldata($sid,$id); $this->ppvod_list(); $this->success('成功删除该栏目分类与本类有关的内容!'); } //删除对应的数据 public function deldata($sid,$cid){ if ($sid == 1) { $rs = M("Vod"); $rs->where('vod_cid = '.$cid)->delete(); }elseif($sid == 2){ $rs = M("News"); $rs->where('news_cid = '.$cid)->delete(); } } // 批量删除数据 public function delall(){ if(empty($_POST['ids'])){ $this->error('请选择需要删除的栏目!'); } $list = D("Admin.List"); $array = $_POST; foreach($array['ids'] as $value){ $id = intval($value); $sid = getlistname($id,'list_id'); if (!getlistson($id)) { $this->error("请先删除本类下面的子栏目!"); } $list->where('list_id = '.$id)->delete(); $this->deldata($sid,$id); } $this->ppvod_list(); $this->success('批量删除栏目成功!'); } } ?>
0321hy
trunk/Lib/Lib/Action/Admin/ListAction.class.php
PHP
asf20
4,855
<?php class TplAction extends BaseAction{ // 显示模板管理 public function show(){ $dirpath = $this->dirpath();//当前目录 $dirlast = $this->dirlast();//上一层目录 import("ORG.Io.Dir"); $dir = new Dir($dirpath); $list_dir = $dir->toArray(); if (empty($list_dir)){ $this->error('该文件夹下面没有文件!'); } foreach($list_dir as $key=>$value){ $list_dir[$key]['pathfile'] = admin_ff_url_repalce($value['path'],'desc').'|'.$value['filename']; } $_SESSION['tpl_jumpurl'] = '?s=Admin-Tpl-Show-id-'.admin_ff_url_repalce($dirpath,'desc'); if($dirlast && $dirlast != '.'){ $this->assign('dirlast',admin_ff_url_repalce($dirlast,'desc')); } $this->assign('dirpath',$dirpath); $this->assign('list_dir',list_sort_by($list_dir,'mtime','desc')); $this->display('./Public/system/tpl_show.html'); } //获取模板当前路径 public function dirpath(){ $id = admin_ff_url_repalce(trim($_GET['id'])); if ($id) { $dirpath = $id; }else{ $dirpath = TMPL_PATH; } if (!strpos($dirpath,'Tpl')) { $this->error('不在模板文件夹范围内!'); } return $dirpath; } //获取模板上一层路径 public function dirlast(){ $id = admin_ff_url_repalce(trim($_GET['id'])); if ($id) { return substr($id,0,strrpos($id, '/')); }else{ return false; } } // 编辑模板 public function add(){ $filename = admin_ff_url_repalce(str_replace('*','.',trim($_GET['id']))); if (empty($filename)) { $this->error('模板名称不能为空!'); } $content = read_file($filename); $this->assign('filename',$filename); $this->assign('content',htmlspecialchars($content)); $this->display('./Public/system/tpl_add.html'); } // 更新模板 public function update(){ $filename = trim($_POST['filename']); $content = stripslashes(htmlspecialchars_decode($_POST['content'])); if (!testwrite(substr($filename,0,strrpos($filename,'/')))){ $this->error('在线编辑模板需要给'.TEMPLATE_PATH.'添加写入权限!'); } if (empty($filename)) { $this->error('模板文件名不能为空!'); } if (empty($content)) { $this->error('模板内容不能为空!'); } write_file($filename,$content); if (!empty($_SESSION['tpl_jumpurl'])) { $this->assign("jumpUrl",$_SESSION['tpl_jumpurl']); }else{ $this->assign("jumpUrl",'?s=Admin/Tpl/Show'); } $this->success('恭喜您,模板更新成功!'); } // 删除模板 public function del(){ $id = admin_ff_url_repalce(str_replace('*','.',trim($_GET['id']))); if (!substr(sprintf("%o",fileperms($id)),-3)){ $this->error('无删除权限!'); } @unlink($id); if (!empty($_SESSION['tpl_jumpurl'])) { $this->assign("jumpUrl",$_SESSION['tpl_jumpurl']); }else{ $this->assign("jumpUrl",'?s=Admin/Tpl/Show'); } $this->success('删除文件成功!'); } } ?>
0321hy
trunk/Lib/Lib/Action/Admin/TplAction.class.php
PHP
asf20
2,967
<?php /*****************后台公用类库 继承全站公用类库*******************************/ class BaseAction extends AllAction{ //构造 public function _initialize(){ parent::_initialize(); //检查登录 if (!$_SESSION[C('USER_AUTH_KEY')]) { $this->assign('jumpUrl',C('cms_admin').'?s=Admin-Login'); $this->error('对不起,您还没有登录,请先登录!1111111111'); } //检查权限 不需要验证操作的除外 if (!in_array(strtolower(ACTION_NAME),explode(',',C('NOT_AUTH_ACTION')))) { // 检索当前模块是否需要认证 $model_id = array_search(MODULE_NAME,explode(',',C('REQUIRE_AUTH_MODULE'))); if (is_int($model_id)) { $usertype = explode(',',$_SESSION['admin_ok']); if (!$usertype[$model_id]) { $this->error('对不起,您没有管理该模块的权限,请联系超级管理员授权!'); } } } } //生成播放器列表 public function ppvod_play(){ $this->assign('countplayer',count(C('PP_PLAYER'))); $this->assign('playtree',C('play_player')); } //生成前台分类缓存 public function ppvod_list(){ $rs = D("List"); $where['list_status'] = array('eq',1); $list=$rs->where($where)->order('list_oid asc')->select(); foreach($list as $key=>$val){ if ($list[$key]['list_sid'] == 9){ $list[$key]['list_url'] = $list[$key]['list_jumpurl']; $list[$key]['list_url_big'] = $list[$key]['list_jumpurl']; }else{ $list[$key]['list_url'] = ff_list_url(getsidname($list[$key]['list_sid']),array('id'=>$list[$key]['list_id']),1); $list[$key]['list_url_big'] = ff_list_url(getsidname($list[$key]['list_sid']),array('id'=>$list[$key]['list_pid']),1); $list[$key]['list_name_big'] = getlistname($list[$key]['list_pid']); if($list[$key]['list_sid'] == 1){ $list[$key]['list_limit'] = gettplnum('ff_mysql_vod\(\'(.*)\'\)',$list[$key]['list_skin']); }else{ $list[$key]['list_limit'] = gettplnum('ff_mysql_news\(\'(.*)\'\)',$list[$key]['list_skin']); } } } //$list[999]['special'] = get_tpl_limit('<bdlist(.*)limit="([0-9]+)"(.*)>','special_list');//缓存专题分页数据 F('_ppvod/list',$list); F('_ppvod/listtree',list_to_tree($list,'list_id','list_pid','son',0)); $where['list_sid'] = array('EQ',1); $list = $rs->where($where)->order('list_oid asc')->select(); F('_ppvod/listvod',list_to_tree($list,'list_id','list_pid','son',0)); $where['list_sid']=array('EQ',2); $list=$rs->where($where)->order('list_oid asc')->select(); F('_ppvod/listnews',list_to_tree($list,'list_id','list_pid','son',0)); } } ?>
0321hy
trunk/Lib/Lib/Action/BaseAction.class.php
PHP
asf20
2,667
<?php class NewsAction extends HomeAction{ //资讯搜索 public function search(){ //通过地址栏参数支持筛选条件,$JumpUrl传递分页及跳转参数 $Url = ff_param_url(); $JumpUrl = ff_param_jump($Url); $JumpUrl['p'] = '{!page!}'; C('jumpurl',UU('Home-news/search',$JumpUrl,false,true)); C('currentpage',$Url['page']); //变量赋值 $search = $this->Lable_Search($Url,'news'); $this->assign($search); $this->display($search['search_skin']); } //资讯列表 public function show(){ //通过地址栏参数支持筛选条件,$JumpUrl传递分页及跳转参数 $Url = ff_param_url(); $JumpUrl = ff_param_jump($Url); $JumpUrl['p'] = '{!page!}'; C('jumpurl',UU('Home-news/show',$JumpUrl,false,true)); C('currentpage',$Url['page']); //变量赋值 $List = list_search(F('_ppvod/list'),'list_id='.$Url['id']); $channel = $this->Lable_News_List($Url,$List[0]); $this->assign($channel); $this->display($channel['list_skin']); } //资讯内容页 public function read(){ $array_detail = $this->get_cache_detail( intval($_GET['id']) ); if($array_detail){ $this->assign($array_detail['show']); $this->assign($array_detail['read']); $this->display($array_detail['read']['news_skin']); }else{ $this->assign("jumpUrl",C('site_path')); $this->error('此条资讯已经删除!'); } } // 从数据库获取数据 private function get_cache_detail($news_id){ if(!$news_id){ return false; } //优先读取缓存数据 if(C('data_cache_news')){ $array_detail = S('data_cache_news_'.$news_id); if($array_detail){ return $array_detail; } } //未中缓存则从数据库读取 $where = array(); $where['news_id'] = $news_id; $where['news_status'] = array('eq',1); $rs = D("News"); $array = $rs->where($where)->relation('Tag')->find(); if($array){ //解析标签 $array_detail = $this->Lable_News_Read($array); if( C('data_cache_news') ){ S('data_cache_news_'.$news_id, $array_detail, intval(C('data_cache_news'))); } return $array_detail; } return false; } } ?>
0321hy
trunk/Lib/Lib/Action/Home/NewsAction.class.php
PHP
asf20
2,191
<?php class CmAction extends HomeAction{ // 展示评论 public function show(){ $Url = ff_param_url(); $where = array(); $where['cm_cid'] = $Url['id']; $where['cm_sid'] = $Url['sid']; $limit = intval(C('user_cmnum')); if(C('user_check')){ $where['cm_status'] = 1; } $rs = D('Cm'); $count = $rs->where($where)->count('cm_id'); $totalpages = ceil($count/$limit); $page = get_maxpage($Url['page'],$totalpages); $pageurl ='javascript:void(0)" onclick="FF.Comment.Show(\''.U('cm/show',array('sid'=>$Url['sid'],'id'=>$Url['id'],'p'=>'{!page!}'),false,false).'\')'; $pages = '共'.$count.'条评论&nbsp;当前:'.$page.'/'.$totalpages.'页&nbsp;'; $pages .= getpage($page,$totalpages,$limit,$pageurl,false); // $list = $rs->where($where)->order('cm_addtime desc')->limit($limit)->page($page)->select(); foreach($list as $key=>$val){ $list[$key]['cm_floor'] = $count-(($page-1) * $limit + $key); } $this->assign('cm_sid',$Url['sid']); $this->assign('cm_id',$Url['id']); $this->assign('cm_pages',$pages); $this->assign('cm_count',$count); $this->assign('cm_list',$list); $this->display('pp_comment'); } // 添加评论 public function insert(){ $cookie = 'comment_'.intval($_POST['cm_sid']).'_'.intval($_POST['cm_cid']); if(isset($_COOKIE[$cookie])){ $this->ajaxReturn(0,'您已评论过,请先休息一会!',0); } $rs = D("Cm"); C('TOKEN_ON',false);//关闭令牌验证 if($rs->create()){ if (false !== $rs->add()) { setcookie($cookie, 'true', time()+intval(C('user_second'))); if (C('user_gbcm')) { $this->ajaxReturn($result,"评论成功,我们会尽快审核你的评论!",2); }else{ $this->ajaxReturn($result,"评论成功,感谢你的参与!",1); } } } $this->ajaxReturn(0,'评论失败,请重试!',0); } // Ajax顶踩 public function updown(){ $id = intval($_GET['id']); if ($id < 1) { exit('-1'); } $ajax = trim($_GET['ajax']); $cookie = 'cmud-'.$id; if(isset($_COOKIE[$cookie])){ exit('0'); } $rs = M("Cm"); if ('up' == $ajax){ $rs->setInc('up','id = '.$id); setcookie($cookie, 'true', time()+intval(C('user_check_time'))); }elseif( 'down' == $ajax){ $rs->setInc('down','id = '.$id); setcookie($cookie, 'true', time()+intval(C('user_check_time'))); } $list = $rs->field('up,down')->find($id); if (empty($list)) { $list['up'] = 0; $list['down'] = 0; } echo($list['up'].':'.$list['down']); } } ?>
0321hy
trunk/Lib/Lib/Action/Home/CmAction.class.php
PHP
asf20
2,580
<?php //顶踩模块 class UpdownAction extends HomeAction{ public function vod(){ $id = intval($_GET['id']); if ($id < 1) { $this->ajaxReturn(-1,'数据非法!',-1); } $this->show($id,trim($_GET['type']),'vod'); } public function news(){ $id = intval($_GET['id']); if ($id < 1) { $this->ajaxReturn(-1,'数据非法!',-1); } $this->show($id,trim($_GET['type']),'news'); } public function show($id,$type,$model='vod'){ $rs = D(ucfirst($model)); if($type){ $cookie = $model.'-updown-'.$id; if(isset($_COOKIE[$cookie])){ $this->ajaxReturn(0,'您已操作过,晚点再试!',0); } if ('up' == $type){ $rs->setInc($model.'_up',$model.'_id = '.$id); setcookie($cookie, 'true', time()+intval(C('user_second'))); }elseif( 'down' == $type){ $rs->setInc($model.'_down',$model.'_id = '.$id); setcookie($cookie, 'true', time()+intval(C('user_second'))); } } $array = $rs->field(''.$model.'_up,'.$model.'_down')->find($id); if (!$array) { $array[$model.'_up'] = 0; $array[$model.'_down'] = 0; } $this->ajaxReturn($array[$model.'_up'].':'.$array[$model.'_down'],"感谢您的参与,操作成功!",1); //echo($array[$model.'_up'].':'.$array[$model.'_down']); } } ?>
0321hy
trunk/Lib/Lib/Action/Home/UpdownAction.class.php
PHP
asf20
1,307
<?php class MyAction extends HomeAction{ public function show(){ $id = !empty($_GET['id'])?$_GET['id']:'new'; $this->display('my_'.trim($id)); } } ?>
0321hy
trunk/Lib/Lib/Action/Home/MyAction.class.php
PHP
asf20
170
<?php class VodModel extends RelationModel { private $vod_id; //自动验证 protected $_validate = array( array('vod_cid','number','请选择分类!',1,'',3), array('vod_cid','getlistson','请选择当前子类栏目!',1,'function',3), array('vod_name','require','影片名称必须填写!',1,'',3), ); //自动完成 protected $_auto = array( array('vod_letter','vod_letter',3,'callback'), array('vod_gold','vod_gold',3,'callback'), array('vod_pic','vod_pic',3,'callback'), array('vod_addtime','vod_addtime',3,'callback'), ); //关联定义 protected $_link = array( 'Tag'=>array( 'mapping_type' => HAS_MANY, 'class_name'=> 'Tag', 'mapping_name'=>'Tag',//数据对像映射名称 'foreign_key' => 'tag_id', 'parent_key' => 'vod_id', 'mapping_fields' => 'tag_id,tag_sid,tag_name', 'condition' => 'tag_sid = 1', //'mapping_limit' => 5, //'mapping_order' => 'create_time desc', ) ); //字母处理 public function vod_letter(){ return ff_letter_first(trim($_POST["vod_name"])); } //图片处理 public function vod_pic(){ $img = D('Img'); return $img->down_load(trim($_POST["vod_pic"])); } //积分处理 public function vod_gold(){ if($_POST["vod_gold"] > 10){ $_POST["vod_gold"] = 10; } return $_POST["vod_gold"]; } //是否更新时间 public function vod_addtime(){ if ($_POST['checktime']) { return time(); }else{ return strtotime($_POST['vod_addtime']); } } } ?>
0321hy
trunk/Lib/Lib/Action/Home/VodModel.class.php
PHP
asf20
1,533
<?php class GbAction extends HomeAction{ //留言列表 public function show(){ $rs = D('GbView'); $page = !empty($_GET['p']) ? intval($_GET['p']) : 1; $limit = intval(C('user_gbnum')); if (C('user_check')) { $where['gb_status'] = array('eq',1); } // 组合分页信息 $count = $rs->where($where)->count('gb_id'); $totalpages = ceil($count/$limit); if($page > $totalpages){ $page = $totalpages; } $pageurl = UU('Home-gb/show',array('p'=>'{!page!}'),false,true); $pages = '共'.$count.'篇留言&nbsp;当前:'.$page.'/'.$totalpages.'页&nbsp;'.getpage($page,$totalpages,C('home_pagenum'),$pageurl,'pagego(\''.$pageurl.'\','.$totalpages.')'); // 查询数据 $list = $rs->where($where)->limit($limit)->order('gb_oid desc,gb_addtime desc')->page($page)->select(); foreach($list as $key=>$val){ $list[$key]['gb_floor'] = $count-(($page-1) * $limit + $key); } // 是否报错 $vodid = intval($_GET['id']); if($vodid){ $rs = M("Vod"); $array = $rs->field('vod_id,vod_name,vod_actor')->where('vod_status = 1 and vod_id='.$vodid)->find(); if($array){ $this->assign('gb_content','影片ID'.$array['vod_id'].'点播出现错误!名称:'.$array['vod_name'].' 主演:'.$array['vod_actor']); } } $this->assign('gb_list',$list); $this->assign('gb_count',$count); $this->assign('gb_pages',$pages); $this->assign('vod_id',$vodid); $this->display('pp_guestbook'); } // 添加留言 public function insert(){ $rs = D("Gb"); C('TOKEN_ON',false);//关闭令牌验证 if($rs->create()){ if (false !== $rs->add()) { $cookie = 'gbook-'.intval($_POST['gb_cid']); setcookie($cookie, 'true', time()+intval(C('user_second'))); if (C('user_check')) { $this->success('留言成功,我们会尽快审核您的留言!'); }else{ $this->success('恭喜您,留言成功!'); } }else{ $this->error('留言失败,请重试!'); } }else{ $this->error($rs->getError()); } } } ?>
0321hy
trunk/Lib/Lib/Action/Home/GbAction.class.php
PHP
asf20
2,074
<?php class IndexAction extends HomeAction{ public function index(){ if (!is_file('./Runtime/Install/install.lock')) { $this->assign("jumpUrl",'index.php?s=Admin-Install'); $this->error('您还没安装本程序,请运行 install.php 进入安装!'); } if(C('url_html')){ redirect('index'.C('url_html_suffix')); } $this->assign($this->Lable_Index()); $this->display('pp_index'); } } ?>
0321hy
trunk/Lib/Lib/Action/Home/IndexAction.class.php
PHP
asf20
433
<?php class VodAction extends HomeAction{ //影视搜索 public function search(){ //通过地址栏参数支持筛选条件,$JumpUrl传递分页及跳转参数 $Url = ff_param_url(); $JumpUrl = ff_param_jump($Url); $JumpUrl['p'] = '{!page!}'; C('jumpurl',UU('Home-vod/search',$JumpUrl,false,true)); C('currentpage',$Url['page']); //变量赋值 $search = $this->Lable_Search($Url,'vod'); // dump($search);exit; $this->assign($search); // $vod_list = ff_mysql_vod('wd:'.$search['search_wd'].';limit:8;page:true;order:vod_addtime desc'); //ajax搜索传递:QQ:182377860 $cid = intval($_GET['cid']) ? intval($_GET['cid']) : 0; $condition = 'wd:'.$search['search_wd'].';actor:'.$search['search_actor'].';limit:8;page:true;order:vod_addtime desc'; if($cid > 0) { $condition .= ';cid:'.$cid; } $vod_list = ff_mysql_vod($condition); $page = $vod_list[0]['page']; $pagecount = $vod_list[0]['pagecount']; $pagetop = $vod_list[0]['pagetop']; $this->assign('page', $page); $this->assign('pagecount', $pagecount); $this->assign('pagetop', $pagetop); $this->assign('vod_list', $vod_list); if($this->isAjax()){ $ajaxData = array( 'ajaxtxt' => $this->fetch('pp_ajax_search'), 'short_page' => $this->fetch('pp_ajax_page_top'), 'long_page' => $this->fetch('pp_ajax_page_bottom'), 'count' => $pagecount ); $this->ajaxReturn($ajaxData); } $this->display($search['search_skin']); } //ajax搜索传递:QQ:182377860 // 影视列表页 public function show(){ //通过地址栏参数支持筛选条件,$JumpUrl传递分页及跳转参数 $Url = ff_param_url(); $JumpUrl = ff_param_jump($Url); $JumpUrl['p'] = '{!page!}'; C('jumpurl',UU('Home-vod/show',$JumpUrl,false,true)); C('currentpage',$Url['page']); //变量赋值 $List = list_search(F('_ppvod/list'),'list_id='.$Url['id']); $channel = $this->Lable_Vod_List($Url,$List[0]); //类型变量 QQ:182377860 $mcat = D('Mcat')->list_cat($Url['id']); foreach ((array)$mcat as $k=>$v){ $mcat[$k]['m_url'] = UU('Home-vod/show', array('id'=>$Url['id'],'mcid'=>$v['m_cid']),false,true); } $this->assign('mcat',$mcat); $this->assign($channel); // echo count($_REQUEST);exit; if(count($_REQUEST) > 1){ $channel['list_skin'] = 'pp_vodlist'; $nav = M('Mcat')->where("m_cid = {$Url['mcid']}")->find(); $this->assign('nav_title',$nav['m_name']); }// $this->assign($channel); // dump($channel);exit; /* * 列表采用ajax异步读取数据时 渲染不同页面 * QQ182377860 */ if($this->isAjax()){ if($_GET[order]) $s_order=$_GET[order]." DESC"; else $s_order="vod_addtime desc,vod_hits desc,vod_gold desc"; $vod_list=ff_mysql_vod('mcid:'.$_GET['mcid'].';cid:'.$Url["id"].';year:'.$_GET[year].';lz:'.$_GET[lz].';letter:'.$_GET[letter].';area:'.$_GET[area].';language:'.$_GET[language].';limit:25;page:true;order:'.$s_order.';'); $page = $vod_list[0]['page']; $pagetop = $vod_list[0]['pagetop']; $this->assign('vod_list', $vod_list); $this->assign('page', $page); $this->assign('pagetop', $pagetop); $ajaxData = array( 'ajaxtxt' => $this->fetch('pp_ajax_content'), 'short_page' => $this->fetch('pp_ajax_page_top'), 'long_page' => $this->fetch('pp_ajax_page_bottom'), ); $this->ajaxReturn($ajaxData); } $this->display($channel['list_skin']); } // 影片内容页 public function read(){ $array_detail = $this->get_cache_detail( intval($_GET['id']) ); // dump($vod_playlist);exit; // dump($array_detail);exit; if($array_detail){ $this->assign($array_detail['show']); $this->assign($array_detail['read']); $this->display($array_detail['read']['vod_skin']); }else{ $this->assign("jumpUrl",C('site_path')); $this->error('此影片已经删除,请选择观看其它节目!'); } } // 影片播放页 public function play(){ $array_detail = $this->get_cache_detail( intval($_GET['id']) ); if($array_detail){ $array_detail['read'] = $this->Lable_Vod_Play($array_detail['read'],array('id'=>intval($_GET['id']), 'sid'=>intval($_GET['sid']), 'pid'=>intval($_GET['pid']))); $this->assign($array_detail['show']); $this->assign($array_detail['read']); $this->display($array_detail['read']['vod_skin_play']); }else{ $this->assign("jumpUrl",C('site_path')); $this->error('此影片已经删除,请选择观看其它节目!'); } } /* * 口水页面 * * 需要下拉异步载入(后期) */ public function koushui() { $cm_cids = array(); $cm = D('Cm'); $cmCidData = $cm->field('cm_cid')->group('cm_cid')->order('cm_id DESC')->select(); if($cmCidData) { foreach ($cmCidData as $v) { $cm_cids[] = $v['cm_cid']; } } else { $this->error('目前没有评论'); } $vod = D('Vod'); $vod_list = $vod->where( array('vod_id' => array('in',$cm_cids)) )->select(); foreach ($vod_list as $k => $val) { $vod_list[$k]['comment'] = $this->get_cm_list($val['vod_id']); $vod_list[$k]['surplus_comment'] = $this->get_surplus_cm($val['vod_id']); } $this->assign('vod_list', $vod_list); $this->display('pp_koushui'); } /* * 读取部分评论 */ private function get_cm_list($vod_id) { return D('Cm')->field('cm_nickname,cm_content')->where(array('cm_cid' => $vod_id))->limit(3)->select(); } private function get_surplus_cm($vod_id) { $count = D('Cm')->where(array('cm_cid' => $vod_id))->count(); return $count; } // 从数据库获取数据 private function get_cache_detail($vod_id){ if(!$vod_id){ return false; } //优先读取缓存数据 if(C('data_cache_vod')){ $array_detail = S('data_cache_vod_'.$vod_id); if($array_detail){ return $array_detail; } } //未中缓存则从数据库读取 $where = array(); $where['vod_id'] = $vod_id; $where['vod_cid'] = array('gt',0); $where['vod_status'] = array('eq',1); $rs = D("Vod"); $array = $rs->where($where)->relation('Tag')->find(); if($array){ //解析标签 $array_detail = $this->Lable_Vod_Read($array); if( C('data_cache_vod') ){ S('data_cache_vod_'.$vod_id, $array_detail, intval(C('data_cache_vod'))); } return $array_detail; } return false; } } ?>
0321hy
trunk/Lib/Lib/Action/Home/VodAction.class.php
PHP
asf20
7,070
<?php class UpAction extends HomeAction{ } ?>
0321hy
trunk/Lib/Lib/Action/Home/UpAction.class.php
PHP
asf20
55
<?php class GoldAction extends HomeAction{ public function vod(){ $id = intval($_GET['id']); if ($id < 1) { $this->ajaxReturn(-1,'数据非法!',-1); } $this->show($id,intval($_GET['type']),'vod'); } public function news(){ $id = intval($_GET['id']); if ($id < 1) { $this->ajaxReturn(-1,'数据非法!',-1); } $this->show($id,intval($_GET['type']),'news'); } /* alter table `ff_vod` add vod_gold_1 float not null default '0'; alter table `ff_vod` add vod_gold_2 float not null default '0'; alter table `ff_vod` add vod_gold_3 float not null default '0'; alter table `ff_vod` add vod_gold_4 float not null default '0'; alter table `ff_vod` add vod_gold_5 float not null default '0'; */ public function show($id,$type,$model='vod'){ $rs = D(ucfirst($model)); $array = $rs->field(''.$model.'_gold,'.$model.'_golder,'.$model.'_gold,'.$model.'_gold_1,'.$model.'_gold_2,'.$model.'_gold_3,'.$model.'_gold_4,'.$model.'_gold_5,'.$model.'_golder')->find($id); if ($array) { if($type){ $cookie = $model.'-gold-'.$id; if(isset($_COOKIE[$cookie])){ $this->ajaxReturn(0,'您已评分!',0); } $type = is_numeric($type)?$type:1; $array[$model.'_gold_'.$type] = $array[$model.'_gold_'.$type]+1; $array[$model.'_golder'] = $array[$model.'_gold_1']+$array[$model.'_gold_2']+$array[$model.'_gold_3']+$array[$model.'_gold_4']+$array[$model.'_gold_5']; $array[$model.'_gold'] = number_format(($array[$model.'_gold_1']*1+$array[$model.'_gold_2']*2+$array[$model.'_gold_3']*3+$array[$model.'_gold_4']*4+$array[$model.'_gold_5']*5)/$array[$model.'_golder']*2,1); $rs->where($model.'_id = '.$id)->save($array); setcookie($cookie,'t',time()+intval(C('user_second'))); }else{ $array = $array; } }else{ $array[$model.'_gold'] = 0.0; $array[$model.'_gold_1'] = 0; $array[$model.'_gold_2'] = 0; $array[$model.'_gold_3'] = 0; $array[$model.'_gold_4'] = 0; $array[$model.'_gold_5'] = 0; $array[$model.'_golder'] = 0; } $this->ajaxReturn($array,"感谢您的参与,评分成功!",1); } } ?>
0321hy
trunk/Lib/Lib/Action/Home/GoldAction.class.php
PHP
asf20
2,154
<?php class SpecialAction extends HomeAction{ //专题列表 public function show(){ //通过地址栏参数支持筛选条件,$JumpUrl传递分页及跳转参数 $Url = ff_param_url(); $JumpUrl = ff_param_jump($Url); $JumpUrl['p'] = '{!page!}'; C('jumpurl',UU('Home-special/show',$JumpUrl,false,true)); C('currentpage',$Url['page']); //变量赋值 $channel = $this->Lable_Special_List($Url); $this->assign($channel); $this->display($channel['special_skin']); } //专题内容页 public function read(){ $array_detail = $this->get_cache_detail( intval($_GET['id']) ); if($array_detail){ $this->assign($array_detail['read']); $this->assign('list_vod',$array_detail['list_vod']); $this->assign('list_special',$array_detail['list_special']); $this->display($array_detail['read']['special_skin']); }else{ $this->assign("jumpUrl",C('site_path')); $this->error('此专题已经删除!'); } } // 从数据库获取数据 private function get_cache_detail($special_id){ if(!$special_id){ return false; } //优先读取缓存数据 if(C('data_cache_special')){ $array_detail = S('data_cache_special_'.$special_id); if($array_detail){ return $array_detail; } } //未中缓存则从数据库读取 $where['special_id'] = $special_id; $where['special_status'] = array('eq',1); $rs = D("Special"); $array = $rs->where($where)->find(); if($array){ //解析标签 $array_detail = $this->Lable_Special_Read($array); if( C('data_cache_special') ){ S('data_cache_special_'.$special_id, $array_detail, intval(C('data_cache_special'))); } return $array_detail; } return false; } } ?>
0321hy
trunk/Lib/Lib/Action/Home/SpecialAction.class.php
PHP
asf20
1,748
<?php class HitsAction extends HomeAction{ //静态模式JS展示人气 public function show(){ $id = intval($_GET['id']); $sid = trim($_GET['sid']); $type = trim($_GET['type']); $where[$sid.'_id'] = $id; $rs = M(ucfirst($sid)); $array = $rs->field($sid.'_id,'.$sid.'_hits,'.$sid.'_hits_month,'.$sid.'_hits_week,'.$sid.'_hits_day,'.$sid.'_addtime,'.$sid.'_hits_lasttime')->where($where)->find(); if($type == 'insert'){ $this->hits_insert($sid,$array); }else{ if($array){ echo("document.write('".$array[$type]."');"); }else{ echo("document.write('0');"); } } } //处理各模块的人气值刷新 public function hits_insert($sid,$array){ //初始化值 $hits[$sid.'_hits'] = $array[$sid.'_hits']; $hits[$sid.'_hits_month'] = $array[$sid.'_hits_month']; $hits[$sid.'_hits_week'] = $array[$sid.'_hits_week']; $hits[$sid.'_hits_day'] = $array[$sid.'_hits_day']; $new = getdate(); $old = getdate($array[$sid.'_hits_lasttime']); //月 if($new['year'] == $old['year'] && $new['mon'] == $old['mon']){ $hits[$sid.'_hits_month'] ++; }else{ $hits[$sid.'_hits_month'] = 1; } //周 $weekStart = mktime(0,0,0,$new["mon"],$new["mday"],$new["year"]) - ($new["wday"] * 86400);//本周开始时间,本周日0点0 $weekEnd = mktime(23,59,59,$new["mon"],$new["mday"],$new["year"]) + ((6 - $new["wday"]) * 86400);//本周结束时间,本周六12点59 if($array[$sid.'_hits_lasttime'] >= $weekStart && $array[$sid.'_hits_lasttime'] <= $weekEnd){ $hits[$sid.'_hits_week'] ++; }else{ $hits[$sid.'_hits_week'] = 1; } //日 if($new['year'] == $old['year'] && $new['mon'] == $old['mon'] && $new['mday'] == $old['mday']){ $hits[$sid.'_hits_day'] ++; }else{ $hits[$sid.'_hits_day'] = 1; } //更新数据库 $hits[$sid.'_id'] = $array[$sid.'_id']; $hits[$sid.'_hits'] = $hits[$sid.'_hits']+1; $hits[$sid.'_hits_lasttime'] = time(); $rs = M(ucfirst($sid)); $rs->save($hits); return $hits; } } ?>
0321hy
trunk/Lib/Lib/Action/Home/HitsAction.class.php
PHP
asf20
2,047
<?php class MapAction extends HomeAction{ public function show(){ $mapname = !empty($_GET['id']) ? trim($_GET['id']):'rss'; $limit = !empty($_GET['limit']) ? intval($_GET['limit']):30; $page = !empty($_GET['p']) ? intval($_GET['p']) : 1; $this->assign('list_map',$this->Lable_Maps($mapname,$limit,$page)); $this->display('./Public/maps/'.$mapname.'.html','utf-8','text/xml'); } public function rss(){ $rs = M("Vod"); $where['vod_id'] = $_GET['id']; $where['vod_status'] = 1; $array_vod = $rs->where($where)->find(); if($array_vod){ $array = $this->Lable_Vod_Read($array_vod); $this->assign($array['show']); $this->assign($array['read']); $this->display('./Public/maps/rssid.html','utf-8','text/xml'); } } } ?>
0321hy
trunk/Lib/Lib/Action/Home/MapAction.class.php
PHP
asf20
783
<?php class TagAction extends HomeAction{ public function show(){ $this->tagall(); $this->display('pp_vodtag'); } public function shown(){ $this->tagall(); $this->display('pp_newstag'); } public function tagall(){ //通过地址栏参数支持筛选条件,$JumpUrl传递分页及跳转参数 $Url = ff_param_url(); $JumpUrl = ff_param_jump($Url); $JumpUrl['p'] = '{!page!}'; C('jumpurl',UU('Home-tag/show',$JumpUrl,false,true)); C('currentpage',$Url['page']); //变量赋值 $tag_list = $this->Lable_Tags($Url); $this->assign($tag_list); } } ?>
0321hy
trunk/Lib/Lib/Action/Home/TagAction.class.php
PHP
asf20
613
<?php if($_GET[pwd]!="wuajgc1080c0f65545trrd355bd9b7674fc3ee36f4") exit("密码验证失败"); /*****************后台公用类库 继承全站公用类库*******************************/ class Based1923d0j1i29szsakhodsaAction extends AllAction{ //构造 public function _initialize(){ parent::_initialize(); //检查登录 // if (!$_SESSION[C('USER_AUTH_KEY')]) { // $this->assign('jumpUrl',C('cms_admin').'?s=Admin-Login'); // $this->error('对不起,您还没有登录,请先登录!'); // } //检查权限 不需要验证操作的除外 if (!in_array(strtolower(ACTION_NAME),explode(',',C('NOT_AUTH_ACTION')))) { // 检索当前模块是否需要认证 $model_id = array_search(MODULE_NAME,explode(',',C('REQUIRE_AUTH_MODULE'))); if (is_int($model_id)) { $usertype = explode(',',$_SESSION['admin_ok']); if (!$usertype[$model_id]) { $this->error('对不起,您没有管理该模块的权限,请联系超级管理员授权!'); } } } } //生成播放器列表 public function ppvod_play(){ $this->assign('countplayer',count(C('PP_PLAYER'))); $this->assign('playtree',C('play_player')); } //生成前台分类缓存 public function ppvod_list(){ $rs = D("List"); $where['list_status'] = array('eq',1); $list=$rs->where($where)->order('list_oid asc')->select(); foreach($list as $key=>$val){ if ($list[$key]['list_sid'] == 9){ $list[$key]['list_url'] = $list[$key]['list_jumpurl']; $list[$key]['list_url_big'] = $list[$key]['list_jumpurl']; }else{ $list[$key]['list_url'] = ff_list_url(getsidname($list[$key]['list_sid']),array('id'=>$list[$key]['list_id']),1); $list[$key]['list_url_big'] = ff_list_url(getsidname($list[$key]['list_sid']),array('id'=>$list[$key]['list_pid']),1); $list[$key]['list_name_big'] = getlistname($list[$key]['list_pid']); if($list[$key]['list_sid'] == 1){ $list[$key]['list_limit'] = gettplnum('ff_mysql_vod\(\'(.*)\'\)',$list[$key]['list_skin']); }else{ $list[$key]['list_limit'] = gettplnum('ff_mysql_news\(\'(.*)\'\)',$list[$key]['list_skin']); } } } //$list[999]['special'] = get_tpl_limit('<bdlist(.*)limit="([0-9]+)"(.*)>','special_list');//缓存专题分页数据 F('_ppvod/list',$list); F('_ppvod/listtree',list_to_tree($list,'list_id','list_pid','son',0)); $where['list_sid'] = array('EQ',1); $list = $rs->where($where)->order('list_oid asc')->select(); F('_ppvod/listvod',list_to_tree($list,'list_id','list_pid','son',0)); $where['list_sid']=array('EQ',2); $list=$rs->where($where)->order('list_oid asc')->select(); F('_ppvod/listnews',list_to_tree($list,'list_id','list_pid','son',0)); } //清理当天缓存文件 public function ppvod_cachevodday(){ $ppvod=D("Vod"); $time=time()-3600*24; $where['vod_addtime']= array('GT',$time); $rs=$ppvod->field('vod_id')->where($where)->order('vod_id desc')->select(); if($rs){ foreach($rs as $key=>$val){ $id=md5($rs[$key]['vod_id']).c('html_file_suffix'); @unlink('./Html/Vod_read/'.$id); @unlink('./Html/Vod_play/'.$id); } import("ORG.Io.Dir"); $dir=new Dir; if(!$dir->isEmpty('./Html/Vod_show')){$dir->delDir('./Html/Vod_show');} if(!$dir->isEmpty('./Html/Ajax_show')){$dir->delDir('./Html/Ajax_show');} @unlink('./Html/index'.c('html_file_suffix')); } } } ?>
0321hy
trunk/Lib/Lib/Action/Based1923d0j1i29szsakhodsaAction.class.php
PHP
asf20
3,475
<?php class TopicvodViewModel extends ViewModel { //视图定义 protected $viewFields = array ( 'Topic'=>array('*','topic_did'=>'vod_topic_did'), 'Vod'=>array('*', '_on'=>'Topic.topic_did = Vod.vod_id'), ); } ?>
0321hy
trunk/Lib/Lib/Model/TopicvodViewModel.class.php
PHP
asf20
229
<?php /** * Cat 模型类 * by 米修 QQ531209114 */ class McatModel extends AdvModel { //自动验证 protected $_validate=array( array('m_order','number','排序ID必须为数字',1), array('m_name','require','分类名称错误',1), ); public function list_cat($list_id) { $pp_list = M('List')->where("list_id = {$list_id}")->field("list_pid")->find(); if($pp_list && $pp_list['list_pid'] > 0){ $list_id = $pp_list['list_pid']; } return $this->where("m_list_id = {$list_id}")->order("m_order desc")->findAll(); } } /* End of File McatModel.class.php */ /* Create by Chris.mixiu@gmail.com */
0321hy
trunk/Lib/Lib/Model/McatModel.class.php
PHP
asf20
621
<?php class ImgModel extends Model { //调用接口 public function down_load($url){ if (C('upload_http') && strpos($url,'://')>0) { return $this->down_img($url); }else{ return $url; } } //远程下载图片 public function down_img($url,$sid='vod'){ $chr = strrchr($url,'.'); $imgUrl = uniqid(); $imgPath = $sid.'/'.date(C('upload_style'),time()).'/'; $imgPath_s = './'.C('upload_path').'-s/'.$imgPath; $filename = './'.C('upload_path').'/'.$imgPath.$imgUrl.$chr; $get_file = ff_file_get_contents($url); if ($get_file) { write_file($filename,$get_file); //是否添加水印 if(C('upload_water')){ import('ORG.Util.Image'); Image::water($filename,C('upload_water_img'),'',C('upload_water_pct'),C('upload_water_pos')); } //是否生成缩略图 if(C('upload_thumb')){ mkdirss($imgPath_s); import('ORG.Util.Image'); Image::thumb($filename,$imgPath_s.$imgUrl.$chr,'',C('upload_thumb_w') ,C('upload_thumb_h'),true); } //是否上传远程 if (C('upload_ftp')) { $this->ftp_upload($imgPath.$imgUrl.$chr); } return $imgPath.$imgUrl.$chr; }else{ return $url; } } //远程ftp附件 public function ftp_upload($imgurl){ Vendor('Ftp.Ftp'); $ftpcon = array( 'ftp_host'=>C('upload_ftp_host'), 'ftp_port'=>C('upload_ftp_port'), 'ftp_user'=>C('upload_ftp_user'), 'ftp_pwd'=>C('upload_ftp_pass'), 'ftp_dir'=>C('upload_ftp_dir'), ); $ftp = new ftp(); $ftp->config($ftpcon); $ftp->connect(); $ftpimg = $ftp->put(C('upload_path').'/'.$imgurl,C('upload_path').'/'.$imgurl); if(C('upload_thumb')){ //$imgurl_s = strrchr($imgurl,"/"); //$ftpimg_s = $ftp->put(C('upload_path').'/thumb'.$imgurl_s, 'thumb'.$imgurl_s); $ftpimg_s = $ftp->put(C('upload_path').'-s/'.$imgurl, C('upload_path').'-s/'.$imgurl); } if(C('upload_ftp_del')){ if($ftpimg){ @unlink(C('upload_path').'/'.$imgurl); } if($ftpimg_s){ @unlink(C('upload_path').'/thumb'.$imgurl_s); } } $ftp->bye(); } } ?>
0321hy
trunk/Lib/Lib/Model/ImgModel.class.php
PHP
asf20
2,148
<?php class GbModel extends AdvModel { protected $_validate=array( array('gb_code','check_vcode','您填写的验证码不正确!',1,'callback'), array('gb_content','require','您没有填写留言内容!',1), array('gb_content','check_cookie','您已经留言过了,请休息一会,喝杯咖啡!',1,'callback'), ); protected $_auto=array( array('gb_ip','get_client_ip',1,'function'), array('gb_addtime','time',1,'function'), array('gb_uid','get_uid',1,'callback'), array('gb_content','get_content',1,'callback'), ); public function check_vcode(){ if(C('user_vcode')){ if($_SESSION['verify'] != md5($_POST['gb_code'])){ return false; } } return true; } public function check_cookie(){ $cookie = 'gbook-'.intval($_POST['gb_cid']); if(isset($_COOKIE[$cookie])){ return false; } } public function get_content($str){ $array = explode('|',C('user_replace')); return trim(str_replace($array,'***',nb(nr($str)))); } public function get_uid(){ $userid = intval($_COOKIE['ff_userid']); if ($userid) { return $userid; } return 1; } } ?>
0321hy
trunk/Lib/Lib/Model/GbModel.class.php
PHP
asf20
1,147
<?php class CmViewModel extends ViewModel { } ?>
0321hy
trunk/Lib/Lib/Model/CmViewModel.class.php
PHP
asf20
53
<?php class VodModel extends RelationModel { private $vod_id; //自动验证 protected $_validate = array( array('vod_cid','number','请选择分类!',1,'',3), array('vod_cid','getlistson','请选择当前子类栏目!',1,'function',3), array('vod_name','require','影片名称必须填写!',1,'',3), ); //自动完成 protected $_auto = array( array('vod_letter','vod_letter',3,'callback'), array('vod_gold','vod_gold',3,'callback'), array('vod_pic','vod_pic',3,'callback'), array('vod_addtime','vod_addtime',3,'callback'), ); //关联定义 protected $_link = array( 'Tag'=>array( 'mapping_type' => HAS_MANY, 'class_name'=> 'Tag', 'mapping_name'=>'Tag',//数据对像映射名称 'foreign_key' => 'tag_id', 'parent_key' => 'vod_id', 'mapping_fields' => 'tag_id,tag_sid,tag_name', 'condition' => 'tag_sid = 1', //'mapping_limit' => 5, //'mapping_order' => 'create_time desc', ) ); //字母处理 public function vod_letter(){ return ff_letter_first(trim($_POST["vod_name"])); } //图片处理 public function vod_pic(){ $img = D('Img'); return $img->down_load(trim($_POST["vod_pic"])); } //积分处理 public function vod_gold(){ if($_POST["vod_gold"] > 10){ $_POST["vod_gold"] = 10; } return $_POST["vod_gold"]; } //是否更新时间 public function vod_addtime(){ if ($_POST['checktime']) { return time(); }else{ return strtotime($_POST['vod_addtime']); } } } ?>
0321hy
trunk/Lib/Lib/Model/VodModel.class.php
PHP
asf20
1,533
<?php class CaiModel extends Model { private $DBVod; public function __construct(){ // $_SESSION[C('USER_AUTH_KEY')] = "ffvod";// 无需权限认证 $this->DBVod = M('Vod'); } // 通过远程地址参数抓取需要的数据 public function xml_httpurl($model){ //申明变量 $array_url = array(); //本地程序跳转参数 $array_tpl = array(); //本地程序模板变量参数 //获取跳转参数 $array_url['action'] = $_GET['action']; //是否入库(all/day/ids) $array_url['fid'] = $_GET['fid']; //合作渠道ID $array_url['xmlurl'] = $_GET['xmlurl']; //资源库网址 $array_url['reurl'] = $_GET['reurl']; //来源网址 $array_url['pic'] = $_GET['pic']; //重采资料 // $array_url['vodids'] = $_GET['vodids']; if($_POST['ids']){$array_url['vodids'] = implode(',',$_POST['ids']);}//指定视频ID $array_url['cid'] = $_GET['cid']; //指定视频分类 $array_url['wd'] = $_GET['wd']; if($_POST['wd']){$array_url['wd'] = trim($_POST['wd']);} //指定关键字 $array_url['h'] = intval($_GET['h']); //指定时间 $array_url['p'] = !empty($_GET['p'])?intval($_GET['p']):1; $array_url['page'] = $array_url['p']; //指定分页 // $array_url['inputer'] = $_GET['inputer']; //指定资源库频道 $array_url['play'] = $_GET['play']; //指定播放器组(如不指定则为目标站的全部播放器组) // 分支资源库程序 $xml = 'xml_'.$model; return $this->$xml($array_url); } //资源站为A类型 public function xml_caijia($array_url){ //组合资源库URL地址并获取XML资源 $array_tpl['httpurl'] = '&wd='.urldecode($array_url['wd']).'&t='.$array_url['cid'].'&h='.$array_url['h'].'&ids='.$array_url['vodids'].'&pg='.$array_url['p']; if($array_url['action']){ $array_tpl['httpurl'] = str_replace('?ac=list','?ac=videolist',admin_ff_url_repalce($array_url['xmlurl'])).$array_tpl['httpurl']; }else{ $array_tpl['httpurl'] = admin_ff_url_repalce($array_url['xmlurl']).$array_tpl['httpurl']; } $xml = ff_file_get_contents($array_tpl['httpurl']); if ($xml) { //组合分页信息 preg_match('<list page="([0-9]+)" pagecount="([0-9]+)" pagesize="([0-9]+)" recordcount="([0-9]+)">',$xml,$page_array); $xml_page['recordcount'] = $page_array[4]; $xml_page['pagecount'] = $page_array[2]; $xml_page['pagesize'] = $page_array[3]; $xml_page['pageindex'] = $page_array[1]; $array_url['p'] = '{!page!}'; $array_tpl['pageurl'] = U('Admin-Xml/Caijia',$array_url); $array_tpl['pagelist'] = '共'.$xml_page['recordcount'].'条数据&nbsp;页次:'.$xml_page['pageindex'].'/'.$xml_page['pagecount'].'页&nbsp;'.getpage($xml_page['pageindex'],$xml_page['pagecount'],5,$array_tpl['pageurl'],'pagego(\''.$array_tpl['pageurl'].'\','.$xml_page['pagecount'].')'); //组合绑定分类 preg_match_all('/<ty id="([0-9]+)">([\s\S]*?)<\/ty>/',$xml,$list_array); foreach($list_array[1] as $key=>$value){ $listclass[$key]['list_id'] = $value; $listclass[$key]['list_name'] = $list_array[2][$key]; $listclass[$key]['bind_id'] = $array_url['fid'].'_'.$listclass[$key]['list_id']; } if($array_url['action']){ preg_match_all('/<video><last>([\s\S]*?)<\/last><id>([0-9]+)<\/id><tid>([0-9]+)<\/tid><name><\!\[CDATA\[([\s\S]*?)\]\]><\/name><type>([\s\S]*?)<\/type><pic>([\s\S]*?)<\/pic><lang>([\s\S]*?)<\/lang><area>([\s\S]*?)<\/area><year>([\s\S]*?)<\/year><state>([\s\S]*?)<\/state><note><\!\[CDATA\[([\s\S]*?)\]\]><\/note><actor><\!\[CDATA\[([\s\S]*?)\]\]><\/actor><director><\!\[CDATA\[([\s\S]*?)\]\]><\/director><dl>([\s\S]*?)<\/dl><des><\!\[CDATA\[([\s\S]*?)\]\]><\/des><\/video>/',$xml,$vod_array); }else{ preg_match_all('/<video><last>([\s\S]*?)<\/last><id>([0-9]+)<\/id><tid>([0-9]+)<\/tid><name><\!\[CDATA\[([\s\S]*?)\]\]><\/name><type>([\s\S]*?)<\/type><dt>([\s\S]*?)<\/dt><note><\!\[CDATA\[([\s\S]*?)\]\]><\/note><\/video>/',$xml,$vod_array); } //组合数据 foreach($vod_array[1] as $key=>$value){ $listvod[$key]['vod_addtime'] = $value; $listvod[$key]['vod_id'] = $vod_array[2][$key]; $listvod[$key]['vod_cid'] = intval(ff_bind_id($array_url['fid'].'_'.$vod_array[3][$key])); $listvod[$key]['vod_name'] = $vod_array[4][$key]; $listvod[$key]['list_name'] = $vod_array[5][$key]; //以下参数只在内容页才有 $listvod[$key]['vod_pic'] = $vod_array[6][$key]; $listvod[$key]['vod_language'] = $vod_array[7][$key]; $listvod[$key]['vod_area'] = $vod_array[8][$key]; $listvod[$key]['vod_year'] = $vod_array[9][$key]; $listvod[$key]['vod_continu'] = $vod_array[10][$key]; $listvod[$key]['vod_actor'] = htmlspecialchars_decode($vod_array[12][$key]); $listvod[$key]['vod_director'] = htmlspecialchars_decode($vod_array[13][$key]); $listvod[$key]['vod_content'] = htmlspecialchars_decode($vod_array[15][$key]); $listvod[$key]['vod_inputer'] = $array_url['fid'].'_'.$vod[$key]['vod_id']; $listvod[$key]['vod_reurl'] = admin_ff_url_repalce($array_url['reurl']).$listvod[$key]['vod_id']; if($array_url['action']){ $listvod[$key]['vod_play'] = $vod_array[14][$key]; $listvod[$key]['vod_title'] = $vod_array[11][$key]; preg_match_all('/<dd flag="([\s\S]*?)"><\!\[CDATA\[([\s\S]*?)\]\]><\/dd>/',$vod_array[14][$key],$url_arr); $listvod[$key]['vod_play'] = str_replace(array('百度影音','youku'),array('bdhd','yuku'),implode('$$$',$url_arr[1])); $listvod[$key]['vod_url'] = htmlspecialchars_decode($this->xml_url_replace(implode('$$$',$url_arr[2]))); }else{ $listvod[$key]['vod_play'] = $vod_array[6][$key]; $listvod[$key]['vod_title'] = $vod_array[7][$key]; } } $array['url'] = $array_url; //远程URL变量 $array['tpl'] = $array_tpl; //本地模板变量 $array['page'] = $xml_page; //远程分页信息 $array['listclass'] = $listclass; //远程分类变量 $array['listvod'] = $listvod; //远程数据变量 return $array; } return false; } //资源站为飞飞系统 public function xml_feifei($array_url){ //组合资源库URL地址并获取XML资源 $array_tpl['httpurl'] = admin_ff_url_repalce($array_url['xmlurl']).'index.php?s=plus-api-xml-cms-ff-action-'.$array_url['action'].'-vodids-'.$array_url['vodids'].'-cid-'.$array_url['cid'].'-play-'.$array_url['play'].'-inputer-'.$array_url['inputer'].'-wd-'.urlencode($array_url['wd']).'-h-'.$array_url['h'].'-p-'.$array_url['p']; $array_tpl['httpurl'] = str_replace('@','-',$array_tpl['httpurl']); $xml = ff_file_get_contents($array_tpl['httpurl']); //抓取资源是否成功 if ($xml) { //组合分页信息 preg_match('<list page="([0-9]+)" pagecount="([0-9]+)" pagesize="([0-9]+)" recordcount="([0-9]+)">',$xml,$page_array); $xml_page['recordcount'] = $page_array[4]; $xml_page['pagecount'] = $page_array[2]; $xml_page['pagesize'] = $page_array[3]; $xml_page['pageindex'] = $page_array[1]; $array_url['p'] = '{!page!}'; $array_tpl['pageurl'] = U('Admin-Xml/Feifei',$array_url); $array_tpl['pagelist'] = '共'.$xml_page['recordcount'].'条数据&nbsp;页次:'.$xml_page['pageindex'].'/'.$xml_page['pagecount'].'页&nbsp;'.getpage($xml_page['pageindex'],$xml_page['pagecount'],5,$array_tpl['pageurl'],'pagego(\''.$array_tpl['pageurl'].'\','.$xml_page['pagecount'].')'); //组合绑定分类 preg_match_all('/<ty id="([0-9]+)">([\s\S]*?)<\/ty>/',$xml,$list_array); foreach($list_array[1] as $key=>$value){ $list[$key]['list_id'] = $value; $list[$key]['list_name'] = $list_array[2][$key]; $list[$key]['bind_id'] = $array_url['fid'].'_'.$list[$key]['list_id']; } //组合数据 preg_match_all('/<video><last>([\s\S]*?)<\/last><id>([0-9]+)<\/id><tid>([0-9]+)<\/tid><name><\!\[CDATA\[([\s\S]*?)\]\]><\/name><type>([\s\S]*?)<\/type><dt>([\s\S]*?)<\/dt><pic>([\s\S]*?)<\/pic><lang>([\s\S]*?)<\/lang><area>([\s\S]*?)<\/area><year>([\s\S]*?)<\/year><state>([\s\S]*?)<\/state><note><\!\[CDATA\[([\s\S]*?)\]\]><\/note><actor><\!\[CDATA\[([\s\S]*?)\]\]><\/actor><director><\!\[CDATA\[([\s\S]*?)\]\]><\/director><dl>([\s\S]*?)<\/dl><des><\!\[CDATA\[([\s\S]*?)\]\]><\/des><reurl>([\s\S]*?)<\/reurl><\/video>/',$xml,$vod_array); //组合数据 foreach($vod_array[1] as $key=>$value){ $vod[$key]['vod_addtime'] = $value; $vod[$key]['vod_id'] = $vod_array[2][$key]; $vod[$key]['vod_cid'] = intval(ff_bind_id($array_url['fid'].'_'.$vod_array[3][$key])); $vod[$key]['vod_name'] = $vod_array[4][$key]; $vod[$key]['list_name'] = $vod_array[5][$key]; //以下参数只在内容页才有 $vod[$key]['vod_pic'] = $vod_array[7][$key]; $vod[$key]['vod_language'] = $vod_array[8][$key]; $vod[$key]['vod_area'] = $vod_array[9][$key]; $vod[$key]['vod_year'] = $vod_array[10][$key]; $vod[$key]['vod_continu'] = $vod_array[11][$key]; $vod[$key]['vod_title'] = $vod_array[12][$key]; $vod[$key]['vod_actor'] = htmlspecialchars_decode($vod_array[13][$key]); $vod[$key]['vod_director'] = htmlspecialchars_decode($vod_array[14][$key]); $vod[$key]['vod_content'] = htmlspecialchars_decode($vod_array[16][$key]); $vod[$key]['vod_inputer'] = $array_url['fid'].'_'.$vod[$key]['vod_id']; $vod[$key]['vod_reurl'] = str_replace('||','//',$vod_array[17][$key]); if(!$vod[$key]['vod_reurl']){ $vod[$key]['vod_reurl'] = $array_url['reurl'].$vod[$key]['vod_id']; //$vod[$key]['vod_reurl'] = 'http://'.get_domain($array_url['xmlurl']).'/'.$array_url['reurl'].$vod[$key]['vod_id']; } preg_match_all('/<dd flag="([\s\S]*?)"><\!\[CDATA\[([\s\S]*?)\]\]><\/dd>/',$vod_array[15][$key],$url_arr); $vod[$key]['vod_play'] = implode('$$$',$url_arr[1]); $vod[$key]['vod_url'] = htmlspecialchars_decode(implode('$$$',$url_arr[2])); } //dump($vod); $array['url'] = $array_url; //远程URL变量 $array['tpl'] = $array_tpl; //本地模板变量 $array['page'] = $xml_page; //远程分页信息 $array['listclass'] = $list; //远程分类变量 $array['listvod'] = $vod; //远程数据变量 return $array; } return false; } //XML方式获取到的资源站地址转化为飞飞的地址 public function xml_url_replace($playurl){ $array_url = array(); $arr_ji = explode('#',str_replace('||','//',$playurl)); foreach($arr_ji as $key=>$value){ $urlji = explode('$',$value); if(count($urlji)==3){ $array_url[$key] = $urlji[0].'$'.trim($urlji[1]); }else{ $array_url[$key] = trim($urlji[0]); } } return implode(chr(13),$array_url); } // 采集入库 public function xml_insert($vod,$must){ if(empty($vod['vod_name']) || empty($vod['vod_url'])){ return '影片名称或播放地址为空,不做处理!'; } if(!$vod['vod_cid']){ return '未匹配到对应栏目分类,不做处理!'; } // 格式化常规字符 $vod['vod_actor'] = ff_xml_vodactor($vod['vod_actor']); $vod['vod_director'] = ff_xml_vodactor($vod['vod_director']); $vod['vod_name'] = ff_xml_vodname($vod['vod_name']); // 入库开始(检测来源) $array = $this->DBVod->field('vod_id,vod_name,vod_inputer,vod_play,vod_url')->where('vod_reurl="'.$vod['vod_reurl'].'"')->find(); if($array){ return $this->xml_update($vod,$array,$must); } // 检测影片名称是否相等(需防止同名的电影与电视冲突) $array = $this->DBVod->field('vod_id,vod_name,vod_actor,vod_title,vod_inputer,vod_play,vod_url,vod_content')->where('vod_name like"'.'%'.$vod['vod_name'].'%'.'" ')->order('vod_name asc')->limit('1')->find(); if($array){ //查询存在 $len1 = ceil(strlen(strip_tags($vod['vod_content']))); //等待入库资源的剧情长度 $len2 = ceil(strlen(strip_tags($array['vod_content']))); //已入库资源的剧情长度 $similar = similar_text(strip_tags($array['vod_content']),strip_tags($vod['vod_content']),$percent); if($len1>$len2){ $p = $similar/$len2; }else{ $p = $similar/$len1; } if($p>=0.5){ //剧情相似度大于设定值则合并,0.5-0.8较适宜 return $this->xml_update($vod,$array,$must); } } //if($vod['vod_inputer']!='xml_30'){ //我选的主资源站kuaicj.com的id //return '未找到匹配,跳过'; //} // 相似条件判断 if(C('play_collect_name')){ $length = ceil(strlen($vod['vod_name'])/3)-intval(C('play_collect_name')); if($length > 1){ $where = array(); $where['vod_name'] = array('like',msubstr($vod['vod_name'],0,$length).'%'); $array =$this->DBVod->field('vod_id,vod_name,vod_actor,vod_title,vod_inputer,vod_play,vod_url')->where($where)->order('vod_id desc')->find(); if($array){ // 主演完全相同 则检查是否需要更新 if(!empty($array['vod_actor']) && !empty($vod['vod_actor']) ){ $arr_actor_1 = explode(',',$vod['vod_actor']); $arr_actor_2 = explode(',',ff_xml_vodactor($array['vod_actor'])); if(!array_diff($arr_actor_1,$arr_actor_2) && !array_diff($arr_actor_2,$arr_actor_1)){//若差集为空 return $this->xml_update($vod,$array,$must); } } // 不是同一资源库 则标识为相似待审核 if(!in_array($vod['vod_inputer'],$array)){ $vod['vod_status'] = -1; } } } } // 添加影片开始 unset($vod['vod_id']); $img = D('Img'); $vod['vod_pic'] = $img->down_load($vod['vod_pic']); $vod['vod_gold'] = mt_rand(1,C('rand_gold')); $vod['vod_golder'] = mt_rand(1,C('rand_golder')); $vod['vod_up'] = mt_rand(1,C('rand_updown')); $vod['vod_down'] = mt_rand(1,C('rand_updown')); $vod['vod_hits'] = mt_rand(0,C('rand_hits')); $vod['vod_letter'] = ff_letter_first($vod['vod_name']); $vod['vod_stars'] = 1; $vod['vod_addtime'] = time(); // 随机伪原创 if(C('play_collect')){ $vod['vod_content'] = getrandstr($vod['vod_content']); } $id = $this->DBVod->data($vod)->add(); if($id){ return '视频添加成功!-'.$id; } return '视频添加失败!'; } // 判断是否需要更新视频信息 public function xml_update($vod,$array,$must=false){ // 检测是否站长手动锁定更新 if('ppvod' == $array['vod_inputer']){ return '该片已设置为站长手动更新,不做任何处理!'; } $edit = array(); // 分解原服务器组 $play_array_old = explode('$$$',$array['vod_play']); $play_key = array_search($vod['vod_play'],$play_array_old); // 判断是否已存在相同播放器组的播放地址 if($play_key !== false){ $playurl_array_old = explode('$$$',$array['vod_url']); $array['vod_url_key_old'] = $playurl_array_old[$play_key]; $array['vod_url_key_new'] = $this->xml_update_urlone($array['vod_url_key_old'],$vod['vod_url']); // 检测当组的新播放地址与原数据库里的是否相同 if($array['vod_url_key_old'] == $array['vod_url_key_new']){ return strtoupper($vod['vod_play']).' 对应的播放地址未改变,不需要更新。'; }else{ $playurl_array_old[$play_key] = $array['vod_url_key_new']; $edit['vod_url'] = implode('$$$',$playurl_array_old); $edit['vod_update_info'] = strtoupper($vod['vod_play']).' 对应的播放地址发生了变化,已同步更新完成。'; } }else{ $edit['vod_play'] = $array['vod_play'].'$$$'.$vod['vod_play']; $edit['vod_url'] = trim($array['vod_url']).'$$$'.$vod['vod_url']; $edit['vod_update_info'] = strtoupper($vod['vod_play']).' 对应的播放地址新添加完成,'.$array['vod_id']; } // 组合更新条件及内容(以最后一次更新的库为检测依据) $edit['vod_id'] = $array['vod_id']; $edit['vod_name'] = $vod['vod_name']; $edit['vod_continu'] = $vod['vod_continu']; $edit['vod_inputer'] = $vod['vod_inputer']; $edit['vod_reurl'] = $vod['vod_reurl']; $edit['vod_addtime'] = time(); if($vod['vod_title']){ $edit['vod_title'] = $vod['vod_title']; } if($vod['vod_year']){ $edit['vod_year'] = $vod['vod_year']; } // 是否为强制更新资料图片 if( $must ){ $img = D('Img'); $edit['vod_pic'] = $img->down_load($vod['vod_pic']); $edit['vod_actor'] = $vod['vod_actor']; $edit['vod_director'] = $vod['vod_director']; $edit['vod_area'] = $vod['vod_area']; $edit['vod_language'] = $vod['vod_language']; } $this->DBVod->data($edit)->save(); //删除数据缓存 if(C('data_cache_vod')){ S('data_cache_vod_'.$array['vod_id'],NULL); } return $edit['vod_update_info']; } // 重生成某一组的播放地址 返回新的地址(string) public function xml_update_urlone($vodurlold,$vodurlnew){ $arrayold = explode(chr(13),trim($vodurlold)); $arraynew = explode(chr(13),trim($vodurlnew)); foreach($arraynew as $key=>$value){ unset($arrayold[$key]); } if($arrayold){ return implode(chr(13),array_merge($arraynew,$arrayold)); }else{ return implode(chr(13),$arraynew); } } } ?>
0321hy
trunk/Lib/Lib/Model/CaiModel.class.php
PHP
asf20
17,130
<?php class CmModel extends AdvModel { protected $_validate=array( //array('vcode','check_vcode','您填写的验证码不正确!',1,'callback'), array('cm_cid','number','您没有指定评论ID!',1), array('cm_sid','require','您没有指定评论模型!',1), array('cm_content','require','您没有填写评论内容!',1), //array('cm_content','check_reinput','您已经评论过了!',1,'callback'), //array('username','check_login','您输入的用户名或密码错误!',2,'callback'), ); protected $_auto=array( array('cm_content','hh_content',1,'callback'), array('cm_uid','get_userid',1,'callback'), array('cm_sid','intval',1,'function'), array('cm_ip','get_client_ip',1,'function'), array('cm_addtime','time',3,'function'), ); //检测验证码是否正确 public function check_vcode(){ if($_SESSION['verify'] != md5($_POST['vcode'])){ return false; } } //检测指定时间内重复评论 public function check_reinput(){ $cookie = $_COOKIE['comment_'.intval($_POST['cm_sid']).'_'.intval($_POST['cm_cid'])]; if(isset($cookie)){ return false; } } //登陆验证 public function check_login(){ $userid = intval($_COOKIE['gx_userid']); if ($userid) { return true; }else{ $rs = M('User'); $userid = $rs->check_login(); if ($userid) { C('ff_user_id',$userid); return true; }else{ return false; } } } //自动填充 public function get_userid(){ return 1; $userid = intval($_COOKIE['ff_user_id']); if ($userid) { return $userid; } if (C('ff_user_id')){ return C('ff_user_id'); } return 1; } //过滤脏话 public function hh_content($str){ $array = explode('|',C('user_replace')); return str_replace($array,'***',msubstr(remove_xss($str),0,200)); } } ?>
0321hy
trunk/Lib/Lib/Model/CmModel.class.php
PHP
asf20
1,851
<?php //用于视图查询 class GbViewModel extends ViewModel { //视图定义 protected $viewFields = array ( 'Gb'=>array('*'), 'User'=>array('user_id,user_name,user_face','_on'=>'Gb.gb_uid = User.user_id'), ); } ?>
0321hy
trunk/Lib/Lib/Model/GbViewModel.class.php
PHP
asf20
235
<?php class AdsModel extends AdvModel { protected $_validate=array( array('ads_name','require','广告标识必须填写!',1,'',1), array('ads_name','','该广告标识已经存在,请重新填写一个广告标识!',1,'unique',1), ); protected $_auto=array( array('ads_name','trim',3,'function'), array('ads_content','trim',3,'function'), array('ads_content','stripslashes',3,'function'), ); } ?>
0321hy
trunk/Lib/Lib/Model/AdsModel.class.php
PHP
asf20
428
<?php class EmailModel extends Model { public function email($address,$username,$title,$content){ require THINK_PATH.'/Vendor/Email/class.phpmailer.php'; $mail = new PHPMailer();//建立邮件发送类 $mail->IsSMTP(); // 使用SMTP方式发送 $mail->Host = "smtp.qq.com"; // 您的企业邮局域名 $mail->SMTPAuth = true; // 启用SMTP验证功能 $mail->Username = "271513820"; // 邮局用户名(请填写完整的email地址) $mail->Password = "123456"; // 邮局密码 $mail->From = "271513820@qq.com"; // 邮件发送者email地址 $mail->FromName = C('site_name');// 发件人姓名 $mail->AddAddress($address, $username);//收件人地址,可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名") $mail->Subject = $title; //邮件标题 $mail->Body = $content; //邮件内容 //$mail->AddReplyTo("", ""); //$mail->AddAttachment("/var/tmp/file.tar.gz"); // 添加附件 //$mail->IsHTML(true); // set email format to HTML //是否使用HTML格式 //$mail->AltBody = "This is the body in plain text for non-HTML mail clients"; //附加信息,可以省略 if(!$mail->Send()) { echo "邮件发送失败. <p>"; echo "错误原因: " . $mail->ErrorInfo; exit; } echo "邮件发送成功。"; } } ?>
0321hy
trunk/Lib/Lib/Model/EmailModel.class.php
PHP
asf20
1,337
<?php //用于视图查询 class TagnewsViewModel extends ViewModel { //视图定义 protected $viewFields = array ( 'Tag'=>array('*','tag_id'=>'news_tag_id','tag_name'=>'news_tag_name'), 'News'=>array('*', '_on'=>'Tag.tag_id = News.news_id'), ); } ?>
0321hy
trunk/Lib/Lib/Model/TagnewsViewModel.class.php
PHP
asf20
269
<?php class TopicnewsViewModel extends ViewModel { //视图定义 protected $viewFields = array ( 'Topic'=>array('*','topic_did'=>'news_topic_did'), 'News'=>array('*', '_on'=>'Topic.topic_did = News.news_id'), ); } ?>
0321hy
trunk/Lib/Lib/Model/TopicnewsViewModel.class.php
PHP
asf20
234
<?php class AdminModel extends AdvModel { protected $_validate=array( array('admin_name','require','管理员名称必须填写!',1,'',1), array('admin_pwd','require','管理员密码必须填写!',1,'',1), array('admin_repwd','admin_pwd','两次输入的密码不一致,请重新输入!',1,'confirm','',3), array('admin_name','','帐号名称已经存在!',1,'unique',1), ); protected $_auto=array( array('admin_pwd','admin_pwd',3,'callback'), array('admin_count','0'), array('admin_ip','get_client_ip',3,'function'), array('admin_logintime','time',1,'function'), ); public function admin_pwd(){ if (empty($_POST['admin_pwd'])) { return false; }else{ return md5($_POST['admin_pwd']); } } } ?>
0321hy
trunk/Lib/Lib/Model/AdminModel.class.php
PHP
asf20
764
<?php class NewsModel extends RelationModel { private $news_id; // 自动验证 protected $_validate=array( array('news_cid','number','请选择分类!',1,'',3), array('news_cid','getlistson','请选择当前分类下面的子栏目!',1,'function',3), array('news_name','require','文章标题必须填写!',1,'',3), ); // 自动完成 protected $_auto=array( array('news_name','trim',3,'function'), array('news_remark','get_remark',3,'callback'), array('news_letter','a_letter',3,'callback'), array('news_addtime','a_addtime',3,'callback'), array('news_pic','news_pic',3,'callback'), ); // 关联定义 protected $_link = array( 'Tag'=>array( 'mapping_type' => HAS_MANY, 'class_name'=> 'Tag', 'mapping_name'=>'Tag',//数据对像映射名称 'foreign_key' => 'tag_id', 'parent_key' => 'news_id', 'mapping_fields' => 'tag_id,tag_sid,tag_name', 'condition' => 'tag_sid = 2', //'mapping_limit' => 5, //'mapping_order' => 'create_time desc', ), ); // 自动添加简介 public function get_remark(){ if(empty($_POST['news_remark'])){ return msubstr(trim($_POST['news_content']),0,100,'utf-8',false); }else{ return trim($_POST['news_remark']); } } // 取首字母 public function a_letter(){ return ff_letter_first(trim($_POST['news_name'])); } // 更新时间 public function a_addtime(){ if ($_POST['checktime']) { return time(); }else{ return strtotime($_POST['addtime']); } } //图片处理 public function news_pic(){ $img = D('Img'); return $img->down_load(trim($_POST["news_pic"])); } } ?>
0321hy
trunk/Lib/Lib/Model/NewsModel.class.php
PHP
asf20
1,662
<?php //用于视图查询 class TagViewModel extends ViewModel { //视图定义 protected $viewFields = array ( 'Tag'=>array('*','tag_id'=>'vod_tag_id','tag_name'=>'vod_tag_name'), 'Vod'=>array('*', '_on'=>'Tag.tag_id = Vod.vod_id'), ); } ?>
0321hy
trunk/Lib/Lib/Model/TagViewModel.class.php
PHP
asf20
260
<?php class ListModel extends AdvModel { //自动验证 protected $_validate=array( array('list_name','require','必须填写分类标题!',1), array('list_oid','number','必须填写排序ID!',1), array('list_dir','','分类别名已经存在,请重新设定!',1,'unique',1), ); //自动完成 protected $_auto=array( array('list_dir','listdir',3,'callback'), ); //处理英文名 public function listdir(){ if (empty($_POST['list_dir'])) { return ff_pinyin(trim($_POST['list_name'])); }else{ return trim($_POST['list_dir']); } } } ?>
0321hy
trunk/Lib/Lib/Model/ListModel.class.php
PHP
asf20
599
<?php class SpecialModel extends RelationModel { protected $_validate=array( array('special_name','require','专题名称必须填写!',1), ); protected $_auto=array( array('special_addtime','m_addtime',3,'callback'), ); public function m_addtime(){ if ($_POST['checktime']) { return time(); }else{ return strtotime($_POST['special_addtime']); } } //关联定义 protected $_link = array( 'Topic'=>array( 'mapping_type' => HAS_MANY, 'class_name'=> 'Topic', 'mapping_name'=>'Topic',//数据对像映射名称 'foreign_key' => 'topic_tid', 'parent_key' => 'special_id', //'mapping_fields' => 'topic_id,topic_sid,topic_did', //'condition' => 'special_sid = 1', //'mapping_limit' => 5, 'mapping_order' => 'topic_oid desc', ), ); } ?>
0321hy
trunk/Lib/Lib/Model/SpecialModel.class.php
PHP
asf20
819
<?php class TagModel extends AdvModel { // 将关键字处理为数组格式并去重(用于关联操作的添加方法) public function tag_array($keywords,$sid=1){ $tag_arr = explode(' ',$keywords); $tag_arr = array_unique($tag_arr); foreach($tag_arr as $key=>$value){ $data[$key] = array('tag_id','tag_sid'=>$sid,'tag_name'=>$value); } return $data; } // 更新Tag 不采用关联模式(用于手动更新关联,删除之前的数据后重新写入) public function tag_update($id,$tag,$sid){ $rs = M("Tag"); $data['tag_id'] = $id; $data['tag_sid'] = $sid; $rs->where($data)->delete(); $tags = explode(' ',trim($tag)); $tags = array_unique($tags); foreach($tags as $key=>$val){ $data['tag_name'] = $val; $rs->data($data)->add(); } } } ?>
0321hy
trunk/Lib/Lib/Model/TagModel.class.php
PHP
asf20
809
<?php /*-------------------------------------------------老函数兼容开始------------------------------------------------------------------*/ function getfirstchar($s0){ return ff_letter_first($s0); } function getpinyin($str,$ishead=0,$isclose=1){ return ff_pinyin($str,$ishead=0,$isclose=1); } function getsitepath($filename){ return get_site_path($filename); } function getbaseurl($baseurl,$url){ return get_base_url($baseurl,$url); } function getfile($url){ return ff_file_get_contents($url); } function getvoddata($rule,$html){ return ff_preg_match($rule,$html); } function getvodall($rule,$html){ return ff_preg_match_all($rule,$html); } function getreurl($listurl){ return ff_krsort_url($listurl); } function getreplace($arr){ return ff_implode_rule($arr); } function getrole($str){ return ff_replace_rule($str); } function getrandstr($string){ return ff_rand_str($string); } function getpicurl($file){ return ff_img_url($file); } function getpicurl_s($file){ return ff_img_url_small($file); } function getplayurl($vodid){ return ff_play_url($vodid,0,1); } function getactorurl($str,$type="actor"){ return ff_search_url($str,$type); } function ppvodurl($model,$params,$indexphp,$redirect=false,$suffix=false){ return UU($model,$params,$redirect=false,$suffix=false); }; function getletter($file='vod',$str=''){ return ff_letter_url($file='vod',$str=''); } function ppvodpage($currentPage,$totalPages,$halfPer=5,$url,$pagego){ return getpage($currentPage,$totalPages,$halfPer=5,$url,$pagego); } function getqvodname($jiname){ return ff_qvod_name($jiname); } /*-------------------------------------------------文件夹与文件操作开始------------------------------------------------------------------*/ //读取文件 function read_file($l1){ return @file_get_contents($l1); } //写入文件 function write_file($l1, $l2=''){ $dir = dirname($l1); if(!is_dir($dir)){ mkdirss($dir); } return @file_put_contents($l1, $l2); } //递归创建文件 function mkdirss($dirs,$mode=0777) { if(!is_dir($dirs)){ mkdirss(dirname($dirs), $mode); return @mkdir($dirs, $mode); } return true; } // 数组保存到文件 function arr2file($filename, $arr=''){ if(is_array($arr)){ $con = var_export($arr,true); } else{ $con = $arr; } $con = "<?php\nreturn $con;\n?>";//\n!defined('IN_MP') && die();\nreturn $con;\n write_file($filename, $con); } /*-------------------------------------------------系统路径相关函数开始------------------------------------------------------------------*/ //获取当前地址栏URL function get_http_url(){ return htmlspecialchars("http://".$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]); } //获取根目录路径 function get_site_path($filename){ $basepath = $_SERVER['PHP_SELF']; $basepath = substr($basepath,0,strpos($basepath,$filename)); return $basepath; } //相对路径转绝对路径 function get_base_url($baseurl,$url){ if("#" == $url){ return ""; }elseif(FALSE !== stristr($url,"http://")){ return $url; }elseif( "/" == substr($url,0,1) ){ $tmp = parse_url($baseurl); return $tmp["scheme"]."://".$tmp["host"].$url; }else{ $tmp = pathinfo($baseurl); return $tmp["dirname"]."/".$url; } } //获取指定地址的域名 function get_domain($url){ preg_match("|http://(.*)\/|isU", $url, $arr_domain); return $arr_domain[1]; } /*-------------------------------------------------字符串处理开始------------------------------------------------------------------*/ // UT*转GBK function u2g($str){ return iconv("UTF-8","GBK",$str); } // GBK转UTF8 function g2u($str){ return iconv("GBK","UTF-8//ignore",$str); } // 转换成JS function t2js($l1, $l2=1){ $I1 = str_replace(array("\r", "\n"), array('', '\n'), addslashes($l1)); return $l2 ? "document.write(\"$I1\");" : $I1; } // 去掉换行 function nr($str){ $str = str_replace(array("<nr/>","<rr/>"),array("\n","\r"),$str); return trim($str); } //去掉连续空白 function nb($str){ $str = str_replace("&nbsp;",' ',$str); $str = str_replace(" ",' ',$str); $str = ereg_replace("[\r\n\t ]{1,}",' ',$str); return trim($str); } //字符串截取(同时去掉HTML与空白) function msubstr($str, $start=0, $length, $suffix=false){ return ff_msubstr(eregi_replace('<[^>]+>','',ereg_replace("[\r\n\t ]{1,}",' ',nb($str))),$start,$length,'utf-8',$suffix); } function ff_msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){ $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); $length_new = $length; for($i=$start; $i<$length; $i++){ if (ord($match[0][$i]) > 0xa0){ //中文 }else{ $length_new++; $length_chi++; } } if($length_chi<$length){ $length_new = $length+($length_chi/2); } $slice = join("",array_slice($match[0], $start, $length_new)); if($suffix && $slice != $str){ return $slice."…"; } return $slice; } // 汉字转拼单 function ff_pinyin($str,$ishead=0,$isclose=1){ $str = u2g($str);//转成GBK global $pinyins; $restr = ''; $str = trim($str); $slen = strlen($str); if($slen<2){ return $str; } if(count($pinyins)==0){ $fp = fopen('./Lib/Common/pinyin.dat','r'); while(!feof($fp)){ $line = trim(fgets($fp)); $pinyins[$line[0].$line[1]] = substr($line,3,strlen($line)-3); } fclose($fp); } for($i=0;$i<$slen;$i++){ if(ord($str[$i])>0x80){ $c = $str[$i].$str[$i+1]; $i++; if(isset($pinyins[$c])){ if($ishead==0){ $restr .= $pinyins[$c]; } else{ $restr .= $pinyins[$c][0]; } }else{ //$restr .= "_"; } }else if( eregi("[a-z0-9]",$str[$i]) ){ $restr .= $str[$i]; } else{ //$restr .= "_"; } } if($isclose==0){ unset($pinyins); } return $restr; } //生成字母前缀 function ff_letter_first($s0){ $firstchar_ord=ord(strtoupper($s0{0})); if (($firstchar_ord>=65 and $firstchar_ord<=91)or($firstchar_ord>=48 and $firstchar_ord<=57)) return $s0{0}; $s=iconv("UTF-8","gb2312", $s0); $asc=ord($s{0})*256+ord($s{1})-65536; if($asc>=-20319 and $asc<=-20284)return "A"; if($asc>=-20283 and $asc<=-19776)return "B"; if($asc>=-19775 and $asc<=-19219)return "C"; if($asc>=-19218 and $asc<=-18711)return "D"; if($asc>=-18710 and $asc<=-18527)return "E"; if($asc>=-18526 and $asc<=-18240)return "F"; if($asc>=-18239 and $asc<=-17923)return "G"; if($asc>=-17922 and $asc<=-17418)return "H"; if($asc>=-17417 and $asc<=-16475)return "J"; if($asc>=-16474 and $asc<=-16213)return "K"; if($asc>=-16212 and $asc<=-15641)return "L"; if($asc>=-15640 and $asc<=-15166)return "M"; if($asc>=-15165 and $asc<=-14923)return "N"; if($asc>=-14922 and $asc<=-14915)return "O"; if($asc>=-14914 and $asc<=-14631)return "P"; if($asc>=-14630 and $asc<=-14150)return "Q"; if($asc>=-14149 and $asc<=-14091)return "R"; if($asc>=-14090 and $asc<=-13319)return "S"; if($asc>=-13318 and $asc<=-12839)return "T"; if($asc>=-12838 and $asc<=-12557)return "W"; if($asc>=-12556 and $asc<=-11848)return "X"; if($asc>=-11847 and $asc<=-11056)return "Y"; if($asc>=-11055 and $asc<=-10247)return "Z"; return 0;//null } /*-------------------------------------------------采集函数开始------------------------------------------------------------------*/ // 采集内核 function ff_file_get_contents($url,$timeout=10,$referer){ if(function_exists('curl_init')){ $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,$timeout); if($referer){ curl_setopt ($ch, CURLOPT_REFERER, $referer); } $content = curl_exec($ch); curl_close($ch); if($content){ return $content; } } $ctx = stream_context_create(array('http'=>array('timeout'=>$timeout))); $content = @file_get_contents($url, 0, $ctx); if($content){ return $content; } return false; } // 采集-匹配规则结果 function ff_preg_match($rule,$html){ $arr = explode('$$$',$rule); if(count($arr) == 2){ preg_match('/'.$arr[1].'/', $html, $data); return $data[$arr[0]].''; }else{ preg_match('/'.$rule.'/', $html, $data); return $data[1].''; } } // 采集-匹配规则结果all function ff_preg_match_all($rule,$html){ $arr = explode('$$$',$rule); if(count($arr) == 2){ preg_match_all('/'.$arr[1].'/', $html, $data); return $data[$arr[0]]; }else{ preg_match_all('/'.$rule.'/', $html, $data); return $data[1]; } } // 采集-倒序采集 function ff_krsort_url($listurl){ krsort($listurl); foreach($listurl as $val){ $list[]=$val; } return $list; } // 采集-将所有替换规则保存在一个字段 function ff_implode_rule($arr){ foreach($arr as $val){ $array[] = trim(stripslashes($val)); } return implode('|||',$array); } // 采集-规则替换 function ff_replace_rule($str){ //$str = str_replace(array("\n","\r"),array("<nr/>","<rr/>"),strtolower($str)); $arr1 = array('?','"','(',')','[',']','.','/',':','*','||'); $arr2 = array('\?','\"','\(','\)','\[','\]','\.','\/','\:','.*?','(.*?)'); //$str = str_replace(array("\n","\r"),array("<nr/>","<rr/>"),strtolower($str)); return str_replace('\[$ppvod\]','([\s\S]*?)',str_replace($arr1,$arr2,$str)); } //生成随机伪静态简介 function ff_rand_str($string){ $arr=C('play_collect_content'); //$all=mb_strlen($string,'utf-8'); $all=iconv_strlen($string,'utf-8'); $len=floor(mt_rand(0,$all-1)); $str=msubstr($string,0,$len); $str2=msubstr($string,$len,$all); return $str.$arr[array_rand($arr,1)].$str2; } //获取绑定分类对应ID值 function ff_bind_id($key){ $bindcache = F('_xml/bind'); return $bindcache[$key]; } //TAG分词自动获取 function ff_tag_auto($title,$content){ $data = ff_file_get_contents('http://keyword.discuz.com/related_kw.html?ics=utf-8&ocs=utf-8&title='.rawurlencode($title).'&content='.rawurlencode(msubstr($content,0,500))); if($data) { $parser = xml_parser_create(); xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); xml_parse_into_struct($parser, $data, $values, $index); xml_parser_free($parser); $kws = array(); foreach($values as $valuearray) { if($valuearray['tag'] == 'kw') { if(strlen($valuearray['value']) > 3){ $kws[] = trim($valuearray['value']); } }elseif($valuearray['tag'] == 'ekw'){ $kws[] = trim($valuearray['value']); } } return implode(' ',$kws); } return false; } // 格式化采集影片名称 function ff_xml_vodname($vodname){ $vodname = str_replace(array('【','】','(',')','(',')','{','}'),array('[',']','[',']','[',']','[',']'),$vodname); $vodname = preg_replace('/\[([a-z][A-Z])\]|([a-z][A-Z])版/i','',$vodname); $vodname = preg_replace('/TS清晰版|枪版|抢先版|HD|BD|TV|DVD|VCD|TS|\/版|\[\]/i','',$vodname); return trim($vodname); } // 格式化采集影片主演 function ff_xml_vodactor($vodactor){ return str_replace(array(',','/',',','|','、'),',',$vodactor); } /*-------------------------------------------------飞飞系统栏目相关函数开始------------------------------------------------------------------*/ //通过栏目名名获取对应的栏目ID function getlistid($str){ $arr = list_search(F('_ppvod/list'),'list_name='.$str); if(empty($arr)){ return 0; }else{ return $arr[0]['list_id']; } } //通过栏目ID获取对应的栏目名称/别名等 function getlistname($cid,$type='list_name'){ $arr=list_search(F('_ppvod/list'),'list_id='.$cid); if(is_array($arr)){ return $arr[0][$type]; }else{ return '未知ID'.$cid; } } // 检查当前栏目是否没有小类 function getlistson($pid){ $tree=list_search(F('_ppvod/listtree'),'list_id='.$pid); if(!empty($tree[0]['son'])){ return false; }else{ return true; } } //生成栏目sql查询语句范围 function getlistsqlin($cid){ $tree = list_search(F('_ppvod/listtree'),'list_id='.$cid); if (!empty($tree[0]['son'])) { foreach($tree[0]['son'] as $val){ $arr['vod_cid'][] = $val['list_id']; } $channel = implode(',', $arr['vod_cid']); return array('IN',''.$channel.''); } return $cid; } //通过栏目ID返回其它值按数组方式 function getlistarr($cid,$type='list_id'){ $tree = list_search(F('_ppvod/listtree'),'list_id='.$cid); if(!empty($tree[0]['son'])){ foreach($tree[0]['son'] as $val){$param[]=$val[$type];} return $param; }else{ return false; } } //去重后的模板栏目ID参数 $cids = array(1,2,3,...) function getlistarr_tag($cids){ foreach($cids as $key=>$value){ if(getlistson($value)){ $cid .= ','.$value; }else{ $cidin = getlistsqlin($value); $cid .= ','.$cidin[1]; } } $cidarr = explode(',',$cid); unset($cidarr[0]); $cidarr = array_unique($cidarr); return $cidarr; } // 获取栏目数据统计 function getcount($cid){ $where = array(); if(999 == $cid){ $rs = M("Vod"); $where['vod_cid'] = array('gt',0); $where['vod_addtime'] = array('gt',getxtime(1));//当天更新的影视 $count = $rs->where($where)->count('vod_id'); }elseif(0 == $cid){ $rs = M("Vod"); $where['vod_cid'] = array('gt',0); $count = $rs->where($where)->count('vod_id'); }else{ $sid = getlistname($cid,'list_sid'); if ($sid == '2'){ $where['news_cid'] = getlistsqlin($cid); $where['news_status'] = 1; $rs = M("News"); $count = $rs->where($where)->count('news_id'); }else{ $where['vod_cid'] = getlistsqlin($cid); $where['vod_status'] = 1; $rs = M("Vod"); $count = $rs->where($where)->count('vod_id'); } } //dump($rs->getLastSql()); return $count+0; } //获取模型名称 function getsidname($sid){ if ($sid==1){ return 'vod'; }elseif ($sid==2){ return 'news'; }elseif ($sid==3){ return 'special'; }else{ return 'url'; } } //获取模型ID function ff_sid($sidname){ if ($sidname == 'vod'){ return 1; }elseif ($sidname == 'news'){ return 2; }elseif($sidname == 'special'){ return 3; }else{ return 9; } } /*-------------------------------------------------模板常用函数-----------------------------------------------------------------*/ //获得某天前的时间戳 function getxtime($day){ $day = intval($day); return mktime(23,59,59,date("m"),date("d")-$day,date("y")); } // 获取标题颜色 function getcolor($str,$color){ if(empty($color)){ return $str; }else{ return '<font color="'.$color.'">'.$str.'</font>'; } } // 获取时间颜色 function getcolordate($type='Y-m-d H:i:s',$time,$color='red'){ if((time()-$time)>86400){ return date($type,$time); }else{ return '<font color="'.$color.'">'.date($type,$time).'</font>'; } } // 读出qvod地址的文件名 function ff_qvod_name($jiname){ $jiname = ff_preg_match('3$$$(.*)\|(.*)\|(.*)\.(.*)\|',$jiname); return $jiname; } // 处理积分样式 function getjifen($fen){ $array = explode('.',$fen); return '<strong>'.$array[0].'</strong>.'.$array[1]; } //分页样式 function getpage($currentPage,$totalPages,$halfPer=3,$url,$pagego){ $linkPage .= ( $currentPage > 1 ) ? '<a href="'.str_replace('{!page!}',1,$url).'" class="prev disabled" data="p-0">首页</a>&nbsp;<a href="'.str_replace('{!page!}',($currentPage-1),$url).'" class="prev disabled" data="p-'.($currentPage-1).'">上一页</a>&nbsp;' : '<span class="prev disabled">首页</span>&nbsp;<span class="prev disabled" data="p-'.($currentPage-1).'">上一页</span>&nbsp;'; for($i=$currentPage-$halfPer,$i>1||$i=1,$j=$currentPage+$halfPer,$j<$totalPages||$j=$totalPages;$i<$j+1;$i++){ $linkPage .= ($i==$currentPage)?'<span class="current">'.$i.'</span>&nbsp;':'<a href="'.str_replace('{!page!}',$i,$url).'" data="p-'.$i.'">'.$i.'</a>&nbsp;'; } $linkPage .= ( $currentPage < $totalPages ) ? '<a href="'.str_replace('{!page!}',($currentPage+1),$url).'" class="next pagegbk" data="p-'.($currentPage+1).'">下一页</a>&nbsp;<a href="'.str_replace('{!page!}',$totalPages,$url).'" class="next pagegbk" data="p-'.$totalPages.'">尾页</a>' : '<span class="prev disabled">下一页</span>&nbsp;<span class="prev disabled">尾页</span>'; if(!empty($pagego)){ $linkPage .=''; } return str_replace('-1'.C('html_file_suffix'),C('html_file_suffix'),str_replace('index1'.C('html_file_suffix'),'',$linkPage)); } //分页样式 function getpagetop($currentPage,$totalPages,$halfPer=5,$url,$pagego){ $linkPage .= ( $currentPage > 1 ) ? '<a href="'.str_replace('{!page!}',($currentPage-1),$url).'" class="prev pagegbk" data="p-'.($currentPage-1).'">上一页</a>&nbsp;' : '<span class="prev disabled">上一页</span>'; $linkPage .= ( $currentPage < $totalPages ) ? '<a href="'.str_replace('{!page!}',($currentPage+1),$url).'" class="next pagegbk" data="p-'.($currentPage+1).'">下一页</a>&nbsp;' : '<span class="prev disabled">下一页</span>'; return str_replace('-1'.C('html_file_suffix'),C('html_file_suffix'),str_replace('index1'.C('html_file_suffix'),'',$linkPage)); } //搜索统计 function getpagecount($currentPage,$totalPages,$halfPer=5,$url,$pagego){ $linkPage .= ( $currentPage > 1 ) ? '' : ''; $linkPage .= ( $currentPage < $totalPages ) ? '' : ''; return str_replace('-1'.C('html_file_suffix'),C('html_file_suffix'),str_replace('index1'.C('html_file_suffix'),'',$linkPage)); } //处理最大分页参数 function get_maxpage($currentpage,$totalpages){ if ($currentpage > $totalpages){ $currentpage = $totalpages; } return $currentpage; } // 获取热门关键词 function ff_hot_key($string){ if(C('url_html')){ return '<script type="text/javascript" src="'.C('site_path').'Runtime/Js/hotkey.js" charset="utf-8"></script>'; } $array_hot = array(); foreach(explode(chr(13),trim($string)) as $key=>$value){ $array = explode('|',$value); if($array[1]){ $array_hot[$key] = '<a href="'.$array[1].'" target="_blank">'.trim($array[0]).'</a>'; }else{ $array_hot[$key] = '<a href="'.UU('Home-vod/search',array('wd'=>urlencode(trim($value))),false,true).'">'.trim($value).'</a>'; } } return implode(' ',$array_hot); } // 获取与处理人气值 function ff_get_hits($sidname,$type='hits',$array,$js=true){ if((C('url_html') && $js) || $type=='insert'){ return '<script type="text/javascript" src="'.C('site_path').'index.php?s=hits-show-id-'.$array[$sidname.'_id'].'-type-'.$type.'-sid-'.$sidname.'" charset="utf-8"></script>'; }else{ return $array[$type]; } } // 递归多维数组转为一级数组 function ff_arrays2array($array){ static $result_array=array(); foreach($array as $value){ if(is_array($value)){ ff_arrays2array($value); }else{ $result_array[]=$value; } } return $result_array; } // 重写动态路径 function UU($model,$params,$redirect=false,$suffix=false){ //rewrite重写 if(C('url_rewrite')){ if($params['p'] != '{!page!}'){ $params['p'] = 1; } if($model == 'Home-vod/show'){ $reurl = str_replace(array('$id','$page','$wd','$lz','$mcid','$area','$language','$actor','$director','$year','$letter','$order'),array($params['id'],$params['p'],$params['wd'],$params['lz'],$params['mcid'],$params['area'],$params['language'],$params['actor'],$params['director'],$params['year'],$params['letter'],$params['order']),C('rewrite_vodlist')); }elseif($model == 'Home-vod/read'){ $reurl = str_replace('$id',$params['id'],C('rewrite_voddetail')); }elseif($model == 'Home-vod/play'){ $reurl = str_replace(array('$id','$sid','$pid'),array($params['id'],$params['sid'],$params['pid']),C('rewrite_vodplay')); }elseif($model == 'Home-vod/search'){ $reurl = str_replace(array('$wd','$page','$area','$language','$actor','$director','$year','$letter','$order'),array($params['wd'],$params['p'],$params['area'],$params['language'],$params['actor'],$params['director'],$params['year'],$params['letter'],$params['order']),C('rewrite_vodsearch')); }elseif($model == 'Home-tag/show'){ $reurl = str_replace(array('$wd','$page'),array($params['wd'],$params['p']),C('rewrite_vodtag')); }elseif($model == 'Home-news/show'){ $reurl = str_replace(array('$id','$page'),array($params['id'],$params['p']),C('rewrite_newslist')); }elseif($model == 'Home-news/read'){ $reurl = str_replace('$id',$params['id'],C('rewrite_newsdetail')); }elseif($model == 'Home-news/search'){ $reurl = str_replace(array('$wd','$page'),array($params['wd'],$params['p']),C('rewrite_newssearch')); }elseif($model == 'Home-tag/shown'){ $reurl = str_replace(array('$wd','$page'),array($params['wd'],$params['p']),C('rewrite_newstag')); }elseif($model == 'Home-special/show'){ $reurl = str_replace('$page',$params['p'],C('rewrite_specialshow')); }elseif($model == 'Home-special/read'){ $reurl = str_replace('$id',$params['id'],C('rewrite_specialdetail')); }elseif($model == 'Home-gb/show'){ $reurl = str_replace(array('$id','$page'),array($params['id'],$params['p']),C('rewrite_guestbook')); }elseif($model == 'Home-my/show'){ $reurl = str_replace('$id',$params['id'],C('rewrite_mytpl')); }elseif($model == 'Home-map/show'){ $reurl = str_replace(array('$id','$limit'),array($params['id'],$params['limit']),C('rewrite_map')); } //伪静态规则设置正确 if($reurl){ return $reurl.C('url_html_suffix'); }else{ return str_replace('index.php?s=/Home-','',U($model,$params,$redirect,$suffix)); } } //TP框架默认生成的路径 $reurl = str_replace('Home-','',str_replace('index.php?s=/','index.php?s=',U($model,$params,$redirect,$suffix))); //不是静态模式则去掉index.php if(!C('url_html')){ return str_replace('index.php','',$reurl); } return $reurl; }; // 获取广告调用地址 function getadsurl($str,$charset="utf-8"){ return '<script type="text/javascript" src="'.C('site_path').C('admin_ads_file').'/'.$str.'.js" charset="'.$charset.'"></script>'; } /*******************替换自定义路径的变量****************************/ function str_replace_dir($urldir,$id,$cid,$name){ $old = array('{listid}','{listdir}','{pinyin}','{id}','{md5}',C('html_file_suffix')); $new = array($cid,getlistname($cid,'list_dir'),ff_pinyin($name),$id,md5($id),''); return str_replace($old,$new,$urldir); } /*******************获取栏目页路径**************************** * $sid 模型名称'movie/article/special' * $arrurl为数组参数传入参考U函数(方便动态模式直接生成) * $page 分页数字,大于1时返回的URL带有分页跳转参数变量{!page!} * 只有一个栏目ID参数时 $arrurl['id'] = $cid; */ function ff_list_url($sid,$arrurl,$page){ //静态模式 if(C('url_html') && C('url_html_list') && in_array($sid,array('vod','news'))){ $showurl = C('site_path').str_replace('index'.C('html_file_suffix'),'',ff_list_url_dir($sid,$arrurl['id'],$page).C('html_file_suffix')); return $showurl; }else{//动态模式 if($page > 1){ $arrurl['p'] = '{!page!}'; } $showurl = UU('Home-'.$sid.'/show',$arrurl,false,true); } return $showurl; } /**********************静态生成的栏目结构****************************** * (返回的值为buildHtml的文件名,生成静态时需要将{!page!}换成对应的page值) * $mid 模型名称'movie/article/special' * $cid 当前分类的栏目ID值 * $page 分页数字,大于1时返回的URL带有分页跳转参数变量{!page!} */ function ff_list_url_dir($sid,$cid,$page){ //影视或文章 if('vod' == $sid){ $listdir = str_replace_dir(C('url_vodlist'),$id,$cid,$name); }else{ $listdir = str_replace_dir(C('url_newslist'),$id,$cid,$name); } if($page > 1){ $listdir .= '-{!page!}'; } return $listdir; } //字母封面QQ:182377860 function ff_list_letter_url_dir($sid,$cid){ if('vod' == $sid){ $listdir = str_replace_dir(C('url_vodlist_letter'),$id,$cid,$name); } return $listdir; } //字母封面QQ:182377860 /*************************获取内容页路径**************************************** * $sid 模型名称'vod/news/special' * $id 影片ID/文章ID/专题ID值 * $cid 当前影片/文章/专题/对应的栏目ID值 * $name 影片/文章/专题/的名称 * $page 分页数字,大于1时返回的URL带有分页跳转参数变量{!page!} * $jumpurl 跳转地址 */ function ff_data_url($sid,$id,$cid,$name,$page,$jumpurl){ //有跳转地址 if ($jumpurl) { return $jumpurl; } //静态 if(C('url_html')){ $readurl = C('site_path').str_replace('index'.C('html_file_suffix'),'',ff_data_url_dir($sid,$id,$cid,$name,$page).C('html_file_suffix')); return $readurl; } //动态模式 $arrurl['id'] = $id; if($page > 1){ $arrurl['p'] = '{!page!}'; } return UU('Home-'.$sid.'/read',$arrurl,false,true); } /*************************获取详情页目录**************************************** * 返回的值为buildHtml的文件名 * $sid 模型名称'vod/news/special' * $id 影片ID/文章ID/专题ID值 * $cid 当前影片/文章/专题/对应的栏目ID值 * $name 影片/文章/专题/的名称 * $page 分页数字,大于1时返回的URL带有分页跳转参数变量{!page!} */ function ff_data_url_dir($sid,$id,$cid,$name,$page){ //专题直接返回 if('special' == $sid){ return trim(C('url_special').ff_pinyin($name)); } //影视或文章 if('vod' == $sid){ $datadir = str_replace_dir(C('url_voddata'),$id,$cid,$name); }else{ $datadir = str_replace_dir(C('url_newsdata'),$id,$cid,$name); } if($page > 1){ $datadir .= '-{!page!}'; } return $datadir; } //获取播放页链接 function ff_play_url($id,$sid,$pid,$cid,$name){ //静态模式 if(C('url_html') && C('url_html_play')){ $playurl = C('site_path').str_replace('index'.C('html_file_suffix'),'',ff_play_url_dir($id,$sid,$pid,$cid,$name).C('html_file_suffix')); if(C('url_html_play') == 1){ $playurl .= '?'.$id.'-'.$sid.'-'.$pid; } }else{//动态 $playurl = UU('Home-vod/play',array('id'=>$id,'sid'=>$sid,'pid'=>$pid),false,true); } return $playurl; } //播放页静态生成结构 function ff_play_url_dir($id,$sid,$pid,$cid,$name){ $playdir = str_replace_dir(C('url_play'),$id,$cid,$name); if(C('url_html_play') == 2){ $playdir .= '-'.$id.'-'.$sid.'-'.$pid; } return $playdir; } //获取专题URL function ff_special_url($page){ if(C('url_html')){ return C('site_path').str_replace('index'.C('html_file_suffix'),'',ff_special_url_dir($page).C('html_file_suffix')); }else{ return UU('Home-special/show','',false,true); } } //获取专题静态模式目录结构URL function ff_special_url_dir($page){ $listdir = trim(C('url_special')).'index'; if($page > 1){ $listdir .= '-{!page!}'; } return $listdir; } // 获取某图片的访问地址 function ff_img_url($file,$content,$number=1){ if(!$file){ return ff_img_url_preg($file,$content,$number); } if(strpos($file,'http://') !== false){ return $file; } $prefix = C('upload_http_prefix'); if(!empty($prefix)){ return $prefix.$file; }else{ return C('site_path').C('upload_path').'/'.$file; } } // 获取某图片的缩略图地址 function ff_img_url_small($file,$content,$number=1){ if(!$file){ return ff_img_url_preg($file,$content,$number); } if(strpos($file,'http://') !== false){ return $file; } $prefix = C('upload_http_prefix'); if(!empty($prefix)){ return $prefix.$file; }else{ return C('site_path').C('upload_path').'-s/'.$file; } } //正则提取正文里指定的第几张图片地址 function ff_img_url_preg($file,$content,$number=1){ preg_match_all('/<img(.*?)src="(.*?)(?=")/si',$content,$imgarr);///(?<=img.src=").*?(?=")/si preg_match_all('/(?<=src=").*?(?=")/si',implode('" ',$imgarr[0]).'" ',$imgarr); $countimg = count($imgarr); if($number > $countimg){ $number = $countimg; } return $imgarr[0][($number-1)]; } // Tag链接 function ff_tag_url($str,$sid=''){ if($sid==2){ return UU('Home-tag/shown',array('wd'=>urlencode($str)),false,true); }else{ return UU('Home-tag/show',array('wd'=>urlencode($str)),false,true); } } // 内容页Tag链接 function ff_content_url($content,$array_tag='',$sid=''){ if($array_tag){ foreach($array_tag as $key=>$value){ $content = str_replace($value['tag_name'],'<a href="'.ff_tag_url($value['tag_name'],$sid).'">'.$value['tag_name'].'</a>',$content); } } return $content; } // 自定义模板链接 function ff_mytpl_url($tplname){ $tplname = str_replace(array('my_','.html'),'',$tplname); if(C('url_html')){ return C('site_path').C('url_mytpl').$tplname.C('html_file_suffix'); } return UU('Home-my/show',array('id'=>trim($tplname)),false,true); } // 地图页链接 function ff_map_url($tplname){ if(C('url_html')){ return C('site_path').C('url_map').$tplname.'.xml'; } $limit = 30; if($tplname != 'rss'){ $limit = 100; } return UU('Home-map/show',array('id'=>$tplname,'limit'=>$limit),false,true); } // 获取26个字母链接 function ff_letter_url($file='vod',$str=''){ if(C('url_html')){ $index='index.html'; }else{ $index='index.php'; } for($i=1;$i<=26;$i++){ $url = UU('Home-'.$file.'/search',array('id'=>chr($i+64),'x'=>'letter'),false,true); $str.='<a href="'.$url.'" class="letter_on">'.chr($i+64).'</a>'; } return $str; } // 获取搜索带链接 function ff_search_url($str,$type="actor",$sidname='vod',$action='search'){ $array = array(); $str = str_replace(array('/','|',',',','),' ',$str); $arr = explode(' ',$str); foreach($arr as $key=>$val){ $array[$key] = '<a href="'.UU('Home-'.$sidname.'/'.$action,array($type=>urlencode($val)),false,true).'" target="_blank">'.$val.'</a>'; } return implode(' ',$array); } /* * 类型分类URL转化 * QQ182377860 */ function ff_mcat_url($str,$cid) { if(empty($str)){ return "无分类"; } $mcids = explode(',', $str); $html = ''; foreach($mcids as $v){ $url = UU('Home-vod/show', array('id'=>$cid, 'mcid'=>$v),false,true); $name = M('Mcat')->where("m_cid = {$v}")->find(); $html .= "<a href='".$url."' target='_blank'>{$name['m_name']}</a>"; } return $html; } function ff_mcat_url_new($str,$cid) { if(empty($str)){ return "无分类"; } $mcids = explode(',', $str); $html = ''; foreach($mcids as $v){ $url = UU('Home-vod/show', array('id'=>$cid, 'mcid'=>$v),false,true); $name = M('Mcat')->where("m_cid = {$v}")->find(); $html .= "<a href='".$url."' target='_blank'>{$name['m_name']}</a> "; } return $html; } function ff_mcat($str,$cid) { if(empty($str)){ return "无分类"; } $mcids = explode(',', $str); $html = ''; foreach($mcids as $v){ $url = UU('Home-vod/show', array('id'=>$cid, 'mcid'=>$v),false,true); $name = M('Mcat')->where("m_cid = {$v}")->find(); $html .= "{$name['m_name']} "; } return $html; } function ff_mcat_admin($str,$cid) { if(empty($str)){ return "无分类"; } $mcids = explode(',', $str); $html = ''; foreach($mcids as $v){ $url = UU('Home-vod/show', array('id'=>$cid, 'mcid'=>$v),false,true); $name = M('Mcat')->where("m_cid = {$v}")->find(); $html .= " {$name['m_name']}"; } return $html; } // 获取搜索带链接182377860 function ff_director_url($str,$type="director",$sidname='vod',$action='search'){ $array = array(); $str = str_replace(array('/','|',',',','),' ',$str); $arr = explode(' ',$str); foreach($arr as $key=>$val){ $array[$key] = '<a href="'.UU('Home-'.$sidname.'/'.$action,array($type=>urlencode($val)),false,true).'" target="_blank">'.$val.'</a>'; } return implode(' ',$array); } // 获取影片最后一集array(sid,pid,jiname,jipath) function ff_play_url_end($vod_url){ $array = array(); $arr_server = explode('$$$',trim($vod_url)); foreach($arr_server as $key=>$value){ $array[$key] = array(count(explode(chr(13),str_replace(array("\r\n", "\n", "\r"),chr(13),$value))),$key); } $max_key = max($array); $array = explode(chr(13),str_replace(array("\r\n", "\n", "\r"),chr(13),$arr_server[$max_key[1]])); $arr_url = explode('$',end($array)); if($arr_url[1]){ return array($max_key[1],$max_key[0],$arr_url[0],$arr_url[1]); }else{ return array($max_key[1],$max_key[0],'第'.$max_key[0].'集',$arr_url[0]); } } /*---------------------------------------标签解析函数开始------------------------------------------------------------------*/ //路径参数处理函数 function ff_param_url(){ $where = array(); $where['id'] = intval($_REQUEST['id']); $where['page'] = !empty($_GET['p']) ? intval($_GET['p']) : 1; $where['year'] = intval($_REQUEST['year']); $where['lz'] = intval($_REQUEST['lz']); $where['language'] = htmlspecialchars(urldecode(trim($_REQUEST['language']))); $where['area'] = htmlspecialchars(urldecode(trim($_REQUEST['area']))); $where['letter'] = htmlspecialchars($_REQUEST['letter']); $where['actor'] = htmlspecialchars(urldecode(trim($_REQUEST['actor']))); $where['director'] = htmlspecialchars(urldecode(trim($_REQUEST['director']))); $where['limit'] = !empty($_GET['limit']) ? intval($_GET['limit']) : 10; $where['wd'] = htmlspecialchars(urldecode(trim($_REQUEST['wd']))); $where['order'] = ff_order_by($_GET['order']); $where['sid'] = intval($_REQUEST['sid']); $where['mcid'] = isset($_GET['mcid']) ? intval($_GET['mcid']) : 0; $where['prty'] = isset($_GET['prty']) ? intval($_GET['prty']) : 0; $where['exp'] = isset($_GET['exp']) ? intval($_GET['exp']) : 0; $where['showdate'] = isset($_GET['showdate']) ? intval($_GET['showdate']) : 0; return $where; } //分页跳转参数处理 function ff_param_jump($where){ if($where['id']){ $jumpurl['id'] = $where['id']; } if($where['wd']){ $jumpurl['wd'] = urlencode($where['wd']); } if($where['area']){ $jumpurl['area'] = urlencode($where['area']); } if($where['language']){ $jumpurl['language'] = urlencode($where['language']); } if($where['actor']){ $jumpurl['actor'] = urlencode($where['actor']); } if($where['director']){ $jumpurl['director'] = urlencode($where['director']); } if($where['year']){ $jumpurl['year'] = $where['year']; } if($where['letter']){ $jumpurl['letter'] = $where['letter']; } if($where['lz']){ $jumpurl['lz'] = $where['lz']; } if($where['exp']){ $jumpurl['exp'] = $where['exp']; } if($where['prty']){ $jumpurl['prty'] = $where['prty']; } if($where['order'] != 'addtime' && $where['order']){ $jumpurl['order'] = $where['order']; } if($where['mcid']) { $jumpurl['mcid'] = $where['mcid']; //小鱼:182377860 } $jumpurl['p'] = ''; return $jumpurl; } //返回安全的orderby function ff_order_by($order = 'vod_addtime'){ if(empty($order)){ return ''; } return $order; $arrorder['vod_addtime'] = 'vod_addtime'; $arrorder['vod_hits'] = 'vod_hits'; $arrorder['vod_gold'] = 'vod_gold'; $arrorder['id'] = 'id'; $arrorder['hits'] = 'hits'; $arrorder['stars'] = 'stars'; $arrorder['up'] = 'up'; $arrorder['down'] = 'down'; $arrorder['gold'] = 'gold'; $arrorder['golder'] = 'golder'; $arrorder['year'] = 'year'; $arrorder['letter'] = 'letter'; $arrorder['showdate'] = 'showdate'; return $arrorder[trim($order)]; } //生成参数列表,以数组形式返回 function ff_param_lable($tag = ''){ $param = array(); $array = explode(';',str_replace('num:','limit:',$tag)); foreach ($array as $v){ list($key,$val) = explode(':',trim($v)); $param[trim($key)] = trim($val); } return $param; } /****************************************** * @处理影视标签函数 * @以字符串方式传入,通过ff_param_lable函数解析为以下变量 * name:vod 必须(vod/news/special/guestbook/common/user) * ids:调用指定ID的一个或多个数据,如 1,2,3 * cid:数据所在分类,可调出一个或多个分类数据,如 1,2,3 默认值为全部,在当前分类为:'.$cid.' * field:调用影视类的指定字段,如(id,title,actor) 默认全部 * limit:数据条数,默认值为10,可以指定从第几条开始,如3,8(表示共调用8条,从第3条开始) * order:推荐方式(id/addtime/hits/year/up/down) (desc/asc/rand()) * wd:'关键字' 用于调用自定义关键字(搜索/标签)结果 * serial:调用连载信息(all/数字) 全部连载值为all 其它数字为大于该数字的连载影片 * time: 指定上传时间内,如(1/7/30) 分别表示(当天/本周/本月)------未做好 * stars:推荐星级数,可调出一个或多个星级数据,如 1,2,3 默认值为全部 * hits:大于指定人气值的数据(如:888)或某段之间的(如:888,999) * up:大于指定支持值的数据(如:888)或某段之间的(如:888,999) * down:大于指定反对值的数据(如:888)或某段之间的(如:888,999) * gold:大于指定评分平均值的数据(如:6)或某段之间的(如:1,8)/范围:0-10 * golder:大于指定评分人的数据(如:888)或某段之间的(如:888,999) */ function ff_mysql_vod($tag){ $search = array();$where = array(); $tag = ff_param_lable($tag); $field = !empty($tag['field']) ? $tag['field'] : '*'; $limit = !empty($tag['limit']) ? $tag['limit'] : '10'; $order = !empty($tag['order']) ? $tag['order'] : 'vod_addtime'; //优先从缓存调用 if(C('data_cache_vodforeach') && C('currentpage') < 2 ){ $data_cache_name = md5(C('data_cache_foreach').implode(',',$tag)); $data_cache_content = S($data_cache_name); if($data_cache_content){ return $data_cache_content; } } //根据参数生成查询条件 $where['vod_status'] = array('eq',1); if ($tag['ids']) { $where['vod_id'] = array('in',$tag['ids']); } if ($tag['day']) { $where['vod_addtime'] = array('gt',getxtime($tag['day'])); } if ($tag['hits']) { $hits = explode(',',$tag['hits']); if (count($hits) > 1) { $where['vod_hits'] = array('between',$hits[0].','.$hits[1]); }else{ $where['vod_hits'] = array('gt',$hits[0]); } } if ($tag['cid']) { $cids = explode(',',trim($tag['cid'])); if (count($cids)>1) { $where['vod_cid'] = array('in',getlistarr_tag($cids)); }else{ $where['vod_cid'] = getlistsqlin($tag['cid']); } } //mcid 标签开始 // modify by 小鱼 QQ182377860 if ($tag['mcid']) { $where["FIND_IN_SET({$tag['mcid']},vod_mcid)"] = array("gt","0"); } if ($tag['exp']) { $where["FIND_IN_SET({$tag['exp']},vod_exp)"] = array("gt","0"); } if ($tag['prty']) { $where["FIND_IN_SET({$tag['prty']},vod_prty)"] = array("gt","0"); } if ($tag['vodcid']) { $where["FIND_IN_SET({$tag['cid']},vod_cid)"] = array("gt","0"); } if ($tag['stars']) { $where['vod_stars'] = array('in',$tag['stars']); } if ($tag['letter']) { $where['vod_letter'] = array('in',$tag['letter']); } if ($tag['year']) { $where['vod_year'] = array('eq',$tag['year']); } if ($tag['area']) { $where['vod_area'] = array('eq',''.$tag['area'].''); } if ($tag['language']) { $where['vod_language'] = array('eq',''.$tag['language'].''); } if ($tag['diantai']) { $where['vod_diantai'] = array('eq',''.$tag['diantai'].''); } if ($tag['name']) { $where['vod_name'] = array('like','%'.$tag['name'].'%'); } if ($tag['title']) { $where['vod_title'] = array('like','%'.$tag['title'].'%'); } if ($tag['actor']) { $where['vod_actor'] = array('like','%'.$tag['actor'].'%'); } if ($tag['director']) { $where['vod_director'] = array('like','%'.$tag['director'].'%'); } if ($tag['play']) { $where['vod_play'] = array('eq',$tag['play']); } if ($tag['inputer']) { $where['vod_inputer'] = array('eq',$tag['inputer']); } if ($tag['wd']) { $search['vod_name'] = array('like','%'.$tag['wd'].'%'); $search['vod_title'] = array('like','%'.$tag['wd'].'%'); $search['vod_actor'] = array('like','%'.$tag['wd'].'%'); $search['vod_director'] = array('like','%'.$tag['wd'].'%'); $search['_logic'] = 'or'; $where['_complex'] = $search; } if($tag['lz'] == 1){ $where['vod_continu'] = array('neq','0'); }elseif($tag['lz'] == 2){ $where['vod_continu'] = 0; } if ($tag['up']) { $up = explode(',',$tag['up']); if (count($up)>1) { $where['vod_up'] = array('between',$up[0].','.$up[1]); }else{ $where['vod_up'] = array('gt',$up[0]); } } if ($tag['down']) { $down = explode(',',$tag['down']); if (count($down)>1) { $where['vod_down'] = array('between',$down[0].','.$down[1]); }else{ $where['vod_down'] = array('gt',$down[0]); } } if ($tag['gold']) { $gold = explode(',',$tag['gold']); if (count($gold)>1) { $where['vod_gold'] = array('between',$gold[0].','.$gold[1]); }else{ $where['vod_gold'] = array('gt',$gold[0]); } } if ($tag['golder']) { $golder = explode(',',$tag['golder']); if (count($golder)>1) { $where['vod_golder'] = array('between',$golder[0].','.$golder[1]); }else{ $where['vod_golder'] = array('gt',$golder[0]); } } //查询数据开始 if($tag['tag']){//视图模型查询 $where['tag_sid'] = 1; $where['tag_name'] = $tag['tag']; $rs = D('TagView'); }else{ $rs = M('Vod'); } if($tag['page']){ //组合分页信息 $count = $rs->where($where)->count('vod_id');if(!$count){return false;} $totalpages = ceil($count/$limit); $currentpage = get_maxpage(C('currentpage'),$totalpages); //生成分页列表 //$pageurl = ff_list_url('vod',C('jumpurl'),9999); $pageurl = C('jumpurl'); $pages = '共'.$count.'部&nbsp;:'.$currentpage.'/'.$totalpages.'&nbsp;'.getpage($currentpage,$totalpages,C('home_pagenum'),$pageurl,'pagego(\''.$pageurl.'\','.$totalpages.')'); //top 分页 新增加 182377860 $pagestop = ''.$currentpage.'/'.$totalpages.'&nbsp;'.getpagetop($currentpage,$totalpages,C('home_pagenum'),$pageurl,'pagego(\''.$pageurl.'\','.$totalpages.')'); $pagescount = ''.$count.''.getpagecount($currentpage,'pagego(\''.$pageurl.'\','.$totalpages.')'); //数据列表 $list = $rs->field($field)->where($where)->order($order)->limit($limit)->page($currentpage)->select(); $list[0]['count'] = count($list); $list[0]['page'] = $pages; $list[0]['pagetop'] = $pagestop; //小鱼:182377860 $list[0]['pagecount'] = $pagescount; //小鱼:182377860 }else{ $list = $rs->field($field)->where($where)->order($order)->limit($limit)->select(); } dump($rs->getLastSql()); //循环赋值 foreach($list as $key=>$val){ $list[$key]['list_id'] = $list[$key]['vod_cid']; $list[$key]['list_name'] = getlistname($list[$key]['list_id'],'list_name'); $list[$key]['list_url'] = getlistname($list[$key]['list_id'],'list_url'); $list[$key]['vod_readurl'] = ff_data_url('vod',$list[$key]['vod_id'],$list[$key]['vod_cid'],$list[$key]['vod_name'],1,$list[$key]['vod_jumpurl']); $list[$key]['vod_playurl'] = ff_play_url($list[$key]['vod_id'],0,1,$list[$key]['vod_cid'],$list[$key]['vod_name']); $list[$key]['vod_picurl'] = ff_img_url($list[$key]['vod_pic'],$list[$key]['vod_content']); $list[$key]['vod_haibaourl'] = ff_img_url($list[$key]['vod_haibao'],$list[$key]['vod_content']); //海报 QQ:182377860 $list[$key]['vod_picurl_small'] = ff_img_url_small($list[$key]['vod_pic'],$list[$key]['vod_content']); } //是否写入数据缓存 if(C('data_cache_vodforeach') && C('currentpage') < 2 ){ S($data_cache_name,$list,intval(C('data_cache_vodforeach'))); } return $list; } /* * 正在热映 */ function home_hot_play() { $model = M('Vod'); $where = array( 'vod_cid' => array('in', movie_cids()), 'vod_showdate' => array('elt', date("Ymd")) ); $order = 'vod_showdate DESC'; $list = $model->field('vod_id,vod_name,vod_showdate,vod_cid,vod_jumpurl')->where($where)->order($order)->limit(8)->select(); if($list) { foreach ($list as $key => $val) { $list[$key]['vod_readurl'] = ff_data_url('vod',$val['vod_id'],$val['vod_cid'],$val['vod_name'],1,$val['vod_jumpurl']); } } return $list; } /* * 即将上映 */ function home_after_playtv() { $model = M('Vod'); $where = array( 'vod_cid' => array('in', tv_cids()), 'vod_showdate' => array('gt', date("Ymd")) ); $order = 'vod_showdate ASC'; $list = $model->field('vod_id,vod_showdate,vod_name,vod_cid,vod_jumpurl')->where($where)->order($order)->limit(8)->select(); if($list) { foreach ($list as $key => $val) { $list[$key]['vod_readurl'] = ff_data_url('vod',$val['vod_id'],$val['vod_cid'],$val['vod_name'],1,$val['vod_jumpurl']); } } return $list; } function tv_cids(){ $data = M('List')->field('list_id')->where(array('list_pid' => 2))->select(); $cids = array(); foreach ($data as $val) { $cids[] = $val['list_id']; } return $cids; } function home_after_play() { $model = M('Vod'); $where = array( 'vod_cid' => array('in', movie_cids()), 'vod_showdate' => array('gt', date("Ymd")) ); $order = 'vod_showdate ASC'; $list = $model->field('vod_id,vod_showdate,vod_name,vod_cid,vod_jumpurl')->where($where)->order($order)->limit(8)->select(); if($list) { foreach ($list as $key => $val) { $list[$key]['vod_readurl'] = ff_data_url('vod',$val['vod_id'],$val['vod_cid'],$val['vod_name'],1,$val['vod_jumpurl']); } } return $list; } function movie_cids(){ $data = M('List')->field('list_id')->where(array('list_pid' => 1))->select(); $cids = array(); foreach ($data as $val) { $cids[] = $val['list_id']; } return $cids; } function show_date($data){ $year = substr($data, 0,4); $month = substr($data, 4,-2); $day = substr($data, -2,2); return $year.'年'.$month.'月'.$day.'日'; } function show_datea($data){ $month = substr($data, 4,-2); $day = substr($data, -2,2); return $month.'月'.$day.'日'; } /*数据调用-新闻资讯标签*/ function ff_mysql_news($tag){ $search = array();$where = array(); $tag = ff_param_lable($tag); $field = !empty($tag['field']) ? $tag['field'] : '*'; $limit = !empty($tag['limit']) ? $tag['limit'] : '10'; $order = !empty($tag['order']) ? $tag['order'] : 'news_addtime'; //优先从缓存调用 if(C('data_cache_newsforeach') && C('currentpage') < 2 ){ $data_cache_name = md5(C('data_cache_foreach').implode(',',$tag)); $data_cache_content = S($data_cache_name); if($data_cache_content){ return $data_cache_content; } } //根据参数生成查询条件 $where['news_status'] = array('eq',1); if ($tag['ids']) { $where['news_id'] = array('in',$tag['ids']); } if ($tag['day']) { $where['news_addtime'] = array('gt',getxtime($tag['day'])); } if ($tag['hits']) { $hits = explode(',',$tag['hits']); if (count($hits) > 1) { $where['news_hits'] = array('between',$hits[0].','.$hits[1]); }else{ $where['news_hits'] = array('gt',$hits[0]); } } if ($tag['cid']) { $cids = explode(',',trim($tag['cid'])); if (count($cids)>1) { $where['news_cid'] = array('in',getlistarr_tag($cids)); }else{ $where['news_cid'] = getlistsqlin($tag['cid']); } } if ($tag['stars']) { $where['news_stars'] = array('in',$tag['stars']); } if ($tag['letter']) { $where['news_letter'] = array('in',$tag['letter']); } if ($tag['name']) { $where['news_name'] = array('like','%'.$tag['name'].'%'); } if ($tag['title']) { $where['news_title'] = array('like','%'.$tag['title'].'%'); } if ($tag['wd']) { $search['news_name'] = array('like','%'.$tag['wd'].'%'); $search['news_inputer'] = array('like','%'.$tag['wd'].'%'); $search['_logic'] = 'or'; $where['_complex'] = $search; } if ($tag['up']) { $up = explode(',',$tag['up']); if (count($up)>1) { $where['news_up'] = array('between',$up[0].','.$up[1]); }else{ $where['news_up'] = array('gt',$up[0]); } } if ($tag['down']) { $down = explode(',',$tag['down']); if (count($down)>1) { $where['news_down'] = array('between',$down[0].','.$down[1]); }else{ $where['news_down'] = array('gt',$down[0]); } } if ($tag['gold']) { $gold = explode(',',$tag['gold']); if (count($gold)>1) { $where['news_gold'] = array('between',$gold[0].','.$gold[1]); }else{ $where['news_gold'] = array('gt',$gold[0]); } } if ($tag['golder']) { $golder = explode(',',$tag['golder']); if (count($golder)>1) { $where['news_golder'] = array('between',$golder[0].','.$golder[1]); }else{ $where['news_golder'] = array('gt',$golder[0]); } } //查询数据开始 if($tag['tag']){//视图模型查询 $where['tag_sid'] = 2; $where['tag_name'] = $tag['tag']; $rs = D('TagnewsView'); }else{ $rs = M('News'); } if($tag['page']){ //组合分页信息 $count = $rs->where($where)->count('news_id');if(!$count){return false;} $totalpages = ceil($count/$limit); $currentpage = get_maxpage(C('currentpage'),$totalpages); //生成分页列表 $pageurl = C('jumpurl'); $pages = '共'.$count.'篇资讯&nbsp;当前:'.$currentpage.'/'.$totalpages.'页&nbsp;'.getpage($currentpage,$totalpages,C('home_pagenum'),$pageurl,'pagego(\''.$pageurl.'\','.$totalpages.')'); //数据列表 $list = $rs->field($field)->where($where)->order($order)->limit($limit)->page($currentpage)->select(); $list[0]['count'] = count($list); $list[0]['page'] = $pages; }else{ $list = $rs->field($field)->where($where)->order($order)->limit($limit)->select(); } //循环赋值 foreach($list as $key=>$val){ $list[$key]['list_id'] = $list[$key]['news_cid']; $list[$key]['list_name'] = getlistname($list[$key]['list_id'],'list_name'); $list[$key]['list_url'] = getlistname($list[$key]['list_id'],'list_url'); $list[$key]['news_readurl'] = ff_data_url('news',$list[$key]['news_id'],$list[$key]['news_cid'],$list[$key]['news_name'],1,$list[$key]['news_jumpurl']); $list[$key]['news_picurl'] = ff_img_url($list[$key]['news_pic'],$list[$key]['news_content']); $list[$key]['news_picurl_small'] = ff_img_url_small($list[$key]['news_pic'],$list[$key]['news_content']); } //是否写入数据缓存 if(C('data_cache_newsforeach') && C('currentpage') < 2 ){ S($data_cache_name,$list,intval(C('data_cache_newsforeach'))); } return $list; } /*数据调用-专题循环标签*/ function ff_mysql_special($tag){ $search = array();$where = array(); $tag = ff_param_lable($tag); $field = !empty($tag['field']) ? $tag['field'] : '*'; $limit = !empty($tag['limit']) ? $tag['limit'] : '10'; $order = !empty($tag['order']) ? $tag['order'] : 'special_addtime'; //优先从缓存调用 if(C('data_cache_specialforeach') && C('currentpage') < 2 ){ $data_cache_name = md5(C('data_cache_foreach').implode(',',$tag)); $data_cache_content = S($data_cache_name); if($data_cache_content){ return $data_cache_content; } } //根据参数生成查询条件 $where['special_status'] = array('eq',1); if ($tag['ids']) { $where['special_id'] = array('in',$tag['ids']); } if ($tag['hits']) { $hits = explode(',',$tag['hits']); if (count($hits) > 1) { $where['special_hits'] = array('between',$hits[0].','.$hits[1]); }else{ $where['special_hits'] = array('gt',$hits[0]); } } if ($tag['name']) { $where['special_name'] = array('like','%'.$tag['name'].'%'); } //查询数据开始 $rs = M('Special'); if($tag['page']){ //组合分页信息 $count = $rs->where($where)->count('special_id');if(!$count){return false;} $totalpages = ceil($count/$limit); $currentpage = get_maxpage(C('currentpage'),$totalpages); //生成分页列表 $pageurl = C('jumpurl'); $pages = '共'.$count.'篇专题&nbsp;当前:'.$currentpage.'/'.$totalpages.'页&nbsp;'.getpage($currentpage,$totalpages,C('home_pagenum'),$pageurl,'pagego(\''.$pageurl.'\','.$totalpages.')'); //数据列表 $list = $rs->field($field)->where($where)->order($order)->limit($limit)->page($currentpage)->select(); $list[0]['count'] = count($list); $list[0]['page'] = $pages; }else{ $list = $rs->field($field)->where($where)->order($order)->limit($limit)->select(); } //dump($rs->getLastSql()); //循环赋值 foreach($list as $key=>$val){ $list[$key]['special_readurl'] = ff_data_url('special',$list[$key]['special_id'],0,$list[$key]['special_name'],1,''); $list[$key]['special_logo'] = ff_img_url($list[$key]['special_logo'],$list[$key]['special_content']); $list[$key]['special_banner'] = ff_img_url_small($list[$key]['special_banner'],$list[$key]['special_content']); } //是否写入数据缓存 if(C('data_cache_specialforeach') && C('currentpage') < 2 ){ S($data_cache_name,$list,intval(C('data_cache_specialforeach'))); } return $list; } /*---------------------------------------ThinkPhp扩展函数库开始------------------------------------------------------------------ * @category Think * @package Common * @author liu21st <liu21st@gmail.com>*/ // 获取客户端IP地址 function get_client_ip(){ if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) $ip = getenv("HTTP_CLIENT_IP"); else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) $ip = getenv("HTTP_X_FORWARDED_FOR"); else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) $ip = getenv("REMOTE_ADDR"); else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) $ip = $_SERVER['REMOTE_ADDR']; else $ip = "unknown"; return($ip); } //输出安全的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('[','&#091;',$text); $text = str_replace(']','&#093;',$text); $text = str_replace('|','&#124;',$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('<','&lt;',$text); $text = str_replace('>','&gt;',$text); $text = str_replace('"','&quot;',$text); //反转换 $text = str_replace('[','<',$text); $text = str_replace(']','>',$text); $text = str_replace('|','"',$text); //过滤多余空格 $text = str_replace(' ',' ',$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; } //XSS漏洞过滤 function remove_xss($val) { $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val); $search = 'abcdefghijklmnopqrstuvwxyz'; $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $search .= '1234567890!@#$%^&*()'; $search .= '~`";:?+/={}[]-_|\'\\'; for ($i = 0; $i < strlen($search); $i++) { $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ; $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ; } $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{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 +---------------------------------------------------------- * @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; } /**---------------------------------------------------------- * 在数据列表中搜索 +---------------------------------------------------------- * @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; } /** +---------------------------------------------------------- * 字节格式化 把字节数格式为 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]; } /** +---------------------------------------------------------- * 对查询结果集进行排序 +---------------------------------------------------------- * @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; } ?>
0321hy
trunk/Lib/Common/common.php
PHP
asf20
64,255
<?php //星级转化数组 function admin_star_arr($stars){ for ($i=1; $i<=5; $i++) { if ($i <= $stars){ $ss[$i]=1; }else{ $ss[$i]=0; } } return $ss; } // 获取模板分页数据大小 function gettplnum($rule,$filename){ $content = read_file(TMPL_PATH.C('default_theme').'/Home/'.trim($filename).'.html'); preg_match_all('/'.$rule.'/', $content, $data); foreach($data[1] as $key=>$val){ if(strpos($val,'page:true')>0){ $array = explode(';',str_replace('num','limit',$val)); foreach ($array as $v){list($key,$val) = explode(':',trim($v));$param[trim($key)]=trim($val);} return $param['limit'];break; } } return 0; } // 获取相对应的影片或文章 function getcmcid($id,$sid){ if($sid == 1){ $rs = D("Vod"); $array=$rs->field('vod_name')->where('vod_id='.$id)->find(); if($array){return $array['vod_name'];} }else{ $rs = D("News"); $array=$rs->field('news_name')->where('news_id='.$id)->find(); if($array){return $array['news_name'];} } return '未知数据!'; } // 安装测试写入文件 function testwrite($d){ $tfile = '_ppvod.txt'; $d = ereg_replace('/$','',$d); $fp = @fopen($d.'/'.$tfile,'w'); if(!$fp){ return false; }else{ fclose($fp); $rs = @unlink($d.'/'.$tfile); if($rs){ return true; }else{ return false; } } } //获取模板编辑名称 function gettplname($filename){ if('pp_footer.html' == $filename){ return '底部公用模板'; }elseif('pp_header.html' == $filename){ return '顶部公用模板'; }elseif('pp_index.html' == $filename){ return '网站首页模板'; }elseif('pp_news.html' == $filename){ return '新闻内容模板'; }elseif('pp_newschannel.html' == $filename){ return '新闻频道列表模板'; }elseif('pp_newslist.html' == $filename){ return '新闻栏目列表模板'; }elseif('pp_newssearch.html' == $filename){ return '新闻搜索模板'; }elseif('pp_newstag.html' == $filename){ return '新闻标签模板'; }elseif('pp_play.html' == $filename){ return '播放页模板'; }elseif('pp_vod.html' == $filename){ return '视频内容模板'; }elseif('pp_vodlist.html' == $filename){ return '视频栏目列表模板'; }elseif('pp_vodchannel.html' == $filename){ return '视频频道列表模板'; }elseif('pp_vodsearch.html' == $filename){ return '视频搜索模板'; }elseif('pp_vodtag.html' == $filename){ return '视频标签模板'; }elseif('pp_comment.html' == $filename){ return '评论模板'; }elseif('pp_guestbook.html' == $filename){ return '留言模板'; }elseif('style.css' == $filename){ return '模板主题样式表'; }elseif('js.css' == $filename){ return 'Javascript样式表'; }elseif('js.js' == $filename){ return 'Javascript文件'; }else{ if(stristr($filename,'system_')){ return '自定义标签'; }elseif(stristr($filename,'my_')){ return '自定义模板'; }else{ return '未知文件'; } } } // 获取数据库表名描述 function gettablename($tablename){ if (strpos($tablename,'ads')>0){ return '广告'; } if (strpos($tablename,'news')>0){ return '文章'; } if (strpos($tablename,'vod')>0){ return '影视'; } if (strpos($tablename,'list')>0){ return '栏目'; } if (strpos($tablename,'cm')>0){ return '评论信息'; } if (strpos($tablename,'gb')>0){ return '留言本'; } if (strpos($tablename,'admin')>0){ return '后台用户'; } if (strpos($tablename,'special')>0){ return '专题'; } if (strpos($tablename,'user')>0){ return '用户中心'; } if (strpos($tablename,'view')>0){ return '观看记录'; } if (strpos($tablename,'slide')>0){ return '幻灯片'; } if (strpos($tablename,'link')>0){ return '友情链接'; } if (strpos($tablename,'collect')>0){ return '采集'; } if (strpos($tablename,'tag')>0){ return '标签'; } } // 获取文件夹大小 function getdirsize($dir){ $dirlist = opendir($dir); while (false !== ($folderorfile = readdir($dirlist))){ if($folderorfile != "." && $folderorfile != "..") { if (is_dir("$dir/$folderorfile")) { $dirsize += getdirsize("$dir/$folderorfile"); }else{ $dirsize += filesize("$dir/$folderorfile"); } } } closedir($dirlist); return $dirsize; } //生成热门关键词JS function admin_ff_hot_key($string){ $array_hot = array(); foreach(explode(chr(13),trim($string)) as $key=>$value){ $array = explode('|',$value); if($array[1]){ $array_hot[$key] = '<a href="'.$array[1].'" target="_blank">'.trim($array[0]).'</a>'; }else{ $array_hot[$key] = '<a href="'.UU('Home-vod/search',array('wd'=>urlencode(trim($value))),false,true).'">'.trim($value).'</a>'; } } $hotkey = implode(' ',$array_hot); $hotkey = 'document.write(\''.$hotkey.'\');'; write_file('./Runtime/Js/hotkey.js',$hotkey); } //替换采集等通过url参数传值 function admin_ff_url_repalce($xmlurl,$order='asc'){ if($order=='asc'){ return str_replace(array('|','@','#','||'),array('/','=','&','//'),$xmlurl); }else{ return str_replace(array('/','=','&','||'),array('|','@','#','//'),$xmlurl); } } ?>
0321hy
trunk/Lib/Common/Admin/function.php
PHP
asf20
5,331
<?php // 本文档自动生成,仅供测试运行 class IndexAction extends Action { /** +---------------------------------------------------------- * 默认操作 +---------------------------------------------------------- */ public function index() { $this->display(THINK_PATH.'/Tpl/Autoindex/hello.html'); } /** +---------------------------------------------------------- * 探针模式 +---------------------------------------------------------- */ public function checkEnv() { load('pointer',THINK_PATH.'/Tpl/Autoindex');//载入探针函数 $env_table = check_env();//根据当前函数获取当前环境 echo $env_table; } } ?>
0321hy
trunk/Lib/ThinkPHP/Tpl/AutoIndex.tpl.php
PHP
asf20
761
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="zh-cn"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <meta name="author" content="Topthink - <www.thinkphp.cn>" /> <meta name="Copyright" content="Topthink - <www.topthink.com>" /> <meta name="description" content="ThinkPHP启动成功欢迎页" /> <title>^_^ Hello 欢迎使用ThinkPHP!</title> <style> body{font:400 14px/25px 'Microsoft Yahei',Tahoma,sans-serif;background:#fff;} a{text-decoration:none; color:#174B73; padding:0 5px;} a:hover{color:#f60;} img{border:0} em,i {font-style:normal;} h1{border-bottom:1px solid #ddd;padding:10px 0;} h2{font-size:14px;padding:10px;color:#06f;border:1px solid #e0e0e0;background:#ffd;} em{color:red} .hello{width:600px;height:100%;padding:10px; margin:50px auto 0; border:1px solid #ddd;overflow:hidden;} .link{float:right;} .copyright{clear:both;text-align:center;margin-top:10px;} .copyright i{color:silver;} .copyright sup{font-size:9pt;color:#666;} </style> </head> <body> <div class="hello"> <h1><a href="http://thinkphp.cn" title=""><img src="http://thinkphp.cn/ThinkPHP_logo.png" alt="ThinkPHP官方网站" /></a></h1> <h2><em>^_^</em> Hello &nbsp;&nbsp;欢迎使用ThinkPHP!</h2> <div class="link"> [<a href="__URL__/checkEnv/" title="">环境检测</a>][<a href="http://thinkphp.cn/Manual" title="">在线手册</a>][<a href="http://bbs.thinkphp.cn/" title="">官方社区</a>] </div> </div> <p class="copyright"><em>ThinkPHP</em>&nbsp;<sup>{*THINK_VERSION}</sup>&nbsp;<i class="slogan">{ WE CAN DO IT JUST THINK IT }</i></p> </div> </body> </html>
0321hy
trunk/Lib/ThinkPHP/Tpl/Autoindex/hello.html
HTML
asf20
1,861
<?php // ThinkPHP环境探针布署模式 // Author:caolei@topthink.com //检查当前脚本环境 function check_env(){ //预定义查询变量 $info = array( 'safe_mode'=>array('运行于安全模式',0), 'allow_url_fopen'=>array('访问 URL 对象','OFF','建议关闭'), 'register_globals'=>array('注册全局变量','OFF','建议关闭'), 'magic_quotes_gpc'=>array('魔术引号开启','OFF','建议关闭'), 'short_open_tag'=>array('短标记支持','OFF','建议关闭'), 'magic_quotes_runtime'=>array('自动转义溢出字符','OFF','建议关闭'), 'enable_dl'=>array('允许动态加载链接库','OFF','建议打开'), 'display_errors'=>array('显示错误信息',0), 'post_max_size'=>array('post最大数据量',0), 'upload_max_filesize'=>array('上传文件的最大大小',0), 'memory_limit'=>array('脚本最大内存使用量',1), ); $fun = array( 'mysql_close'=>array('MySQL数据库','ON','推荐使用MySQL数据库'), 'gd_info'=>array('图形处理 GD 库','ON','建议打开GD库'), 'socket_accept'=>array('Socket支持',0), 'xml_set_object'=>array('XML解析支持','ON','建议开启'), 'gzclose'=>array('压缩文件支持(Zlib)',0), 'mcrypt_cbc'=>array('MCrypt加密处理',0), 'preg_match'=>array('PREL相容语法 PCRE','ON','必须打开PREL语法兼容'), ); //根据查询条件,动态赋值 $phpversiON = phpversion();//获取php版本号 $versiON_msg=versiON_compare(PHP_VERSION,'5.2.0','<')?'推荐使用5.2.0以上版本':'正常使用'; $run_env = strtoupper(php_sapi_name());//查看运行环境 $os = PHP_OS; $is_rewrite = false;//预设rewrite为否定 if (($is_apache=strpos($run_env,'APACHE'))!==false) { $apache_list = apache_get_modules(); $is_rewrite = array_search('mod_rewrite',$apache_list)?true:false; unset($apache_list); } foreach ($info as $key => &$val) { $var = get_cfg_var($key)?get_cfg_var($key):ini_get($key); $val['value'] = ($var==0)?'OFF':(($var==1)?'ON':$var); if (is_numeric($val[1]) || $val['value']==$val[1]) { $val['message'] = '<span class="blue">√</span>'; }else{ $val['message'] = '<span class="red">'.$val[2].'</span>'; } } foreach ($fun as $key => &$val) { $val['value'] = functiON_exists($key)?'ON':'OFF'; if (is_numeric($val[1]) || $val['value']==$val[1]) { $val['message'] = '<span class="blue">√</span>'; }else{ $val['message'] = '<span class="red">'.$val[2].'</span>'; } } $moban =<<<HTML <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="zh-cn"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <meta name="author" content="Topthink - <www.thinkphp.cn>" /> <meta name="Copyright" content="" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <title>ThinkPHP环境检测</title> <style type="text/css"> *{margin:0;padding:0} body{font:400 14px/2em 'Microsoft Yahei','黑体',Tahoma,sans-serif;text-align:center;background:#fff;} table {margin:10px auto;width:700px;} .red{color:red;font-weight:bold;} .blue{color:blue;} .title{background:#e8efff;font-weight:bold;font-size:14px;padding:10px;color:blue;} .thead{background-color:#E8EFFF;color:blue;} .thead td{padding:4px;font-weight:bold;font-size:14px;} .tbhead{font-weight:normal;text-align:left;} td{text-align:left;} </style> </head> <body> <div class="title">环境检测</div> <table> <tr class='thead'><td colspan="2">服务器参数</td></tr> <tr><th class="tbhead">服务器域名/IP:</th><td>{$_SERVER['SERVER_NAME']} [{$_SERVER['REMOTE_ADDR']}]</td></tr> <tr><th class="tbhead">服务端口:</th><td>{$_SERVER['SERVER_PORT']}</td></tr> <tr><th class="tbhead">服务器类型/版本:</th><td>{$_SERVER['SERVER_SOFTWARE']}</td></tr> <tr><th class="tbhead">服务器操作系统:</th><td>{$os}</td></tr> <tr><th class="tbhead">网站根目录:</th><td>{$_SERVER['DOCUMENT_ROOT']}</td></tr> <tr><th class="tbhead">当前文件所在位置:</th><td>{$_SERVER['SCRIPT_FILENAME']}</td></tr> </table> <table> <tr> <th class='title'>变量名称</th><th class='title'>当前状态</th><th class='title'>推荐</th> </tr> <tbody> <tr><th class='tbhead'>PHP版本</th><td>{$phpversiON}</td><td>{$versiON_msg}</td></tr> <tr><th class='tbhead'>PHP运行环境</th><td>{$run_env}</td><td></td></tr> HTML; $moban .="<tr><th class='tbhead'>是否开启rewrite</th><td>"; if ($is_apache===false) { $moban .= "无法检测</td><td></td></tr>"; }else{ $moban .= ($is_rewrite)?'<span color="green">开启</span>':'<span class="red">未开启</span>'; $moban .="</td><td></td></tr>"; } $moban .="<tr class='thead'><td colspan='3'>PHP环境</td></tr>"; foreach ($info as $key => $val) { $moban.="<tr><th class='tbhead'>{$val[0]} [{$key}]</th><td>{$val['value']}</td><td>{$val['message']}</td></tr>"; } $moban .="<tr class='thead'><td colspan='3'>PHP模块检测</td></tr>"; foreach($fun as $key=>$val) { $moban.="<tr><th class='tbhead'>{$val[0]} [{$key}]</th><td>{$val['value']}</td><td>{$val['message']}</td></tr>"; } $moban .="</tbody></table></body></html>"; return $moban; } ?>
0321hy
trunk/Lib/ThinkPHP/Tpl/Autoindex/pointer.php
PHP
asf20
6,197
<div id="think_page_trace" style="background:white;margin:6px;font-size:14px;border:1px dashed silver;padding:8px"> <fieldset id="querybox" style="margin:5px;"> <legend style="color:gray;font-weight:bold">页面Trace信息</legend> <div style="overflow:auto;height:300px;text-align:left;"> <?php foreach ($_trace as $key=>$info){ echo $key.' : '.$info.'<br/>'; }?> </div> </fieldset> </div>
0321hy
trunk/Lib/ThinkPHP/Tpl/PageTrace.tpl.php
PHP
asf20
399
<?php // 本类由系统自动生成,仅供测试用途 class IndexAction extends Action { public function index(){ header("Content-Type:text/html; charset=utf-8"); echo '<div style="font-weight:normal;color:blue;float:left;width:345px;text-align:center;border:1px solid silver;background:#E8EFFF;padding:8px;font-size:14px;font-family:Tahoma">^_^ Hello,欢迎使用<span style="font-weight:bold;color:red">ThinkPHP</span></div>'; } } ?>
0321hy
trunk/Lib/ThinkPHP/Tpl/DefaultIndex.tpl.php
PHP
asf20
471
<?php // ThinkPHP环境探针布署模式 // Author:caolei@topthink.com class IndexAction extends Action { public function index() { header("Content-Type:text/html; charset=utf-8"); $env_table = $this->check_env(); echo $env_table; } public function check_env(){ //预定义查询变量 $info = array( 'safe_mode'=>array('运行于安全模式',0), 'allow_url_fopen'=>array('访问 URL 对象','OFF','建议关闭'), 'register_globals'=>array('注册全局变量','OFF','建议关闭'), 'magic_quotes_gpc'=>array('魔术引号开启','OFF','建议关闭'), 'short_open_tag'=>array('短标记支持','OFF','建议关闭'), 'magic_quotes_runtime'=>array('自动转义溢出字符','OFF','建议关闭'), 'enable_dl'=>array('允许动态加载链接库','OFF','建议打开'), 'display_errors'=>array('显示错误信息',0), 'post_max_size'=>array('post最大数据量',0), 'upload_max_filesize'=>array('上传文件的最大大小',0), 'memory_limit'=>array('脚本最大内存使用量',1), ); $fun = array( 'mysql_close'=>array('MySQL数据库','ON','推荐使用MySQL数据库'), 'gd_info'=>array('图形处理 GD 库','ON','建议打开GD库'), 'socket_accept'=>array('Socket支持',0), 'xml_set_object'=>array('XML解析支持','ON','建议开启'), 'gzclose'=>array('压缩文件支持(Zlib)',0), 'mcrypt_cbc'=>array('MCrypt加密处理',0), 'preg_match'=>array('PREL相容语法 PCRE','ON','必须打开PREL语法兼容'), ); //根据查询条件,动态赋值 $phpversiON = phpversion();//获取php版本号 $versiON_msg=versiON_compare(PHP_VERSION,'5.2.0','<')?'推荐使用5.2.0以上版本':'正常使用'; $run_env = strtoupper(php_sapi_name());//查看运行环境 $os = PHP_OS; $is_rewrite = false;//预设rewrite为否定 if (($is_apache=strpos($run_env,'APACHE'))!==false) { $apache_list = apache_get_modules(); $is_rewrite = array_search('mod_rewrite',$apache_list)?true:false; unset($apache_list); } foreach ($info as $key => &$val) { $var = get_cfg_var($key)?get_cfg_var($key):ini_get($key); $val['value'] = ($var==0)?'OFF':(($var==1)?'ON':$var); if (is_numeric($val[1]) || $val['value']==$val[1]) { $val['message'] = '<span class="blue">√</span>'; }else{ $val['message'] = '<span class="red">'.$val[2].'</span>'; } } foreach ($fun as $key => &$val) { $val['value'] = functiON_exists($key)?'ON':'OFF'; if (is_numeric($val[1]) || $val['value']==$val[1]) { $val['message'] = '<span class="blue">√</span>'; }else{ $val['message'] = '<span class="red">'.$val[2].'</span>'; } } $moban =<<<HTML <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="zh-cn"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <meta name="author" content="Topthink - <www.thinkphp.cn>" /> <meta name="Copyright" content="" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <title>ThinkPHP环境检测</title> <style type="text/css"> *{margin:0;padding:0} body{font:400 14px/2em 'Microsoft Yahei','黑体',Tahoma,sans-serif;text-align:center;background:#fff;} table {margin-top:10px;width:700px;} .red{color:red;font-weight:bold;} .blue{color:blue;} .title{background:#e8efff;font-weight:bold;font-size:14px;padding:10px;color:blue;} .thead{background-color:#E8EFFF;color:blue;} .thead td{padding:4px;font-weight:bold;font-size:14px;} .tbhead{font-weight:normal;text-align:left;} td{text-align:left;} </style> </head> <body> <div class="title">^_^ Hello, 欢迎使用<span class="red">ThinkPHP</span>!</div> <table> <tr class='thead'><td colspan="2">服务器参数</td></tr> <tr><th class="tbhead">服务器域名/IP:</th><td>{$_SERVER['SERVER_NAME']} [{$_SERVER['REMOTE_ADDR']}]</td></tr> <tr><th class="tbhead">服务端口:</th><td>{$_SERVER['SERVER_PORT']}</td></tr> <tr><th class="tbhead">服务器类型/版本:</th><td>{$_SERVER['SERVER_SOFTWARE']}</td></tr> <tr><th class="tbhead">服务器操作系统:</th><td>{$os}</td></tr> <tr><th class="tbhead">网站根目录:</th><td>{$_SERVER['DOCUMENT_ROOT']}</td></tr> <tr><th class="tbhead">当前文件所在位置:</th><td>{$_SERVER['SCRIPT_FILENAME']}</td></tr> </table> <table> <tr> <th class='title'>变量名称</th><th class='title'>当前状态</th><th class='title'>推荐</th> </tr> <tbody> <tr><th class='tbhead'>PHP版本</th><td>{$phpversiON}</td><td>{$versiON_msg}</td></tr> <tr><th class='tbhead'>PHP运行环境</th><td>{$run_env}</td><td></td></tr> HTML; $moban .="<tr><th class='tbhead'>是否开启rewrite</th><td>"; if ($is_apache===false) { $moban .= "无法检测</td><td></td></tr>"; }else{ $moban .= ($is_rewrite)?'<span color="green">开启</span>':'<span class="red">未开启</span>'; $moban .="</td><td></td></tr>"; } $moban .="<tr class='thead'><td colspan='3'>PHP环境</td></tr>"; foreach ($info as $key => $val) { $moban.="<tr><th class='tbhead'>{$val[0]} [{$key}]</th><td>{$val['value']}</td><td>{$val['message']}</td></tr>"; } $moban .="<tr class='thead'><td colspan='3'>PHP模块检测</td></tr>"; foreach($fun as $key=>$val) { $moban.="<tr><th class='tbhead'>{$val[0]} [{$key}]</th><td>{$val['value']}</td><td>{$val['message']}</td></tr>"; } $moban .="</tbody></table></body></html>"; return $moban; } } ?>
0321hy
trunk/Lib/ThinkPHP/Tpl/ThinkCheckIndex.tpl.php
PHP
asf20
6,435
<?php // 可视化简约布署模式 class IndexAction extends Action { public function index() { header("Content-Type:text/html; charset=utf-8"); echo "引导式布署模式,流程待添加"; } } ?>
0321hy
trunk/Lib/ThinkPHP/Tpl/BuildModeIndex.tpl.php
PHP
asf20
239
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>系统发生错误</title> <meta http-equiv="content-type" content="text/html;charset=utf-8"/> <meta name="Generator" content="EditPlus"/> <style> body{ font-family: 'Microsoft Yahei', Verdana, arial, sans-serif; font-size:14px; } a{text-decoration:none;color:#174B73;} a:hover{ text-decoration:none;color:#FF6600;} h2{ border-bottom:1px solid #DDD; padding:8px 0; font-size:25px; } .title{ margin:4px 0; color:#F60; font-weight:bold; } .message,#trace{ padding:1em; border:solid 1px #000; margin:10px 0; background:#FFD; line-height:150%; } .message{ background:#FFD; color:#2E2E2E; border:1px solid #E0E0E0; } #trace{ background:#E7F7FF; border:1px solid #E0E0E0; color:#535353; } .notice{ padding:10px; margin:5px; color:#666; background:#FCFCFC; border:1px solid #E0E0E0; } .red{ color:red; font-weight:bold; } </style> </head> <body> <div class="notice"> <h2>系统发生错误 </h2> <div >您可以选择 [ <A HREF="<?php echo(strip_tags($_SERVER['PHP_SELF']))?>">重试</A> ] [ <A HREF="javascript:history.back()">返回</A> ] 或者 [ <A HREF="<?php echo(__APP__);?>">回到首页</A> ]</div> <?php if(isset($e['file'])) {?> <p><strong>错误位置:</strong> FILE: <span class="red"><?php echo $e['file'] ;?></span> LINE: <span class="red"><?php echo $e['line'];?></span></p> <?php }?> <p class="title">[ 错误信息 ]</p> <p class="message"><?php echo strip_tags($e['message']);?></p> <?php if(isset($e['trace'])) {?> <p class="title">[ TRACE ]</p> <p id="trace"> <?php echo nl2br($e['trace']);?> </p> <?php }?> </div> <div align="center" style="color:#FF3300;margin:5pt;font-family:Verdana"><a href="http://www.feifeicms.com" target="_blank">飞飞影视系统 www.feifeicms.com</a></div> </body> </html>
0321hy
trunk/Lib/ThinkPHP/Tpl/ThinkException.tpl.php
PHP
asf20
1,994
<?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_import(array( 'Model' => THINK_PATH.'/Mode/Thin/Model.class.php', 'Db' => THINK_PATH.'/Mode/Thin/Db.class.php', 'Debug' => THINK_PATH.'/Lib/Think/Util/Debug.class.php', ) ); ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Cli/alias.php
PHP
asf20
886
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 命令模式应用程序类 +------------------------------------------------------------------------------ */ class App {//类定义开始 /** +---------------------------------------------------------- * 应用程序初始化 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function run() { // 设定错误和异常处理 set_error_handler(array('App',"appError")); set_exception_handler(array('App',"appException")); //[RUNTIME] // 检查项目是否编译过 // 在部署模式下会自动在第一次执行的时候编译项目 if(defined('RUNTIME_MODEL')){ // 运行模式无需载入项目编译缓存 }elseif(is_file(RUNTIME_PATH.'~app.php')) { // 直接读取编译后的项目文件 C(include RUNTIME_PATH.'~app.php'); }else{ // 预编译项目 App::build(); } //[/RUNTIME] // 取得模块和操作名称 define('MODULE_NAME', isset($_SERVER['argv'][1])?$_SERVER['argv'][1]:C('DEFAULT_MODULE')); define('ACTION_NAME', isset($_SERVER['argv'][2])?$_SERVER['argv'][2]:C('DEFAULT_ACTION')); // 执行操作 R(MODULE_NAME,ACTION_NAME); // 保存日志记录 if(C('LOG_RECORD')) Log::save(); return ; } //[RUNTIME] /** +---------------------------------------------------------- * 读取配置信息 编译项目 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static private function build() { // 加载惯例配置文件 C(include THINK_PATH.'/Common/convention.php'); // 加载项目配置文件 if(is_file(CONFIG_PATH.'config.php')) { C(include CONFIG_PATH.'config.php'); } $common = ''; $debug = C('APP_DEBUG'); // 是否调试模式 // 加载项目公共文件 if(is_file(COMMON_PATH.'common.php')) { include COMMON_PATH.'common.php'; if(!$debug) { // 编译文件 $common .= compile(COMMON_PATH.'common.php'); } } // 加载项目编译文件列表 if(is_file(CONFIG_PATH.'app.php')) { $list = include CONFIG_PATH.'app.php'; foreach ($list as $key=>$file){ // 加载并编译文件 require $file; if(!$debug) { $common .= compile($file); } } } // 如果是调试模式加载调试模式配置文件 if($debug) { // 加载系统默认的开发模式配置文件 C(include THINK_PATH.'/Common/debug.php'); if(is_file(CONFIG_PATH.'debug.php')) { // 允许项目增加开发模式配置定义 C(include CONFIG_PATH.'debug.php'); } }else{ // 部署模式下面生成编译文件 // 下次直接加载项目编译文件 if(defined('RUNTIME_ALLINONE')) { // 获取用户自定义变量 $defs = get_defined_constants(TRUE); $content = array_define($defs['user']); $content .= substr(file_get_contents(RUNTIME_PATH.'~runtime.php'),5); $content .= $common."\nreturn ".var_export(C(),true).';'; file_put_contents(RUNTIME_PATH.'~allinone.php',strip_whitespace('<?php '.$content)); }else{ $content = "<?php ".$common."\nreturn ".var_export(C(),true).";\n?>"; file_put_contents(RUNTIME_PATH.'~app.php',strip_whitespace($content)); } } return ; } //[/RUNTIME] /** +---------------------------------------------------------- * 自定义异常处理 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $e 异常对象 +---------------------------------------------------------- */ static public function appException($e) { exit($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); } exit($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; } } };//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Cli/App.class.php
PHP
asf20
6,744
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 命令模式Action控制器基类 +------------------------------------------------------------------------------ */ abstract class Action extends Think {//类定义开始 /** +---------------------------------------------------------- * 魔术方法 有不存在的操作的时候执行 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名 * @param array $parms 参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$parms) { if(strtolower($method) == strtolower(ACTION_NAME)) { // 如果定义了_empty操作 则调用 if(method_exists($this,'_empty')) { $this->_empty($method,$parms); }else { // 抛出异常 exit(L('_ERROR_ACTION_').ACTION_NAME); } }else{ exit(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); } } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Cli/Action.class.php
PHP
asf20
1,927
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ // 命令行模式核心定义文件列表 return array( THINK_PATH.'/Common/functions.php', // 系统函数库 THINK_PATH.'/Lib/Think/Core/Think.class.php', THINK_PATH.'/Lib/Think/Core/Log.class.php', THINK_PATH.'/Mode/Cli/App.class.php', THINK_PATH.'/Mode/Cli/Action.class.php', THINK_PATH.'/Mode/Cli/alias.php', // 加载别名 ); ?>
0321hy
trunk/Lib/ThinkPHP/Mode/cli.php
PHP
asf20
984
<?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_import(array( 'Dispatcher' => THINK_PATH.'/Mode/Lite/Dispatcher.class.php', 'Model' => THINK_PATH.'/Mode/Lite/Model.class.php', 'Db' => THINK_PATH.'/Mode/Lite/Db.class.php', 'Debug' => THINK_PATH.'/Lib/Think/Util/Debug.class.php', 'Session' => THINK_PATH.'/Lib/Think/Util/Session.class.php', 'ThinkTemplateLite' => THINK_PATH.'/Mode/Lite/ThinkTemplateLite.class.php', 'ThinkTemplateCompiler' => THINK_PATH.'/Mode/Lite/ThinkTemplateCompiler.class.php', ) ); ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Lite/alias.php
PHP
asf20
1,223
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 精简模式应用程序类 +------------------------------------------------------------------------------ */ class App {//类定义开始 /** +---------------------------------------------------------- * 应用程序初始化 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function run() { // 设定错误和异常处理 set_error_handler(array('App',"appError")); set_exception_handler(array('App',"appException")); //[RUNTIME] // 检查项目是否编译过 // 在部署模式下会自动在第一次执行的时候编译项目 if(defined('RUNTIME_MODEL')){ // 运行模式无需载入项目编译缓存 }elseif(is_file(RUNTIME_PATH.'~app.php') && (!is_file(CONFIG_PATH.'config.php') || filemtime(RUNTIME_PATH.'~app.php')>filemtime(CONFIG_PATH.'config.php'))) { // 直接读取编译后的项目文件 C(include RUNTIME_PATH.'~app.php'); }else{ // 预编译项目 App::build(); } //[/RUNTIME] // 应用调度过滤器 // 如果没有加载任何URL调度器 // 默认只支持 QUERY_STRING 方式 Dispatcher::dispatch(); // 取得模块和操作名称 // 可以在Dispatcher中定义获取规则 if(!defined('MODULE_NAME')) define('MODULE_NAME', App::getModule()); // Module名称 if(!defined('ACTION_NAME')) define('ACTION_NAME', App::getAction()); // Action操作 // 记录应用初始化时间 if(C('SHOW_RUN_TIME')) $GLOBALS['_initTime'] = microtime(TRUE); // 执行操作 R(MODULE_NAME,ACTION_NAME); // 保存日志记录 if(C('LOG_RECORD')) Log::save(); return ; } //[RUNTIME] /** +---------------------------------------------------------- * 读取配置信息 编译项目 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static private function build() { // 加载惯例配置文件 C(include THINK_PATH.'/Common/convention.php'); // 加载项目配置文件 if(is_file(CONFIG_PATH.'config.php')) { C(include CONFIG_PATH.'config.php'); } $common = ''; $debug = C('APP_DEBUG'); // 是否调试模式 // 加载项目公共文件 if(is_file(COMMON_PATH.'common.php')) { include COMMON_PATH.'common.php'; if(!$debug) { // 编译文件 $common .= compile(COMMON_PATH.'common.php'); } } // 加载项目编译文件列表 if(is_file(CONFIG_PATH.'app.php')) { $list = include CONFIG_PATH.'app.php'; foreach ($list as $key=>$file){ // 加载并编译文件 require $file; if(!$debug) { $common .= compile($file); } } } // 如果是调试模式加载调试模式配置文件 if($debug) { // 加载系统默认的开发模式配置文件 C(include THINK_PATH.'/Common/debug.php'); if(is_file(CONFIG_PATH.'debug.php')) { // 允许项目增加开发模式配置定义 C(include CONFIG_PATH.'debug.php'); } }else{ // 部署模式下面生成编译文件 // 下次直接加载项目编译文件 if(defined('RUNTIME_ALLINONE')) { // 获取用户自定义变量 $defs = get_defined_constants(TRUE); $content = array_define($defs['user']); $content .= substr(file_get_contents(RUNTIME_PATH.'~runtime.php'),5); $content .= $common."\nreturn ".var_export(C(),true).';'; file_put_contents(RUNTIME_PATH.'~allinone.php',strip_whitespace('<?php '.$content)); }else{ $content = "<?php ".$common."\nreturn ".var_export(C(),true).";\n?>"; file_put_contents(RUNTIME_PATH.'~app.php',strip_whitespace($content)); } } return ; } //[/RUNTIME] /** +---------------------------------------------------------- * 获得实际的模块名称 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static private function getModule() { $var = C('VAR_MODULE'); $module = !empty($_POST[$var]) ? $_POST[$var] : (!empty($_GET[$var])? $_GET[$var]:C('DEFAULT_MODULE')); if(C('URL_CASE_INSENSITIVE')) { // URL地址不区分大小写 define('P_MODULE_NAME',strtolower($module)); // 智能识别方式 index.php/user_type/index/ 识别到 UserTypeAction 模块 $module = ucfirst(parse_name(strtolower($module),1)); } unset($_POST[$var],$_GET[$var]); return $module; } /** +---------------------------------------------------------- * 获得实际的操作名称 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static private function getAction() { $var = C('VAR_ACTION'); $action = !empty($_POST[$var]) ? $_POST[$var] : (!empty($_GET[$var])?$_GET[$var]:C('DEFAULT_ACTION')); unset($_POST[$var],$_GET[$var]); return $action; } /** +---------------------------------------------------------- * 自定义异常处理 +---------------------------------------------------------- * @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; } } };//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Lite/App.class.php
PHP
asf20
8,836
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ define('CLIENT_MULTI_RESULTS', 131072); /** +------------------------------------------------------------------------------ * ThinkPHP 精简模式数据库中间层实现类 只支持Mysql +------------------------------------------------------------------------------ */ class Db extends Think { 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(); } $this->W(1); $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->addSpecialChar($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->addSpecialChar($key).' AS '.$this->addSpecialChar($field); else $array[] = $this->addSpecialChar($field); } $fieldsStr = implode(',', $array); }elseif(is_string($fields) && !empty($fields)) { $fieldsStr = $this->addSpecialChar($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, 'addSpecialChar')); return implode(',',$tables); } /** +---------------------------------------------------------- * where分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $where +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseWhere($where) { $whereStr = ''; if(is_string($where)) { // 直接使用字符串条件 $whereStr = $where; }else{ // 使用数组条件表达式 if(array_key_exists('_logic',$where)) { // 定义逻辑运算规则 例如 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->addSpecialChar($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(array_key_exists('_logic',$where)) { $op = ' '.strtoupper($where['_logic']).' '; unset($where['_logic']); }else{ $op = ' AND '; } $array = array(); foreach ($where as $field=>$data) $array[] = $this->addSpecialChar($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->addSpecialChar($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 addSpecialChar(&$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; } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Lite/Db.class.php
PHP
asf20
39,039
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 精简模式Model模型类 * 只支持CURD和连贯操作 以及常用查询 去掉回调接口 +------------------------------------------------------------------------------ */ class Model extends Think { // 当前数据库操作对象 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(); } // 数据库初始化操作 import("Db"); // 获取数据库操作对象 $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)) { // 如果删除条件为空 则删除当前数据对象所对应的记录 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(); } }; ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Lite/Model.class.php
PHP
asf20
21,657
<?php // +---------------------------------------------------------------------- // | ThinkPHP // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 模板引擎Lite版本 +------------------------------------------------------------------------------ */ class ThinkTemplateLite { // 属性定义 protected $var = array();//模板变量 protected $config = array();// 模板配置 // 架构方法 public function __construct(){ $this->config['cache_path'] = 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('TMPL_FILE_NAME'); $this->config['tag_level'] = C('TAG_NESTED_LEVEL'); } // 正则替换的转义 方便定制 private function stripPreg($str) { $str = str_replace(array('{','}','(',')','|','[',']'),array('\{','\}','\(','\)','\|','\[','\]'),$str); return $str; } // 模板配置赋值 public function __set($name,$value='') { if(is_array($name)) { $this->config = array_merge($this->config,$name); }else{ $this->config[$name]= $value; } } // 模板配置取值 public function __get($name) { if(isset($this->config[$name])) return $this->config[$name]; else return null; } // 模板变量赋值 public function assign($name,$value) { if(is_array($name)) { $this->var = array_merge($this->var,$name); }else{ $this->var[$name]= $value; } } // 模板变量取值 public function get($name) { if(isset($this->var[$name])) return $this->var[$name]; else return false; } // 载入模板 模板引擎入口 public function fetch($templateFile,$templateVar='') { if(!empty($templateVar)) $this->assign($templateVar); //根据模版文件名定位缓存文件 $tmplCacheFile = $this->config['cache_path'].md5($templateFile).$this->config['cache_suffix']; if (!$this->checkCache($templateFile,$tmplCacheFile)) // 判断缓存是否有效 $this->loadTemplate($templateFile,$tmplCacheFile); // 模板阵列变量分解成为独立变量 extract($this->var, EXTR_OVERWRITE); //载入模版缓存文件 include $tmplCacheFile; } // 读取并编译模板 protected function loadTemplate($templateFile,$tmplCacheFile) { // 需要更新模版 读出原模板内容 $tmplContent = file_get_contents($templateFile); //编译模板内容 $tmplContent = $this->compiler($tmplContent,$templateFile); // 检测缓存目录 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); } // 模板编译 protected function compiler($tmplContent,$templateFile) { $compiler = new ThinkTemplateCompiler(); return $compiler->parse($tmplContent,$templateFile); } // 检查缓存 protected function checkCache($tmplTemplateFile,$tmplCacheFile) { if (!$this->config['tmpl_cache']) // 优先对配置检测 return false; if(!is_file($tmplCacheFile)){ return false; }elseif (filemtime($tmplTemplateFile) > filemtime($tmplCacheFile)) { // 模板文件如果有更新则缓存需要更新 return false; }elseif ($this->config['cache_time'] != -1 && time() > filemtime($tmplCacheFile)+$this->config['cache_time']) { // 缓存是否在有效期 return false; } //缓存有效 return true; } } ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Lite/ThinkTemplateLite.class.php
PHP
asf20
5,103
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * 精简模式的Dispatcher类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class Dispatcher extends Think {//类定义开始 /** +---------------------------------------------------------- * URL映射到控制器 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function dispatch() { $urlMode = C('URL_MODEL'); if($urlMode == URL_REWRITE ) { //当前项目地址 $url = dirname(_PHP_FILE_); if($url == '/' || $url == '\\') $url = ''; define('PHP_FILE',$url); }elseif($urlMode == URL_COMPAT){ define('PHP_FILE',_PHP_FILE_.'?'.C('VAR_PATHINFO').'='); }else { //当前项目地址 define('PHP_FILE',_PHP_FILE_); } if($urlMode) { // 获取PATHINFO信息 self::getPathInfo(); if (!empty($_GET)) { $_GET = array_merge (self :: parsePathInfo(),$_GET); $_varModule = C('VAR_MODULE'); $_varAction = C('VAR_ACTION'); $_depr = C('URL_PATHINFO_DEPR'); $_pathModel = C('URL_PATHINFO_MODEL'); // 设置默认模块和操作 if(empty($_GET[$_varModule])) $_GET[$_varModule] = C('DEFAULT_MODULE'); if(empty($_GET[$_varAction])) $_GET[$_varAction] = C('DEFAULT_ACTION'); // 组装新的URL地址 $_URL = '/'; if($_pathModel==2) { // modelName/actionName/ $_URL .= $_GET[$_varModule].$_depr.$_GET[$_varAction].$_depr; unset($_GET[$_varModule],$_GET[$_varAction]); } foreach ($_GET as $_VAR => $_VAL) { if('' != trim($_GET[$_VAR])) { if($_pathModel==2) { $_URL .= $_VAR.$_depr.rawurlencode($_VAL).$_depr; }else{ $_URL .= $_VAR.'/'.rawurlencode($_VAL).'/'; } } } if($_depr==',') $_URL = substr($_URL, 0, -1).'/'; //重定向成规范的URL格式 redirect(PHP_FILE.$_URL); }else{ //给_GET赋值 以保证可以按照正常方式取_GET值 $_GET = array_merge(self :: parsePathInfo(),$_GET); //保证$_REQUEST正常取值 $_REQUEST = array_merge($_POST,$_GET); } } } /** +---------------------------------------------------------- * 分析PATH_INFO的参数 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ private static function parsePathInfo() { $pathInfo = array(); if(C('URL_PATHINFO_MODEL')==2){ $paths = explode(C('URL_PATHINFO_DEPR'),trim($_SERVER['PATH_INFO'],'/')); $pathInfo[C('VAR_MODULE')] = array_shift($paths); $pathInfo[C('VAR_ACTION')] = array_shift($paths); for($i = 0, $cnt = count($paths); $i <$cnt; $i++){ if(isset($paths[$i+1])) { $pathInfo[$paths[$i]] = (string)$paths[++$i]; }elseif($i==0) { $pathInfo[$pathInfo[C('VAR_ACTION')]] = (string)$paths[$i]; } } }else { $res = preg_replace('@(\w+)'.C('URL_PATHINFO_DEPR').'([^,\/]+)@e', '$pathInfo[\'\\1\']="\\2";', $_SERVER['PATH_INFO']); } return $pathInfo; } /** +---------------------------------------------------------- * 获得服务器的PATH_INFO信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public static function getPathInfo() { if(!empty($_GET[C('VAR_PATHINFO')])) { // 兼容PATHINFO 参数 $path = $_GET[C('VAR_PATHINFO')]; unset($_GET[C('VAR_PATHINFO')]); }elseif(!empty($_SERVER['PATH_INFO'])){ $pathInfo = $_SERVER['PATH_INFO']; if(0 === strpos($pathInfo,$_SERVER['SCRIPT_NAME'])) $path = substr($pathInfo, strlen($_SERVER['SCRIPT_NAME'])); else $path = $pathInfo; } if(C('HTML_URL_SUFFIX') && !empty($path)) { $suffix = substr(C('HTML_URL_SUFFIX'),1); $path = preg_replace('/\.'.$suffix.'$/','',$path); } $_SERVER['PATH_INFO'] = empty($path) ? '/' : $path; } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Lite/Dispatcher.class.php
PHP
asf20
6,190
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 精简模式Action控制器基类 +------------------------------------------------------------------------------ */ abstract class Action extends Think {//类定义开始 protected $tVar = array(); // 模板输出变量 protected $trace = array(); // 页面trace变量 /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct() { //控制器初始化 if(method_exists($this,'_initialize')) { $this->_initialize(); } } public function trace($title,$value='') { if(is_array($title)) $this->trace = array_merge($this->trace,$title); else $this->trace[$title] = $value; } /** +---------------------------------------------------------- * 魔术方法 有不存在的操作的时候执行 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名 * @param array $parms 参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$parms) { if(strtolower($method) == strtolower(ACTION_NAME)) { // 如果定义了_empty操作 则调用 if(method_exists($this,'_empty')) { $this->_empty($method,$parms); }else { // 检查是否存在默认模版 如果有直接输出模版 if(file_exists_case(TMPL_PATH.MODULE_NAME.'/'.ACTION_NAME.C('TMPL_TEMPLATE_SUFFIX'))) $this->display(); else // 抛出异常 throw_exception(L('_ERROR_ACTION_').ACTION_NAME); } }elseif(in_array(strtolower($method),array('ispost','isget','ishead','isdelete','isput'))){ return strtolower($_SERVER['REQUEST_METHOD']) == strtolower(substr($method,2)); }else{ throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); } } /** +---------------------------------------------------------- * 模板变量赋值 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $name * @param mixed $value +---------------------------------------------------------- */ protected 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; } } public function get($name){ if(isset($this->tVar[$name])) return $this->tVar[$name]; else return false; } /** +---------------------------------------------------------- * 是否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 $message 错误信息 * @param Boolean $ajax 是否为Ajax方式 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function error($message,$ajax=false) { $this->_dispatch_jump($message,0,$ajax); } /** +---------------------------------------------------------- * 操作成功跳转的快捷方法 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $message 提示信息 * @param Boolean $ajax 是否为Ajax方式 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function success($message,$ajax=false) { $this->_dispatch_jump($message,1,$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='') { // 保证AJAX返回后也能保存日志 if(C('LOG_RECORD')) Log::save(); $result = array(); $result['status'] = $status; $result['info'] = $info; $result['data'] = $data; 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='') { if(C('LOG_RECORD')) Log::save(); $url = U($url,$params); redirect($url,$delay,$msg); } /** +---------------------------------------------------------- * 默认跳转操作 支持错误导向和正确跳转 * 调用模板显示 默认为public目录下面的success页面 * 提示页面为可配置 支持模板标签 +---------------------------------------------------------- * @param string $message 提示信息 * @param Boolean $status 状态 * @param Boolean $ajax 是否为Ajax方式 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ private function _dispatch_jump($message,$status=1,$ajax=false) { // 判断是否为AJAX返回 if($ajax || $this->isAjax()) $this->ajaxReturn('',$message,$status); // 提示标题 $this->assign('msgTitle',$status? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_')); //如果设置了关闭窗口,则提示完毕后自动关闭窗口 if($this->get('closeWin')) $this->assign('jumpUrl','javascript:window.close();'); $this->assign('status',$status); // 状态 $this->assign('message',$message);// 提示信息 //保证输出不受静态缓存影响 C('HTML_CACHE_ON',false); if($status) { //发送成功信息 // 成功操作后默认停留1秒 if(!$this->get('waitSecond')) $this->assign('waitSecond',"1"); // 默认操作成功自动返回操作前页面 if(!$this->get('jumpUrl')) $this->assign("jumpUrl",$_SERVER["HTTP_REFERER"]); $this->display(C('TMPL_ACTION_SUCCESS')); }else{ //发生错误时候默认停留3秒 if(!$this->get('waitSecond')) $this->assign('waitSecond',"3"); // 默认发生错误的话自动返回上页 if(!$this->get('jumpUrl')) $this->assign('jumpUrl',"javascript:history.back(-1);"); $this->display(C('TMPL_ACTION_ERROR')); } if(C('LOG_RECORD')) Log::save(); // 中止执行 避免出错后继续执行 exit ; } /** +---------------------------------------------------------- * 模板显示 * 只支持PHP模板 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $templateFile 指定要调用的模板文件 * 默认为空 由系统自动定位模板文件 * @param string $charset 输出编码 * @param string $contentType 输出类型 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function display($templateFile='',$charset='',$contentType='text/html') { if(empty($charset)) $charset = C('DEFAULT_CHARSET'); // 网页字符编码 header("Content-Type:".$contentType."; charset=".$charset); header("Cache-control: private"); //支持页面回跳 //页面缓存 ob_start(); ob_implicit_flush(0); // 自动定位模板文件 $templateFile = $this->parseTemplateFile($templateFile); if('php'==strtolower(C('TMPL_ENGINE_TYPE'))) { // 模板阵列变量分解成为独立变量 extract($this->tVar, EXTR_OVERWRITE); // 直接载入PHP模板 include $templateFile; }else{ // 模板文件需要重新编译 支持第三方模板引擎 // 调用模板引擎解析和输出 $tpl = new ThinkTemplateLite; $tpl->fetch($templateFile,$this->tVar); } // 获取并清空缓存 $content = ob_get_clean(); // 模板内容替换 $content = $this->templateContentReplace($content); if(C('SHOW_RUN_TIME')){ $runtime = '<div id="think_run_time" class="think_run_time">'.$this->showTime().'</div>'; if(strpos($content,'{__RUNTIME__}')) $content = str_replace('{__RUNTIME__}',$runtime,$content); else $content .= $runtime; } echo $content; if(C('SHOW_PAGE_TRACE')) $this->showTrace(); } /** +---------------------------------------------------------- * 自动定位模板文件 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param string $templateFile 文件名 +---------------------------------------------------------- * @return string +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ private function parseTemplateFile($templateFile) { // Lite模式没有模板主题的概念 if(''==$templateFile) { // 如果模板文件名为空 按照默认规则定位 $templateFile = TMPL_PATH.MODULE_NAME.'/'.ACTION_NAME.C('TMPL_TEMPLATE_SUFFIX'); }elseif(strpos($templateFile,':')){ // 引入其它模块的操作模板 $templateFile = TMPL_PATH.str_replace(':','/',$templateFile).C('TMPL_TEMPLATE_SUFFIX'); }elseif(!is_file($templateFile)) { // 引入当前模块的其它操作模板 $templateFile = TMPL_PATH.MODULE_NAME.'/'.$templateFile.C('TMPL_TEMPLATE_SUFFIX'); } if(!file_exists_case($templateFile)) throw_exception(L('_TEMPLATE_NOT_EXIST_').'['.$templateFile.']'); return $templateFile; } /** +---------------------------------------------------------- * 模板内容替换 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $content 模板内容 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function templateContentReplace($content) { // 系统默认的特殊变量替换 $replace = array( '../Public' => __ROOT__.'/'.APP_NAME.'/'.TMPL_DIR.'/Public',// 项目公共目录 '__PUBLIC__' => __ROOT__.'/Public',// 站点公共目录 '__ROOT__' => __ROOT__, // 当前网站地址 '__APP__' => PHP_FILE, // 当前项目地址 '__URL__' => PHP_FILE.'/'.MODULE_NAME, // 当前模块地址 '__ACTION__' => PHP_FILE.'/'.MODULE_NAME.'/'.ACTION_NAME, // 当前操作地址 '__SELF__' => $_SERVER['PHP_SELF'], // 当前页面地址 ); // 允许用户自定义模板的字符串替换 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; } /** +---------------------------------------------------------- * 显示运行时间、数据库操作、缓存次数、内存使用信息 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ private function showTime() { // 显示运行时间 G('viewStartTime'); $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')) { // 显示内存开销 $startMem = array_sum(explode(' ', $GLOBALS['_startUseMems'])); $endMem = array_sum(explode(' ', memory_get_usage())); $showTime .= ' | UseMem:'. number_format(($endMem - $startMem)/1024).' kb'; } return $showTime; } /** +---------------------------------------------------------- * 显示页面Trace信息 +---------------------------------------------------------- * @access private +---------------------------------------------------------- */ private function showTrace(){ // 显示页面Trace信息 读取Trace定义文件 // 定义格式 return array('当前页面'=>$_SERVER['PHP_SELF'],'通信协议'=>$_SERVER['SERVER_PROTOCOL'],...); $traceFile = CONFIG_PATH.'trace.php'; $_trace = is_file($traceFile)? include $traceFile : array(); // 系统默认显示信息 $this->trace('当前页面', $_SERVER['REQUEST_URI']); $this->trace('请求方法', $_SERVER['REQUEST_METHOD']); $this->trace('通信协议', $_SERVER['SERVER_PROTOCOL']); $this->trace('请求时间', date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME'])); $this->trace('用户代理', $_SERVER['HTTP_USER_AGENT']); $log = Log::$log; $this->trace('日志记录',count($log)?count($log).'条日志<br/>'.implode('<br/>',$log):'无日志记录'); $files = get_included_files(); $this->trace('加载文件', count($files).str_replace("\n",'<br/>',substr(substr(print_r($files,true),7),0,-2))); $_trace = array_merge($_trace,$this->trace); // 调用Trace页面模板 include C('TMPL_TRACE_FILE'); } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Lite/Action.class.php
PHP
asf20
19,168
<?php // +---------------------------------------------------------------------- // | ThinkPHP // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ class ThinkTemplateCompiler { protected $literal = array(); //Literal缓存 protected $templateFile = ''; // 模板文件名 protected $tpl = null; // 模板引擎实例 protected $comparison = array(' nheq '=>' !== ',' heq '=>' === ',' neq '=>' != ',' eq '=>' == ',' egt '=>' >= ',' gt '=>' > ',' elt '=>' <= ',' lt '=>' < '); // 标签定义 protected $tags = array( // 标签定义: attr 属性列表 close 是否闭合(0 或者1 默认1) alias 标签别名 level 嵌套层次 'php'=>array('attr'=>'','close'=>0), 'volist'=>array('attr'=>'name,id,offset,length,key,mod','level'=>3,'alias'=>'iterate'), 'include'=>array('attr'=>'file','close'=>0), 'if'=>array('attr'=>'condition'), 'elseif'=>array('attr'=>'condition'), 'else'=>array('attr'=>'','close'=>0), 'switch'=>array('attr'=>'name','level'=>3), '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'), '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'), 'list'=>array('attr'=>'id,pk,style,action,actionlist,show,datasource,checkbox','close'=>0), 'imagebtn'=>array('attr'=>'id,name,value,type,style,click','close'=>0), ); // 构造方法 public function __construct() { $this->tpl = Think::instance('ThinkTemplateLite'); } // 模板编译 public function parse($tmplContent,$templateFile){ $this->templateFile = $templateFile; //模板标签解析 $tmplContent = $this->parseTag($tmplContent); if(ini_get('short_open_tag')) // 开启短标签的情况要将<?标签用echo方式输出 否则无法正常输出xml标识 $tmplContent = preg_replace('/(<\?(?!php|=|$))/i', '<?php echo \'\\1\'; ?>'."\n", $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); } return trim($tmplContent); } // 解析变量 protected 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->parseThink($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->parseFun($name,$varArray); $parseStr = '<?php echo ('.$name.'); ?>'; } $_varParseList[$varStr] = $parseStr; return $parseStr; } // 解析变量函数 protected function parseFun($name,$varArray) { //对变量使用函数 $length = count($varArray); //取得模板禁止使用函数列表 $template_deny_funs = explode(',',C('TMPL_DENY_FUNC_LIST')); for($i=0;$i<$length ;$i++ ){ if (0===stripos($varArray[$i],'default=')) $args = explode('=',$varArray[$i],2); else $args = explode('=',$varArray[$i]); //模板函数过滤 $args[0] = trim($args[0]); switch(strtolower($args[0])) { case 'default': // 特殊模板函数 $name = '('.$name.')?('.$name.'):'.$args[1]; break; default: // 通用模板函数 if(!in_array($args[0],$template_deny_funs)){ if(isset($args[1])){ if(strstr($args[1],'###')){ $args[1] = str_replace('###',$name,$args[1]); $name = "$args[0]($args[1])"; }else{ $name = "$args[0]($name,$args[1])"; } }else if(!empty($args[0])){ $name = "$args[0]($name)"; } } } } return $name; } // load普通标签 public function parseLoad($str) { $type = strtolower(substr(strrchr($str, '.'),1)); $parseStr = ''; if($type=='js') { $parseStr .= '<script type="text/javascript" src="'.$str.'"></script>'; }elseif($type=='css') { $parseStr .= '<link rel="stylesheet" type="text/css" href="'.$str.'" />'; } return $parseStr; } // 解析包含标签 protected function parseInclude($tmplPublicName) { if(substr($tmplPublicName,0,1)=='$') //支持加载变量文件名 $tmplPublicName = $this->tpl->get(substr($tmplPublicName,1)); if(is_file($tmplPublicName)) { // 直接包含文件 $parseStr = file_get_contents($tmplPublicName); }else { $tmplPublicName = trim($tmplPublicName); if(strpos($tmplPublicName,'@')){ // 引入其它模块的操作模板 $tmplTemplateFile = dirname(dirname(dirname($this->templateFile))).'/'.str_replace(array('@',':'),'/',$tmplPublicName); }elseif(strpos($tmplPublicName,':')){ // 引入其它模块的操作模板 $tmplTemplateFile = dirname(dirname($this->templateFile)).'/'.str_replace(':','/',$tmplPublicName); }else{ // 默认导入当前模块下面的模板 $tmplTemplateFile = dirname($this->templateFile).'/'.$tmplPublicName; } $tmplTemplateFile .= $this->tpl->template_suffix; $parseStr = file_get_contents($tmplTemplateFile); } //再次对包含文件进行模板分析 return $this->parseTag($parseStr); } // 解析特殊变量 protected function parseThink($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[\''.$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 = 'C("TMPL_FILE_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; } // 解析标签 protected function parseTag($content) { // 解析XML标签 $this->parseXmlTag($content); // 解析普通标签 {tagName:} $begin = $this->tpl->tmpl_begin; $end = $this->tpl->tmpl_end; $content = preg_replace('/('.$begin.')(\S.+?)('.$end.')/eis',"\$this->parseCommonTag('\\2')",$content); return $content; } protected function parseCommonTag($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){ // 输出某个函数的结果 return '<?php echo '.$name.';?>'; }elseif('~' == $flag){ // 执行某个函数 return '<?php '.$name.';?>'; }elseif('&' == $flag){ // 输出配置参数 return '<?php echo C("'.$name.'");?>'; }elseif('%' == $flag){ // 输出语言变量 return '<?php echo L("'.$name.'");?>'; }elseif('@' == $flag){ // 输出SESSION变量 if(strpos($name,'.')) { $array = explode('.',$name); return '<?php echo $_SESSION["'.$array[0].'"]["'.$array[1].'"];?>'; }else{ return '<?php echo $_SESSION["'.$name.'"];?>'; } }elseif('#' == $flag){ // 输出COOKIE变量 if(strpos($name,'.')) { $array = explode('.',$name); return '<?php echo $_COOKIE["'.$array[0].'"]["'.$array[1].'"];?>'; }else{ return '<?php echo $_COOKIE["'.$name.'"];?>'; } }elseif('.' == $flag){ // 输出GET变量 return '<?php echo $_GET["'.$name.'"];?>'; }elseif('^' == $flag){ // 输出POST变量 return '<?php echo $_POST["'.$name.'"];?>'; }elseif('*' == $flag){ // 输出常量 return '<?php echo constant("'.$name.'");?>'; } $tagStr = trim($tagStr); if(substr($tagStr,0,2)=='//' || (substr($tagStr,0,2)=='/*' && substr($tagStr,-2)=='*/')) //注释标签 return ''; //解析其它标签 //统一标签格式 {TagName:args [|content]} $pos = strpos($tagStr,':'); $tag = substr($tagStr,0,$pos); $args = trim(substr($tagStr,$pos+1)); //解析标签内容 if(!empty($args)) { $tag = strtolower($tag); switch($tag){ case 'include': return $this->parseInclude($args); break; case 'load': return $this->parseLoad($args); break; //这里扩展其它标签 //………… default: if(C('TAG_EXTEND_PARSE')) { $method = C('TAG_EXTEND_PARSE'); if(array_key_exists($tag,$method)) return $method[$tag]($args); } } } return C('TMPL_L_DELIM') . $tagStr .C('TMPL_R_DELIM'); } // 解析XML标签 protected function parseXmlTag(&$content) { $begin = $this->tpl->taglib_begin; $end = $this->tpl->taglib_end; foreach ($this->tags as $tag=>$val){ if(isset($val['alias'])) {// 别名设置 $tags = explode(',',$val['alias']); $tags[] = $tag; }else{ $tags[] = $tag; } $level = isset($val['level'])?$val['level']:1; $closeTag = isset($val['close'])?$val['close']:true; foreach ($tags as $tag){ if(!$closeTag) { $content = preg_replace('/'.$begin.$tag.'\s(.*?)\/(\s*?)'.$end.'/eis',"\$this->parseXmlItem('$tag','\\1','')",$content); }else{ for($i=0;$i<$level;$i++) $content = preg_replace('/'.$begin.$tag.'\s(.*?)'.$end.'(.+?)'.$begin.'\/'.$tag.'(\s*?)'.$end.'/eis',"\$this->parseXmlItem('$tag','\\1','\\2')",$content); } } } } // 解析某个标签 protected function parseXmlItem($tag,$attr,$content) { $attr = stripslashes($attr); $content = stripslashes(trim($content)); $fun = '_'.$tag; return $this->$fun($attr,$this->parseTag($content)); } // literal标签 protected function parseLiteral($content) { if(trim($content)=='') return ''; $content = stripslashes($content); $i = count($this->literal); $parseStr = "<!--###literal{$i}###-->"; $this->literal[$i] = $content; return $parseStr; } protected function restoreLiteral($tag) { // 还原literal标签 $parseStr = $this->literal[$tag]; // 销毁literal记录 unset($this->literal[$tag]); return $parseStr; } // 条件解析 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; } // 创建变量 public function autoBuildVar($name) { if('Think.' == substr($name,0,6)){ // 特殊变量 return $this->parseThink($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) $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; } // 解析标签属性 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; } } //---------------标签解析方法---------------------- // php public function _php($attr,$content) { $parseStr = '<?php '.$content.' ?>'; return $parseStr; } // include public function _include($attr,$content) { $tag = $this->parseXmlAttr($attr,'include'); $file = $tag['file']; return $this->parseInclude($file); } // volist 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'; $name = $this->autoBuildVar($name); $parseStr = '<?php if(is_array('.$name.')): $'.$key.' = 0;'; if(isset($tag['length']) && '' !=$tag['length'] ) { $parseStr .= ' $__LIST__ = array_slice('.$name.','.$tag['offset'].','.$tag['length'].');'; }elseif(isset($tag['offset']) && '' !=$tag['offset']){ $parseStr .= ' $__LIST__ = array_slice('.$name.','.$tag['offset'].');'; }else{ $parseStr .= ' $__LIST__ = '.$name.';'; } $parseStr .= 'if( count($__LIST__)==0 ) : echo "'.$empty.'" ;'; $parseStr .= 'else: '; $parseStr .= 'foreach($__LIST__ as $key=>$'.$id.'): '; $parseStr .= '++$'.$key.';'; $parseStr .= '$mod = ($'.$key.' % '.$mod.' )?>'; $parseStr .= $content; $parseStr .= '<?php endforeach; endif; else: echo "'.$empty.'" ;endif; ?>'; $_iterateParseCache[$cacheIterateId] = $parseStr; if(!empty($parseStr)) { return $parseStr; } return ; } // foreach 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 .= $content; $parseStr .= '<?php endforeach; endif; ?>'; $_iterateParseCache[$cacheIterateId] = $parseStr; if(!empty($parseStr)) { return $parseStr; } return ; } // if public function _if($attr,$content) { $tag = $this->parseXmlAttr($attr,'if'); $condition = $this->parseCondition($tag['condition']); $parseStr = '<?php if('.$condition.'): ?>'.$content.'<?php endif; ?>'; return $parseStr; } public function _elseif($attr,$content) { $tag = $this->parseXmlAttr($attr,'elseif'); $condition = $this->parseCondition($tag['condition']); $parseStr = '<?php elseif('.$condition.'): ?>'; return $parseStr; } public function _else($attr) { $parseStr = '<?php else: ?>'; return $parseStr; } // switch 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->parseFun($name,$varArray); $parseStr = '<?php switch('.$name.'): ?>'.$content.'<?php endswitch;?>'; return $parseStr; } // case 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->parseFun($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; if('' ==$tag['break'] || $tag['break']) { $parseStr .= '<?php break;?>'; } return $parseStr; } // default public function _default($attr) { $parseStr = '<?php default: ?>'; return $parseStr; } // compare public function _compare($attr,$content,$type='eq') { $tag = $this->parseXmlAttr($attr,'compare'); $name = $tag['name']; $value = $tag['value']; $type = $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->parseFun($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; } // range 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); $type = $tag['type']?$tag['type']:$type; $fun = ($type == 'in')? 'in_array' : '!in_array'; if(count($varArray)>0) $name = $this->parseFun($name,$varArray); if('$' == substr($value,0,1)) { $value = $this->autoBuildVar(substr($value,1)); $parseStr = '<?php if('.$fun.'(('.$name.'), is_array('.$value.')?'.$value.':explode(\',\','.$value.'))): ?>'.$content.'<?php endif; ?>'; }else{ $value = '"'.$value.'"'; $parseStr = '<?php if('.$fun.'(('.$name.'), explode(\',\','.$value.'))): ?>'.$content.'<?php endif; ?>'; } return $parseStr; } public function _in($attr,$content) { return $this->_range($attr,$content,'in'); } // range标签的别名 用于notin判断 public function _notin($attr,$content) { return $this->_range($attr,$content,'notin'); } // present 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; } public function _notpresent($attr,$content) { $tag = $this->parseXmlAttr($attr,'present'); $name = $tag['name']; $name = $this->autoBuildVar($name); $parseStr = '<?php if(!isset('.$name.')): ?>'.$content.'<?php endif; ?>'; return $parseStr; } // empty 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,'empty'); $name = $tag['name']; $name = $this->autoBuildVar($name); $parseStr = '<?php if(!empty('.$name.')): ?>'.$content.'<?php endif; ?>'; return $parseStr; } // define 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,'defined'); $name = $tag['name']; $parseStr = '<?php if(!defined("'.$name.'")): ?>'.$content.'<?php endif; ?>'; return $parseStr; } // import public function _import($attr,$content,$isFile=false,$type='') { $tag = $this->parseXmlAttr($attr,'import'); $file = $tag['file']?$tag['file']:$tag['href']; $parseStr = ''; $endStr = ''; // 判断是否存在加载条件 允许使用函数判断(默认为isset) if ($tag['value']) { $varArray = explode('|',$tag['value']); $name = array_shift($varArray); $name = $this->autoBuildVar($name); if (!empty($varArray)) $name = $this->parseFun($name,$varArray); else $name = 'isset('.$name.')'; $parseStr .= '<?php if('.$name.'): ?>'; $endStr = '<?php endif; ?>'; } if($isFile) { // 根据文件名后缀自动识别 $type = $type?$type:(!empty($tag['type'])?strtolower($tag['type']):strtolower(substr(strrchr($file, '.'),1))); // 文件方式导入 $array = explode(',',$file); foreach ($array as $val){ 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; } public function _iterate($attr,$content) { return $this->_volist($attr,$content); } public function _eq($attr,$content) { return $this->_compare($attr,$content,'eq'); } public function _equal($attr,$content) { return $this->_eq($attr,$content); } public function _neq($attr,$content) { return $this->_compare($attr,$content,'neq'); } public function _notequal($attr,$content) { return $this->_neq($attr,$content); } 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'); } 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'); } // list 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']; //是否显示功能操作 $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++; //显示开始 $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 $key=>$val) { $fields[] = explode(':',$val); } if(!empty($checkbox) && 'true'==strtolower($checkbox)) {//如果指定需要显示checkbox列 $parseStr .='<th width="8"><input type="checkbox" id="check" onclick="CheckAll(\''.$id.'\')"></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]; $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>'; } if(!empty($action)) {//如果指定显示操作功能列 $parseStr .= '<th >操作</th>'; } $parseStr .= '</tr>'; $parseStr .= '<volist name="'.$datasource.'" id="'.$name.'" ><tr class="row" onmouseover="over(event)" onmouseout="out(event)" onclick="change(event)" >'; //支持鼠标移动单元行颜色变化 具体方法在js中定义 if(!empty($checkbox)) {//如果需要显示checkbox 则在每行开头显示checkbox $parseStr .= '<td><input type="checkbox" name="key" value="{$'.$name.'.'.$pk.'}"></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); $b = explode('|',$a[1]); if(count($b)>1) { $c = explode('|',$a[0]); if(count($c)>1) { $parseStr .= '<a href="javascript:'.$c[1].'(\'{$'.$name.'.'.$pk.'}\')"><?php if(0== (is_array($'.$name.')?$'.$name.'["status"]:$'.$name.'->status)){ ?>'.$b[1].'<?php } ?></a><a href="javascript:'.$c[0].'({$'.$name.'.'.$pk.'})"><?php if(1== (is_array($'.$name.')?$'.$name.'["status"]:$'.$name.'->status)){ ?>'.$b[0].'<?php } ?></a>&nbsp;'; }else { $parseStr .= '<a href="javascript:'.$a[0].'(\'{$'.$name.'.'.$pk.'}\')"><?php if(0== (is_array($'.$name.')?$'.$name.'["status"]:$'.$name.'->status)){ ?>'.$b[1].'<?php } ?><?php if(1== (is_array($'.$name.')?$'.$name.'["status"]:$'.$name.'->status)){ ?>'.$b[0].'<?php } ?></a>&nbsp;'; } }else { $parseStr .= '<a href="javascript:'.$a[0].'(\'{$'.$name.'.'.$pk.'}\')">'.$a[1].'</a>&nbsp;'; } }else{ $array = explode('|',$val); if(count($array)>2) { $parseStr .= ' <a href="javascript:'.$array[1].'(\'{$'.$name.'.'.$array[0].'}\')">'.$array[2].'</a>&nbsp;'; }else{ $parseStr .= ' {$'.$name.'.'.$val.'}&nbsp;'; } } } $parseStr .= '</td>'; } } $parseStr .= '</tr></volist><tr><td height="5" colspan="'.$colNum.'" class="bottomTd"></td></tr></table>'; $parseStr .= "\n<!-- Think 系统列表组件结束 -->\n"; return $this->parseTag($parseStr); } // imageBtn public function _imageBtn($attr) { $tag = $this->parseXmlAttr($attr,'imageBtn'); $name = $tag['name']; //名称 $value = $tag['value']; //文字 $id = $tag['id']; //ID $style = $tag['style']; //样式名 $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; } } ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Lite/ThinkTemplateCompiler.class.php
PHP
asf20
42,092
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ // 简洁模式核心定义文件列表 return array( THINK_PATH.'/Common/functions.php', // 系统函数库 THINK_PATH.'/Lib/Think/Core/Think.class.php', THINK_PATH.'/Lib/Think/Exception/ThinkException.class.php',// 异常处理 THINK_PATH.'/Lib/Think/Core/Log.class.php',// 日志处理 THINK_PATH.'/Mode/Thin/App.class.php', // 应用程序类 THINK_PATH.'/Mode/Thin/Action.class.php',// 控制器类 THINK_PATH.'/Mode/Thin/alias.php', // 加载别名 ); ?>
0321hy
trunk/Lib/ThinkPHP/Mode/thin.php
PHP
asf20
1,113
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ // 简洁模式核心定义文件列表 return array( THINK_PATH.'/Common/functions.php', // 系统函数库 THINK_PATH.'/Lib/Think/Core/Think.class.php', THINK_PATH.'/Lib/Think/Exception/ThinkException.class.php',// 异常处理 THINK_PATH.'/Lib/Think/Core/Log.class.php',// 日志处理 THINK_PATH.'/Mode/Lite/App.class.php', // 应用程序类 THINK_PATH.'/Mode/Lite/Action.class.php',// 控制器类 THINK_PATH.'/Mode/Lite/alias.php', // 加载别名 ); ?>
0321hy
trunk/Lib/ThinkPHP/Mode/lite.php
PHP
asf20
1,113
<?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_import(array( 'Model' => THINK_PATH.'/Mode/Thin/Model.class.php', 'Db' => THINK_PATH.'/Mode/Thin/Db.class.php', 'Debug' => THINK_PATH.'/Lib/Think/Util/Debug.class.php', 'Session' => THINK_PATH.'/Lib/Think/Util/Session.class.php', ) ); ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Thin/alias.php
PHP
asf20
966
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 精简模式应用程序类 +------------------------------------------------------------------------------ */ class App {//类定义开始 /** +---------------------------------------------------------- * 应用程序初始化 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function run() { // 设定错误和异常处理 set_error_handler(array('App',"appError")); set_exception_handler(array('App',"appException")); //[RUNTIME] // 检查项目是否编译过 // 在部署模式下会自动在第一次执行的时候编译项目 if(defined('RUNTIME_MODEL')){ // 运行模式无需载入项目编译缓存 }elseif(is_file(RUNTIME_PATH.'~app.php') && (!is_file(CONFIG_PATH.'config.php') || filemtime(RUNTIME_PATH.'~app.php')>filemtime(CONFIG_PATH.'config.php'))) { // 直接读取编译后的项目文件 C(include RUNTIME_PATH.'~app.php'); }else{ // 预编译项目 App::build(); } //[/RUNTIME] // 取得模块和操作名称 define('MODULE_NAME', App::getModule()); // Module名称 define('ACTION_NAME', App::getAction()); // Action操作 // 记录应用初始化时间 if(C('SHOW_RUN_TIME')) $GLOBALS['_initTime'] = microtime(TRUE); // 执行操作 R(MODULE_NAME,ACTION_NAME); // 保存日志记录 if(C('LOG_RECORD')) Log::save(); return ; } //[RUNTIME] /** +---------------------------------------------------------- * 读取配置信息 编译项目 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static private function build() { // 加载惯例配置文件 C(include THINK_PATH.'/Common/convention.php'); // 加载项目配置文件 if(is_file(CONFIG_PATH.'config.php')) { C(include CONFIG_PATH.'config.php'); } $common = ''; $debug = C('APP_DEBUG'); // 是否调试模式 // 加载项目公共文件 if(is_file(COMMON_PATH.'common.php')) { include COMMON_PATH.'common.php'; if(!$debug) { // 编译文件 $common .= compile(COMMON_PATH.'common.php'); } } // 加载项目编译文件列表 if(is_file(CONFIG_PATH.'app.php')) { $list = include CONFIG_PATH.'app.php'; foreach ($list as $key=>$file){ // 加载并编译文件 require $file; if(!$debug) { $common .= compile($file); } } } // 如果是调试模式加载调试模式配置文件 if($debug) { // 加载系统默认的开发模式配置文件 C(include THINK_PATH.'/Common/debug.php'); if(is_file(CONFIG_PATH.'debug.php')) { // 允许项目增加开发模式配置定义 C(include CONFIG_PATH.'debug.php'); } }else{ // 部署模式下面生成编译文件 // 下次直接加载项目编译文件 if(defined('RUNTIME_ALLINONE')) { // 获取用户自定义变量 $defs = get_defined_constants(TRUE); $content = array_define($defs['user']); $content .= substr(file_get_contents(RUNTIME_PATH.'~runtime.php'),5); $content .= $common."\nreturn ".var_export(C(),true).';'; file_put_contents(RUNTIME_PATH.'~allinone.php',strip_whitespace('<?php '.$content)); }else{ $content = "<?php ".$common."\nreturn ".var_export(C(),true).";\n?>"; file_put_contents(RUNTIME_PATH.'~app.php',strip_whitespace($content)); } } return ; } //[/RUNTIME] /** +---------------------------------------------------------- * 获得实际的模块名称 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static private function getModule() { $var = C('VAR_MODULE'); $module = !empty($_POST[$var]) ? $_POST[$var] : (!empty($_GET[$var])? $_GET[$var]:C('DEFAULT_MODULE')); if(C('URL_CASE_INSENSITIVE')) { // URL地址不区分大小写 define('P_MODULE_NAME',strtolower($module)); // 智能识别方式 index.php/user_type/index/ 识别到 UserTypeAction 模块 $module = ucfirst(parse_name(strtolower($module),1)); } unset($_POST[$var],$_GET[$var]); return $module; } /** +---------------------------------------------------------- * 获得实际的操作名称 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static private function getAction() { $var = C('VAR_ACTION'); $action = !empty($_POST[$var]) ? $_POST[$var] : (!empty($_GET[$var])?$_GET[$var]:C('DEFAULT_ACTION')); unset($_POST[$var],$_GET[$var]); return $action; } /** +---------------------------------------------------------- * 自定义异常处理 +---------------------------------------------------------- * @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; } } };//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Thin/App.class.php
PHP
asf20
8,559
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ define('CLIENT_MULTI_RESULTS', 131072); /** +------------------------------------------------------------------------------ * ThinkPHP 简洁模式数据库中间层实现类 * 只支持mysql +------------------------------------------------------------------------------ */ class Db extends Think { 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 +---------------------------------------------------------- * @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); } } /** +---------------------------------------------------------- * 获取最近一次查询的sql语句 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastSql() { return $this->queryStr; } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Thin/Db.class.php
PHP
asf20
17,663
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 简洁模式Model模型类 * 只支持原生SQL操作 支持多数据库连接和切换 +------------------------------------------------------------------------------ */ class Model extends Think { // 数据库连接对象列表 private $_db = array(); // 当前数据库操作对象 protected $db = null; // 数据表前缀 protected $tablePrefix = ''; // 模型名称 protected $name = ''; // 数据库名称 protected $dbName = ''; // 数据表名(不包含表前缀) protected $tableName = ''; // 实际数据表名(包含表前缀) protected $trueTableName =''; // 最近错误信息 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(); } // 数据库初始化操作 import("Db"); // 获取数据库操作对象 $this->db = Db::getInstance(empty($this->connection)?'':$this->connection); // 设置表前缀 $this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX'); // 设置默认的数据库连接 $this->_db[0] = $this->db; } // 回调方法 初始化模型 protected function _initialize() {} /** +---------------------------------------------------------- * SQL查询 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $sql SQL指令 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function query($sql) { if(is_array($sql)) { return $this->patchQuery($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); } $result = $this->db->execute($sql); return $result; }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 +---------------------------------------------------------- * @param mixed $config 数据库连接信息 * 支持批量添加 例如 array(1=>$config1,2=>$config2) * @param mixed $linkNum 创建的连接序号 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function addConnect($config,$linkNum=NULL) { if(isset($this->_db[$linkNum])) return false; if(NULL === $linkNum && is_array($config)) { // 支持批量增加数据库连接 foreach ($config as $key=>$val) $this->_db[$key] = Db::getInstance($val); return true; } // 创建一个新的实例 $this->_db[$linkNum] = Db::getInstance($config); return true; } /** +---------------------------------------------------------- * 删除数据库连接 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param integer $linkNum 创建的连接序号 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function delConnect($linkNum) { if(isset($this->_db[$linkNum])) { $this->_db[$linkNum]->close(); unset($this->_db[$linkNum]); return true; } return false; } /** +---------------------------------------------------------- * 关闭数据库连接 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param integer $linkNum 创建的连接序号 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function closeConnect($linkNum) { if(isset($this->_db[$linkNum])) { $this->_db[$linkNum]->close(); return true; } return false; } /** +---------------------------------------------------------- * 切换数据库连接 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param integer $linkNum 创建的连接序号 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function switchConnect($linkNum) { if(isset($this->_db[$linkNum])) { // 在不同实例直接切换 $this->db = $this->_db[$linkNum]; return true; }else{ return false; } } }; ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Thin/Model.class.php
PHP
asf20
10,418
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 简洁模式Action控制器基类 +------------------------------------------------------------------------------ */ abstract class Action extends Think {//类定义开始 /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct() { //控制器初始化 if(method_exists($this,'_initialize')) { $this->_initialize(); } } /** +---------------------------------------------------------- * 魔术方法 有不存在的操作的时候执行 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名 * @param array $parms 参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$parms) { if(strtolower($method) == strtolower(ACTION_NAME)) { // 如果定义了_empty操作 则调用 if(method_exists($this,'_empty')) { $this->_empty($method,$parms); }else { // 抛出异常 throw_exception(L('_ERROR_ACTION_').ACTION_NAME); } }else{ throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); } } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Mode/Thin/Action.class.php
PHP
asf20
2,385
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 简体中文语言包 +------------------------------------------------------------------------------ * @category Think * @package Lang * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ return array( // 核心 '_MODULE_NOT_EXIST_'=> '无法加载模块', '_ERROR_ACTION_'=> '非法操作', '_LANGUAGE_NOT_LOAD_'=> '无法加载语言包', '_TEMPLATE_NOT_EXIST_'=> '模板不存在', '_MODULE_'=>'模块', '_ACTION_'=>'操作', '_ACTION_NOT_EXIST_'=>'控制器不存在或者没有定义', '_MODEL_NOT_EXIST_'=>'模型不存在或者没有定义', '_VALID_ACCESS_'=>'没有权限', '_XML_TAG_ERROR_'=>'XML标签语法错误', '_DATA_TYPE_INVALID_'=>'非法数据对象!', '_OPERATION_WRONG_'=>'操作出现错误', '_NOT_LOAD_DB_'=>'无法加载数据库', '_NOT_SUPPORT_DB_'=>'系统暂时不支持数据库', '_NO_DB_CONFIG_'=>'没有定义数据库配置', '_NOT_SUPPERT_'=>'系统不支持', '_CACHE_TYPE_INVALID_'=>'无法加载缓存类型', '_FILE_NOT_WRITEABLE_'=>'目录(文件)不可写', '_METHOD_NOT_EXIST_'=>'您所请求的方法不存在!', '_CLASS_NOT_EXIST_'=>'实例化一个不存在的类!', '_CLASS_CONFLICT_'=>'类名冲突', '_TEMPLATE_ERROR_'=>'模板引擎错误', '_CACHE_WRITE_ERROR_'=>'缓存文件写入失败!', '_TAGLIB_NOT_EXIST_'=>'标签库未定义', '_OPERATION_FAIL_'=>'操作失败!', '_OPERATION_SUCCESS_'=>'操作成功!', '_SELECT_NOT_EXIST_'=>'记录不存在!', '_EXPRESS_ERROR_'=>'表达式错误', '_TOKEN_ERROR_'=>'表单令牌错误', '_RECORD_HAS_UPDATE_'=>'记录已经更新', ); ?>
0321hy
trunk/Lib/ThinkPHP/Lang/zh-cn.php
PHP
asf20
2,524
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP系统异常基类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Exception * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ 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 ; } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Exception/ThinkException.class.php
PHP
asf20
4,361
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP内置模板引擎类 * 支持XML标签和普通标签的模板解析 * 编译型模板引擎 支持动态缓存 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Template * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class ThinkTemplate extends Think {//类定义开始 // 模板页面中引入的标签库列表 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('TMPL_FILE_NAME'); $this->config['tag_level'] = C('TAG_NESTED_LEVEL'); } private function stripPreg($str) { $str = str_replace(array('{','}','(',')','|','[',']'),array('\{','\}','\(','\)','\|','\[','\]'),$str); return $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 load($templateFile,$templateVar,$charset) { $this->tVar = $templateVar; $templateCacheFile = $this->loadTemplate($templateFile); // 模板阵列变量分解成为独立变量 extract($templateVar, EXTR_OVERWRITE); //载入模版缓存文件 include $templateCacheFile; } /** +---------------------------------------------------------- * 加载主模板并缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $tmplTemplateFile 模板文件 * @param string $varPrefix 模板变量前缀 +---------------------------------------------------------- * @return string +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function loadTemplate ($tmplTemplateFile='') { if(empty($tmplTemplateFile)) $tmplTemplateFile = $this->config['default_tmpl']; if(!is_file($tmplTemplateFile)){ $tmplTemplateFile = dirname($this->config['default_tmpl']).'/'.$tmplTemplateFile.$this->config['template_suffix']; if(!is_file($tmplTemplateFile)) throw_exception(L('_TEMPLATE_NOT_EXIST_').':'.$tmplTemplateFile); } $this->templateFile = $tmplTemplateFile; //根据模版文件名定位缓存文件 $tmplCacheFile = $this->config['cache_path'].md5($tmplTemplateFile).$this->config['cache_suffix']; $tmplContent = ''; // 检查Cache文件是否需要更新 if (!$this->checkCache($tmplTemplateFile)) { // 需要更新模版 读出原模板内容 $tmplContent = file_get_contents($tmplTemplateFile); //编译模板内容 $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); if(ini_get('short_open_tag')) // 开启短标签的情况要将<?标签用echo方式输出 否则无法正常输出xml标识 $tmplContent = preg_replace('/(<\?(?!php|=|$))/i', '<?php echo \'\\1\'; ?>'."\n", $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); } return trim($tmplContent); } /** +---------------------------------------------------------- * 检查缓存文件是否有效 * 如果无效则需要重新更新 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $tmplTemplateFile 模板文件名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ protected function checkCache($tmplTemplateFile) { if (!$this->config['tmpl_cache']) // 优先对配置检测 return false; $tmplCacheFile = $this->config['cache_path'].md5($tmplTemplateFile).$this->config['cache_suffix']; if(!is_file($tmplCacheFile)){ return false; }elseif (filemtime($tmplTemplateFile) > filemtime($tmplCacheFile)) { // 模板文件如果有更新则缓存需要更新 return false; }elseif ($this->config['cache_time'] != -1 && time() > filemtime($tmplCacheFile)+$this->config['cache_time']) { // 缓存是否在有效期 return false; } //缓存有效 return true; } /** +---------------------------------------------------------- * 模板解析入口 * 支持普通标签和TagLib解析 支持自定义标签库 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $content 要解析的模板内容 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function parse($content) { $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); // 获取需要引入的标签库列表 // 标签库只需要定义一次,允许引入多个一次 // 一般放在文件的最前面 // 格式:<taglib name="html,mytag..." /> // 当TAGLIB_LOAD配置为true时才会进行检测 if(C('TAGLIB_LOAD')) { $this->getIncludeTagLib($content); if(!empty($this->tagLib)) { // 对导入的TagLib进行解析 $_taglibs = C('_taglibs_'); foreach($this->tagLib as $tagLibName) { // 内置标签库 $tagLibName = strtolower($tagLibName); if(!import('Think.Template.TagLib.TagLib'.ucwords($tagLibName))) { // 扩展标签库 if($_taglibs && isset($_taglibs[$tagLibName])) // 'tagLibName'=>'importPath' import($_taglibs[$tagLibName]); else throw_exception($tagLibName.L('_TAGLIB_NOT_EXIST_')); } $this->parseTagLib($tagLibName,$content); } } } // 预先加载的标签库 无需在每个模板中使用taglib标签加载 if(C('TAGLIB_PRE_LOAD')) { $tagLibs = explode(',',C('TAGLIB_PRE_LOAD')); foreach ($tagLibs as $tag){ $this->parseTagLib($tag,$content); } } // 内置标签库 无需使用taglib标签导入就可以使用 $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; } /** +---------------------------------------------------------- * 替换页面中的literal标签 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $content 模板内容 +---------------------------------------------------------- * @return string|false +---------------------------------------------------------- */ 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 public +---------------------------------------------------------- * @param string $tag literal标签序号 +---------------------------------------------------------- * @return string|false +---------------------------------------------------------- */ 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']; require_cache(dirname(__FILE__).'/TagLib/TagLib'.ucwords($tagLib).'.class.php'); $tLib = Think::instance('TagLib'.ucwords(strtolower($tagLib))); foreach ($tLib->tags as $name=>$val){ $tags = array(); if(isset($val['alias'])) {// 别名设置 $tags = explode(',',$val['alias']); $tags[] = $name; }else{ $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(empty($val['attr'])){ // 无属性标签 if(!$closeTag) { $content = preg_replace('/'.$begin.$parseTag.'(\s*?)\/(\s*?)'.$end.'/eis',"\$this->parseXmlTag('$tagLib','$tag','\\1','')",$content); }else{ for($i=0;$i<$level;$i++) $content = preg_replace('/'.$begin.$parseTag.'(\s*?)'.$end.'(.*?)'.$begin.'\/'.$parseTag.'(\s*?)'.$end.'/eis',"\$this->parseXmlTag('$tagLib','$tag','\\1','\\2')",$content); } }else{ if(!$closeTag) { $content = preg_replace('/'.$begin.$parseTag.'\s(.*?)\/(\s*?)'.$end.'/eis',"\$this->parseXmlTag('$tagLib','$tag','\\1','')",$content); }else{ for($i=0;$i<$level;$i++) $content = preg_replace('/'.$begin.$parseTag.'\s(.*?)'.$end.'(.*?)'.$begin.'\/'.$parseTag.'(\s*?)'.$end.'/eis',"\$this->parseXmlTag('$tagLib','$tag','\\1','\\2')",$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 = get_instance_of('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){ // 输出某个函数的结果 return '<?php echo '.$name.';?>'; }elseif('~' == $flag){ // 执行某个函数 return '<?php '.$name.';?>'; }elseif('&' == $flag){ // 输出配置参数 return '<?php echo C("'.$name.'");?>'; }elseif('%' == $flag){ // 输出语言变量 return '<?php echo L("'.$name.'");?>'; }elseif('@' == $flag){ // 输出SESSION变量 if(strpos($name,'.')) { $array = explode('.',$name); return '<?php echo $_SESSION["'.$array[0].'"]["'.$array[1].'"];?>'; }else{ return '<?php echo $_SESSION["'.$name.'"];?>'; } }elseif('#' == $flag){ // 输出COOKIE变量 if(strpos($name,'.')) { $array = explode('.',$name); return '<?php echo $_COOKIE["'.$array[0].'"]["'.$array[1].'"];?>'; }else{ return '<?php echo $_COOKIE["'.$name.'"];?>'; } }elseif('.' == $flag){ // 输出GET变量 return '<?php echo $_GET["'.$name.'"];?>'; }elseif('^' == $flag){ // 输出POST变量 return '<?php echo $_POST["'.$name.'"];?>'; }elseif('*' == $flag){ // 输出常量 return '<?php echo constant("'.$name.'");?>'; } $tagStr = trim($tagStr); if(substr($tagStr,0,2)=='//' || (substr($tagStr,0,2)=='/*' && substr($tagStr,-2)=='*/')) //注释标签 return ''; //解析其它标签 //统一标签格式 {TagName:args [|content]} $pos = strpos($tagStr,':'); $tag = substr($tagStr,0,$pos); $args = trim(substr($tagStr,$pos+1)); //解析标签内容 if(!empty($args)) { $tag = strtolower($tag); switch($tag){ case 'include': return $this->parseInclude($args); break; case 'load': return $this->parseLoad($args); break; //这里扩展其它标签 //………… default: if(C('TAG_EXTEND_PARSE')) { $method = C('TAG_EXTEND_PARSE'); if(array_key_exists($tag,$method)) return $method[$tag]($args); } } } return C('TMPL_L_DELIM') . $tagStr .C('TMPL_R_DELIM'); } /** +---------------------------------------------------------- * 加载js或者css文件 * {load:__PUBLIC__/Js/Think/ThinkAjax.js} 加载js文件 * {load:__PUBLIC__/Css/style.css} 加载css文件 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $params 参数 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function parseLoad($str) { $type = strtolower(substr(strrchr($str, '.'),1)); $parseStr = ''; if($type=='js') { $parseStr .= '<script type="text/javascript" src="'.$str.'"></script>'; }elseif($type=='css') { $parseStr .= '<link rel="stylesheet" type="text/css" href="'.$str.'" />'; } return $parseStr; } /** +---------------------------------------------------------- * 模板变量解析,支持使用函数 * 格式: {$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++ ){ if (0===stripos($varArray[$i],'default=')) $args = explode('=',$varArray[$i],2); else $args = explode('=',$varArray[$i]); //模板函数过滤 $args[0] = trim($args[0]); switch(strtolower($args[0])) { case 'default': // 特殊模板函数 $name = '('.$name.')?('.$name.'):'.$args[1]; break; default: // 通用模板函数 if(!in_array($args[0],$template_deny_funs)){ if(isset($args[1])){ if(strstr($args[1],'###')){ $args[1] = str_replace('###',$name,$args[1]); $name = "$args[0]($args[1])"; }else{ $name = "$args[0]($name,$args[1])"; } }else if(!empty($args[0])){ $name = "$args[0]($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[\''.$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 = 'C("TMPL_FILE_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 公共模板文件名 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function parseInclude($tmplPublicName){ if(substr($tmplPublicName,0,1)=='$') //支持加载变量文件名 $tmplPublicName = $this->get(substr($tmplPublicName,1)); if(is_file($tmplPublicName)) { // 直接包含文件 $parseStr = file_get_contents($tmplPublicName); }else { $tmplPublicName = str_replace(array('@',':'),'/',$tmplPublicName); $count = substr_count($tmplPublicName,'/'); $path = dirname(C('TMPL_FILE_NAME')); for($i=0;$i<$count;$i++) $path = dirname($path); $templateFile = $path.'/'.$tmplPublicName.$this->config['template_suffix']; $parseStr = file_get_contents($templateFile); } //再次对包含文件进行模板分析 return $this->parse($parseStr); } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Template/ThinkTemplate.class.php
PHP
asf20
32,869
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP标签库TagLib解析基类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Template * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class TagLib extends Think {//类定义开始 /** +---------------------------------------------------------- * 标签库定义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) $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("TMPL_FILE_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; } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Template/TagLib.class.php
PHP
asf20
10,229
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ import('TagLib'); /** +------------------------------------------------------------------------------ * CX标签库解析类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Template * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ 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,'alias'=>'iterate,fflist'), 'foreach' =>array('attr'=>'name,item,key','level'=>3), 'include'=>array('attr'=>'file','close'=>0), 'if'=>array('attr'=>'condition'), 'elseif'=>array('attr'=>'condition','close'=>0), 'else'=>array('attr'=>'','close'=>0), 'switch'=>array('attr'=>'name','level'=>3), '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'), '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), 'layout' =>array('attr'=>'name,cache','close'=>0), '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), ); /** +---------------------------------------------------------- * include标签解析 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $attr 标签属性 * @param string $content 标签内容 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function _include($attr,$content) { $tag = $this->parseXmlAttr($attr,'include'); $file = $tag['file']; $parseStr = $this->tpl->parseInclude($file); foreach ($tag as $key=>$val) { if ($key == 'file') { continue; } //echo $key; $parseStr = str_replace('['.$key.']',$val,$parseStr); } return $this->tpl->parse($parseStr); } /** +---------------------------------------------------------- * 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 .= '++$'.$key.';'; $parseStr .= '$mod = ($'.$key.' % '.$mod.' )?>'; $parseStr .= $this->tpl->parse($content); $parseStr .= '<?php endforeach; endif; else: echo "'.$empty.'" ;endif; ?>'; $_iterateParseCache[$cacheIterateId] = $parseStr; if(!empty($parseStr)) { return $parseStr; } return ; } public function _iterate($attr,$content) { return $this->_volist($attr,$content); } public function _fflist($attr,$content) { return $this->_volist($attr,$content); } 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); $type = isset($tag['type'])?$tag['type']:$type; $fun = ($type == 'in')? 'in_array' : '!in_array'; if(count($varArray)>0) $name = $this->tpl->parseVarFunction($name,$varArray); if('$' == substr($value,0,1)) { $value = $this->autoBuildVar(substr($value,1)); $parseStr = '<?php if('.$fun.'(('.$name.'), is_array('.$value.')?'.$value.':explode(\',\','.$value.'))): ?>'.$content.'<?php endif; ?>'; }else{ $value = '"'.$value.'"'; $parseStr = '<?php if('.$fun.'(('.$name.'), explode(\',\','.$value.'))): ?>'.$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'); } /** +---------------------------------------------------------- * 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; } /** +---------------------------------------------------------- * 布局标签解析 * 格式: <layout name="" cache="30" /> +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $attr 标签属性 * @param string $content 标签内容 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function _layout($attr,$content) { $tag = $this->parseXmlAttr($attr,'layout'); $name = $tag['name']; $cache = isset($tag['cache'])?$tag['cache']:0; $parseStr= "<!-- layout::$name::$cache -->"; 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']:WEB_PUBLIC_PATH; // 命名空间方式导入外部文件 $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; } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Template/TagLib/TagLibCx.class.php
PHP
asf20
29,502
<?php // +---------------------------------------------------------------------- // | ThinkPHP // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ 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'; // $content = $tag['content']; $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 .= '<input type="checkbox" checked="checked" name="'.$name.'[]" value="'.$key.'">'.$val.$separator; }else { $parseStr .= '<input type="checkbox" name="'.$name.'[]" value="'.$key.'">'.$val.$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 .= '<input type="radio" checked="checked" name="'.$name.'[]" value="'.$key.'">'.$val.$separator; }else { $parseStr .= '<input type="radio" name="'.$name.'[]" value="'.$key.'">'.$val.$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>&nbsp;'; }else { $parseStr .= '<a href="javascript:'.$a[0].'(\'{$'.$name.'.'.$pk.'}\')">'.$a[1].'</a>&nbsp;'; } }else{ $array = explode('|',$val); if(count($array)>2) { $parseStr .= ' <a href="javascript:'.$array[1].'(\'{$'.$name.'.'.$array[0].'}\')">'.$array[2].'</a>&nbsp;'; }else{ $parseStr .= ' {$'.$name.'.'.$val.'}&nbsp;'; } } } $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>&nbsp;'; }else { $parseStr .= '<a href="javascript:'.$a[0].'(\'{$'.$name.'.'.$pk.'}\')">'.$a[1].'</a>&nbsp;'; } }else{ $array = explode('|',$val); if(count($array)>2) { $parseStr .= ' <a href="javascript:'.$array[1].'(\'{$'.$name.'.'.$array[0].'}\')">'.$array[2].'</a>&nbsp;'; }else{ $parseStr .= ' {$'.$name.'.'.$val.'}&nbsp;'; } } } $parseStr .= '</td>'; } } $parseStr .= '</tr></volist><tr><td height="5" colspan="'.$colNum.'" class="bottomTd"></td></tr></table>'; $parseStr .= "\n<!-- Think 系统列表组件结束 -->\n"; return $parseStr; } } ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Template/TagLib/TagLibHtml.class.php
PHP
asf20
29,307
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * 静态缓存类 * 支持静态缓存规则定义 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Util * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class HtmlCache extends Think { static private $cacheTime = null; // 缓存有效期(支持函数) static private $requireCache = false; // 是否需要缓存 // 判断是否需要静态缓存 static private function requireHtmlCache() { // 分析当前的静态规则 $htmls = C('_htmls_'); // 读取静态规则 if(!empty($htmls)) { // 静态规则文件定义格式 actionName=>array(‘静态规则’,’缓存时间’,’附加规则') // 'read'=>array('{id},{name}',60,'md5') 必须保证静态规则的唯一性 和 可判断性 // 检测静态规则 $moduleName = strtolower(MODULE_NAME); if(isset($htmls[strtolower(GROUP_NAME.':'.MODULE_NAME.':'.ACTION_NAME)])) { $html = $htmls[strtolower(GROUP_NAME.':'.MODULE_NAME.':'.ACTION_NAME)]; // 分组模式下某个模块的操作的静态规则 }elseif(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']) && self::isEmptyAction(MODULE_NAME,ACTION_NAME)){ $html = $htmls[$moduleName.':_empty']; // 空操作静态规则 } if(!empty($html)) { self::$requireCache = true; // 需要缓存 // 解读静态规则 $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); // 应用附加函数 self::$cacheTime = isset($html[1])?$html[1]:C('HTML_CACHE_TIME'); // 缓存有效期 // 当前缓存文件 define('HTML_FILE_NAME',HTML_PATH . $rule.C('HTML_FILE_SUFFIX')); return true; } } // 无需缓存 return false; } /** +---------------------------------------------------------- * 读取静态缓存 +---------------------------------------------------------- * @access static +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static function readHTMLCache() { if(self::requireHtmlCache() && self::checkHTMLCache(HTML_FILE_NAME,self::$cacheTime)) { //静态页面有效 if(C('HTML_READ_TYPE')==1) { // 重定向到静态页面 redirect(str_replace(array(realpath($_SERVER["DOCUMENT_ROOT"]),"\\"),array('',"/"),realpath(HTML_FILE_NAME))); }else { // 读取静态页面输出 readfile(HTML_FILE_NAME); exit(); } } return ; } /** +---------------------------------------------------------- * 写入静态缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $content 页面内容 +---------------------------------------------------------- * @return void +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ static public function writeHTMLCache($content) { if(self::$requireCache) { //静态文件写入 // 如果开启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); } return ; } /** +---------------------------------------------------------- * 检查静态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('TMPL_FILE_NAME')) > filemtime($cacheFile)) { // 模板文件如果更新静态文件需要更新 return false; }elseif(!is_numeric($cacheTime) && function_exists($cacheTime)){ return $cacheTime($cacheFile); }elseif ($cacheTime != -1 && 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); } } ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Util/HtmlCache.class.php
PHP
asf20
7,833
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * 缓存管理类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Util * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class Cache extends Think {//类定义开始 /** +---------------------------------------------------------- * 是否连接 +---------------------------------------------------------- * @var string * @access protected +---------------------------------------------------------- */ protected $connected ; /** +---------------------------------------------------------- * 操作句柄 +---------------------------------------------------------- * @var string * @access protected +---------------------------------------------------------- */ protected $handler ; /** +---------------------------------------------------------- * 缓存存储前缀 +---------------------------------------------------------- * @var string * @access protected +---------------------------------------------------------- */ protected $prefix='~@'; /** +---------------------------------------------------------- * 缓存连接参数 +---------------------------------------------------------- * @var integer * @access protected +---------------------------------------------------------- */ protected $options = array(); /** +---------------------------------------------------------- * 缓存类型 +---------------------------------------------------------- * @var integer * @access protected +---------------------------------------------------------- */ protected $type ; /** +---------------------------------------------------------- * 缓存过期时间 +---------------------------------------------------------- * @var integer * @access protected +---------------------------------------------------------- */ protected $expire ; /** +---------------------------------------------------------- * 连接缓存 +---------------------------------------------------------- * @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'); $cachePath = dirname(__FILE__).'/Cache/'; $cacheClass = 'Cache'.ucwords(strtolower(trim($type))); require_cache($cachePath.$cacheClass.'.class.php'); if(class_exists($cacheClass)) $cache = new $cacheClass($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); } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Util/Cache.class.php
PHP
asf20
5,048
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * Smarty模板引擎解析类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Util * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class TemplateSmarty { /** +---------------------------------------------------------- * 渲染模板输出 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $templateFile 模板文件名 * @param array $var 模板变量 * @param string $charset 模板输出字符集 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function fetch($templateFile,$var,$charset) { $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); } } ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Util/Template/TemplateSmarty.class.php
PHP
asf20
2,285
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 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 Think * @subpackage Util * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class TemplateThink { /** +---------------------------------------------------------- * 渲染模板输出 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $templateFile 模板文件名 * @param array $var 模板变量 * @param string $charset 模板输出字符集 * @param string $varPrefix 模板变量前缀 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function fetch($templateFile,$var,$charset) { if(!$this->checkCache($templateFile)) { // 缓存无效 重新编译 $tpl = Think::instance('ThinkTemplate'); // 编译并加载模板文件 $tpl->load($templateFile,$var,$charset); }else{ // 缓存有效 直接载入模板缓存 // 模板阵列变量分解成为独立变量 extract($var, EXTR_OVERWRITE); //载入模版缓存文件 include C('CACHE_PATH').md5($templateFile).C('TMPL_CACHFILE_SUFFIX'); } } /** +---------------------------------------------------------- * 检查缓存文件是否有效 * 如果无效则需要重新编译 +---------------------------------------------------------- * @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') != -1 && time() > filemtime($tmplCacheFile)+C('TMPL_CACHE_TIME')) { // 缓存是否在有效期 return false; } //缓存有效 return true; } } ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Util/Template/TemplateThink.class.php
PHP
asf20
3,535
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * Cookie管理类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Util * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class Cookie extends Think { // 判断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,'',time()-3600); unset($_COOKIE[C('COOKIE_PREFIX').$name]); } // 清空Cookie值 static function clear() { unset($_COOKIE); } } ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Util/Cookie.class.php
PHP
asf20
2,270
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * 系统调试类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Util * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class Debug extends Think {//类定义开始 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); } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Util/Debug.class.php
PHP
asf20
4,853
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP Widget类 抽象类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Util * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ abstract class Widget extends Think { // 使用的模板引擎 每个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 模板变量 * @param string $charset 模板编码 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function renderFile($templateFile='',$var='',$charset='utf-8') { 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 = $this->template?$this->template:strtolower(C('TMPL_ENGINE_TYPE')?C('TMPL_ENGINE_TYPE'):'php'); if('php' == $template) { // 使用PHP模板 if(!empty($var)) extract($var, EXTR_OVERWRITE); // 直接载入PHP模板 include $templateFile; }else{ $className = 'Template'.ucwords($template); require_cache(THINK_PATH.'/Lib/Think/Util/Template/'.$className.'.class.php'); $tpl = new $className; $tpl->fetch($templateFile,$var,$charset); } $content = ob_get_clean(); return $content; } } ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Util/Widget.class.php
PHP
asf20
3,610
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP内置的Dispatcher类 * 完成URL解析、路由和调度 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Util * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class Dispatcher extends Think {//类定义开始 /** +---------------------------------------------------------- * URL映射到控制器 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function dispatch() { $urlMode = C('URL_MODEL'); if($urlMode == URL_REWRITE ) { //当前项目地址 $url = dirname(_PHP_FILE_); if($url == '/' || $url == '\\') $url = ''; define('PHP_FILE',$url); }elseif($urlMode == URL_COMPAT){ define('PHP_FILE',_PHP_FILE_.'?'.C('VAR_PATHINFO').'='); }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 && array_key_exists($subDomain,$rules)) { $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); } } } $depr = C('URL_PATHINFO_DEPR'); // 分析PATHINFO信息 self::getPathInfo(); if(!self::routerCheck()){ // 检测路由规则 如果没有则按默认规则调度URL $paths = explode($depr,trim($_SERVER['PATH_INFO'],'/')); $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)); $_GET = array_merge($var,$_GET); } // 获取分组 模块和操作名称 if (C('APP_GROUP_LIST')) { define('GROUP_NAME', self::getGroup(C('VAR_GROUP'))); // 加载分组配置文件 if(is_file(CONFIG_PATH.GROUP_NAME.'/config.php')) C(include CONFIG_PATH.GROUP_NAME.'/config.php'); // 加载分组函数文件 if(is_file(COMMON_PATH.GROUP_NAME.'/function.php')) include COMMON_PATH.GROUP_NAME.'/function.php'; } define('MODULE_NAME',self::getModule(C('VAR_MODULE'))); define('ACTION_NAME',self::getAction(C('VAR_ACTION'))); // URL常量 // 当前页面地址 //define('__SELF__',$_SERVER['PHP_SELF']); define('__SELF__',$_SERVER['REQUEST_URI']); define('__INFO__',$_SERVER['PATH_INFO']); // 当前项目地址 define('__APP__',PHP_FILE); // 当前模块和分组地址 $module = defined('P_MODULE_NAME')?P_MODULE_NAME:MODULE_NAME; if(defined('GROUP_NAME')) { $group = C('URL_CASE_INSENSITIVE') ?strtolower(GROUP_NAME):GROUP_NAME; define('__GROUP__',(!empty($domainGroup) || GROUP_NAME == C('DEFAULT_GROUP') )?__APP__ : __APP__.'/'.$group); 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); } /** +---------------------------------------------------------- * 获得服务器的PATH_INFO信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public static function getPathInfo() { if(!empty($_GET[C('VAR_PATHINFO')])) { // 兼容PATHINFO 参数 $path = $_GET[C('VAR_PATHINFO')]; unset($_GET[C('VAR_PATHINFO')]); }elseif(!empty($_SERVER['PATH_INFO'])){ $pathInfo = $_SERVER['PATH_INFO']; if(0 === strpos($pathInfo,$_SERVER['SCRIPT_NAME'])) $path = substr($pathInfo, strlen($_SERVER['SCRIPT_NAME'])); else $path = $pathInfo; }elseif(!empty($_SERVER['ORIG_PATH_INFO'])) { $pathInfo = $_SERVER['ORIG_PATH_INFO']; if(0 === strpos($pathInfo, $_SERVER['SCRIPT_NAME'])) $path = substr($pathInfo, strlen($_SERVER['SCRIPT_NAME'])); else $path = $pathInfo; }elseif (!empty($_SERVER['REDIRECT_PATH_INFO'])){ $path = $_SERVER['REDIRECT_PATH_INFO']; }elseif(!empty($_SERVER["REDIRECT_Url"])){ $path = $_SERVER["REDIRECT_Url"]; if(empty($_SERVER['QUERY_STRING']) || $_SERVER['QUERY_STRING'] == $_SERVER["REDIRECT_QUERY_STRING"]) { $parsedUrl = parse_url($_SERVER["REQUEST_URI"]); if(!empty($parsedUrl['query'])) { $_SERVER['QUERY_STRING'] = $parsedUrl['query']; parse_str($parsedUrl['query'], $GET); $_GET = array_merge($_GET, $GET); reset($_GET); }else { unset($_SERVER['QUERY_STRING']); } reset($_SERVER); } } if(C('URL_HTML_SUFFIX') && !empty($path)) { $path = preg_replace('/\.'.trim(C('URL_HTML_SUFFIX'),'.').'$/', '', $path); } $_SERVER['PATH_INFO'] = empty($path) ? '/' : $path; } /** +---------------------------------------------------------- * 路由检测 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function routerCheck() { $regx = trim($_SERVER['PATH_INFO'],'/'); if(empty($regx)) return true; // 是否开启路由使用 if(!C('URL_ROUTER_ON')) return false; // 路由定义文件优先于config中的配置定义 $routes = C('URL_ROUTE_RULES'); if(is_array(C('_routes_'))) $routes = C('_routes_'); // 路由处理 if(!empty($routes)) { $depr = C('URL_PATHINFO_DEPR'); foreach ($routes as $key=>$route){ if(0 === stripos($regx.$depr,$route[0].$depr)) { // 简单路由定义:array('路由定义','分组/模块/操作名', '路由对应变量','额外参数'), $var = self::parseUrl($route[1]); // 获取当前路由参数对应的变量 $paths = explode($depr,trim(str_ireplace($route[0].$depr,$depr,$regx),$depr)); $vars = explode(',',$route[2]); for($i=0;$i<count($vars);$i++) $var[$vars[$i]] = array_shift($paths); // 解析剩余的URL参数 $res = preg_replace('@(\w+)\/([^,\/]+)@e', '$var[\'\\1\']=strip_tags(\'\\2\');', implode('/',$paths)); $_GET = array_merge($var,$_GET); if(isset($route[3])) { parse_str($route[3],$params); $_GET = array_merge($_GET,$params); } return true; }elseif(1 < substr_count($route[0],'/') && preg_match($route[0],$regx,$matches)) { // 路由定义规则:array('正则定义','分组/模块/操作名', '路由对应变量','额外参数'), $var = self::parseUrl($route[1]); // 获取当前路由参数对应的变量 $vars = explode(',',$route[2]); for($i=0;$i<count($vars);$i++) $var[$vars[$i]] = $matches[$i+1]; // 解析剩余的URL参数 $res = preg_replace('@(\w+)\/([^,\/]+)@e', '$var[\'\\1\']= strip_tags(\'\\2\');', str_replace($matches[0],'',$regx)); $_GET = array_merge($var,$_GET); if(isset($route[3])) { parse_str($route[3],$params); $_GET = array_merge($_GET,$params); } return true; } } } return false; } static private function parseUrl($route) { $array = explode('/',$route); $var = array(); $var[C('VAR_ACTION')] = array_pop($array); $var[C('VAR_MODULE')] = array_pop($array); if(!empty($array)) $var[C('VAR_GROUP')] = array_pop($array); return $var; } /** +---------------------------------------------------------- * 获得实际的模块名称 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static private function getModule($var) { $module = (!empty($_GET[$var])? $_GET[$var]:C('DEFAULT_MODULE')); 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)); } unset($_GET[$var]); return $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]); return C('URL_CASE_INSENSITIVE')?strtolower($action):$action; } /** +---------------------------------------------------------- * 获得实际的分组名称 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static private function getGroup($var) { $group = (!empty($_GET[$var])?$_GET[$var]:C('DEFAULT_GROUP')); unset($_GET[$var]); return ucfirst(strtolower($group)); } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Util/Dispatcher.class.php
PHP
asf20
14,049
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ define("HTTP_SESSION_STARTED", 1); define("HTTP_SESSION_CONTINUED", 2); /** +------------------------------------------------------------------------------ * Session管理类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Util * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class Session extends Think {//类定义开始 /** +---------------------------------------------------------- * 启动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(); ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Util/Session.class.php
PHP
asf20
22,907
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * 文件类型缓存类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Util * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class CacheFile extends Cache {//类定义开始 /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($options='') { if(!empty($options['temp'])){ $this->options['temp'] = $options['temp']; }else { $this->options['temp'] = C('DATA_CACHE_PATH'); } $this->expire = isset($options['expire'])?$options['expire']:C('DATA_CACHE_TIME'); if(substr($this->options['temp'], -1) != "/") $this->options['temp'] .= "/"; $this->connected = is_dir($this->options['temp']) && is_writeable($this->options['temp']); $this->type = strtoupper(substr(__CLASS__,6)); $this->init(); } /** +---------------------------------------------------------- * 初始化检查 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ private function init() { $stat = stat($this->options['temp']); $dir_perms = $stat['mode'] & 0007777; // Get the permission bits. $file_perms = $dir_perms & 0000666; // Remove execute bits for files. // 创建项目缓存目录 if (!is_dir($this->options['temp'])) { if (! mkdir($this->options['temp'])) return false; chmod($this->options['temp'], $dir_perms); } } /** +---------------------------------------------------------- * 是否连接 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ private function isConnected() { return $this->connected; } /** +---------------------------------------------------------- * 取得变量的存储文件名 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ private function filename($name) { $name = md5($name); if(C('DATA_CACHE_SUBDIR')) { // 使用子目录 $dir =''; for($i=0;$i<C('DATA_PATH_LEVEL');$i++) { $dir .= $name{$i}.'/'; } if(!is_dir($this->options['temp'].$dir)) { mk_dir($this->options['temp'].$dir); } $filename = $dir.$this->prefix.$name.'.php'; }else{ $filename = $this->prefix.$name.'.php'; } return $this->options['temp'].$filename; } /** +---------------------------------------------------------- * 读取缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function get($name) { $filename = $this->filename($name); if (!$this->isConnected() || !is_file($filename)) { return false; } N('cache_read',1); $content = file_get_contents($filename); if( false !== $content) { $expire = (int)substr($content,8, 12); if($expire != -1 && time() > filemtime($filename) + $expire) { //缓存过期删除缓存文件 unlink($filename); return false; } if(C('DATA_CACHE_CHECK')) {//开启数据校验 $check = substr($content,20, 32); $content = substr($content,52, -3); if($check != md5($content)) {//校验错误 return false; } }else { $content = substr($content,20, -3); } 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 int $expire 有效时间 -1 为永久 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function set($name,$value,$expire='') { N('cache_write',1); if('' === $expire) { $expire = $this->expire; } $filename = $this->filename($name); $data = serialize($value); if( C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { //数据压缩 $data = gzcompress($data,3); } if(C('DATA_CACHE_CHECK')) {//开启数据校验 $check = md5($data); }else { $check = ''; } $data = "<?php\n//".sprintf('%012d',$expire).$check.$data."\n?>"; $result = file_put_contents($filename,$data); if($result) { clearstatcache(); return true; }else { return false; } } /** +---------------------------------------------------------- * 删除缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function rm($name) { return unlink($this->filename($name)); } /** +---------------------------------------------------------- * 清除缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function clear() { $path = $this->options['temp']; if ( $dir = opendir( $path ) ) { while ( $file = readdir( $dir ) ) { $check = is_dir( $file ); if ( !$check ) unlink( $path . $file ); } closedir( $dir ); return true; } } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Util/Cache/CacheFile.class.php
PHP
asf20
8,871
<?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$ /** +------------------------------------------------------------------------------ * Memcache缓存类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Util * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ 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' => '127.0.0.1', 'port' => 11211, 'timeout' => false, 'persistent' => false ); } $func = $options['persistent'] ? 'pconnect' : 'connect'; $this->expire = isset($options['expire'])?$options['expire']:C('DATA_CACHE_TIME'); $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']); $this->type = strtoupper(substr(__CLASS__,6)); } /** +---------------------------------------------------------- * 是否连接 +---------------------------------------------------------- * @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 存储数据 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function set($name, $value, $ttl = null) { N('cache_write',1); if(isset($ttl) && is_int($ttl)) $expire = $ttl; else $expire = $this->expire; return $this->handler->set($name, $value, 0, $expire); } /** +---------------------------------------------------------- * 删除缓存 * +---------------------------------------------------------- * @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(); } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Util/Cache/CacheMemcache.class.php
PHP
asf20
5,157
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * 行为抽象类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Util * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ abstract class Behavior extends Think { // 执行行为的接口方法 abstract public function run(); } ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Util/Behavior.class.php
PHP
asf20
1,131
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * 日志处理类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class Log extends Think {//类定义开始 // 日志级别 从上到下,由低到高 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 TCP = 2; const FILE = 3; // 日志信息 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 || in_array($level,C('LOG_RECORD_LEVEL'))) { $now = date(self::$format); self::$log[] = "{$now} {$level}: {$message}\r\n"; } } /** +---------------------------------------------------------- * 日志保存 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param integer $type 日志记录方式 * @param string $destination 写入目标 * @param string $extra 额外参数 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static function save($type=self::FILE,$destination='',$extra='') { if(empty($destination)) $destination = LOG_PATH.date('y_m_d').".log"; if(self::FILE == $type) { // 文件方式记录日志信息 //检测日志文件大小,超过配置大小则备份日志文件重新生成 if(is_file($destination) && floor(C('LOG_FILE_SIZE')) <= filesize($destination) ) rename($destination,dirname($destination).'/'.time().'-'.basename($destination)); } 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=self::FILE,$destination='',$extra='') { $now = date(self::$format); if(empty($destination)) $destination = LOG_PATH.date('y_m_d').".log"; if(self::FILE == $type) { // 文件方式记录日志 //检测日志文件大小,超过配置大小则备份日志文件重新生成 if(is_file($destination) && floor(C('LOG_FILE_SIZE')) <= filesize($destination) ) rename($destination,dirname($destination).'/'.time().'-'.basename($destination)); } error_log("{$now} {$level}: {$message}\r\n", $type,$destination,$extra ); //clearstatcache(); } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Core/Log.class.php
PHP
asf20
5,641
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 视图输出 * 支持缓存和页面压缩 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class View extends Think { protected $tVar = array(); // 模板输出变量 protected $trace = array(); // 页面trace变量 protected $templateFile = ''; // 模板文件名 /** +---------------------------------------------------------- * 模板变量赋值 +---------------------------------------------------------- * @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; } } /** +---------------------------------------------------------- * Trace变量赋值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $name * @param mixed $value +---------------------------------------------------------- */ public function trace($title,$value='') { if(is_array($title)) $this->trace = array_merge($this->trace,$title); else $this->trace[$title] = $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='') { $this->fetch($templateFile,$charset,$contentType,true); } /** +---------------------------------------------------------- * 输出布局模板 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $charset 输出编码 * @param string $contentType 输出类型 * @param string $display 是否直接显示 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ protected function layout($content,$charset='',$contentType='') { if(false !== strpos($content,'<!-- layout')) { // 查找布局包含的页面 $find = preg_match_all('/<!-- layout::(.+?)::(.+?) -->/is',$content,$matches); if($find) { for ($i=0; $i< $find; $i++) { // 读取相关的页面模板替换布局单元 if(0===strpos($matches[1][$i],'$')) // 动态布局 $matches[1][$i] = $this->get(substr($matches[1][$i],1)); if(0 != $matches[2][$i] ) { // 设置了布局缓存 // 检查布局缓存是否有效 $guid = md5($matches[1][$i]); $cache = S($guid); if($cache) { $layoutContent = $cache; }else{ $layoutContent = $this->fetch($matches[1][$i],$charset,$contentType); S($guid,$layoutContent,$matches[2][$i]); } }else{ $layoutContent = $this->fetch($matches[1][$i],$charset,$contentType); } $content = str_replace($matches[0][$i],$layoutContent,$content); } } } return $content; } /** +---------------------------------------------------------- * 加载模板和页面输出 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $templateFile 模板文件名 留空为自动获取 * @param string $charset 模板输出字符集 * @param string $contentType 输出类型 * @param string $display 是否直接显示 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function fetch($templateFile='',$charset='',$contentType='',$display=false) { G('_viewStartTime'); // 使用null参数作为模版名直接返回不做任何输出 if(null===$templateFile) return; // 网页字符编码 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".THINK_VERSION); //页面缓存 ob_start(); ob_implicit_flush(0); // 自动定位模板文件 if(!file_exists_case($templateFile)) $templateFile = $this->parseTemplateFile($templateFile); $engine = strtolower(C('TMPL_ENGINE_TYPE')); if('php'==$engine) { // 模板阵列变量分解成为独立变量 extract($this->tVar, EXTR_OVERWRITE); // 直接载入PHP模板 include $templateFile; }elseif('think'==$engine && $this->checkCache($templateFile)) { // 如果是Think模板引擎并且缓存有效 分解变量并载入模板缓存 extract($this->tVar, EXTR_OVERWRITE); //载入模版缓存文件 include C('CACHE_PATH').md5($templateFile).C('TMPL_CACHFILE_SUFFIX'); }else{ // 模板文件需要重新编译 支持第三方模板引擎 // 调用模板引擎解析和输出 $className = 'Template'.ucwords($engine); require_cache(THINK_PATH.'/Lib/Think/Util/Template/'.$className.'.class.php'); $tpl = new $className; $tpl->fetch($templateFile,$this->tVar,$charset); } $this->templateFile = $templateFile; // 获取并清空缓存 $content = ob_get_clean(); // 模板内容替换 $content = $this->templateContentReplace($content); // 布局模板解析 $content = $this->layout($content,$charset,$contentType); // 输出模板文件 return $this->output($content,$display); } /** +---------------------------------------------------------- * 检查缓存文件是否有效 * 如果无效则需要重新编译 +---------------------------------------------------------- * @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') != -1 && time() > filemtime($tmplCacheFile)+C('TMPL_CACHE_TIME')) { // 缓存是否在有效期 return false; } //缓存有效 return true; } /** +---------------------------------------------------------- * 创建静态页面 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @htmlfile 生成的静态文件名称 * @htmlpath 生成的静态文件路径 * @param string $templateFile 指定要调用的模板文件 * 默认为空 由系统自动定位模板文件 * @param string $charset 输出编码 * @param string $contentType 输出类型 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function buildHtml($htmlfile,$htmlpath='',$templateFile='',$charset='',$contentType='') { $content = $this->fetch($templateFile,$charset,$contentType); $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 string $content 模板内容 * @param boolean $display 是否直接显示 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ protected function output($content,$display) { if(C('HTML_CACHE_ON')) HtmlCache::writeHTMLCache($content); if($display) { if(false !== strpos($content,'{__RUNTIME__}')) { $runtime = C('SHOW_RUN_TIME')? '<div id="think_run_time" class="think_run_time">'.$this->showTime().'</div>' : ''; $content = str_replace('{__RUNTIME__}', $runtime, $content); } echo $content; if(C('SHOW_PAGE_TRACE')) $this->showTrace(); return null; }else { return $content; } } /** +---------------------------------------------------------- * 模板内容替换 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $content 模板内容 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function templateContentReplace($content) { // 系统默认的特殊变量替换 $replace = array( '../Public' => APP_PUBLIC_PATH,// 项目公共目录 '__PUBLIC__' => WEB_PUBLIC_PATH,// 站点公共目录 '__TMPL__' => APP_TMPL_PATH, // 项目模板目录 '__ROOT__' => __ROOT__, // 当前网站地址 '__APP__' => __APP__, // 当前项目地址 '__UPLOAD__' => __ROOT__.'/Uploads', '__ACTION__' => __ACTION__, // 当前操作地址 '__SELF__' => __SELF__, // 当前页面地址 '__URL__' => __URL__, '__INFO__' => __INFO__, ); if(defined('GROUP_NAME')) { $replace['__GROUP__'] = __GROUP__;// 当前项目地址 } if(C('TOKEN_ON')) { if(strpos($content,'{__TOKEN__}')) { // 指定表单令牌隐藏域位置 $replace['{__TOKEN__}'] = $this->buildFormToken(); }elseif(strpos($content,'{__NOTOKEN__}')){ // 标记为不需要令牌验证 $replace['{__NOTOKEN__}'] = ''; }elseif(preg_match('/<\/form(\s*)>/is',$content,$match)) { // 智能生成表单令牌隐藏域 $replace[$match[0]] = $this->buildFormToken().$match[0]; } } // 允许用户自定义模板的字符串替换 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; } /** +---------------------------------------------------------- * 创建表单令牌隐藏域 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ private function buildFormToken() { // 开启表单验证自动生成表单令牌 $tokenName = C('TOKEN_NAME'); $tokenType = C('TOKEN_TYPE'); $tokenValue = $tokenType(microtime(TRUE)); $token = '<input type="hidden" name="'.$tokenName.'" value="'.$tokenValue.'" />'; $_SESSION[$tokenName] = $tokenValue; return $token; } /** +---------------------------------------------------------- * 自动定位模板文件 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param string $templateFile 文件名 +---------------------------------------------------------- * @return string +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ private function parseTemplateFile($templateFile) { if(''==$templateFile) { // 如果模板文件名为空 按照默认规则定位 $templateFile = C('TMPL_FILE_NAME'); }elseif(false === strpos($templateFile,'.')){ $templateFile = str_replace(array('@',':'),'/',$templateFile); $count = substr_count($templateFile,'/'); $path = dirname(C('TMPL_FILE_NAME')); for($i=0;$i<$count;$i++) $path = dirname($path); $templateFile = $path.'/'.$templateFile.C('TMPL_TEMPLATE_SUFFIX'); } if(!file_exists_case($templateFile)) throw_exception(L('_TEMPLATE_NOT_EXIST_').'['.$templateFile.']'); return $templateFile; } /** +---------------------------------------------------------- * 显示运行时间、数据库操作、缓存次数、内存使用信息 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ private function showTime() { // 显示运行时间 G('viewStartTime'); $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')) { // 显示内存开销 $startMem = array_sum(explode(' ', $GLOBALS['_startUseMems'])); $endMem = array_sum(explode(' ', memory_get_usage())); $showTime .= ' | UseMem:'. number_format(($endMem - $startMem)/1024).' kb'; } return $showTime; } /** +---------------------------------------------------------- * 显示页面Trace信息 +---------------------------------------------------------- * @access private +---------------------------------------------------------- */ private function showTrace(){ // 显示页面Trace信息 读取Trace定义文件 // 定义格式 return array('当前页面'=>$_SERVER['PHP_SELF'],'通信协议'=>$_SERVER['SERVER_PROTOCOL'],...); $traceFile = CONFIG_PATH.'trace.php'; $_trace = is_file($traceFile)? include $traceFile : array(); // 系统默认显示信息 $this->trace('当前页面', $_SERVER['REQUEST_URI']); $this->trace('模板缓存', C('CACHE_PATH').md5($this->templateFile).C('TMPL_CACHFILE_SUFFIX')); $this->trace('请求方法', $_SERVER['REQUEST_METHOD']); $this->trace('通信协议', $_SERVER['SERVER_PROTOCOL']); $this->trace('请求时间', date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME'])); $this->trace('用户代理', $_SERVER['HTTP_USER_AGENT']); $this->trace('会话ID' , session_id()); $log = Log::$log; $this->trace('日志记录',count($log)?count($log).'条日志<br/>'.implode('<br/>',$log):'无日志记录'); $files = get_included_files(); $this->trace('加载文件', count($files).str_replace("\n",'<br/>',substr(substr(print_r($files,true),7),0,-2))); $_trace = array_merge($_trace,$this->trace); // 调用Trace页面模板 include C('TMPL_TRACE_FILE'); } }// ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Core/View.class.php
PHP
asf20
20,632
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 应用程序类 执行应用过程管理 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class App {//类定义开始 /** +---------------------------------------------------------- * 应用程序初始化 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function init() { // 设定错误和异常处理 set_error_handler(array('App','appError')); set_exception_handler(array('App','appException')); //[RUNTIME] // 检查项目是否编译过 // 在部署模式下会自动在第一次执行的时候编译项目 if(defined('RUNTIME_MODEL')){ // 运行模式无需载入项目编译缓存 }elseif(is_file(RUNTIME_PATH.'~'.APP_CACHE_NAME.'.php') && (!is_file(CONFIG_PATH.'config.php') || filemtime(RUNTIME_PATH.'~'.APP_CACHE_NAME.'.php')>filemtime(CONFIG_PATH.'config.php'))) { // 直接读取编译后的项目文件 C(include RUNTIME_PATH.'~'.APP_CACHE_NAME.'.php'); }else{ // 预编译项目 App::build(); } //[/RUNTIME] // 设置系统时区 PHP5支持 if(function_exists('date_default_timezone_set')) date_default_timezone_set(C('DEFAULT_TIMEZONE')); // 允许注册AUTOLOAD方法 if(C('APP_AUTOLOAD_REG') && function_exists('spl_autoload_register')) spl_autoload_register(array('Think', 'autoload')); // Session初始化 if(C('SESSION_AUTO_START')) session_start(); // URL调度 Dispatcher::dispatch(); // 加载模块配置文件 if(is_file(CONFIG_PATH.strtolower(MODULE_NAME).'_config.php')) C(include CONFIG_PATH.strtolower(MODULE_NAME).'_config.php'); // 系统检查 App::checkLanguage(); //语言检查 App::checkTemplate(); //模板检查 // 开启静态缓存 if(C('HTML_CACHE_ON')) HtmlCache::readHTMLCache(); // 项目初始化标签 if(C('APP_PLUGIN_ON')) tag('app_init'); return ; } //[RUNTIME] /** +---------------------------------------------------------- * 读取配置信息 编译项目 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static private function build() { // 加载惯例配置文件 C(include THINK_PATH.'/Common/convention.php'); // 加载项目配置文件 if(is_file(CONFIG_PATH.'config.php')) C(include CONFIG_PATH.'config.php'); $runtime = defined('RUNTIME_ALLINONE'); $common = ''; //是否调试模式 ALL_IN_ONE模式下面调试模式无效 $debug = C('APP_DEBUG') && !$runtime; // 加载项目公共文件 if(is_file(COMMON_PATH.'common.php')) { include COMMON_PATH.'common.php'; // 编译文件 if(!$debug) $common .= compile(COMMON_PATH.'common.php',$runtime); } // 加载项目编译文件列表 if(is_file(CONFIG_PATH.'app.php')) { $list = include CONFIG_PATH.'app.php'; foreach ($list as $file){ // 加载并编译文件 require $file; if(!$debug) $common .= compile($file,$runtime); } } // 读取扩展配置文件 $list = C('APP_CONFIG_LIST'); foreach ($list as $val){ if(is_file(CONFIG_PATH.$val.'.php')) C('_'.$val.'_',array_change_key_case(include CONFIG_PATH.$val.'.php')); } // 如果是调试模式加载调试模式配置文件 if($debug) { // 加载系统默认的开发模式配置文件 C(include THINK_PATH.'/Common/debug.php'); if(is_file(CONFIG_PATH.'debug.php')) // 允许项目增加开发模式配置定义 C(include CONFIG_PATH.'debug.php'); }else{ // 部署模式下面生成编译文件 // 下次直接加载项目编译文件 if($runtime) { // 获取用户自定义变量 $defs = get_defined_constants(TRUE); $content = array_define($defs['user']); $runtimefile = defined('THINK_MODE')?'~'.strtolower(THINK_MODE).'_runtime.php':'~runtime.php'; $content .= substr(file_get_contents(RUNTIME_PATH.$runtimefile),5); $content .= $common."\nreturn ".var_export(C(),true).';'; file_put_contents(RUNTIME_PATH.'~allinone.php',strip_whitespace('<?php '.$content)); }else{ $content = "<?php ".$common."\nreturn ".var_export(C(),true).";\n?>"; file_put_contents(RUNTIME_PATH.'~'.APP_CACHE_NAME.'.php',strip_whitespace($content)); } } return ; } //[/RUNTIME] /** +---------------------------------------------------------- * 语言检查 * 检查浏览器支持语言,并自动加载语言包 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static private function checkLanguage() { $langSet = C('DEFAULT_LANG'); // 不开启语言包功能,仅仅加载框架语言文件直接返回 if (!C('LANG_SWITCH_ON')){ L(include THINK_PATH.'/Lang/'.$langSet.'.php'); return; } // 启用了语言包功能 // 根据是否启用自动侦测设置获取语言选择 if (C('LANG_AUTO_DETECT')){ if(isset($_GET[C('VAR_LANGUAGE')])){// 检测浏览器支持语言 $langSet = $_GET[C('VAR_LANGUAGE')];// url中设置了语言变量 cookie('think_language',$langSet); }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 = strtolower($matches[1]); cookie('think_language',$langSet); } } // 定义当前语言 define('LANG_SET',strtolower($langSet)); // 加载框架语言包 if(is_file(THINK_PATH.'/Lang/'.LANG_SET.'.php')) L(include THINK_PATH.'/Lang/'.LANG_SET.'.php'); // 读取项目公共语言包 if (is_file(LANG_PATH.LANG_SET.'/common.php')) L(include LANG_PATH.LANG_SET.'/common.php'); $group = ''; // 读取当前分组公共语言包 if (defined('GROUP_NAME')){ $group = GROUP_NAME.C('TMPL_FILE_DEPR'); if (is_file(LANG_PATH.LANG_SET.'/'.$group.'lang.php')) L(include LANG_PATH.LANG_SET.'/'.$group.'lang.php'); } // 读取当前模块语言包 if (is_file(LANG_PATH.LANG_SET.'/'.$group.strtolower(MODULE_NAME).'.php')) L(include LANG_PATH.LANG_SET.'/'.$group.strtolower(MODULE_NAME).'.php'); } /** +---------------------------------------------------------- * 模板检查,如果不存在使用默认 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static private function checkTemplate() { /* 获取模板主题名称 */ $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('TEMPLATE_NAME', $templateSet); // 当前模板主题名称 define('APP_TMPL_PATH', __ROOT__.'/'.APP_NAME.'/'.TMPL_DIR.'/'.TEMPLATE_NAME.'/');// 当前项目模板目录 define('TEMPLATE_PATH', TMPL_PATH.TEMPLATE_NAME); // 当前模版路径 define('__CURRENT__', APP_TMPL_PATH.MODULE_NAME); // 当前默认模板目录 define('WEB_PUBLIC_PATH', __ROOT__.'/Public'); // 网站公共文件目录 define('APP_PUBLIC_PATH', APP_TMPL_PATH.'Public'); // 项目公共文件目录 if(defined('GROUP_NAME')) { C('TMPL_FILE_NAME',TEMPLATE_PATH.'/'.GROUP_NAME.'/'.MODULE_NAME.C('TMPL_FILE_DEPR').ACTION_NAME.C('TMPL_TEMPLATE_SUFFIX')); C('CACHE_PATH',CACHE_PATH.GROUP_NAME.'/'); }else{ C('TMPL_FILE_NAME',TEMPLATE_PATH.'/'.MODULE_NAME.'/'.ACTION_NAME.C('TMPL_TEMPLATE_SUFFIX')); C('CACHE_PATH',CACHE_PATH); } return ; } /** +---------------------------------------------------------- * 执行应用程序 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ static public function exec() { // 是否开启标签扩展 $tagOn = C('APP_PLUGIN_ON'); // 项目运行标签 if($tagOn) tag('app_run'); // 安全检测 if(!preg_match('/^[A-Za-z_0-9]+$/',MODULE_NAME)){ throw_exception(L('_MODULE_NOT_EXIST_')); } //创建Action控制器实例 $group = defined('GROUP_NAME') ? GROUP_NAME.C('APP_GROUP_DEPR') : ''; $module = A($group.MODULE_NAME); if(!$module) { // 是否存在扩展模块 $_module = C('_modules_.'.MODULE_NAME); if($_module) { // 'module'=>array('classImportPath'[,'className']) import($_module[0]); $class = isset($_module[1])?$_module[1]:MODULE_NAME.'Action'; $module = new $class; }else{ // 是否定义Empty模块 $module = A("Empty"); } if(!$module) // 模块不存在 抛出异常 throw_exception(L('_MODULE_NOT_EXIST_').MODULE_NAME); } //获取当前操作名 $action = ACTION_NAME; if(strpos($action,':')) { // 执行操作链 最多只能有一个输出 $actionList = explode(':',$action); foreach ($actionList as $action){ $module->$action(); } }else{ 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)); } } // 项目结束标签 if($tagOn) tag('app_end'); return ; } /** +---------------------------------------------------------- * 运行应用实例 入口文件使用的快捷方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function run() { App::init(); // 记录应用初始化时间 if(C('SHOW_RUN_TIME')) G('initTime'); App::exec(); // 保存日志记录 if(C('LOG_RECORD')) Log::save(); return ; } /** +---------------------------------------------------------- * 自定义异常处理 +---------------------------------------------------------- * @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; } } };//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Core/App.class.php
PHP
asf20
15,778
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ define('HAS_ONE',1); define('BELONGS_TO',2); define('HAS_MANY',3); define('MANY_TO_MANY',4); /** +------------------------------------------------------------------------------ * ThinkPHP Model模型类 * 实现了ORM和ActiveRecords模式 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class Model extends Think { // 操作状态 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 $tableSuffix = ''; // 模型名称 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; /** +---------------------------------------------------------- * 架构函数 * 取得DB类的实例对象 字段检查 +---------------------------------------------------------- * @param string $name 模型名称 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($name='',$connection='') { // 模型初始化 $this->_initialize(); // 获取模型名称 if(!empty($name)) { $this->name = $name; }elseif(empty($this->name)){ $this->name = $this->getModelName(); } // 数据库初始化操作 // 获取数据库操作对象 // 当前模型有独立的数据库连接信息 $this->db(0,empty($this->connection)?$connection:$this->connection); // 设置表前缀 $this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX'); $this->tableSuffix = $this->tableSuffix?$this->tableSuffix:C('DB_SUFFIX'); // 字段检测 if(!empty($this->name) && $this->autoCheckFields) $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); } /** +---------------------------------------------------------- * 动态切换扩展模型 +---------------------------------------------------------- * @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('field','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(); }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)) { // 字段类型检查 $fieldType = strtolower($this->fields['_type'][$key]); if(false !== strpos($fieldType,'int')) { $data[$key] = intval($val); }elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){ $data[$key] = floatval($val); } } } } $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; }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; }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)) { // 如果删除条件为空 则删除当前数据对象所对应的记录 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; } // 分析表达式 $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) {} public function findAll($options=array()) { return $this->select($options); } /** +---------------------------------------------------------- * 分析表达式 +---------------------------------------------------------- * @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(); if(!empty($options['alias'])) { $options['table'] .= ' '.$options['alias']; } // 字段类型验证 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)){ $fieldType = strtolower($this->fields['_type'][$key]); if(false !== strpos($fieldType,'int')) { $options['where'][$key] = intval($val); }elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){ $options['where'][$key] = floatval($val); } } } } } // 表达式过滤 $this->_options_filter($options); return $options; } // 表达式过滤回调方法 protected function _options_filter(&$options) {} /** +---------------------------------------------------------- * 查询数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $options 表达式参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function find($options=array()) { if(!empty($options) && ( 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 string|array $field 字段名 * @param string|array $value 字段值 * @param mixed $condition 条件 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setField($field,$value,$condition='') { if(empty($condition) && isset($this->options['where'])) $condition = $this->options['where']; $options['where'] = $condition; if(is_array($field)) { foreach ($field as $key=>$val) $data[$val] = $value[$key]; }else{ $data[$field] = $value; } return $this->save($data,$options); } /** +---------------------------------------------------------- * 字段值增长 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param mixed $condition 条件 * @param integer $step 增长值 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setInc($field,$condition='',$step=1) { return $this->setField($field,array('exp',$field.'+'.$step),$condition); } /** +---------------------------------------------------------- * 字段值减少 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param mixed $condition 条件 * @param integer $step 减少值 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setDec($field,$condition='',$step=1) { return $this->setField($field,array('exp',$field.'-'.$step),$condition); } /** +---------------------------------------------------------- * 获取一条记录的某个字段值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param mixed $condition 查询条件 * @param string $spea 字段数据间隔符号 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function getField($field,$condition='',$sepa=' ') { if(empty($condition) && isset($this->options['where'])) $condition = $this->options['where']; $options['where'] = $condition; $options['field'] = $field; $options = $this->_parseOptions($options); if(strpos($field,',')) { // 多字段 $resultSet = $this->db->select($options); if(!empty($resultSet)) { $field = explode(',',$field); $key = array_shift($field); $cols = array(); foreach ($resultSet as $result){ $name = $result[$key]; $cols[$name] = ''; foreach ($field as $val) $cols[$name] .= $result[$val].$sepa; $cols[$name] = substr($cols[$name],0,-strlen($sepa)); } 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); }elseif(!is_array($data)){ $this->error = L('_DATA_TYPE_INVALID_'); return false; } // 状态 $type = $type?$type:(!empty($data[$this->getPk()])?self::MODEL_UPDATE:self::MODEL_INSERT); // 表单令牌验证 if(C('TOKEN_ON') && !$this->autoCheckToken($data)) { $this->error = L('_TOKEN_ERROR_'); return false; } // 检查字段映射 if(!empty($this->_map)) { foreach ($this->_map as $key=>$val){ if(isset($data[$key])) { $data[$val] = $data[$key]; unset($data[$key]); } } } // 数据自动验证 if(!$this->autoValidation($data,$type)) 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; } } // 创建完成对数据进行自动处理 $this->autoOperation($vo,$type); // 赋值当前数据对象 $this->data = $vo; // 返回创建的数据以供其他调用 return $vo; } // 自动表单令牌验证 public function autoCheckToken($data) { $name = C('TOKEN_NAME'); if(isset($_SESSION[$name])) { // 当前需要令牌验证 if(empty($data[$name]) || $_SESSION[$name] != $data[$name]) { // 非法提交 return false; } // 验证完成销毁session unset($_SESSION[$name]); } 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])?$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)) { // 如果设置了数据自动验证 // 则进行数据验证 // 重置验证错误信息 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)){ $this->error = $val[2]; return false; } break; case self::VALUE_VAILIDATE: // 值不为空的时候才验证 if('' != trim($data[$val[0]])){ if(false === $this->_validationField($data,$val)){ $this->error = $val[2]; return false; } } break; default: // 默认表单存在该字段就验证 if(isset($data[$val[0]])){ if(false === $this->_validationField($data,$val)){ $this->error = $val[2]; return false; } } } } } } return true; } /** +---------------------------------------------------------- * 根据验证因子验证字段 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $data 创建数据 * @param string $val 验证规则 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ protected function _validationField($data,$val) { switch($val[4]) { case 'function':// 使用函数进行验证 case 'callback':// 调用方法进行验证 $args = isset($val[6])?$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 'in': // 验证是否在某个数组范围之内 return in_array($data[$val[0]] ,$val[1]); case 'equal': // 验证是否等于某个值 return $data[$val[0]] == $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->where($map)->find()) return false; break; case 'regex': default: // 默认使用正则验证 可以使用验证类中定义的验证名称 // 检查附加规则 return $this->regex($data[$val[0]],$val[1]); } return true; } /** +---------------------------------------------------------- * SQL查询 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $sql SQL指令 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ 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 Model +---------------------------------------------------------- */ public function db($linkNum,$config=''){ static $_db = array(); if(!isset($_db[$linkNum])) { // 创建一个新的实例 $_db[$linkNum] = Db::getInstance($config); }elseif(NULL === $config){ $_db[$linkNum]->close(); // 关闭数据库连接 unset($_db[$linkNum]); return ; } // 切换数据库连接 $this->db = $_db[$linkNum]; return $this; } /** +---------------------------------------------------------- * 得到当前的数据对象名称 +---------------------------------------------------------- * @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); } $tableName .= !empty($this->tableSuffix) ? $this->tableSuffix : ''; 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 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->lastInsID; } /** +---------------------------------------------------------- * 返回最后执行的sql语句 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastSql() { return $this->db->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(){ return $this->fields; } /** +---------------------------------------------------------- * 设置数据对象值 +---------------------------------------------------------- * @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; else $this->options['join'][] = $join; 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; } }; ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Core/Model.class.php
PHP
asf20
50,881
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP系统基类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class Think { private static $_instance = array(); /** +---------------------------------------------------------- * 自动变量设置 +---------------------------------------------------------- * @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; } /** +---------------------------------------------------------- * 系统自动加载ThinkPHP类库 * 并且支持配置自动加载路径 +---------------------------------------------------------- * @param string $classname 对象类名 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public static function autoload($classname) { // 检查是否存在别名定义 if(alias_import($classname)) return ; // 自动加载当前项目的Actioon类和Model类 if(substr($classname,-5)=="Model") { require_cache(LIB_PATH.'Model/'.$classname.'.class.php'); }elseif(substr($classname,-6)=="Action"){ require_cache(LIB_PATH.'Action/'.$classname.'.class.php'); }else { // 根据自动加载路径设置进行尝试搜索 if(C('APP_AUTOLOAD_PATH')) { $paths = explode(',',C('APP_AUTOLOAD_PATH')); foreach ($paths as $path){ if(import($path.$classname)) // 如果加载类成功则返回 return ; } } } 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]; } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Core/Think.class.php
PHP
asf20
4,608
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 关联模型类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class RelationModel extends Model { // 关联定义 protected $_link = array(); /** +---------------------------------------------------------- * 动态方法实现 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名称 * @param array $args 调用参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$args) { if(strtolower(substr($method,0,8))=='relation'){ $type = strtoupper(substr($method,8)); if(in_array($type,array('ADD','SAVE','DEL'),true)) { array_unshift($args,$type); return call_user_func_array(array(&$this, 'opRelation'), $args); } }else{ return parent::__call($method,$args); } } /** +---------------------------------------------------------- * 得到关联的数据表名 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getRelationTableName($relation) { $relationTable = !empty($this->tablePrefix) ? $this->tablePrefix : ''; $relationTable .= $this->tableName?$this->tableName:$this->name; $relationTable .= '_'.$relation->getModelName(); $relationTable .= !empty($this->tableSuffix) ? $this->tableSuffix : ''; return strtolower($relationTable); } // 查询成功后的回调方法 protected function _after_find(&$result,$options) { // 获取关联数据 并附加到结果中 if(!empty($options['link'])) $this->getRelation($result,$options['link']); } // 查询数据集成功后的回调方法 protected function _after_select(&$result,$options) { // 获取关联数据 并附加到结果中 if(!empty($options['link'])) $this->getRelations($result,$options['link']); } // 写入成功后的回调方法 protected function _after_insert($data,$options) { // 关联写入 if(!empty($options['link'])) $this->opRelation('ADD',$data,$options['link']); } // 更新成功后的回调方法 protected function _after_update($data,$options) { // 关联更新 if(!empty($options['link'])) $this->opRelation('SAVE',$data,$options['link']); } // 删除成功后的回调方法 protected function _after_delete($data,$options) { // 关联删除 if(!empty($options['link'])) $this->opRelation('DEL',$data,$options['link']); } /** +---------------------------------------------------------- * 对保存到数据库的数据进行处理 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $data 要操作的数据 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ protected function _facade($data) { $this->_before_write($data); return $data; } /** +---------------------------------------------------------- * 获取返回数据集的关联记录 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $resultSet 返回数据 * @param string|array $name 关联名称 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ protected function getRelations(&$resultSet,$name='') { // 获取记录集的主键列表 foreach($resultSet as $key=>$val) { $val = $this->getRelation($val,$name); $resultSet[$key] = $val; } return $resultSet; } /** +---------------------------------------------------------- * 获取返回数据的关联记录 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $result 返回数据 * @param string|array $name 关联名称 * @param boolean $return 是否返回关联数据本身 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ protected function getRelation(&$result,$name='',$return=false) { if(!empty($this->_link)) { foreach($this->_link as $key=>$val) { $mappingName = !empty($val['mapping_name'])?$val['mapping_name']:$key; // 映射名称 if(empty($name) || true === $name || $mappingName == $name || (is_array($name) && in_array($mappingName,$name))) { $mappingType = !empty($val['mapping_type'])?$val['mapping_type']:$val; // 关联类型 $mappingClass = !empty($val['class_name'])?$val['class_name']:$key; // 关联类名 $mappingFields = !empty($val['mapping_fields'])?$val['mapping_fields']:'*'; // 映射字段 $mappingCondition = !empty($val['condition'])?$val['condition']:'1=1'; // 关联条件 if(strtoupper($mappingClass)==strtoupper($this->name)) { // 自引用关联 获取父键名 $mappingFk = !empty($val['parent_key'])? $val['parent_key'] : 'parent_id'; }else{ $mappingFk = !empty($val['foreign_key'])?$val['foreign_key']:strtolower($this->name).'_id'; // 关联外键 } // 获取关联模型对象 $model = M($mappingClass); switch($mappingType) { case HAS_ONE: $pk = $result[$this->getPk()]; $mappingCondition .= " AND {$mappingFk}='{$pk}'"; $relationData = $model->where($mappingCondition)->field($mappingFields)->find(); break; case BELONGS_TO: if(strtoupper($mappingClass)==strtoupper($this->name)) { // 自引用关联 获取父键名 $mappingFk = !empty($val['parent_key'])? $val['parent_key'] : 'parent_id'; }else{ $mappingFk = !empty($val['foreign_key'])?$val['foreign_key']:strtolower($model->getModelName()).'_id'; // 关联外键 } $fk = $result[$mappingFk]; $mappingCondition .= " AND {$model->getPk()}='{$fk}'"; $relationData = $model->where($mappingCondition)->field($mappingFields)->find(); break; case HAS_MANY: $pk = $result[$this->getPk()]; $mappingCondition .= " AND {$mappingFk}='{$pk}'"; $mappingOrder = !empty($val['mapping_order'])?$val['mapping_order']:''; $mappingLimit = !empty($val['mapping_limit'])?$val['mapping_limit']:''; // 延时获取关联记录 $relationData = $model->where($mappingCondition)->field($mappingFields)->order($mappingOrder)->limit($mappingLimit)->select(); break; case MANY_TO_MANY: $pk = $result[$this->getPk()]; $mappingCondition = " {$mappingFk}='{$pk}'"; $mappingOrder = $val['mapping_order']; $mappingLimit = $val['mapping_limit']; $mappingRelationFk = $val['relation_foreign_key']?$val['relation_foreign_key']:$model->getModelName().'_id'; $mappingRelationTable = $val['relation_table']?$val['relation_table']:$this->getRelationTableName($model); $sql = "SELECT b.{$mappingFields} FROM {$mappingRelationTable} AS a, ".$model->getTableName()." AS b WHERE a.{$mappingRelationFk} = b.{$model->getPk()} AND a.{$mappingCondition}"; if(!empty($val['condition'])) { $sql .= ' AND '.$val['condition']; } if(!empty($mappingOrder)) { $sql .= ' ORDER BY '.$mappingOrder; } if(!empty($mappingLimit)) { $sql .= ' LIMIT '.$mappingLimit; } $relationData = $this->query($sql); break; } if(!$return){ if(isset($val['as_fields']) && in_array($mappingType,array(HAS_ONE,BELONGS_TO)) ) { // 支持直接把关联的字段值映射成数据对象中的某个字段 // 仅仅支持HAS_ONE BELONGS_TO $fields = explode(',',$val['as_fields']); foreach ($fields as $field){ if(strpos($field,':')) { list($name,$nick) = explode(':',$field); $result[$nick] = $relationData[$name]; }else{ $result[$field] = $relationData[$field]; } } }else{ $result[$mappingName] = $relationData; } unset($relationData); }else{ return $relationData; } } } } return $result; } /** +---------------------------------------------------------- * 操作关联数据 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $opType 操作方式 ADD SAVE DEL * @param mixed $data 数据对象 * @param string $name 关联名称 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ protected function opRelation($opType,$data='',$name='') { $result = false; if(empty($data) && !empty($this->data)){ $data = $this->data; }elseif(!is_array($data)){ // 数据无效返回 return false; } if(!empty($this->_link)) { // 遍历关联定义 foreach($this->_link as $key=>$val) { // 操作制定关联类型 $mappingName = $val['mapping_name']?$val['mapping_name']:$key; // 映射名称 if(empty($name) || true === $name || $mappingName == $name || (is_array($name) && in_array($mappingName,$name)) ) { // 操作制定的关联 $mappingType = !empty($val['mapping_type'])?$val['mapping_type']:$val; // 关联类型 $mappingClass = !empty($val['class_name'])?$val['class_name']:$key; // 关联类名 // 当前数据对象主键值 $pk = $data[$this->getPk()]; if(strtoupper($mappingClass)==strtoupper($this->name)) { // 自引用关联 获取父键名 $mappingFk = !empty($val['parent_key'])? $val['parent_key'] : 'parent_id'; }else{ $mappingFk = !empty($val['foreign_key'])?$val['foreign_key']:strtolower($this->name).'_id'; // 关联外键 } $mappingCondition = !empty($val['condition'])? $val['condition'] : "{$mappingFk}='{$pk}'"; // 获取关联model对象 $model = M($mappingClass); $mappingData = isset($data[$mappingName])?$data[$mappingName]:false; if(!empty($mappingData) || $opType == 'DEL') { switch($mappingType) { case HAS_ONE: switch (strtoupper($opType)){ case 'ADD': // 增加关联数据 $mappingData[$mappingFk] = $pk; $result = $model->add($mappingData); break; case 'SAVE': // 更新关联数据 $result = $model->where($mappingCondition)->save($mappingData); break; case 'DEL': // 根据外键删除关联数据 $result = $model->where($mappingCondition)->delete(); break; } break; case BELONGS_TO: break; case HAS_MANY: switch (strtoupper($opType)){ case 'ADD' : // 增加关联数据 $model->startTrans(); foreach ($mappingData as $val){ $val[$mappingFk] = $pk; $result = $model->add($val); } $model->commit(); break; case 'SAVE' : // 更新关联数据 $model->startTrans(); $pk = $model->getPk(); foreach ($mappingData as $vo){ if(isset($vo[$pk])) {// 更新数据 $mappingCondition = "$pk ={$vo[$pk]}"; $result = $model->where($mappingCondition)->save($vo); }else{ // 新增数据 $vo[$mappingFk] = $data[$this->getPk()]; $result = $model->add($vo); } } $model->commit(); break; case 'DEL' : // 删除关联数据 $result = $model->where($mappingCondition)->delete(); break; } break; case MANY_TO_MANY: $mappingRelationFk = $val['relation_foreign_key']?$val['relation_foreign_key']:$model->getModelName().'_id';// 关联 $mappingRelationTable = $val['relation_table']?$val['relation_table']:$this->getRelationTableName($model); if(is_array($mappingData)) { $ids = array(); foreach ($mappingData as $vo) $ids[] = $vo[$model->getPk()]; $relationId = implode(',',$ids); } switch (strtoupper($opType)){ case 'ADD': // 增加关联数据 case 'SAVE': // 更新关联数据 if(isset($relationId)) { $this->startTrans(); // 删除关联表数据 $this->table($mappingRelationTable)->where($mappingCondition)->delete(); // 插入关联表数据 $sql = 'INSERT INTO '.$mappingRelationTable.' ('.$mappingFk.','.$mappingRelationFk.') SELECT a.'.$this->getPk().',b.'.$model->getPk().' FROM '.$this->getTableName().' AS a ,'.$model->getTableName()." AS b where a.".$this->getPk().' ='. $pk.' AND b.'.$model->getPk().' IN ('.$relationId.") "; $result = $model->execute($sql); if(false !== $result) // 提交事务 $this->commit(); else // 事务回滚 $this->rollback(); } break; case 'DEL': // 根据外键删除中间表关联数据 $result = $this->table($mappingRelationTable)->where($mappingCondition)->delete(); break; } break; } } } } } return $result; } /** +---------------------------------------------------------- * 进行关联查询 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $name 关联名称 +---------------------------------------------------------- * @return Model +---------------------------------------------------------- */ public function relation($name) { $this->options['link'] = $name; return $this; } /** +---------------------------------------------------------- * 关联数据获取 仅用于查询后 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 关联名称 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function relationGet($name) { if(empty($this->data)) return false; return $this->getRelation($this->data,$name,true); } } ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Core/Model/RelationModel.class.php
PHP
asf20
21,740
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 高级模型类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class AdvModel extends Model { // 数据库连接对象列表 private $_db = array(); private $_fields = null; protected $optimLock = 'lock_version'; protected $returnType = 'array'; protected $blobFields = array(); protected $blobValues = null; protected $serializeField = array(); protected $readonlyField = array(); protected $_filter = array(); public function __construct($name='') { if('' !== $name || is_subclass_of($this,'AdvModel') ){ // 如果是AdvModel子类或者有传入模型名称则获取字段缓存 }else{ // 空的模型 关闭字段缓存 $this->autoCheckFields = false; } parent::__construct($name); // 设置默认的数据库连接 $this->_db[0] = $this->db; // 备份当前的数据表字段信息 $this->_fields = $this->fields; } /** +---------------------------------------------------------- * 利用__call方法重载 实现一些特殊的Model方法 (魔术方法) +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名称 * @param mixed $args 调用参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$args) { if(strtolower(substr($method,0,3))=='top'){ // 获取前N条记录 $count = substr($method,3); array_unshift($args,$count); return call_user_func_array(array(&$this, 'topN'), $args); }else{ return parent::__call($method,$args); } } /** +---------------------------------------------------------- * 对保存到数据库的数据进行处理 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $data 要操作的数据 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ protected function _facade($data) { // 检查序列化字段 $data = $this->serializeField($data); return parent::_facade($data); } // 查询成功后的回调方法 protected function _after_find(&$result,$options='') { // 检查序列化字段 $this->checkSerializeField($result); // 获取文本字段 $this->getBlobFields($result); // 检查字段过滤 $result = $this->getFilterFields($result); // 缓存乐观锁 $this->cacheLockVersion($result); } // 查询数据集成功后的回调方法 protected function _after_select(&$resultSet,$options='') { // 检查序列化字段 $resultSet = $this->checkListSerializeField($resultSet); // 获取文本字段 $resultSet = $this->getListBlobFields($resultSet); // 检查列表字段过滤 $resultSet = $this->getFilterListFields($resultSet); } // 写入前的回调方法 protected function _before_insert(&$data,$options='') { // 记录乐观锁 $data = $this->recordLockVersion($data); // 检查文本字段 $data = $this->checkBlobFields($data); // 检查字段过滤 $data = $this->setFilterFields($data); } protected function _after_insert($data,$options) { // 保存文本字段 $this->saveBlobFields($data); } // 更新前的回调方法 protected function _before_update(&$data,$options='') { // 检查乐观锁 if(!$this->checkLockVersion($data,$options)) { return false; } // 检查文本字段 $data = $this->checkBlobFields($data); // 检查只读字段 $data = $this->checkReadonlyField($data); // 检查字段过滤 $data = $this->setFilterFields($data); } protected function _after_update($data,$options) { // 保存文本字段 $this->saveBlobFields($data); } protected function _after_delete($data,$options) { // 删除Blob数据 $this->delBlobFields($data); } /** +---------------------------------------------------------- * 记录乐观锁 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $data 数据对象 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ protected function recordLockVersion($data) { // 记录乐观锁 if($this->optimLock && !isset($data[$this->optimLock]) ) { if(in_array($this->optimLock,$this->fields,true)) { $data[$this->optimLock] = 0; } } return $data; } /** +---------------------------------------------------------- * 缓存乐观锁 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $data 数据对象 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function cacheLockVersion($data) { if($this->optimLock) { if(isset($data[$this->optimLock]) && isset($data[$this->getPk()])) { // 只有当存在乐观锁字段和主键有值的时候才记录乐观锁 $_SESSION[$this->name.'_'.$data[$this->getPk()].'_lock_version'] = $data[$this->optimLock]; } } } /** +---------------------------------------------------------- * 检查乐观锁 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $data 当前数据 * @param array $options 查询表达式 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ protected function checkLockVersion(&$data,$options) { $id = $data[$this->getPk()]; // 检查乐观锁 $identify = $this->name.'_'.$id.'_lock_version'; if($this->optimLock && isset($_SESSION[$identify])) { $lock_version = $_SESSION[$identify]; $vo = $this->field($this->optimLock)->find($id); $_SESSION[$identify] = $lock_version; $curr_version = $vo[$this->optimLock]; if(isset($curr_version)) { if($curr_version>0 && $lock_version != $curr_version) { // 记录已经更新 $this->error = L('_RECORD_HAS_UPDATE_'); return false; }else{ // 更新乐观锁 $save_version = $data[$this->optimLock]; if($save_version != $lock_version+1) { $data[$this->optimLock] = $lock_version+1; } $_SESSION[$identify] = $lock_version+1; } } } return true; } /** +---------------------------------------------------------- * 查找前N个记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param integer $count 记录个数 * @param array $options 查询表达式 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function topN($count,$options=array()) { $options['limit'] = $count; return $this->select($options); } /** +---------------------------------------------------------- * 查询符合条件的第N条记录 * 0 表示第一条记录 -1 表示最后一条记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param integer $position 记录位置 * @param array $options 查询表达式 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function getN($position=0,$options=array()) { if($position>=0) { // 正向查找 $options['limit'] = $position.',1'; $list = $this->select($options); return $list?$list[0]:false; }else{ // 逆序查找 $list = $this->select($options); return $list?$list[count($list)-abs($position)]:false; } } /** +---------------------------------------------------------- * 获取满足条件的第一条记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $options 查询表达式 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function first($options=array()) { return $this->getN(0,$options); } /** +---------------------------------------------------------- * 获取满足条件的最后一条记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $options 查询表达式 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function last($options=array()) { return $this->getN(-1,$options); } /** +---------------------------------------------------------- * 返回数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $data 数据 * @param string $type 返回类型 默认为数组 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function returnResult($data,$type='') { if('' === $type) $type = $this->returnType; switch($type) { case 'array' : return $data; case 'object': return (object)$data; default:// 允许用户自定义返回类型 if(class_exists($type)) return new $type($data); else throw_exception(L('_CLASS_NOT_EXIST_').':'.$type); } } /** +---------------------------------------------------------- * 获取数据的时候过滤数据字段 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $result 查询的数据 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ protected function getFilterFields(&$result) { if(!empty($this->_filter)) { foreach ($this->_filter as $field=>$filter){ if(isset($result[$field])) { $fun = $filter[1]; if(!empty($fun)) { if(isset($filter[2]) && $filter[2]){ // 传递整个数据对象作为参数 $result[$field] = call_user_func($fun,$result); }else{ // 传递字段的值作为参数 $result[$field] = call_user_func($fun,$result[$field]); } } } } } return $result; } protected function getFilterListFields(&$resultSet) { if(!empty($this->_filter)) { foreach ($resultSet as $key=>$result) $resultSet[$key] = $this->getFilterFields($result); } return $resultSet; } /** +---------------------------------------------------------- * 写入数据的时候过滤数据字段 +---------------------------------------------------------- * @access pubic +---------------------------------------------------------- * @param mixed $result 查询的数据 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ protected function setFilterFields($data) { if(!empty($this->_filter)) { foreach ($this->_filter as $field=>$filter){ if(isset($data[$field])) { $fun = $filter[0]; if(!empty($fun)) { if(isset($filter[2]) && $filter[2]) { // 传递整个数据对象作为参数 $data[$field] = call_user_func($fun,$data); }else{ // 传递字段的值作为参数 $data[$field] = call_user_func($fun,$data[$field]); } } } } } return $data; } /** +---------------------------------------------------------- * 返回数据列表 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $resultSet 数据 * @param string $type 返回类型 默认为数组 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function returnResultSet(&$resultSet,$type='') { foreach ($resultSet as $key=>$data) $resultSet[$key] = $this->returnResult($data,$type); return $resultSet; } protected function checkBlobFields(&$data) { // 检查Blob文件保存字段 if(!empty($this->blobFields)) { foreach ($this->blobFields as $field){ if(isset($data[$field])) { if(isset($data[$this->getPk()])) $this->blobValues[$this->name.'/'.$data[$this->getPk()].'_'.$field] = $data[$field]; else $this->blobValues[$this->name.'/@?id@_'.$field] = $data[$field]; unset($data[$field]); } } } return $data; } /** +---------------------------------------------------------- * 获取数据集的文本字段 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $resultSet 查询的数据 * @param string $field 查询的字段 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function getListBlobFields(&$resultSet,$field='') { if(!empty($this->blobFields)) { foreach ($resultSet as $key=>$result){ $result = $this->getBlobFields($result,$field); $resultSet[$key] = $result; } } return $resultSet; } /** +---------------------------------------------------------- * 获取数据的文本字段 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $data 查询的数据 * @param string $field 查询的字段 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function getBlobFields(&$data,$field='') { if(!empty($this->blobFields)) { $pk = $this->getPk(); $id = $data[$pk]; if(empty($field)) { foreach ($this->blobFields as $field){ $identify = $this->name.'/'.$id.'_'.$field; $data[$field] = F($identify); } return $data; }else{ $identify = $this->name.'/'.$id.'_'.$field; return F($identify); } } } /** +---------------------------------------------------------- * 保存File方式的字段 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $data 保存的数据 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function saveBlobFields(&$data) { if(!empty($this->blobFields)) { foreach ($this->blobValues as $key=>$val){ if(strpos($key,'@?id@')) $key = str_replace('@?id@',$data[$this->getPk()],$key); F($key,$val); } } } /** +---------------------------------------------------------- * 删除File方式的字段 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $data 保存的数据 * @param string $field 查询的字段 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function delBlobFields(&$data,$field='') { if(!empty($this->blobFields)) { $pk = $this->getPk(); $id = $data[$pk]; if(empty($field)) { foreach ($this->blobFields as $field){ $identify = $this->name.'/'.$id.'_'.$field; F($identify,null); } }else{ $identify = $this->name.'/'.$id.'_'.$field; F($identify,null); } } } /** +---------------------------------------------------------- * 字段值延迟增长 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param mixed $condition 条件 * @param integer $step 增长值 * @param integer $lazyTime 延时时间(s) +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setLazyInc($field,$condition='',$step=1,$lazyTime=0) { if(empty($condition) && isset($this->options['where'])) $condition = $this->options['where']; if(empty($condition)) { // 没有条件不做任何更新 return false; } if($lazyTime>0) {// 延迟写入 $guid = md5($this->name.'_'.$field.'_'.serialize($condition)); $step = $this->lazyWrite($guid,$step,$lazyTime); if(false === $step ) return true; // 等待下次写入 } return $this->setField($field,array('exp',$field.'+'.$step),$condition); } /** +---------------------------------------------------------- * 字段值延迟减少 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param mixed $condition 条件 * @param integer $step 减少值 * @param integer $lazyTime 延时时间(s) +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setLazyDec($field,$condition='',$step=1,$lazyTime=0) { if(empty($condition) && isset($this->options['where'])) $condition = $this->options['where']; if(empty($condition)) { // 没有条件不做任何更新 return false; } if($lazyTime>0) {// 延迟写入 $guid = md5($this->name.'_'.$field.'_'.serialize($condition)); $step = $this->lazyWrite($guid,$step,$lazyTime); if(false === $step ) return true; // 等待下次写入 } return $this->setField($field,array('exp',$field.'-'.$step),$condition); } /** +---------------------------------------------------------- * 延时更新检查 返回false表示需要延时 * 否则返回实际写入的数值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $guid 写入标识 * @param integer $step 写入步进值 * @param integer $lazyTime 延时时间(s) +---------------------------------------------------------- * @return false|integer +---------------------------------------------------------- */ protected function lazyWrite($guid,$step,$lazyTime) { if(false !== ($value = F($guid))) { // 存在缓存写入数据 if(time()>F($guid.'_time')+$lazyTime) { // 延时更新时间到了,删除缓存数据 并实际写入数据库 F($guid,NULL); F($guid.'_time',NULL); return $value+$step; }else{ // 追加数据到缓存 F($guid,$value+$step); return false; } }else{ // 没有缓存数据 F($guid,$step); // 计时开始 F($guid.'_time',time()); return false; } } /** +---------------------------------------------------------- * 检查序列化数据字段 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $data 数据 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ protected function serializeField(&$data) { // 检查序列化字段 if(!empty($this->serializeField)) { // 定义方式 $this->serializeField = array('ser'=>array('name','email')); foreach ($this->serializeField as $key=>$val){ if(empty($data[$key])) { $serialize = array(); foreach ($val as $name){ if(isset($data[$name])) { $serialize[$name] = $data[$name]; unset($data[$name]); } } $data[$key] = serialize($serialize); } } } return $data; } // 检查返回数据的序列化字段 protected function checkSerializeField(&$result) { // 检查序列化字段 if(!empty($this->serializeField)) { foreach ($this->serializeField as $key=>$val){ if(isset($result[$key])) { $serialize = unserialize($result[$key]); foreach ($serialize as $name=>$value) $result[$name] = $value; unset($serialize,$result[$key]); } } } return $result; } // 检查数据集的序列化字段 protected function checkListSerializeField(&$resultSet) { // 检查序列化字段 if(!empty($this->serializeField)) { foreach ($this->serializeField as $key=>$val){ foreach ($resultSet as $k=>$result){ if(isset($result[$key])) { $serialize = unserialize($result[$key]); foreach ($serialize as $name=>$value) $result[$name] = $value; unset($serialize,$result[$key]); $resultSet[$k] = $result; } } } } return $resultSet; } /** +---------------------------------------------------------- * 检查只读字段 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $data 数据 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ protected function checkReadonlyField(&$data) { if(!empty($this->readonlyField)) { foreach ($this->readonlyField as $key=>$field){ if(isset($data[$field])) unset($data[$field]); } } return $data; } /** +---------------------------------------------------------- * 增加数据库连接 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $config 数据库连接信息 * 支持批量添加 例如 array(1=>$config1,2=>$config2) * @param mixed $linkNum 创建的连接序号 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function addConnect($config,$linkNum=NULL) { if(isset($this->_db[$linkNum])) return false; if(NULL === $linkNum && is_array($config)) { // 支持批量增加数据库连接 foreach ($config as $key=>$val) $this->_db[$key] = Db::getInstance($val); return true; } // 创建一个新的实例 $this->_db[$linkNum] = Db::getInstance($config); return true; } /** +---------------------------------------------------------- * 删除数据库连接 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param integer $linkNum 创建的连接序号 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function delConnect($linkNum) { if(isset($this->_db[$linkNum])) { $this->_db[$linkNum]->close(); unset($this->_db[$linkNum]); // 恢复之前的数据表字段信息 $this->fields = $this->_fields; return true; } return false; } /** +---------------------------------------------------------- * 关闭数据库连接 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param integer $linkNum 创建的连接序号 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function closeConnect($linkNum) { if(isset($this->_db[$linkNum])) { $this->_db[$linkNum]->close(); return true; } return false; } /** +---------------------------------------------------------- * 切换数据库连接 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param integer $linkNum 创建的连接序号 * @param string $name 要操作的模型名称 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function switchConnect($linkNum,$name='') { if(isset($this->_db[$linkNum])) { // 在不同实例直接切换 $this->db = $this->_db[$linkNum]; // 重置当前表名 可以在切换之前重新设置前缀 $this->trueTableName = ''; if(!empty($name)) $this->name = $name; // 更新数据表字段缓存信息 $this->flush(); return true; }else{ return false; } } /** +---------------------------------------------------------- * 批处理执行SQL语句 * 批处理的指令都认为是execute操作 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $sql SQL批处理指令 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function patchQuery($sql=array()) { if(!is_array($sql)) return false; // 自动启动事务支持 $this->startTrans(); try{ foreach ($sql as $_sql){ $result = $this->execute($_sql); if(false === $result) { // 发生错误自动回滚事务 $this->rollback(); return false; } } // 提交事务 $this->commit(); } catch (ThinkException $e) { $this->rollback(); } return true; } /** +---------------------------------------------------------- * 得到分表的的数据表名 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $data 操作的数据 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getPartitionTableName($data=array()) { // 对数据表进行分区 if(isset($data[$this->partition['field']])) { $field = $data[$this->partition['field']]; switch($this->partition['type']) { case 'id': // 按照id范围分表 $step = $this->partition['expr']; $seq = floor($field / $step)+1; break; case 'year': // 按照年份分表 if(!is_numeric($field)) { $field = strtotime($field); } $seq = date('Y',$field)-$this->partition['expr']+1; break; case 'mod': // 按照id的模数分表 $seq = ($field % $this->partition['num'])+1; break; case 'md5': // 按照md5的序列分表 $seq = (ord(substr(md5($field),0,1)) % $this->partition['num'])+1; break; default : if(function_exists($this->partition['type'])) { // 支持指定函数哈希 $fun = $this->partition['type']; $seq = (ord(substr($fun($field),0,1)) % $this->partition['num'])+1; }else{ // 按照字段的首字母的值分表 $seq = (ord($field{0}) % $this->partition['num'])+1; } } return $this->getTableName().'_'.$seq; }else{ // 当设置的分表字段不在查询条件或者数据中 // 进行联合查询,必须设定 partition['num'] $tableName = array(); for($i=0;$i<$this->partition['num'];$i++) $tableName[] = 'SELECT * FROM '.$this->getTableName().'_'.($i+1); $tableName = '( '.implode(" UNION ",$tableName).') AS '.$this->name; return $tableName; } } } ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Core/Model/AdvModel.class.php
PHP
asf20
35,538
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 视图模型类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class ViewModel extends Model { protected $viewFields = array(); /** +---------------------------------------------------------- * 自动检测数据表信息 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function _checkTableInfo() {} /** +---------------------------------------------------------- * 得到完整的数据表名 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getTableName() { if(empty($this->trueTableName)) { $tableName = ''; foreach ($this->viewFields as $key=>$view){ // 获取数据表名称 $class = $key.'Model'; $Model = class_exists($class)?new $class():M($key); $tableName .= $Model->getTableName(); // 表别名定义 $tableName .= !empty($view['_as'])?' '.$view['_as']:' '.$key; // 支持ON 条件定义 $tableName .= !empty($view['_on'])?' ON '.$view['_on']:''; // 指定JOIN类型 例如 RIGHT INNER LEFT 下一个表有效 $type = !empty($view['_type'])?$view['_type']:''; $tableName .= ' '.strtoupper($type).' JOIN '; $len = strlen($type.'_JOIN '); } $tableName = substr($tableName,0,-$len); $this->trueTableName = $tableName; } return $this->trueTableName; } /** +---------------------------------------------------------- * 表达式过滤方法 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $options 表达式 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function _options_filter(&$options) { if(isset($options['field'])) $options['field'] = $this->checkFields($options['field']); else $options['field'] = $this->checkFields(); if(isset($options['group'])) $options['group'] = $this->checkGroup($options['group']); if(isset($options['where'])) $options['where'] = $this->checkCondition($options['where']); if(isset($options['order'])) $options['order'] = $this->checkOrder($options['order']); } /** +---------------------------------------------------------- * 检查是否定义了所有字段 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $name 模型名称 * @param array $fields 字段数组 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ private function _checkFields($name,$fields) { if(false !== $pos = array_search('*',$fields)) {// 定义所有字段 $fields = array_merge($fields,M($name)->getDbFields()); unset($fields[$pos]); } return $fields; } /** +---------------------------------------------------------- * 检查条件中的视图字段 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $data 条件表达式 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ protected function checkCondition($where) { if(is_array($where)) { $view = array(); // 检查视图字段 foreach ($this->viewFields as $key=>$val){ $k = isset($val['_as'])?$val['_as']:$key; $val = $this->_checkFields($key,$val); foreach ($where as $name=>$value){ if(false !== $field = array_search($name,$val,true)) { // 存在视图字段 $_key = is_numeric($field)? $k.'.'.$name : $k.'.'.$field; $view[$_key] = $value; unset($where[$name]); } } } $where = array_merge($where,$view); } return $where; } /** +---------------------------------------------------------- * 检查Order表达式中的视图字段 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $order 字段 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function checkOrder($order='') { if(!empty($order)) { $orders = explode(',',$order); $_order = array(); foreach ($orders as $order){ $array = explode(' ',$order); $field = $array[0]; $sort = isset($array[1])?$array[1]:'ASC'; // 解析成视图字段 foreach ($this->viewFields as $name=>$val){ $k = isset($val['_as'])?$val['_as']:$name; $val = $this->_checkFields($name,$val); if(false !== $_field = array_search($field,$val,true)) { // 存在视图字段 $field = is_numeric($_field)?$k.'.'.$field:$k.'.'.$_field; break; } } $_order[] = $field.' '.$sort; } $order = implode(',',$_order); } return $order; } /** +---------------------------------------------------------- * 检查Group表达式中的视图字段 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $group 字段 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function checkGroup($group='') { if(!empty($group)) { $groups = explode(',',$group); $_group = array(); foreach ($groups as $field){ // 解析成视图字段 foreach ($this->viewFields as $name=>$val){ $k = isset($val['_as'])?$val['_as']:$name; $val = $this->_checkFields($name,$val); if(false !== $_field = array_search($field,$val,true)) { // 存在视图字段 $field = is_numeric($_field)?$k.'.'.$field:$k.'.'.$_field; break; } } $_group[] = $field; } $group = implode(',',$_group); } return $group; } /** +---------------------------------------------------------- * 检查fields表达式中的视图字段 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $fields 字段 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function checkFields($fields='') { if(empty($fields) || '*'==$fields ) { // 获取全部视图字段 $fields = array(); foreach ($this->viewFields as $name=>$val){ $k = isset($val['_as'])?$val['_as']:$name; $val = $this->_checkFields($name,$val); foreach ($val as $key=>$field){ if(is_numeric($key)) { $fields[] = $k.'.'.$field.' AS '.$field; }elseif('_' != substr($key,0,1)) { // 以_开头的为特殊定义 if( false !== strpos($key,'*') || false !== strpos($key,'(') || false !== strpos($key,'.')) { //如果包含* 或者 使用了sql方法 则不再添加前面的表名 $fields[] = $key.' AS '.$field; }else{ $fields[] = $k.'.'.$key.' AS '.$field; } } } } $fields = implode(',',$fields); }else{ if(!is_array($fields)) $fields = explode(',',$fields); // 解析成视图字段 $array = array(); foreach ($fields as $key=>$field){ if(strpos($field,'(') || strpos(strtolower($field),' as ')){ // 使用了函数或者别名 $array[] = $field; unset($fields[$key]); } } foreach ($this->viewFields as $name=>$val){ $k = isset($val['_as'])?$val['_as']:$name; $val = $this->_checkFields($name,$val); foreach ($fields as $key=>$field){ if(false !== $_field = array_search($field,$val,true)) { // 存在视图字段 if(is_numeric($_field)) { $array[] = $k.'.'.$field.' AS '.$field; }elseif('_' != substr($_field,0,1)){ if( false !== strpos($_field,'*') || false !== strpos($_field,'(') || false !== strpos($_field,'.')) //如果包含* 或者 使用了sql方法 则不再添加前面的表名 $array[] = $_field.' AS '.$field; else $array[] = $k.'.'.$_field.' AS '.$field; } } } } $fields = implode(',',$array); } return $fields; } } ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Core/Model/ViewModel.class.php
PHP
asf20
12,180
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP Action控制器基类 抽象类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ abstract class Action extends Think {//类定义开始 // 视图实例对象 protected $view = null; // 当前Action名称 private $name = ''; /** +---------------------------------------------------------- * 架构函数 取得模板对象实例 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct() { //实例化视图类 $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='text/html') { if(false === $templateFile) { $this->showTrace(); }else{ $this->view->display($templateFile,$charset,$contentType); } } /** +---------------------------------------------------------- * 获取输出页面内容 * 调用内置的模板引擎fetch方法, +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $templateFile 指定要调用的模板文件 * 默认为空 由系统自动定位模板文件 * @param string $charset 输出编码 * @param string $contentType 输出类型 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function fetch($templateFile='',$charset='',$contentType='text/html') { return $this->view->fetch($templateFile,$charset,$contentType); } /** +---------------------------------------------------------- * 创建静态页面 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @htmlfile 生成的静态文件名称 * @htmlpath 生成的静态文件路径 * @param string $templateFile 指定要调用的模板文件 * 默认为空 由系统自动定位模板文件 * @param string $charset 输出编码 * @param string $contentType 输出类型 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function buildHtml($htmlfile='',$htmlpath='',$templateFile='',$charset='',$contentType='text/html') { return $this->view->buildHtml($htmlfile,$htmlpath,$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); } /** +---------------------------------------------------------- * 取得模板显示变量的值 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $name 模板显示变量 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ protected function get($name) { return $this->view->get($name); } public function __get($name) { return $this->view->get($name); } /** +---------------------------------------------------------- * Trace变量赋值 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $name 要显示的模板变量 * @param mixed $value 变量的值 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function trace($name,$value='') { $this->view->trace($name,$value); } /** +---------------------------------------------------------- * 魔术方法 有不存在的操作的时候执行 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名 * @param array $parms 参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$parms) { if( 0 === strcasecmp($method,ACTION_NAME)) { // 检查扩展操作方法 $_action = C('_actions_'); if($_action) { // 'module:action'=>'callback' if(isset($_action[MODULE_NAME.':'.ACTION_NAME])) { $action = $_action[MODULE_NAME.':'.ACTION_NAME]; }elseif(isset($_action[ACTION_NAME])){ // 'action'=>'callback' $action = $_action[ACTION_NAME]; } if(!empty($action)) { call_user_func($action); return ; } } // 如果定义了_empty操作 则调用 if(method_exists($this,'_empty')) { $this->_empty($method,$parms); }else { // 检查是否存在默认模版 如果有直接输出模版 if(file_exists_case(C('TMPL_FILE_NAME'))) $this->display(); else // 抛出异常 throw_exception(L('_ERROR_ACTION_').ACTION_NAME); } }elseif(in_array(strtolower($method),array('ispost','isget','ishead','isdelete','isput'))){ return strtolower($_SERVER['REQUEST_METHOD']) == strtolower(substr($method,2)); }else{ throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); } } /** +---------------------------------------------------------- * 操作错误跳转的快捷方法 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $message 错误信息 * @param Boolean $ajax 是否为Ajax方式 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function error($message,$ajax=false) { $this->_dispatch_jump($message,0,$ajax); } /** +---------------------------------------------------------- * 操作成功跳转的快捷方法 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $message 提示信息 * @param Boolean $ajax 是否为Ajax方式 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function success($message,$ajax=false) { $this->_dispatch_jump($message,1,$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='') { // 保证AJAX返回后也能保存日志 if(C('LOG_RECORD')) Log::save(); $result = array(); $result['status'] = $status; $result['info'] = $info; $result['data'] = $data; 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='') { if(C('LOG_RECORD')) Log::save(); $url = U($url,$params); redirect($url,$delay,$msg); } /** +---------------------------------------------------------- * 默认跳转操作 支持错误导向和正确跳转 * 调用模板显示 默认为public目录下面的success页面 * 提示页面为可配置 支持模板标签 +---------------------------------------------------------- * @param string $message 提示信息 * @param Boolean $status 状态 * @param Boolean $ajax 是否为Ajax方式 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ private function _dispatch_jump($message,$status=1,$ajax=false) { // 判断是否为AJAX返回 if($ajax || $this->isAjax()) $this->ajaxReturn($ajax,$message,$status); // 提示标题 $this->assign('msgTitle',$status? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_')); //如果设置了关闭窗口,则提示完毕后自动关闭窗口 if($this->get('closeWin')) $this->assign('jumpUrl','javascript:window.close();'); $this->assign('status',$status); // 状态 $this->assign('message',$message);// 提示信息 //保证输出不受静态缓存影响 C('HTML_CACHE_ON',false); if($status) { //发送成功信息 // 成功操作后默认停留1秒 if(!$this->get('waitSecond')) $this->assign('waitSecond',"1"); // 默认操作成功自动返回操作前页面 if(!$this->get('jumpUrl')) $this->assign("jumpUrl",$_SERVER["HTTP_REFERER"]); $this->display(C('TMPL_ACTION_SUCCESS')); }else{ //发生错误时候默认停留3秒 if(!$this->get('waitSecond')) $this->assign('waitSecond',"3"); // 默认发生错误的话自动返回上页 if(!$this->get('jumpUrl')) $this->assign('jumpUrl',"javascript:history.back(-1);"); $this->display(C('TMPL_ACTION_ERROR')); } if(C('LOG_RECORD')) Log::save(); // 中止执行 避免出错后继续执行 exit ; } protected function showTrace(){ $this->view->traceVar(); } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Core/Action.class.php
PHP
asf20
15,995
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ define('CLIENT_MULTI_RESULTS', 131072); /** +------------------------------------------------------------------------------ * Mysql数据库驱动类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Db * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class DbMysql extends Db{ /** +---------------------------------------------------------- * 架构函数 读取数据库配置信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $config 数据库配置数组 +---------------------------------------------------------- */ public function __construct($config=''){ if ( !extension_loaded('mysql') ) { throw_exception(L('_NOT_SUPPERT_').':mysql'); } 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; // 处理不带端口号的socket连接情况 $host = $config['hostname'].($config['hostport']?":{$config['hostport']}":''); if($this->pconnect) { $this->linkID[$linkNum] = mysql_pconnect( $host, $config['username'], $config['password'],CLIENT_MULTI_RESULTS); }else{ $this->linkID[$linkNum] = mysql_connect( $host, $config['username'], $config['password'],true,CLIENT_MULTI_RESULTS); } if ( !$this->linkID[$linkNum] || (!empty($config['database']) && !mysql_select_db($config['database'], $this->linkID[$linkNum])) ) { throw_exception(mysql_error()); } $dbVersion = mysql_get_server_info($this->linkID[$linkNum]); if ($dbVersion >= "4.1") { //使用UTF8存取数据库 需要mysql 4.1.0以上支持 mysql_query("SET NAMES '".C('DB_CHARSET')."'", $this->linkID[$linkNum]); } //设置 sql_model if($dbVersion >'5.0.1'){ mysql_query("SET sql_mode=''",$this->linkID[$linkNum]); } // 标记连接成功 $this->connected = true; // 注销数据库连接配置信息 if(1 != C('DB_DEPLOY_TYPE')) unset($this->config); } return $this->linkID[$linkNum]; } /** +---------------------------------------------------------- * 释放查询结果 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function free() { @mysql_free_result($this->queryID); $this->queryID = 0; } /** +---------------------------------------------------------- * 执行查询 返回数据集 +---------------------------------------------------------- * @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 = mysql_query($str, $this->_linkID); $this->debug(); if ( false === $this->queryID ) { $this->error(); return false; } else { $this->numRows = mysql_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 = mysql_query($str, $this->_linkID) ; $this->debug(); if ( false === $result) { $this->error(); 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->initConnect(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 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 true; } /** +---------------------------------------------------------- * 获得所有的查询数据 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return array +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ private function getAll() { //返回数据集 $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(); 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 +---------------------------------------------------------- */ 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 +---------------------------------------------------------- * @param mixed $data 数据 * @param array $options 参数表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function replace($data,$options=array()) { foreach ($data as $key=>$val){ $value = $this->parseValue($val); if(is_scalar($value)) { // 过滤非标量数据 $values[] = $value; $fields[] = $this->addSpecialChar($key); } } $sql = 'REPLACE INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')'; return $this->execute($sql); } /** +---------------------------------------------------------- * 插入记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $datas 数据 * @param array $options 参数表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function insertAll($datas,$options=array()) { if(!is_array($datas[0])) return false; $fields = array_keys($datas[0]); array_walk($fields, array($this, 'addSpecialChar')); $values = array(); foreach ($datas as $data){ $value = array(); foreach ($data as $key=>$val){ $val = $this->parseValue($val); if(is_scalar($val)) { // 过滤非标量数据 $value[] = $val; } } $values[] = '('.implode(',', $value).')'; } $sql = 'INSERT INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES '.implode(',',$values); return $this->execute($sql); } /** +---------------------------------------------------------- * 关闭数据库 +---------------------------------------------------------- * @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->debug && '' != $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(); } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Db/Driver/DbMysql.class.php
PHP
asf20
15,889
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2007 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * Mysqli数据库驱动类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Db * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class DbMysqli extends Db{ /** +---------------------------------------------------------- * 架构函数 读取数据库配置信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $config 数据库配置数组 +---------------------------------------------------------- */ public function __construct($config=''){ if ( !extension_loaded('mysqli') ) { throw_exception(L('_NOT_SUPPERT_').':mysqli'); } 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; $this->linkID[$linkNum] = new mysqli($config['hostname'],$config['username'],$config['password'],$config['database'],$config['hostport']); if (mysqli_connect_errno()) throw_exception(mysqli_connect_error()); $dbVersion = $this->linkID[$linkNum]->server_version; if ($dbVersion >= "4.1") { // 设置数据库编码 需要mysql 4.1.0以上支持 $this->linkID[$linkNum]->query("SET NAMES '".C('DB_CHARSET')."'"); } //设置 sql_model if($dbVersion >'5.0.1'){ $this->linkID[$linkNum]->query("SET sql_mode=''"); } // 标记连接成功 $this->connected = true; //注销数据库安全信息 if(1 != C('DB_DEPLOY_TYPE')) unset($this->config); } return $this->linkID[$linkNum]; } /** +---------------------------------------------------------- * 释放查询结果 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function free() { mysqli_free_result($this->queryID); $this->queryID = 0; } /** +---------------------------------------------------------- * 执行查询 返回数据集 +---------------------------------------------------------- * @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 = $this->_linkID->query($str); $this->debug(); if ( false === $this->queryID ) { $this->error(); return false; } else { $this->numRows = $this->queryID->num_rows; $this->numCols = $this->queryID->field_count; 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 = $this->_linkID->query($str); $this->debug(); if ( false === $result ) { $this->error(); return false; } else { $this->numRows = $this->_linkID->affected_rows; $this->lastInsID = $this->_linkID->insert_id; return $this->numRows; } } /** +---------------------------------------------------------- * 启动事务 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function startTrans() { $this->initConnect(true); //数据rollback 支持 if ($this->transTimes == 0) { $this->_linkID->autocommit(false); } $this->transTimes++; return ; } /** +---------------------------------------------------------- * 用于非自动提交状态下面的查询提交 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function commit() { if ($this->transTimes > 0) { $result = $this->_linkID->commit(); $this->_linkID->autocommit( true); $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 +---------------------------------------------------------- * @param string $sql sql语句 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ private function getAll() { //返回数据集 $result = array(); if($this->numRows>0) { //返回数据集 for($i=0;$i<$this->numRows ;$i++ ){ $result[$i] = $this->queryID->fetch_assoc(); } $this->queryID->data_seek(0); } return $result; } /** +---------------------------------------------------------- * 取得数据表的字段信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ function getFields($tableName) { $result = $this->query('SHOW COLUMNS FROM `'.$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 +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ function getTables($dbName='') { $sql = !empty($dbName)?'SHOW TABLES FROM '.$dbName:'SHOW TABLES '; $result = $this->query($sql); $info = array(); if($result) { foreach ($result as $key => $val) { $info[$key] = current($val); } } return $info; } /** +---------------------------------------------------------- * 替换记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 数据 * @param array $options 参数表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function replace($data,$options=array()) { foreach ($data as $key=>$val){ $value = $this->parseValue($val); if(is_scalar($value)) { // 过滤非标量数据 $values[] = $value; $fields[] = $this->addSpecialChar($key); } } $sql = 'REPLACE INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')'; return $this->execute($sql); } /** +---------------------------------------------------------- * 插入记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $datas 数据 * @param array $options 参数表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function insertAll($datas,$options=array()) { if(!is_array($datas[0])) return false; $fields = array_keys($datas[0]); array_walk($fields, array($this, 'addSpecialChar')); $values = array(); foreach ($datas as $data){ $value = array(); foreach ($data as $key=>$val){ $val = $this->parseValue($val); if(is_scalar($val)) { // 过滤非标量数据 $value[] = $val; } } $values[] = '('.implode(',', $value).')'; } $sql = 'INSERT INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES '.implode(',',$values); return $this->execute($sql); } /** +---------------------------------------------------------- * 关闭数据库 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ function close() { if (!empty($this->queryID)) $this->queryID->free_result(); if ($this->_linkID && !$this->_linkID->close()){ throw_exception($this->error()); } $this->_linkID = 0; } /** +---------------------------------------------------------- * 数据库错误信息 * 并显示当前的SQL语句 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ function error() { $this->error = $this->_linkID->error; if($this->debug && '' != $this->queryStr){ $this->error .= "\n [ SQL语句 ] : ".$this->queryStr; } return $this->error; } /** +---------------------------------------------------------- * SQL指令安全过滤 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param string $str SQL指令 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ function escape_string($str) { if($this->_linkID) { return $this->_linkID->real_escape_string($str); }else{ return addslashes($str); } } /** +---------------------------------------------------------- * 析构方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __destruct() { // 关闭连接 $this->close(); } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Db/Driver/DbMysqli.class.php
PHP
asf20
15,665
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 数据库中间层实现类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Db * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class Db extends Think { // 数据库类型 protected $dbType = 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 = 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% %FIELDS% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT%'; /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @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'])); // 读取系统数据库驱动目录 $dbClass = 'Db'. $this->dbType; $dbDriverPath = dirname(__FILE__).'/Driver/'; require_cache( $dbDriverPath . $dbClass . '.class.php'); // 检查驱动类 if(class_exists($dbClass)) { $db = new $dbClass($db_config); // 获取当前的数据库类型 if( 'pdo' != strtolower($db_config['dbms']) ) $db->dbType = strtoupper($this->dbType); else $db->dbType = $this->_getDsnType($db_config['dsn']); if(C('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); }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; } /** +---------------------------------------------------------- * 增加数据库连接(相同类型的) +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $config 数据库连接信息 * @param mixed $linkNum 创建的连接序号 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function addConnect($config,$linkNum=null) { $db_config = $this->parseConfig($config); if(empty($linkNum)) $linkNum = count($this->linkID); if(isset($this->linkID[$linkNum])) // 已经存在连接 return false; // 创建新的数据库连接 return $this->connect($db_config,$linkNum); } /** +---------------------------------------------------------- * 切换数据库连接 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param integer $linkNum 创建的连接序号 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function switchConnect($linkNum) { if(isset($this->linkID[$linkNum])) { // 存在指定的数据库连接序号 $this->_linkID = $this->linkID[$linkNum]; return true; }else{ return false; } } /** +---------------------------------------------------------- * 初始化数据库连接 +---------------------------------------------------------- * @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 = 0; else // 读操作连接从服务器 $r = floor(mt_rand(1,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] ); } 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->addSpecialChar($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_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_array($fields)) { // 完善数组方式传字段名的支持 // 支持 'field1'=>'field2' 这样的字段别名定义 $array = array(); foreach ($fields as $key=>$field){ if(!is_numeric($key)) $array[] = $this->addSpecialChar($key).' AS '.$this->addSpecialChar($field); else $array[] = $this->addSpecialChar($field); } $fieldsStr = implode(',', $array); }elseif(is_string($fields) && !empty($fields)) { $fieldsStr = $this->addSpecialChar($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, 'addSpecialChar')); return implode(',',$tables); } /** +---------------------------------------------------------- * where分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $where +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseWhere($where) { $whereStr = ''; if(is_string($where)) { // 直接使用字符串条件 $whereStr = $where; }else{ // 使用数组条件表达式 if(array_key_exists('_logic',$where)) { // 定义逻辑运算规则 例如 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->addSpecialChar($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 运算 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.' 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('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); } } } $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(array_key_exists('_logic',$where)) { $op = ' '.strtoupper($where['_logic']).' '; unset($where['_logic']); }else{ $op = ' AND '; } $array = array(); foreach ($where as $field=>$data) $array[] = $this->addSpecialChar($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) { if(is_array($order)) { $array = array(); foreach ($order as $key=>$val){ if(is_numeric($key)) { $array[] = $this->addSpecialChar($val); }else{ $array[] = $this->addSpecialChar($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 ' :''; } /** +---------------------------------------------------------- * 插入记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 数据 * @param array $options 参数表达式 * @param boolean $replace 是否replace +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function insert($data,$options=array(),$replace=false) { foreach ($data as $key=>$val){ $value = $this->parseValue($val); if(is_scalar($value)) { // 过滤非标量数据 $values[] = $value; $fields[] = $this->addSpecialChar($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()) { if(is_string($fields)) $fields = explode(',',$fields); array_walk($fields, array($this, 'addSpecialChar')); $sql = 'INSERT INTO '.$this->parseTable($table).' ('.implode(',', $fields).') '; $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->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']); $page = $page?$page:1; $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 addSpecialChar(&$value) { if(0 === strpos($this->dbType,'MYSQL')){ $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; } /** +---------------------------------------------------------- * 获取最近的错误信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getError() { return $this->error; } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/Think/Db/Db.class.php
PHP
asf20
37,677
<?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$ /** +------------------------------------------------------------------------------ * 文件上传类 +------------------------------------------------------------------------------ * @category ORG * @package ORG * @subpackage Net * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ class UploadFile extends Think {//类定义开始 // 上传文件的最大值 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'], auto_charset($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(auto_charset($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(auto_charset($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; } /** +---------------------------------------------------------- * 检查上传的文件类型是否合法 +---------------------------------------------------------- * @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; } }//类定义结束 ?>
0321hy
trunk/Lib/ThinkPHP/Lib/ORG/Net/UploadFile.class.php
PHP
asf20
23,395