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
<include file="Public:header" /> <div id="user"> <if condition="$is_log eq false"> <h2>会员登录</h2> <form method="post" name="login" action="__APP__/User/loginSubmit"> <label>用户名:<input type="text" name="user" class="text" /></label> <label>密 码:<input type="password" name="password" class="text" /></label> <label class="yzm">验证码:<input type="text" name="verify" class="text code" /> <img src="__APP__/Public/verify" onclick="javascript:this.src='__APP__/Public/verify/tm/'+Math.random();" class="code" /></label> <p><input type="submit" name="send" value="登录" onclick="return checkLogin();" class="submit" /> <a href="__APP__/User/register">注册会员</a> <a href="###">忘记密码?</a></p> </form> <else /> <h2>会员信息</h2> <div class="a">您好,<strong>{$name}</strong> 欢迎光临</div> <div class="b"> <img src="__PUBLIC__/Images/{$face}" alt="{$user}" /> <a href="###">个人中心</a> <a href="###">我的评论</a> <a href="__APP__/User/logout">退出登录</a> </div> </if> <h3>最近登录会员 <span>────────────</span></h3> <if condition="$lastLogin neq null"> <volist name="lastLogin" id="lastLogin"> <dl> <dt><img src="__PUBLIC__/Images/{$lastLogin.face}" alt="{$lastLogin.user}" /></dt> <dd>{$lastLogin.user}</dd> </dl> </volist> </if> </div> <div id="news"> <if condition="$topNews eq null"> <h3>暂无头条新闻!</h3> <else /> <h3><a href="__APP__/List/details/id/{$topNews[0].id}" target="_blank">{$topNews[0].title}</a></h3> <p>内容摘要:{$topNews[0].info}<a href="__APP__/List/details/id/{$topNews[0].id}" target="_blank">[查看全文]</a></p> <p class="link"> <volist name="topNews" id="topNews" offset="1" length="4"> <a href="__APP__/List/details/id/{$topNews.id}" target="_blank">{$topNews.title}</a> {$topNews.line} </volist> </p> </if> <ul> <if condition="$topTenNews eq null"> <li>暂无文章!</li> <else /> <volist name="topTenNews" id="topTenNews"> <li><em>{$topTenNews.date|date="Y-m-d",###}</em><a href="__APP__/List/details/id/{$topTenNews.id}" target="_blank">{$topTenNews.title}</a></li> </volist> </if> </ul> </div> <div id="pic"> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="scriptmain" name="scriptmain" codebase="http://download.macromedia.com/pub/shockwave/cabs/ flash/swflash.cab#version=6,0,29,0" width="268" height="193"> <param name="movie" value="__PUBLIC__/Images/lbxml.swf"> <param name="quality" value="high"> <param name="scale" value="noscale"> <param name="LOOP" value="false"> <param name="menu" value="false"> <param name="wmode" value="transparent"> <embed src="__PUBLIC__/Images/lbxml.swf" width="268" height="193" loop="false" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" salign="T" name="scriptmain" menu="false" wmode="transparent"> </object> </div> <div id="rec"> <h2>特别推荐</h2> <ul> <if condition="$rec eq null"> <li>暂无推荐文章!</li> <else /> <volist name="rec" id="rec"> <li><em>{$rec.date|date="Y-m-d",###}</em><a href="__APP__/List/details/id/{$rec.id}" target="_blank">{$rec.title}</a></li> </volist> </if> </ul> </div> <div id="sidebar-right"> <div class="adver"><script type="text/javascript" src="__PUBLIC__/Js/siderbar_adver.js"></script></div> <div class="hot"> <h2>本月热点</h2> <ul> <if condition="$hotNews eq null" > <li>暂无本月热点文章</li> <else /> <volist name="hotNews" id="hotNews"> <li><em>{$hotNews.date|date="Y-m-d",###}</em><a href="__APP__/List/details/id/{$hotNews.id}" target="_blank">{$hotNews.title}</a></li> </volist> </if> </ul> </div> <div class="comm"> <h2>本月热门评论文章</h2> <ul> <if condition="$hotComArt"> <volist name="hotComArt" id="hotComArt"> <li><em>{$hotComArt.date|date="Y-m-d",###}</em><a href="__APP__/List/details/id/{$hotComArt.id}" target="_blank">{$hotComArt.title}</a></li> </volist> <else /> <li>本月暂无热门评论文章</li> </if> </ul> </div> <div class="vote"> <h2>调查投票</h2> <h3>{$voteSub.title}</h3> <form method="post" action="__APP__/Vote/vote" target="_blank"> <if condition="$voteItemData"> <volist name="voteItemData" id="voteItemData"> <label><input type="radio" name="vote" value="{$voteItemData.id}" /> {$voteItemData.title}</label> </volist> </if> <p><input type="submit" value="投票" name="send" /> <input type="button" onclick="javascript:window.open('__APP__/Vote/show')" value="查看" /></p> </form> </div> </div> <div id="picnews"> <h2>图文资讯</h2> <if condition="$picNews"> <volist name="picNews" id="picNews"> <dl> <dt><a href="__APP__/List/details/id/{$picNews.id}" target="_blank"><img src="__PUBLIC__/Uploads/s_{$picNews.thumbnail}" alt="{$picNews.title}" /></a></dt> <dd><a href="__APP__/List/details/id/{$picNews.id}" target="_blank">{$picNews.title}</a></dd> </dl> </volist> </if> </div> <div id="newslist"> <if condition="$fourNav neq null"> <volist name="fourNav" id="fourNav"> <div class="{$fourNav.class}"> <h2><a href="__APP__/List/show/id/{$fourNav.id}" target="_blank">更多</a>{$fourNav.category_name}</h2> <ul> <if condition="$fourNav.art eq null"> <li>此栏目下暂无文章</li> <else /> <php> $end = count($fourNav['art']); </php> <for start="0" end="$end"> <php> $art = $fourNav['art']; </php> <li><em>{$art[$i].date|date="Y-m-d",###}</em><a href="__APP__/List/details/id/{$art[$i].id}" target="_blank">{$art[$i].title}</a></li> </for> </if> </ul> </div> </volist> </if> </div> <include file="Public:footer" />
zzgcms
ZGCMS/Home/Tpl/Index/index.html
HTML
art
5,938
<include file="Public:header" /> <div id="list"> <h2>当前位置 &gt;搜索:{$titlec}</h2> <if condition="$art eq null"> <p class="none">没有任何数据</p> <else /> <volist name="art" id="art"> <dl> <dt><a href="__APP__/List/details/id/{$art.id}" target="_blank"><if condition="$art.thumbnail eq null"><img src="__PUBLIC__/Images/none.jpg" alt="暂无缩略图" /><else /><img src="__PUBLIC__/Uploads/s_{$art.thumbnail}" alt="{$art.t}" /></if></a></dt> <dd>[<strong>{$art.category_name}</strong>] <a href="__APP__/List/details/id/{$art.id}" target="_blank">{$art.title}</a></dd> <dd>日期:{$art.date|date="Y-m-d H:i:s",###} 点击率:{$art.count} 关键字:[{$art.keyword}]</dd> <dd>简介:{$art.info}</dd> </dl> </volist> </if> <div id="page">{$page}</div> </div> <div id="sidebar"> <div class="right"> <h2>本月总推荐</h2> <ul> </ul> </div> <div class="right"> <h2>本月总热点</h2> <ul> </ul> </div> <div class="right"> <h2>本月总图文</h2> <ul> </ul> </div> </div> <include file="Public:footer" />
zzgcms
ZGCMS/Home/Tpl/Search/show.html
HTML
art
1,106
<include file="Public:header" /> <div id="friendlink"> <h2>所有链接</h2> <h3>文字链接</h3> <div> <if condition="$textLink"> <volist name="textLink" id="textLink"> <a href="{$textLink.weburl}" target="_blank">{$textLink.webname}</a> </volist> </if> </div> <h3>Logo链接</h3> <div> <if condition="$logoLink"> <volist name="logoLink" id="logoLink"> <a href="{$logoLink.weburl}" target="_blank"><img src="__PUBLIC__/Images/{$logoLink.logourl}" alt="{$logoLink.webname}" /></a> </volist> </if> </div> </div> <include file="Public:footer" />
zzgcms
ZGCMS/Home/Tpl/Link/show.html
HTML
art
592
<include file="Public:header" /> <div id="friendlink"> <h2>申请加入链接</h2> <form method="post" name="friendlink" action="__URL__/insert"> <input type="hidden" value="0" name="state" /> <dl> <dd>网站类型:<input type="radio" name="type" onclick="link(1)" value="1" checked="checked" /> 文字链接 <input type="radio" name="type" onclick="link(2)" value="2" /> Logo链接 </dd> <dd>网站名称:<input type="text" class="text" name="webname" /> <span class="red">[必填]</span> ( * 网站名称不能为空,不大于20位 )</dd> <dd>网站地址:<input type="text" class="text" name="weburl" /> <span class="red">[必填]</span> ( * 网站地址不能为空,请以http://开头 )</dd> <dd id="logo" style="display:none;">Logo地址:<input type="text" class="text" name="logourl" /> <span class="red">[必填]</span> ( * Logo地址不能为空,不大于100位 )</dd> <dd>站 长 名:<input type="text" class="text" name="admin" /></dd> <dd>验 证 码:<input type="text" class="text" name="verify" /> <span class="red">[必填]</span></dd> <dd><img src="__APP__/Public/verify" onclick="javascript:this.src='__APP__/Public/verify/tm/'+Math.random();" class="code" /></dd> <dd><input type="submit" class="submit" name="send" onclick="return checkLink();" value="申请友情链接" /></dd> </dl> </form> </div> <include file="Public:footer" />
zzgcms
ZGCMS/Home/Tpl/Link/add.html
HTML
art
1,435
<?php if(!defined('THINK_PATH')) exit(); $configInc = require './config.inc.php'; $config = array( //'配置项'=>'配置值' // 'PAGESIZE' => 100, // 'ROTATION_NUM' => 3,//首页轮播器播放的图片数 ); return array_merge($configInc,$config); ?>
zzgcms
ZGCMS/Home/Conf/config.php
PHP
art
258
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * Think 标准模式公共函数库 +------------------------------------------------------------------------------ * @category Think * @package Common * @author liu21st <liu21st@gmail.com> * @version $Id$ +------------------------------------------------------------------------------ */ // 错误输出 function halt($error) { $e = array(); if (APP_DEBUG) { //调试模式下输出错误信息 if (!is_array($error)) { $trace = debug_backtrace(); $e['message'] = $error; $e['file'] = $trace[0]['file']; $e['class'] = $trace[0]['class']; $e['function'] = $trace[0]['function']; $e['line'] = $trace[0]['line']; $traceInfo = ''; $time = date('y-m-d H:i:m'); foreach ($trace as $t) { $traceInfo .= '[' . $time . '] ' . $t['file'] . ' (' . $t['line'] . ') '; $traceInfo .= $t['class'] . $t['type'] . $t['function'] . '('; $traceInfo .= implode(', ', $t['args']); $traceInfo .=')<br/>'; } $e['trace'] = $traceInfo; } else { $e = $error; } // 包含异常页面模板 include C('TMPL_EXCEPTION_FILE'); } else { //否则定向到错误页面 $error_page = C('ERROR_PAGE'); if (!empty($error_page)) { redirect($error_page); } else { if (C('SHOW_ERROR_MSG')) $e['message'] = is_array($error) ? $error['message'] : $error; else $e['message'] = C('ERROR_MESSAGE'); // 包含异常页面模板 include C('TMPL_EXCEPTION_FILE'); } } exit; } // 自定义异常处理 function throw_exception($msg, $type='ThinkException', $code=0) { if (class_exists($type, false)) throw new $type($msg, $code, true); else halt($msg); // 异常类型不存在则输出错误信息字串 } // 浏览器友好的变量输出 function dump($var, $echo=true, $label=null, $strict=true) { $label = ($label === null) ? '' : rtrim($label) . ' '; if (!$strict) { if (ini_get('html_errors')) { $output = print_r($var, true); $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>'; } else { $output = $label . print_r($var, true); } } else { ob_start(); var_dump($var); $output = ob_get_clean(); if (!extension_loaded('xdebug')) { $output = preg_replace("/\]\=\>\n(\s+)/m", '] => ', $output); $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>'; } } if ($echo) { echo($output); return null; }else return $output; } // 区间调试开始 function debug_start($label='') { $GLOBALS[$label]['_beginTime'] = microtime(TRUE); if (MEMORY_LIMIT_ON) $GLOBALS[$label]['_beginMem'] = memory_get_usage(); } // 区间调试结束,显示指定标记到当前位置的调试 function debug_end($label='') { $GLOBALS[$label]['_endTime'] = microtime(TRUE); echo '<div style="text-align:center;width:100%">Process ' . $label . ': Times ' . number_format($GLOBALS[$label]['_endTime'] - $GLOBALS[$label]['_beginTime'], 6) . 's '; if (MEMORY_LIMIT_ON) { $GLOBALS[$label]['_endMem'] = memory_get_usage(); echo ' Memories ' . number_format(($GLOBALS[$label]['_endMem'] - $GLOBALS[$label]['_beginMem']) / 1024) . ' k'; } echo '</div>'; } // 添加和获取页面Trace记录 function trace($title='',$value='') { if(!C('SHOW_PAGE_TRACE')) return; static $_trace = array(); if(is_array($title)) { // 批量赋值 $_trace = array_merge($_trace,$title); }elseif('' !== $value){ // 赋值 $_trace[$title] = $value; }elseif('' !== $title){ // 取值 return $_trace[$title]; }else{ // 获取全部Trace数据 return $_trace; } } // 设置当前页面的布局 function layout($layout) { if(false !== $layout) { // 开启布局 C('LAYOUT_ON',true); if(is_string($layout)) { C('LAYOUT_NAME',$layout); } } } // URL组装 支持不同模式 // 格式:U('[分组/模块/操作]?参数','参数','伪静态后缀','是否跳转','显示域名') function U($url,$vars='',$suffix=true,$redirect=false,$domain=false) { // 解析URL $info = parse_url($url); $url = !empty($info['path'])?$info['path']:ACTION_NAME; // 解析子域名 if($domain===true){ $domain = $_SERVER['HTTP_HOST']; if(C('APP_SUB_DOMAIN_DEPLOY') ) { // 开启子域名部署 $domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.'); // '子域名'=>array('项目[/分组]'); foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) { if(false === strpos($key,'*') && 0=== strpos($url,$rule[0])) { $domain = $key.strstr($domain,'.'); // 生成对应子域名 $url = substr_replace($url,'',0,strlen($rule[0])); break; } } } } // 解析参数 if(is_string($vars)) { // aaa=1&bbb=2 转换成数组 parse_str($vars,$vars); }elseif(!is_array($vars)){ $vars = array(); } if(isset($info['query'])) { // 解析地址里面参数 合并到vars parse_str($info['query'],$params); $vars = array_merge($params,$vars); } // URL组装 $depr = C('URL_PATHINFO_DEPR'); if($url) { if(0=== strpos($url,'/')) {// 定义路由 $route = true; $url = substr($url,1); if('/' != $depr) { $url = str_replace('/',$depr,$url); } }else{ if('/' != $depr) { // 安全替换 $url = str_replace('/',$depr,$url); } // 解析分组、模块和操作 $url = trim($url,$depr); $path = explode($depr,$url); $var = array(); $var[C('VAR_ACTION')] = !empty($path)?array_pop($path):ACTION_NAME; $var[C('VAR_MODULE')] = !empty($path)?array_pop($path):MODULE_NAME; if(C('URL_CASE_INSENSITIVE')) { $var[C('VAR_MODULE')] = parse_name($var[C('VAR_MODULE')]); } if(C('APP_GROUP_LIST')) { if(!empty($path)) { $group = array_pop($path); $var[C('VAR_GROUP')] = $group; }else{ if(GROUP_NAME != C('DEFAULT_GROUP')) { $var[C('VAR_GROUP')] = GROUP_NAME; } } } } } if(C('URL_MODEL') == 0) { // 普通模式URL转换 $url = __APP__.'?'.http_build_query($var); if(!empty($vars)) { $vars = http_build_query($vars); $url .= '&'.$vars; } }else{ // PATHINFO模式或者兼容URL模式 if(isset($route)) { $url = __APP__.'/'.$url; }else{ $url = __APP__.'/'.implode($depr,array_reverse($var)); } if(!empty($vars)) { // 添加参数 $vars = http_build_query($vars); $url .= $depr.str_replace(array('=','&'),$depr,$vars); } if($suffix) { $suffix = $suffix===true?C('URL_HTML_SUFFIX'):$suffix; if($suffix) { $url .= '.'.ltrim($suffix,'.'); } } } if($domain) { $url = 'http://'.$domain.$url; } if($redirect) // 直接跳转URL redirect($url); else return $url; } // URL重定向 function redirect($url, $time=0, $msg='') { //多行URL地址支持 $url = str_replace(array("\n", "\r"), '', $url); if (empty($msg)) $msg = "系统将在{$time}秒之后自动跳转到{$url}!"; if (!headers_sent()) { // redirect if (0 === $time) { header('Location: ' . $url); } else { header("refresh:{$time};url={$url}"); echo($msg); } exit(); } else { $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>"; if ($time != 0) $str .= $msg; exit($str); } } // 全局缓存设置和读取 function S($name, $value='', $expire=null, $type='',$options=null) { static $_cache = array(); //取得缓存对象实例 $cache = Cache::getInstance($type,$options); if ('' !== $value) { if (is_null($value)) { // 删除缓存 $result = $cache->rm($name); if ($result) unset($_cache[$type . '_' . $name]); return $result; }else { // 缓存数据 $cache->set($name, $value, $expire); $_cache[$type . '_' . $name] = $value; } return; } if (isset($_cache[$type . '_' . $name])) return $_cache[$type . '_' . $name]; // 获取缓存数据 $value = $cache->get($name); $_cache[$type . '_' . $name] = $value; return $value; } // 快速文件数据读取和保存 针对简单类型数据 字符串、数组 function F($name, $value='', $path=DATA_PATH) { static $_cache = array(); $filename = $path . $name . '.php'; if ('' !== $value) { if (is_null($value)) { // 删除缓存 return unlink($filename); } else { // 缓存数据 $dir = dirname($filename); // 目录不存在则创建 if (!is_dir($dir)) mkdir($dir); $_cache[$name] = $value; return file_put_contents($filename, strip_whitespace("<?php\nreturn " . var_export($value, true) . ";\n?>")); } } if (isset($_cache[$name])) return $_cache[$name]; // 获取缓存数据 if (is_file($filename)) { $value = include $filename; $_cache[$name] = $value; } else { $value = false; } return $value; } // 取得对象实例 支持调用类的静态方法 function get_instance_of($name, $method='', $args=array()) { static $_instance = array(); $identify = empty($args) ? $name . $method : $name . $method . to_guid_string($args); if (!isset($_instance[$identify])) { if (class_exists($name)) { $o = new $name(); if (method_exists($o, $method)) { if (!empty($args)) { $_instance[$identify] = call_user_func_array(array(&$o, $method), $args); } else { $_instance[$identify] = $o->$method(); } } else $_instance[$identify] = $o; } else halt(L('_CLASS_NOT_EXIST_') . ':' . $name); } return $_instance[$identify]; } // 根据PHP各种类型变量生成唯一标识号 function to_guid_string($mix) { if (is_object($mix) && function_exists('spl_object_hash')) { return spl_object_hash($mix); } elseif (is_resource($mix)) { $mix = get_resource_type($mix) . strval($mix); } else { $mix = serialize($mix); } return md5($mix); } // xml编码 function xml_encode($data, $encoding='utf-8', $root='think') { $xml = '<?xml version="1.0" encoding="' . $encoding . '"?>'; $xml.= '<' . $root . '>'; $xml.= data_to_xml($data); $xml.= '</' . $root . '>'; return $xml; } function data_to_xml($data) { $xml = ''; foreach ($data as $key => $val) { is_numeric($key) && $key = "item id=\"$key\""; $xml.="<$key>"; $xml.= ( is_array($val) || is_object($val)) ? data_to_xml($val) : $val; list($key, ) = explode(' ', $key); $xml.="</$key>"; } return $xml; } // session管理函数 function session($name,$value='') { $prefix = C('SESSION_PREFIX'); if(is_array($name)) { // session初始化 在session_start 之前调用 if(isset($name['prefix'])) C('SESSION_PREFIX',$name['prefix']); if(isset($_REQUEST[C('VAR_SESSION_ID')])){ session_id($_REQUEST[C('VAR_SESSION_ID')]); }elseif(isset($name['id'])) { session_id($name['id']); } ini_set('session.auto_start', 0); if(isset($name['name'])) session_name($name['name']); if(isset($name['path'])) session_save_path($name['path']); if(isset($name['domain'])) ini_set('session.cookie_domain', $name['domain']); if(isset($name['expire'])) ini_set('session.gc_maxlifetime', $name['expire']); if(isset($name['use_trans_sid'])) ini_set('session.use_trans_sid', $name['use_trans_sid']?1:0); if(isset($name['use_cookies'])) ini_set('session.use_cookies', $name['use_cookies']?1:0); if(isset($name['type'])) C('SESSION_TYPE',$name['type']); if(C('SESSION_TYPE')) { // 读取session驱动 $class = 'Session'. ucwords(strtolower(C('SESSION_TYPE'))); // 检查驱动类 if(require_cache(EXTEND_PATH.'Driver/Session/'.$class.'.class.php')) { $hander = new $class(); $hander->execute(); }else { // 类没有定义 throw_exception(L('_CLASS_NOT_EXIST_').': ' . $class); } } // 启动session if(C('SESSION_AUTO_START')) session_start(); }elseif('' === $value){ if(0===strpos($name,'[')) { // session 操作 if('[pause]'==$name){ // 暂停session session_write_close(); }elseif('[start]'==$name){ // 启动session session_start(); }elseif('[destroy]'==$name){ // 销毁session $_SESSION = array(); session_unset(); session_destroy(); }elseif('[regenerate]'==$name){ // 重新生成id session_regenerate_id(); } }elseif(0===strpos($name,'?')){ // 检查session $name = substr($name,1); if($prefix) { return isset($_SESSION[$prefix][$name]); }else{ return isset($_SESSION[$name]); } }elseif(is_null($name)){ // 清空session if($prefix) { unset($_SESSION[$prefix]); }else{ $_SESSION = array(); } }elseif($prefix){ // 获取session return $_SESSION[$prefix][$name]; }else{ return $_SESSION[$name]; } }elseif(is_null($value)){ // 删除session if($prefix){ unset($_SESSION[$prefix][$name]); }else{ unset($_SESSION[$name]); } }else{ // 设置session if($prefix){ if (!is_array($_SESSION[$prefix])) { $_SESSION[$prefix] = array(); } $_SESSION[$prefix][$name] = $value; }else{ $_SESSION[$name] = $value; } } } // Cookie 设置、获取、删除 function cookie($name, $value='', $option=null) { // 默认设置 $config = array( 'prefix' => C('COOKIE_PREFIX'), // cookie 名称前缀 'expire' => C('COOKIE_EXPIRE'), // cookie 保存时间 'path' => C('COOKIE_PATH'), // cookie 保存路径 'domain' => C('COOKIE_DOMAIN'), // cookie 有效域名 ); // 参数设置(会覆盖黙认设置) if (!empty($option)) { if (is_numeric($option)) $option = array('expire' => $option); elseif (is_string($option)) parse_str($option, $option); $config = array_merge($config, array_change_key_case($option)); } // 清除指定前缀的所有cookie if (is_null($name)) { if (empty($_COOKIE)) return; // 要删除的cookie前缀,不指定则删除config设置的指定前缀 $prefix = empty($value) ? $config['prefix'] : $value; if (!empty($prefix)) {// 如果前缀为空字符串将不作处理直接返回 foreach ($_COOKIE as $key => $val) { if (0 === stripos($key, $prefix)) { setcookie($key, '', time() - 3600, $config['path'], $config['domain']); unset($_COOKIE[$key]); } } } return; } $name = $config['prefix'] . $name; if ('' === $value) { return isset($_COOKIE[$name]) ? $_COOKIE[$name] : null; // 获取指定Cookie } else { if (is_null($value)) { setcookie($name, '', time() - 3600, $config['path'], $config['domain']); unset($_COOKIE[$name]); // 删除指定cookie } else { // 设置cookie $expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0; setcookie($name, $value, $expire, $config['path'], $config['domain']); $_COOKIE[$name] = $value; } } } // 加载扩展配置文件 function load_ext_file() { // 加载自定义外部文件 if(C('LOAD_EXT_FILE')) { $files = explode(',',C('LOAD_EXT_FILE')); foreach ($files as $file){ $file = COMMON_PATH.$file.'.php'; if(is_file($file)) include $file; } } // 加载自定义的动态配置文件 if(C('LOAD_EXT_CONFIG')) { $configs = C('LOAD_EXT_CONFIG'); if(is_string($configs)) $configs = explode(',',$configs); foreach ($configs as $key=>$config){ $file = CONF_PATH.$config.'.php'; if(is_file($file)) { is_numeric($key)?C(include $file):C($key,include $file); } } } } // 获取客户端IP地址 function get_client_ip() { static $ip = NULL; if ($ip !== NULL) return $ip; if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $pos = array_search('unknown',$arr); if(false !== $pos) unset($arr[$pos]); $ip = trim($arr[0]); }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; }elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } // IP地址合法验证 $ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0'; return $ip; } function send_http_status($code) { static $_status = array( // Success 2xx 200 => 'OK', // Redirection 3xx 301 => 'Moved Permanently', 302 => 'Moved Temporarily ', // 1.1 // Client Error 4xx 400 => 'Bad Request', 403 => 'Forbidden', 404 => 'Not Found', // Server Error 5xx 500 => 'Internal Server Error', 503 => 'Service Unavailable', ); if(isset($_status[$code])) { header('HTTP/1.1 '.$code.' '.$_status[$code]); // 确保FastCGI模式下正常 header('Status:'.$code.' '.$_status[$code]); } }
zzgcms
ZGCMS/ThinkPHP/Common/functions.php
PHP
art
20,420
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: common.php 2799 2012-03-05 07:18:06Z liu21st $ /** +------------------------------------------------------------------------------ * Think 基础函数库 +------------------------------------------------------------------------------ * @category Think * @package Common * @author liu21st <liu21st@gmail.com> * @version $Id: common.php 2799 2012-03-05 07:18:06Z liu21st $ +------------------------------------------------------------------------------ */ // 记录和统计时间(微秒) function G($start,$end='',$dec=4) { static $_info = array(); if(is_float($end)) { // 记录时间 $_info[$start] = $end; }elseif(!empty($end)){ // 统计时间 if(!isset($_info[$end])) $_info[$end] = microtime(TRUE); return number_format(($_info[$end]-$_info[$start]),$dec); }else{ // 记录时间 $_info[$start] = microtime(TRUE); } } // 设置和获取统计数据 function N($key, $step=0) { static $_num = array(); if (!isset($_num[$key])) { $_num[$key] = 0; } if (empty($step)) return $_num[$key]; else $_num[$key] = $_num[$key] + (int) $step; } /** +---------------------------------------------------------- * 字符串命名风格转换 * type * =0 将Java风格转换为C的风格 * =1 将C风格转换为Java的风格 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $name 字符串 * @param integer $type 转换类型 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ function parse_name($name, $type=0) { if ($type) { return ucfirst(preg_replace("/_([a-zA-Z])/e", "strtoupper('\\1')", $name)); } else { return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_")); } } // 优化的require_once function require_cache($filename) { static $_importFiles = array(); if (!isset($_importFiles[$filename])) { if (file_exists_case($filename)) { require $filename; $_importFiles[$filename] = true; } else { $_importFiles[$filename] = false; } } return $_importFiles[$filename]; } // 区分大小写的文件存在判断 function file_exists_case($filename) { if (is_file($filename)) { if (IS_WIN && C('APP_FILE_CASE')) { if (basename(realpath($filename)) != basename($filename)) return false; } return true; } return false; } /** +---------------------------------------------------------- * 导入所需的类库 同java的Import * 本函数有缓存功能 +---------------------------------------------------------- * @param string $class 类库命名空间字符串 * @param string $baseUrl 起始路径 * @param string $ext 导入的文件扩展名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ function import($class, $baseUrl = '', $ext='.class.php') { static $_file = array(); $class = str_replace(array('.', '#'), array('/', '.'), $class); if ('' === $baseUrl && false === strpos($class, '/')) { // 检查别名导入 return alias_import($class); } if (isset($_file[$class . $baseUrl])) return true; else $_file[$class . $baseUrl] = true; $class_strut = explode('/', $class); if (empty($baseUrl)) { if ('@' == $class_strut[0] || APP_NAME == $class_strut[0]) { //加载当前项目应用类库 $baseUrl = dirname(LIB_PATH); $class = substr_replace($class, basename(LIB_PATH).'/', 0, strlen($class_strut[0]) + 1); }elseif ('think' == strtolower($class_strut[0])){ // think 官方基类库 $baseUrl = CORE_PATH; $class = substr($class,6); }elseif (in_array(strtolower($class_strut[0]), array('org', 'com'))) { // org 第三方公共类库 com 企业公共类库 $baseUrl = LIBRARY_PATH; }else { // 加载其他项目应用类库 $class = substr_replace($class, '', 0, strlen($class_strut[0]) + 1); $baseUrl = APP_PATH . '../' . $class_strut[0] . '/'.basename(LIB_PATH).'/'; } } if (substr($baseUrl, -1) != '/') $baseUrl .= '/'; $classfile = $baseUrl . $class . $ext; if (!class_exists(basename($class),false)) { // 如果类不存在 则导入类库文件 return require_cache($classfile); } } /** +---------------------------------------------------------- * 基于命名空间方式导入函数库 * load('@.Util.Array') +---------------------------------------------------------- * @param string $name 函数库命名空间字符串 * @param string $baseUrl 起始路径 * @param string $ext 导入的文件扩展名 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ function load($name, $baseUrl='', $ext='.php') { $name = str_replace(array('.', '#'), array('/', '.'), $name); if (empty($baseUrl)) { if (0 === strpos($name, '@/')) { //加载当前项目函数库 $baseUrl = COMMON_PATH; $name = substr($name, 2); } else { //加载ThinkPHP 系统函数库 $baseUrl = EXTEND_PATH . 'Function/'; } } if (substr($baseUrl, -1) != '/') $baseUrl .= '/'; require_cache($baseUrl . $name . $ext); } // 快速导入第三方框架类库 // 所有第三方框架的类库文件统一放到 系统的Vendor目录下面 // 并且默认都是以.php后缀导入 function vendor($class, $baseUrl = '', $ext='.php') { if (empty($baseUrl)) $baseUrl = VENDOR_PATH; return import($class, $baseUrl, $ext); } // 快速定义和导入别名 function alias_import($alias, $classfile='') { static $_alias = array(); if (is_string($alias)) { if(isset($_alias[$alias])) { return require_cache($_alias[$alias]); }elseif ('' !== $classfile) { // 定义别名导入 $_alias[$alias] = $classfile; return; } }elseif (is_array($alias)) { $_alias = array_merge($_alias,$alias); return; } return false; } /** +---------------------------------------------------------- * D函数用于实例化Model 格式 项目://分组/模块 +---------------------------------------------------------- * @param string name Model资源地址 +---------------------------------------------------------- * @return Model +---------------------------------------------------------- */ function D($name='') { if(empty($name)) return new Model; static $_model = array(); if(isset($_model[$name])) return $_model[$name]; if(strpos($name,'://')) {// 指定项目 $name = str_replace('://','/Model/',$name); }else{ $name = C('DEFAULT_APP').'/Model/'.$name; } import($name.'Model'); $class = basename($name.'Model'); if(class_exists($class)) { $model = new $class(); }else { $model = new Model(basename($name)); } $_model[$name] = $model; return $model; } /** +---------------------------------------------------------- * M函数用于实例化一个没有模型文件的Model +---------------------------------------------------------- * @param string name Model名称 支持指定基础模型 例如 MongoModel:User * @param string tablePrefix 表前缀 * @param mixed $connection 数据库连接信息 +---------------------------------------------------------- * @return Model +---------------------------------------------------------- */ function M($name='', $tablePrefix='',$connection='') { static $_model = array(); if(strpos($name,':')) { list($class,$name) = explode(':',$name); }else{ $class = 'Model'; } if (!isset($_model[$name . '_' . $class])) $_model[$name . '_' . $class] = new $class($name,$tablePrefix,$connection); return $_model[$name . '_' . $class]; } /** +---------------------------------------------------------- * A函数用于实例化Action 格式:[项目://][分组/]模块 +---------------------------------------------------------- * @param string name Action资源地址 +---------------------------------------------------------- * @return Action +---------------------------------------------------------- */ function A($name) { static $_action = array(); if(isset($_action[$name])) return $_action[$name]; if(strpos($name,'://')) {// 指定项目 $name = str_replace('://','/Action/',$name); }else{ $name = '@/Action/'.$name; } import($name.'Action'); $class = basename($name.'Action'); if(class_exists($class,false)) { $action = new $class(); $_action[$name] = $action; return $action; }else { return false; } } // 远程调用模块的操作方法 // URL 参数格式 [项目://][分组/]模块/操作 function R($url,$vars=array()) { $info = pathinfo($url); $action = $info['basename']; $module = $info['dirname']; $class = A($module); if($class) return call_user_func_array(array(&$class,$action),$vars); else return false; } // 获取和设置语言定义(不区分大小写) function L($name=null, $value=null) { static $_lang = array(); // 空参数返回所有定义 if (empty($name)) return $_lang; // 判断语言获取(或设置) // 若不存在,直接返回全大写$name if (is_string($name)) { $name = strtoupper($name); if (is_null($value)) return isset($_lang[$name]) ? $_lang[$name] : $name; $_lang[$name] = $value; // 语言定义 return; } // 批量定义 if (is_array($name)) $_lang = array_merge($_lang, array_change_key_case($name, CASE_UPPER)); return; } // 获取配置值 function C($name=null, $value=null) { static $_config = array(); // 无参数时获取所有 if (empty($name)) return $_config; // 优先执行设置获取或赋值 if (is_string($name)) { if (!strpos($name, '.')) { $name = strtolower($name); if (is_null($value)) return isset($_config[$name]) ? $_config[$name] : null; $_config[$name] = $value; return; } // 二维数组设置和获取支持 $name = explode('.', $name); $name[0] = strtolower($name[0]); if (is_null($value)) return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null; $_config[$name[0]][$name[1]] = $value; return; } // 批量设置 if (is_array($name)){ return $_config = array_merge($_config, array_change_key_case($name)); } return null; // 避免非法参数 } // 处理标签扩展 function tag($tag, &$params=NULL) { // 系统标签扩展 $extends = C('extends.' . $tag); // 应用标签扩展 $tags = C('tags.' . $tag); if (!empty($tags)) { if(empty($tags['_overlay']) && !empty($extends)) { // 合并扩展 $tags = array_unique(array_merge($extends,$tags)); }elseif(isset($tags['_overlay'])){ // 通过设置 '_overlay'=>1 覆盖系统标签 unset($tags['_overlay']); } }elseif(!empty($extends)) { $tags = $extends; } if($tags) { if(APP_DEBUG) { G($tag.'Start'); Log::record('Tag[ '.$tag.' ] --START--',Log::INFO); } // 执行扩展 foreach ($tags as $key=>$name) { if(!is_int($key)) { // 指定行为类的完整路径 用于模式扩展 $name = $key; } B($name, $params); } if(APP_DEBUG) { // 记录行为的执行日志 Log::record('Tag[ '.$tag.' ] --END-- [ RunTime:'.G($tag.'Start',$tag.'End',6).'s ]',Log::INFO); } }else{ // 未执行任何行为 返回false return false; } } // 动态添加行为扩展到某个标签 function add_tag_behavior($tag,$behavior,$path='') { $array = C('tags.'.$tag); if(!$array) { $array = array(); } if($path) { $array[$behavior] = $path; }else{ $array[] = $behavior; } C('tags.'.$tag,$array); } // 过滤器方法 function filter($name, &$content) { $class = $name . 'Filter'; require_cache(LIB_PATH . 'Filter/' . $class . '.class.php'); $filter = new $class(); $content = $filter->run($content); } // 执行行为 function B($name, &$params=NULL) { $class = $name.'Behavior'; G('behaviorStart'); $behavior = new $class(); $behavior->run($params); if(APP_DEBUG) { // 记录行为的执行日志 G('behaviorEnd'); Log::record('Run '.$name.' Behavior [ RunTime:'.G('behaviorStart','behaviorEnd',6).'s ]',Log::INFO); } } // 渲染输出Widget function W($name, $data=array(), $return=false) { $class = $name . 'Widget'; require_cache(LIB_PATH . 'Widget/' . $class . '.class.php'); if (!class_exists($class)) throw_exception(L('_CLASS_NOT_EXIST_') . ':' . $class); $widget = Think::instance($class); $content = $widget->render($data); if ($return) return $content; else echo $content; } // 去除代码中的空白和注释 function strip_whitespace($content) { $stripStr = ''; //分析php源码 $tokens = token_get_all($content); $last_space = false; for ($i = 0, $j = count($tokens); $i < $j; $i++) { if (is_string($tokens[$i])) { $last_space = false; $stripStr .= $tokens[$i]; } else { switch ($tokens[$i][0]) { //过滤各种PHP注释 case T_COMMENT: case T_DOC_COMMENT: break; //过滤空格 case T_WHITESPACE: if (!$last_space) { $stripStr .= ' '; $last_space = true; } break; case T_START_HEREDOC: $stripStr .= "<<<THINK\n"; break; case T_END_HEREDOC: $stripStr .= "THINK;\n"; for($k = $i+1; $k < $j; $k++) { if(is_string($tokens[$k]) && $tokens[$k] == ';') { $i = $k; break; } else if($tokens[$k][0] == T_CLOSE_TAG) { break; } } break; default: $last_space = false; $stripStr .= $tokens[$i][1]; } } } return $stripStr; } // 循环创建目录 function mk_dir($dir, $mode = 0777) { if (is_dir($dir) || @mkdir($dir, $mode)) return true; if (!mk_dir(dirname($dir), $mode)) return false; return @mkdir($dir, $mode); } //[RUNTIME] // 编译文件 function compile($filename) { $content = file_get_contents($filename); // 替换预编译指令 $content = preg_replace('/\/\/\[RUNTIME\](.*?)\/\/\[\/RUNTIME\]/s', '', $content); $content = substr(trim($content), 5); if ('?>' == substr($content, -2)) $content = substr($content, 0, -2); return $content; } // 根据数组生成常量定义 function array_define($array,$check=true) { $content = "\n"; foreach ($array as $key => $val) { $key = strtoupper($key); if($check) $content .= 'defined(\'' . $key . '\') or '; if (is_int($val) || is_float($val)) { $content .= "define('" . $key . "'," . $val . ');'; } elseif (is_bool($val)) { $val = ($val) ? 'true' : 'false'; $content .= "define('" . $key . "'," . $val . ');'; } elseif (is_string($val)) { $content .= "define('" . $key . "','" . addslashes($val) . "');"; } $content .= "\n"; } return $content; } //[/RUNTIME]
zzgcms
ZGCMS/ThinkPHP/Common/common.php
PHP
art
17,616
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * ThinkPHP 运行时文件 编译后不再加载 +------------------------------------------------------------------------------ */ if (!defined('THINK_PATH')) exit(); if(version_compare(PHP_VERSION,'5.2.0','<')) die('require PHP > 5.2.0 !'); // 版本信息 define('THINK_VERSION', '3.0'); define('THINK_RELEASE', '20120323'); // 系统信息 if(version_compare(PHP_VERSION,'5.4.0','<') ) { @set_magic_quotes_runtime (0); define('MAGIC_QUOTES_GPC',get_magic_quotes_gpc()?True:False); } define('IS_CGI',substr(PHP_SAPI, 0,3)=='cgi' ? 1 : 0 ); define('IS_WIN',strstr(PHP_OS, 'WIN') ? 1 : 0 ); define('IS_CLI',PHP_SAPI=='cli'? 1 : 0); // 项目名称 defined('APP_NAME') or define('APP_NAME', basename(dirname($_SERVER['SCRIPT_FILENAME']))); if(!IS_CLI) { // 当前文件名 if(!defined('_PHP_FILE_')) { if(IS_CGI) { //CGI/FASTCGI模式下 $_temp = explode('.php',$_SERVER['PHP_SELF']); define('_PHP_FILE_', rtrim(str_replace($_SERVER['HTTP_HOST'],'',$_temp[0].'.php'),'/')); }else { define('_PHP_FILE_', rtrim($_SERVER['SCRIPT_NAME'],'/')); } } if(!defined('__ROOT__')) { // 网站URL根目录 if( strtoupper(APP_NAME) == strtoupper(basename(dirname(_PHP_FILE_))) ) { $_root = dirname(dirname(_PHP_FILE_)); }else { $_root = dirname(_PHP_FILE_); } define('__ROOT__', (($_root=='/' || $_root=='\\')?'':$_root)); } //支持的URL模式 define('URL_COMMON', 0); //普通模式 define('URL_PATHINFO', 1); //PATHINFO模式 define('URL_REWRITE', 2); //REWRITE模式 define('URL_COMPAT', 3); // 兼容模式 } // 路径设置 可在入口文件中重新定义 所有路径常量都必须以/ 结尾 defined('CORE_PATH') or define('CORE_PATH',THINK_PATH.'Lib/'); // 系统核心类库目录 defined('EXTEND_PATH') or define('EXTEND_PATH',THINK_PATH.'Extend/'); // 系统扩展目录 defined('MODE_PATH') or define('MODE_PATH',EXTEND_PATH.'Mode/'); // 模式扩展目录 defined('ENGINE_PATH') or define('ENGINE_PATH',EXTEND_PATH.'Engine/'); // 引擎扩展目录 defined('VENDOR_PATH') or define('VENDOR_PATH',EXTEND_PATH.'Vendor/'); // 第三方类库目录 defined('LIBRARY_PATH') or define('LIBRARY_PATH',EXTEND_PATH.'Library/'); // 扩展类库目录 defined('COMMON_PATH') or define('COMMON_PATH', APP_PATH.'Common/'); // 项目公共目录 defined('LIB_PATH') or define('LIB_PATH', APP_PATH.'Lib/'); // 项目类库目录 defined('CONF_PATH') or define('CONF_PATH', APP_PATH.'Conf/'); // 项目配置目录 defined('LANG_PATH') or define('LANG_PATH', APP_PATH.'Lang/'); // 项目语言包目录 defined('TMPL_PATH') or define('TMPL_PATH',APP_PATH.'Tpl/'); // 项目模板目录 defined('HTML_PATH') or define('HTML_PATH',APP_PATH.'Html/'); // 项目静态目录 defined('LOG_PATH') or define('LOG_PATH', RUNTIME_PATH.'Logs/'); // 项目日志目录 defined('TEMP_PATH') or define('TEMP_PATH', RUNTIME_PATH.'Temp/'); // 项目缓存目录 defined('DATA_PATH') or define('DATA_PATH', RUNTIME_PATH.'Data/'); // 项目数据目录 defined('CACHE_PATH') or define('CACHE_PATH', RUNTIME_PATH.'Cache/'); // 项目模板缓存目录 // 为了方便导入第三方类库 设置Vendor目录到include_path set_include_path(get_include_path() . PATH_SEPARATOR . VENDOR_PATH); // 加载运行时所需要的文件 并负责自动目录生成 function load_runtime_file() { // 加载系统基础函数库 require THINK_PATH.'Common/common.php'; // 读取核心编译文件列表 $list = array( CORE_PATH.'Core/Think.class.php', CORE_PATH.'Core/ThinkException.class.php', // 异常处理类 CORE_PATH.'Core/Behavior.class.php', ); // 加载模式文件列表 foreach ($list as $key=>$file){ if(is_file($file)) require_cache($file); } // 加载系统类库别名定义 alias_import(include THINK_PATH.'Conf/alias.php'); // 检查项目目录结构 如果不存在则自动创建 if(!is_dir(LIB_PATH)) { // 创建项目目录结构 build_app_dir(); }elseif(!is_dir(CACHE_PATH)){ // 检查缓存目录 check_runtime(); }elseif(APP_DEBUG){ // 调试模式切换删除编译缓存 if(is_file(RUNTIME_FILE)) unlink(RUNTIME_FILE); } } // 检查缓存目录(Runtime) 如果不存在则自动创建 function check_runtime() { if(!is_dir(RUNTIME_PATH)) { mkdir(RUNTIME_PATH); }elseif(!is_writeable(RUNTIME_PATH)) { header('Content-Type:text/html; charset=utf-8'); exit('目录 [ '.RUNTIME_PATH.' ] 不可写!'); } mkdir(CACHE_PATH); // 模板缓存目录 if(!is_dir(LOG_PATH)) mkdir(LOG_PATH); // 日志目录 if(!is_dir(TEMP_PATH)) mkdir(TEMP_PATH); // 数据缓存目录 if(!is_dir(DATA_PATH)) mkdir(DATA_PATH); // 数据文件目录 return true; } // 创建编译缓存 function build_runtime_cache($append='') { // 生成编译文件 $defs = get_defined_constants(TRUE); $content = '$GLOBALS[\'_beginTime\'] = microtime(TRUE);'; if(defined('RUNTIME_DEF_FILE')) { // 编译后的常量文件外部引入 file_put_contents(RUNTIME_DEF_FILE,'<?php '.array_define($defs['user'])); $content .= 'require \''.RUNTIME_DEF_FILE.'\';'; }else{ $content .= array_define($defs['user']); } $content .= 'set_include_path(get_include_path() . PATH_SEPARATOR . VENDOR_PATH);'; // 读取核心编译文件列表 $list = array( THINK_PATH.'Common/common.php', CORE_PATH.'Core/Think.class.php', CORE_PATH.'Core/ThinkException.class.php', CORE_PATH.'Core/Behavior.class.php', ); foreach ($list as $file){ $content .= compile($file); } // 系统行为扩展文件统一编译 if(C('APP_TAGS_ON')) { $content .= build_tags_cache(); } $alias = include THINK_PATH.'Conf/alias.php'; $content .= 'alias_import('.var_export($alias,true).');'; // 编译框架默认语言包和配置参数 $content .= $append."\nL(".var_export(L(),true).");C(".var_export(C(),true).');G(\'loadTime\');Think::Start();'; file_put_contents(RUNTIME_FILE,strip_whitespace('<?php '.$content)); } // 编译系统行为扩展类库 function build_tags_cache() { $tags = C('extends'); $content = ''; foreach ($tags as $tag=>$item){ foreach ($item as $key=>$name) { $content .= is_int($key)?compile(CORE_PATH.'Behavior/'.$name.'Behavior.class.php'):compile($name); } } return $content; } // 创建项目目录结构 function build_app_dir() { // 没有创建项目目录的话自动创建 if(!is_dir(APP_PATH)) mk_dir(APP_PATH,0777); if(is_writeable(APP_PATH)) { $dirs = array( LIB_PATH, RUNTIME_PATH, CONF_PATH, COMMON_PATH, LANG_PATH, CACHE_PATH, TMPL_PATH, TMPL_PATH.C('DEFAULT_THEME').'/', LOG_PATH, TEMP_PATH, DATA_PATH, LIB_PATH.'Model/', LIB_PATH.'Action/', LIB_PATH.'Behavior/', LIB_PATH.'Widget/', ); foreach ($dirs as $dir){ if(!is_dir($dir)) mk_dir($dir,0777); } // 目录安全写入 defined('BUILD_DIR_SECURE') or define('BUILD_DIR_SECURE',false); if(BUILD_DIR_SECURE) { defined('DIR_SECURE_FILENAME') or define('DIR_SECURE_FILENAME','index.html'); defined('DIR_SECURE_CONTENT') or define('DIR_SECURE_CONTENT',' '); // 自动写入目录安全文件 $content = DIR_SECURE_CONTENT; $a = explode(',', DIR_SECURE_FILENAME); foreach ($a as $filename){ foreach ($dirs as $dir) file_put_contents($dir.$filename,$content); } } // 写入配置文件 if(!is_file(CONF_PATH.'config.php')) file_put_contents(CONF_PATH.'config.php',"<?php\nreturn array(\n\t//'配置项'=>'配置值'\n);\n?>"); // 写入测试Action if(!is_file(LIB_PATH.'Action/IndexAction.class.php')) build_first_action(); }else{ header('Content-Type:text/html; charset=utf-8'); exit('项目目录不可写,目录无法自动生成!<BR>请使用项目生成器或者手动生成项目目录~'); } } // 创建测试Action function build_first_action() { $content = file_get_contents(THINK_PATH.'Tpl/default_index.tpl'); file_put_contents(LIB_PATH.'Action/IndexAction.class.php',$content); } // 加载运行时所需文件 load_runtime_file(); // 记录加载文件时间 G('loadTime'); // 执行入口 Think::Start();
zzgcms
ZGCMS/ThinkPHP/Common/runtime.php
PHP
art
9,790
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: RobotCheckBehavior.class.php 2616 2012-01-16 08:36:46Z liu21st $ class RobotCheckBehavior extends Behavior { protected $options = array( 'LIMIT_ROBOT_VISIT'=>true, ); public function run(&$params) { // 机器人访问检测 if(C('LIMIT_ROBOT_VISIT') && self::isRobot()) { // 禁止机器人访问 exit('Access Denied'); } } static private function isRobot() { static $_robot = null; if(is_null($_robot)) { $spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla'; $browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla'; if(preg_match("/($browsers)/", $_SERVER['HTTP_USER_AGENT'])) { $_robot = false ; } elseif(preg_match("/($spiders)/", $_SERVER['HTTP_USER_AGENT'])) { $_robot = true; } else { $_robot = false; } } return $_robot; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Behavior/RobotCheckBehavior.class.php
PHP
art
1,631
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: luofei614 <www.3g4k.com> // +---------------------------------------------------------------------- // $Id$ /** +------------------------------------------------------------------------------ * 将Trace信息输出到火狐的firebug,从而不影响ajax效果和页面的布局。 +------------------------------------------------------------------------------ * 使用前,你需要先在火狐浏览器上安装firebug和firePHP两个插件。 * 定义项目的tags.php文件, * <code> * <?php return array( * 'view_end'=>array( * '_overlay'=>true, * 'FireShowPageTrace' * ) * ); * </code> * 再将此文件放到项目的Behavior文件夹中即可 * 如果trace信息没有正常输出,请查看您的日志。 * firePHP,是通过http headers和firebug通讯的,所以要保证在输出trace信息之前不能有 * headers输出,你可以在入口文件第一个加入代码 ob_start(); 或者配置output_buffering * */ class FireShowPageTraceBehavior extends Behavior { // 行为参数定义 protected $options = array( 'FIRE_SHOW_PAGE_TRACE' => true, // 显示页面Trace信息 ); // 行为扩展的执行入口必须是run public function run(&$params){ if(C('FIRE_SHOW_PAGE_TRACE')) { $this->showTrace(); } } /** +---------------------------------------------------------- * 显示页面Trace信息 +---------------------------------------------------------- * @access private +---------------------------------------------------------- */ private function showTrace() { // 系统默认显示信息 $log = Log::$log; $files = get_included_files(); $trace = array( '请求时间'=> date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']), '当前页面'=> __SELF__, '请求协议'=> $_SERVER['SERVER_PROTOCOL'].' '.$_SERVER['REQUEST_METHOD'], '运行信息'=> $this->showTime(), '会话ID' => session_id(), '日志记录'=> !empty($log)?$log:'无日志记录', '加载文件'=>$files, ); // 读取项目定义的Trace文件 $traceFile = CONF_PATH.'trace.php'; if(is_file($traceFile)) { // 定义格式 return array('当前页面'=>$_SERVER['PHP_SELF'],'通信协议'=>$_SERVER['SERVER_PROTOCOL'],...); $trace = array_merge(include $traceFile,$trace); } // 设置trace信息 trace($trace); $fire=array( array('','') ); foreach(trace() as $key=>$value){ $fire[]=array($key,$value); } if(headers_sent($filename, $linenum)){ $fileInfo=!empty($filename)?"(在{$filename}文件的第{$linenum}行)":''; Log::record("已经有Http Header信息头输出{$fileInfo},请在你的入口文件加入ob_start() 或通过配置output_buffering,已确保headers不被提前输出"); }else{ fb(array('页面Trace信息',$fire),FirePHP::TABLE); } } /** +---------------------------------------------------------- * 显示运行时间、数据库操作、缓存次数、内存使用信息 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ private function showTime() { // 显示运行时间 G('beginTime',$GLOBALS['_beginTime']); G('viewEndTime'); $showTime = 'Process: '.G('beginTime','viewEndTime').'s '; // 显示详细运行时间 $showTime .= '( Load:'.G('beginTime','loadTime').'s Init:'.G('loadTime','initTime').'s Exec:'.G('initTime','viewStartTime').'s Template:'.G('viewStartTime','viewEndTime').'s )'; // 显示数据库操作次数 if(class_exists('Db',false) ) { $showTime .= ' | DB :'.N('db_query').' queries '.N('db_write').' writes '; } // 显示缓存读写次数 if( class_exists('Cache',false)) { $showTime .= ' | Cache :'.N('cache_read').' gets '.N('cache_write').' writes '; } // 显示内存开销 if(MEMORY_LIMIT_ON ) { $showTime .= ' | UseMem:'. number_format((memory_get_usage() - $GLOBALS['_startUseMems'])/1024).' kb'; } // 显示文件加载数 $showTime .= ' | LoadFile:'.count(get_included_files()); // 显示函数调用次数 自定义函数,内置函数 $fun = get_defined_functions(); $showTime .= ' | CallFun:'.count($fun['user']).','.count($fun['internal']); return $showTime; } } function fb() { $instance = FirePHP::getInstance(true); $args = func_get_args(); return call_user_func_array(array($instance,'fb'),$args); } class FB { /** * Enable and disable logging to Firebug * * @see FirePHP->setEnabled() * @param boolean $Enabled TRUE to enable, FALSE to disable * @return void */ public static function setEnabled($Enabled) { $instance = FirePHP::getInstance(true); $instance->setEnabled($Enabled); } /** * Check if logging is enabled * * @see FirePHP->getEnabled() * @return boolean TRUE if enabled */ public static function getEnabled() { $instance = FirePHP::getInstance(true); return $instance->getEnabled(); } /** * Specify a filter to be used when encoding an object * * Filters are used to exclude object members. * * @see FirePHP->setObjectFilter() * @param string $Class The class name of the object * @param array $Filter An array or members to exclude * @return void */ public static function setObjectFilter($Class, $Filter) { $instance = FirePHP::getInstance(true); $instance->setObjectFilter($Class, $Filter); } /** * Set some options for the library * * @see FirePHP->setOptions() * @param array $Options The options to be set * @return void */ public static function setOptions($Options) { $instance = FirePHP::getInstance(true); $instance->setOptions($Options); } /** * Get options for the library * * @see FirePHP->getOptions() * @return array The options */ public static function getOptions() { $instance = FirePHP::getInstance(true); return $instance->getOptions(); } /** * Log object to firebug * * @see http://www.firephp.org/Wiki/Reference/Fb * @param mixed $Object * @return true * @throws Exception */ public static function send() { $instance = FirePHP::getInstance(true); $args = func_get_args(); return call_user_func_array(array($instance,'fb'),$args); } /** * Start a group for following messages * * Options: * Collapsed: [true|false] * Color: [#RRGGBB|ColorName] * * @param string $Name * @param array $Options OPTIONAL Instructions on how to log the group * @return true */ public static function group($Name, $Options=null) { $instance = FirePHP::getInstance(true); return $instance->group($Name, $Options); } /** * Ends a group you have started before * * @return true * @throws Exception */ public static function groupEnd() { return self::send(null, null, FirePHP::GROUP_END); } /** * Log object with label to firebug console * * @see FirePHP::LOG * @param mixes $Object * @param string $Label * @return true * @throws Exception */ public static function log($Object, $Label=null) { return self::send($Object, $Label, FirePHP::LOG); } /** * Log object with label to firebug console * * @see FirePHP::INFO * @param mixes $Object * @param string $Label * @return true * @throws Exception */ public static function info($Object, $Label=null) { return self::send($Object, $Label, FirePHP::INFO); } /** * Log object with label to firebug console * * @see FirePHP::WARN * @param mixes $Object * @param string $Label * @return true * @throws Exception */ public static function warn($Object, $Label=null) { return self::send($Object, $Label, FirePHP::WARN); } /** * Log object with label to firebug console * * @see FirePHP::ERROR * @param mixes $Object * @param string $Label * @return true * @throws Exception */ public static function error($Object, $Label=null) { return self::send($Object, $Label, FirePHP::ERROR); } /** * Dumps key and variable to firebug server panel * * @see FirePHP::DUMP * @param string $Key * @param mixed $Variable * @return true * @throws Exception */ public static function dump($Key, $Variable) { return self::send($Variable, $Key, FirePHP::DUMP); } /** * Log a trace in the firebug console * * @see FirePHP::TRACE * @param string $Label * @return true * @throws Exception */ public static function trace($Label) { return self::send($Label, FirePHP::TRACE); } /** * Log a table in the firebug console * * @see FirePHP::TABLE * @param string $Label * @param string $Table * @return true * @throws Exception */ public static function table($Label, $Table) { return self::send($Table, $Label, FirePHP::TABLE); } } if (!defined('E_STRICT')) { define('E_STRICT', 2048); } if (!defined('E_RECOVERABLE_ERROR')) { define('E_RECOVERABLE_ERROR', 4096); } if (!defined('E_DEPRECATED')) { define('E_DEPRECATED', 8192); } if (!defined('E_USER_DEPRECATED')) { define('E_USER_DEPRECATED', 16384); } /** * Sends the given data to the FirePHP Firefox Extension. * The data can be displayed in the Firebug Console or in the * "Server" request tab. * * For more information see: http://www.firephp.org/ * * @copyright Copyright (C) 2007-2009 Christoph Dorn * @author Christoph Dorn <christoph@christophdorn.com> * @license http://www.opensource.org/licenses/bsd-license.php * @package FirePHPCore */ class FirePHP { /** * FirePHP version * * @var string */ const VERSION = '0.3'; // @pinf replace '0.3' with '%%package.version%%' /** * Firebug LOG level * * Logs a message to firebug console. * * @var string */ const LOG = 'LOG'; /** * Firebug INFO level * * Logs a message to firebug console and displays an info icon before the message. * * @var string */ const INFO = 'INFO'; /** * Firebug WARN level * * Logs a message to firebug console, displays an warning icon before the message and colors the line turquoise. * * @var string */ const WARN = 'WARN'; /** * Firebug ERROR level * * Logs a message to firebug console, displays an error icon before the message and colors the line yellow. Also increments the firebug error count. * * @var string */ const ERROR = 'ERROR'; /** * Dumps a variable to firebug's server panel * * @var string */ const DUMP = 'DUMP'; /** * Displays a stack trace in firebug console * * @var string */ const TRACE = 'TRACE'; /** * Displays an exception in firebug console * * Increments the firebug error count. * * @var string */ const EXCEPTION = 'EXCEPTION'; /** * Displays an table in firebug console * * @var string */ const TABLE = 'TABLE'; /** * Starts a group in firebug console * * @var string */ const GROUP_START = 'GROUP_START'; /** * Ends a group in firebug console * * @var string */ const GROUP_END = 'GROUP_END'; /** * Singleton instance of FirePHP * * @var FirePHP */ protected static $instance = null; /** * Flag whether we are logging from within the exception handler * * @var boolean */ protected $inExceptionHandler = false; /** * Flag whether to throw PHP errors that have been converted to ErrorExceptions * * @var boolean */ protected $throwErrorExceptions = true; /** * Flag whether to convert PHP assertion errors to Exceptions * * @var boolean */ protected $convertAssertionErrorsToExceptions = true; /** * Flag whether to throw PHP assertion errors that have been converted to Exceptions * * @var boolean */ protected $throwAssertionExceptions = false; /** * Wildfire protocol message index * * @var int */ protected $messageIndex = 1; /** * Options for the library * * @var array */ protected $options = array('maxDepth' => 10, 'maxObjectDepth' => 5, 'maxArrayDepth' => 5, 'useNativeJsonEncode' => true, 'includeLineNumbers' => true); /** * Filters used to exclude object members when encoding * * @var array */ protected $objectFilters = array( 'firephp' => array('objectStack', 'instance', 'json_objectStack'), 'firephp_test_class' => array('objectStack', 'instance', 'json_objectStack') ); /** * A stack of objects used to detect recursion during object encoding * * @var object */ protected $objectStack = array(); /** * Flag to enable/disable logging * * @var boolean */ protected $enabled = true; /** * The insight console to log to if applicable * * @var object */ protected $logToInsightConsole = null; /** * When the object gets serialized only include specific object members. * * @return array */ public function __sleep() { return array('options','objectFilters','enabled'); } /** * Gets singleton instance of FirePHP * * @param boolean $AutoCreate * @return FirePHP */ public static function getInstance($AutoCreate = false) { if ($AutoCreate===true && !self::$instance) { self::init(); } return self::$instance; } /** * Creates FirePHP object and stores it for singleton access * * @return FirePHP */ public static function init() { return self::setInstance(new self()); } /** * Set the instance of the FirePHP singleton * * @param FirePHP $instance The FirePHP object instance * @return FirePHP */ public static function setInstance($instance) { return self::$instance = $instance; } /** * Set an Insight console to direct all logging calls to * * @param object $console The console object to log to * @return void */ public function setLogToInsightConsole($console) { if(is_string($console)) { if(get_class($this)!='FirePHP_Insight' && !is_subclass_of($this, 'FirePHP_Insight')) { throw new Exception('FirePHP instance not an instance or subclass of FirePHP_Insight!'); } $this->logToInsightConsole = $this->to('request')->console($console); } else { $this->logToInsightConsole = $console; } } /** * Enable and disable logging to Firebug * * @param boolean $Enabled TRUE to enable, FALSE to disable * @return void */ public function setEnabled($Enabled) { $this->enabled = $Enabled; } /** * Check if logging is enabled * * @return boolean TRUE if enabled */ public function getEnabled() { return $this->enabled; } /** * Specify a filter to be used when encoding an object * * Filters are used to exclude object members. * * @param string $Class The class name of the object * @param array $Filter An array of members to exclude * @return void */ public function setObjectFilter($Class, $Filter) { $this->objectFilters[strtolower($Class)] = $Filter; } /** * Set some options for the library * * Options: * - maxDepth: The maximum depth to traverse (default: 10) * - maxObjectDepth: The maximum depth to traverse objects (default: 5) * - maxArrayDepth: The maximum depth to traverse arrays (default: 5) * - useNativeJsonEncode: If true will use json_encode() (default: true) * - includeLineNumbers: If true will include line numbers and filenames (default: true) * * @param array $Options The options to be set * @return void */ public function setOptions($Options) { $this->options = array_merge($this->options,$Options); } /** * Get options from the library * * @return array The currently set options */ public function getOptions() { return $this->options; } /** * Set an option for the library * * @param string $Name * @param mixed $Value * @throws Exception * @return void */ public function setOption($Name, $Value) { if (!isset($this->options[$Name])) { throw $this->newException('Unknown option: ' . $Name); } $this->options[$Name] = $Value; } /** * Get an option from the library * * @param string $Name * @throws Exception * @return mixed */ public function getOption($Name) { if (!isset($this->options[$Name])) { throw $this->newException('Unknown option: ' . $Name); } return $this->options[$Name]; } /** * Register FirePHP as your error handler * * Will throw exceptions for each php error. * * @return mixed Returns a string containing the previously defined error handler (if any) */ public function registerErrorHandler($throwErrorExceptions = false) { //NOTE: The following errors will not be caught by this error handler: // E_ERROR, E_PARSE, E_CORE_ERROR, // E_CORE_WARNING, E_COMPILE_ERROR, // E_COMPILE_WARNING, E_STRICT $this->throwErrorExceptions = $throwErrorExceptions; return set_error_handler(array($this,'errorHandler')); } /** * FirePHP's error handler * * Throws exception for each php error that will occur. * * @param int $errno * @param string $errstr * @param string $errfile * @param int $errline * @param array $errcontext */ public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext) { // Don't throw exception if error reporting is switched off if (error_reporting() == 0) { return; } // Only throw exceptions for errors we are asking for if (error_reporting() & $errno) { $exception = new ErrorException($errstr, 0, $errno, $errfile, $errline); if ($this->throwErrorExceptions) { throw $exception; } else { $this->fb($exception); } } } /** * Register FirePHP as your exception handler * * @return mixed Returns the name of the previously defined exception handler, * or NULL on error. * If no previous handler was defined, NULL is also returned. */ public function registerExceptionHandler() { return set_exception_handler(array($this,'exceptionHandler')); } /** * FirePHP's exception handler * * Logs all exceptions to your firebug console and then stops the script. * * @param Exception $Exception * @throws Exception */ function exceptionHandler($Exception) { $this->inExceptionHandler = true; header('HTTP/1.1 500 Internal Server Error'); try { $this->fb($Exception); } catch (Exception $e) { echo 'We had an exception: ' . $e; } $this->inExceptionHandler = false; } /** * Register FirePHP driver as your assert callback * * @param boolean $convertAssertionErrorsToExceptions * @param boolean $throwAssertionExceptions * @return mixed Returns the original setting or FALSE on errors */ public function registerAssertionHandler($convertAssertionErrorsToExceptions = true, $throwAssertionExceptions = false) { $this->convertAssertionErrorsToExceptions = $convertAssertionErrorsToExceptions; $this->throwAssertionExceptions = $throwAssertionExceptions; if ($throwAssertionExceptions && !$convertAssertionErrorsToExceptions) { throw $this->newException('Cannot throw assertion exceptions as assertion errors are not being converted to exceptions!'); } return assert_options(ASSERT_CALLBACK, array($this, 'assertionHandler')); } /** * FirePHP's assertion handler * * Logs all assertions to your firebug console and then stops the script. * * @param string $file File source of assertion * @param int $line Line source of assertion * @param mixed $code Assertion code */ public function assertionHandler($file, $line, $code) { if ($this->convertAssertionErrorsToExceptions) { $exception = new ErrorException('Assertion Failed - Code[ '.$code.' ]', 0, null, $file, $line); if ($this->throwAssertionExceptions) { throw $exception; } else { $this->fb($exception); } } else { $this->fb($code, 'Assertion Failed', FirePHP::ERROR, array('File'=>$file,'Line'=>$line)); } } /** * Start a group for following messages. * * Options: * Collapsed: [true|false] * Color: [#RRGGBB|ColorName] * * @param string $Name * @param array $Options OPTIONAL Instructions on how to log the group * @return true * @throws Exception */ public function group($Name, $Options = null) { if (!$Name) { throw $this->newException('You must specify a label for the group!'); } if ($Options) { if (!is_array($Options)) { throw $this->newException('Options must be defined as an array!'); } if (array_key_exists('Collapsed', $Options)) { $Options['Collapsed'] = ($Options['Collapsed'])?'true':'false'; } } return $this->fb(null, $Name, FirePHP::GROUP_START, $Options); } /** * Ends a group you have started before * * @return true * @throws Exception */ public function groupEnd() { return $this->fb(null, null, FirePHP::GROUP_END); } /** * Log object with label to firebug console * * @see FirePHP::LOG * @param mixes $Object * @param string $Label * @return true * @throws Exception */ public function log($Object, $Label = null, $Options = array()) { return $this->fb($Object, $Label, FirePHP::LOG, $Options); } /** * Log object with label to firebug console * * @see FirePHP::INFO * @param mixes $Object * @param string $Label * @return true * @throws Exception */ public function info($Object, $Label = null, $Options = array()) { return $this->fb($Object, $Label, FirePHP::INFO, $Options); } /** * Log object with label to firebug console * * @see FirePHP::WARN * @param mixes $Object * @param string $Label * @return true * @throws Exception */ public function warn($Object, $Label = null, $Options = array()) { return $this->fb($Object, $Label, FirePHP::WARN, $Options); } /** * Log object with label to firebug console * * @see FirePHP::ERROR * @param mixes $Object * @param string $Label * @return true * @throws Exception */ public function error($Object, $Label = null, $Options = array()) { return $this->fb($Object, $Label, FirePHP::ERROR, $Options); } /** * Dumps key and variable to firebug server panel * * @see FirePHP::DUMP * @param string $Key * @param mixed $Variable * @return true * @throws Exception */ public function dump($Key, $Variable, $Options = array()) { if (!is_string($Key)) { throw $this->newException('Key passed to dump() is not a string'); } if (strlen($Key)>100) { throw $this->newException('Key passed to dump() is longer than 100 characters'); } if (!preg_match_all('/^[a-zA-Z0-9-_\.:]*$/', $Key, $m)) { throw $this->newException('Key passed to dump() contains invalid characters [a-zA-Z0-9-_\.:]'); } return $this->fb($Variable, $Key, FirePHP::DUMP, $Options); } /** * Log a trace in the firebug console * * @see FirePHP::TRACE * @param string $Label * @return true * @throws Exception */ public function trace($Label) { return $this->fb($Label, FirePHP::TRACE); } /** * Log a table in the firebug console * * @see FirePHP::TABLE * @param string $Label * @param string $Table * @return true * @throws Exception */ public function table($Label, $Table, $Options = array()) { return $this->fb($Table, $Label, FirePHP::TABLE, $Options); } /** * Insight API wrapper * * @see Insight_Helper::to() */ public static function to() { $instance = self::getInstance(); if (!method_exists($instance, "_to")) { throw new Exception("FirePHP::to() implementation not loaded"); } $args = func_get_args(); return call_user_func_array(array($instance, '_to'), $args); } /** * Insight API wrapper * * @see Insight_Helper::plugin() */ public static function plugin() { $instance = self::getInstance(); if (!method_exists($instance, "_plugin")) { throw new Exception("FirePHP::plugin() implementation not loaded"); } $args = func_get_args(); return call_user_func_array(array($instance, '_plugin'), $args); } /** * Check if FirePHP is installed on client * * @return boolean */ public function detectClientExtension() { // Check if FirePHP is installed on client via User-Agent header if (@preg_match_all('/\sFirePHP\/([\.\d]*)\s?/si',$this->getUserAgent(),$m) && version_compare($m[1][0],'0.0.6','>=')) { return true; } else // Check if FirePHP is installed on client via X-FirePHP-Version header if (@preg_match_all('/^([\.\d]*)$/si',$this->getRequestHeader("X-FirePHP-Version"),$m) && version_compare($m[1][0],'0.0.6','>=')) { return true; } return false; } /** * Log varible to Firebug * * @see http://www.firephp.org/Wiki/Reference/Fb * @param mixed $Object The variable to be logged * @return true Return TRUE if message was added to headers, FALSE otherwise * @throws Exception */ public function fb($Object) { if($this instanceof FirePHP_Insight && method_exists($this, '_logUpgradeClientMessage')) { if(!FirePHP_Insight::$upgradeClientMessageLogged) { // avoid infinite recursion as _logUpgradeClientMessage() logs a message $this->_logUpgradeClientMessage(); } } static $insightGroupStack = array(); if (!$this->getEnabled()) { return false; } if ($this->headersSent($filename, $linenum)) { // If we are logging from within the exception handler we cannot throw another exception if ($this->inExceptionHandler) { // Simply echo the error out to the page echo '<div style="border: 2px solid red; font-family: Arial; font-size: 12px; background-color: lightgray; padding: 5px;"><span style="color: red; font-weight: bold;">FirePHP ERROR:</span> Headers already sent in <b>'.$filename.'</b> on line <b>'.$linenum.'</b>. Cannot send log data to FirePHP. You must have Output Buffering enabled via ob_start() or output_buffering ini directive.</div>'; } else { throw $this->newException('Headers already sent in '.$filename.' on line '.$linenum.'. Cannot send log data to FirePHP. You must have Output Buffering enabled via ob_start() or output_buffering ini directive.'); } } $Type = null; $Label = null; $Options = array(); if (func_num_args()==1) { } else if (func_num_args()==2) { switch(func_get_arg(1)) { case self::LOG: case self::INFO: case self::WARN: case self::ERROR: case self::DUMP: case self::TRACE: case self::EXCEPTION: case self::TABLE: case self::GROUP_START: case self::GROUP_END: $Type = func_get_arg(1); break; default: $Label = func_get_arg(1); break; } } else if (func_num_args()==3) { $Type = func_get_arg(2); $Label = func_get_arg(1); } else if (func_num_args()==4) { $Type = func_get_arg(2); $Label = func_get_arg(1); $Options = func_get_arg(3); } else { throw $this->newException('Wrong number of arguments to fb() function!'); } if($this->logToInsightConsole!==null && (get_class($this)=='FirePHP_Insight' || is_subclass_of($this, 'FirePHP_Insight'))) { $msg = $this->logToInsightConsole; if ($Object instanceof Exception) { $Type = self::EXCEPTION; } if($Label && $Type!=self::TABLE && $Type!=self::GROUP_START) { $msg = $msg->label($Label); } switch($Type) { case self::DUMP: case self::LOG: return $msg->log($Object); case self::INFO: return $msg->info($Object); case self::WARN: return $msg->warn($Object); case self::ERROR: return $msg->error($Object); case self::TRACE: return $msg->trace($Object); case self::EXCEPTION: return $this->plugin('engine')->handleException($Object, $msg); case self::TABLE: if (isset($Object[0]) && !is_string($Object[0]) && $Label) { $Object = array($Label, $Object); } return $msg->table($Object[0], array_slice($Object[1],1), $Object[1][0]); case self::GROUP_START: $insightGroupStack[] = $msg->group(md5($Label))->open(); return $msg->log($Label); case self::GROUP_END: if(count($insightGroupStack)==0) { throw new Error('Too many groupEnd() as opposed to group() calls!'); } $group = array_pop($insightGroupStack); return $group->close(); default: return $msg->log($Object); } } if (!$this->detectClientExtension()) { return false; } $meta = array(); $skipFinalObjectEncode = false; if ($Object instanceof Exception) { $meta['file'] = $this->_escapeTraceFile($Object->getFile()); $meta['line'] = $Object->getLine(); $trace = $Object->getTrace(); if ($Object instanceof ErrorException && isset($trace[0]['function']) && $trace[0]['function']=='errorHandler' && isset($trace[0]['class']) && $trace[0]['class']=='FirePHP') { $severity = false; switch($Object->getSeverity()) { case E_WARNING: $severity = 'E_WARNING'; break; case E_NOTICE: $severity = 'E_NOTICE'; break; case E_USER_ERROR: $severity = 'E_USER_ERROR'; break; case E_USER_WARNING: $severity = 'E_USER_WARNING'; break; case E_USER_NOTICE: $severity = 'E_USER_NOTICE'; break; case E_STRICT: $severity = 'E_STRICT'; break; case E_RECOVERABLE_ERROR: $severity = 'E_RECOVERABLE_ERROR'; break; case E_DEPRECATED: $severity = 'E_DEPRECATED'; break; case E_USER_DEPRECATED: $severity = 'E_USER_DEPRECATED'; break; } $Object = array('Class'=>get_class($Object), 'Message'=>$severity.': '.$Object->getMessage(), 'File'=>$this->_escapeTraceFile($Object->getFile()), 'Line'=>$Object->getLine(), 'Type'=>'trigger', 'Trace'=>$this->_escapeTrace(array_splice($trace,2))); $skipFinalObjectEncode = true; } else { $Object = array('Class'=>get_class($Object), 'Message'=>$Object->getMessage(), 'File'=>$this->_escapeTraceFile($Object->getFile()), 'Line'=>$Object->getLine(), 'Type'=>'throw', 'Trace'=>$this->_escapeTrace($trace)); $skipFinalObjectEncode = true; } $Type = self::EXCEPTION; } else if ($Type==self::TRACE) { $trace = debug_backtrace(); if (!$trace) return false; for( $i=0 ; $i<sizeof($trace) ; $i++ ) { if (isset($trace[$i]['class']) && isset($trace[$i]['file']) && ($trace[$i]['class']=='FirePHP' || $trace[$i]['class']=='FB') && (substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php' || substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) { /* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */ } else if (isset($trace[$i]['class']) && isset($trace[$i+1]['file']) && $trace[$i]['class']=='FirePHP' && substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') { /* Skip fb() */ } else if ($trace[$i]['function']=='fb' || $trace[$i]['function']=='trace' || $trace[$i]['function']=='send') { $Object = array('Class'=>isset($trace[$i]['class'])?$trace[$i]['class']:'', 'Type'=>isset($trace[$i]['type'])?$trace[$i]['type']:'', 'Function'=>isset($trace[$i]['function'])?$trace[$i]['function']:'', 'Message'=>$trace[$i]['args'][0], 'File'=>isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'', 'Line'=>isset($trace[$i]['line'])?$trace[$i]['line']:'', 'Args'=>isset($trace[$i]['args'])?$this->encodeObject($trace[$i]['args']):'', 'Trace'=>$this->_escapeTrace(array_splice($trace,$i+1))); $skipFinalObjectEncode = true; $meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):''; $meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:''; break; } } } else if ($Type==self::TABLE) { if (isset($Object[0]) && is_string($Object[0])) { $Object[1] = $this->encodeTable($Object[1]); } else { $Object = $this->encodeTable($Object); } $skipFinalObjectEncode = true; } else if ($Type==self::GROUP_START) { if (!$Label) { throw $this->newException('You must specify a label for the group!'); } } else { if ($Type===null) { $Type = self::LOG; } } if ($this->options['includeLineNumbers']) { if (!isset($meta['file']) || !isset($meta['line'])) { $trace = debug_backtrace(); for( $i=0 ; $trace && $i<sizeof($trace) ; $i++ ) { if (isset($trace[$i]['class']) && isset($trace[$i]['file']) && ($trace[$i]['class']=='FirePHP' || $trace[$i]['class']=='FB') && (substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php' || substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) { /* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */ } else if (isset($trace[$i]['class']) && isset($trace[$i+1]['file']) && $trace[$i]['class']=='FirePHP' && substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') { /* Skip fb() */ } else if (isset($trace[$i]['file']) && substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php') { /* Skip FB::fb() */ } else { $meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):''; $meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:''; break; } } } } else { unset($meta['file']); unset($meta['line']); } $this->setHeader('X-Wf-Protocol-1','http://meta.wildfirehq.org/Protocol/JsonStream/0.2'); $this->setHeader('X-Wf-1-Plugin-1','http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/'.self::VERSION); $structure_index = 1; if ($Type==self::DUMP) { $structure_index = 2; $this->setHeader('X-Wf-1-Structure-2','http://meta.firephp.org/Wildfire/Structure/FirePHP/Dump/0.1'); } else { $this->setHeader('X-Wf-1-Structure-1','http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1'); } if ($Type==self::DUMP) { $msg = '{"'.$Label.'":'.$this->jsonEncode($Object, $skipFinalObjectEncode).'}'; } else { $msg_meta = $Options; $msg_meta['Type'] = $Type; if ($Label!==null) { $msg_meta['Label'] = $Label; } if (isset($meta['file']) && !isset($msg_meta['File'])) { $msg_meta['File'] = $meta['file']; } if (isset($meta['line']) && !isset($msg_meta['Line'])) { $msg_meta['Line'] = $meta['line']; } $msg = '['.$this->jsonEncode($msg_meta).','.$this->jsonEncode($Object, $skipFinalObjectEncode).']'; } $parts = explode("\n",chunk_split($msg, 5000, "\n")); for( $i=0 ; $i<count($parts) ; $i++) { $part = $parts[$i]; if ($part) { if (count($parts)>2) { // Message needs to be split into multiple parts $this->setHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex, (($i==0)?strlen($msg):'') . '|' . $part . '|' . (($i<count($parts)-2)?'\\':'')); } else { $this->setHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex, strlen($part) . '|' . $part . '|'); } $this->messageIndex++; if ($this->messageIndex > 99999) { throw $this->newException('Maximum number (99,999) of messages reached!'); } } } $this->setHeader('X-Wf-1-Index',$this->messageIndex-1); return true; } /** * Standardizes path for windows systems. * * @param string $Path * @return string */ protected function _standardizePath($Path) { return preg_replace('/\\\\+/','/',$Path); } /** * Escape trace path for windows systems * * @param array $Trace * @return array */ protected function _escapeTrace($Trace) { if (!$Trace) return $Trace; for( $i=0 ; $i<sizeof($Trace) ; $i++ ) { if (isset($Trace[$i]['file'])) { $Trace[$i]['file'] = $this->_escapeTraceFile($Trace[$i]['file']); } if (isset($Trace[$i]['args'])) { $Trace[$i]['args'] = $this->encodeObject($Trace[$i]['args']); } } return $Trace; } /** * Escape file information of trace for windows systems * * @param string $File * @return string */ protected function _escapeTraceFile($File) { /* Check if we have a windows filepath */ if (strpos($File,'\\')) { /* First strip down to single \ */ $file = preg_replace('/\\\\+/','\\',$File); return $file; } return $File; } /** * Check if headers have already been sent * * @param string $Filename * @param integer $Linenum */ protected function headersSent(&$Filename, &$Linenum) { return headers_sent($Filename, $Linenum); } /** * Send header * * @param string $Name * @param string $Value */ protected function setHeader($Name, $Value) { return header($Name.': '.$Value); } /** * Get user agent * * @return string|false */ protected function getUserAgent() { if (!isset($_SERVER['HTTP_USER_AGENT'])) return false; return $_SERVER['HTTP_USER_AGENT']; } /** * Get all request headers * * @return array */ public static function getAllRequestHeaders() { static $_cached_headers = false; if($_cached_headers!==false) { return $_cached_headers; } $headers = array(); if(function_exists('getallheaders')) { foreach( getallheaders() as $name => $value ) { $headers[strtolower($name)] = $value; } } else { foreach($_SERVER as $name => $value) { if(substr($name, 0, 5) == 'HTTP_') { $headers[strtolower(str_replace(' ', '-', str_replace('_', ' ', substr($name, 5))))] = $value; } } } return $_cached_headers = $headers; } /** * Get a request header * * @return string|false */ protected function getRequestHeader($Name) { $headers = self::getAllRequestHeaders(); if (isset($headers[strtolower($Name)])) { return $headers[strtolower($Name)]; } return false; } /** * Returns a new exception * * @param string $Message * @return Exception */ protected function newException($Message) { return new Exception($Message); } /** * Encode an object into a JSON string * * Uses PHP's jeson_encode() if available * * @param object $Object The object to be encoded * @return string The JSON string */ public function jsonEncode($Object, $skipObjectEncode = false) { if (!$skipObjectEncode) { $Object = $this->encodeObject($Object); } if (function_exists('json_encode') && $this->options['useNativeJsonEncode']!=false) { return json_encode($Object); } else { return $this->json_encode($Object); } } /** * Encodes a table by encoding each row and column with encodeObject() * * @param array $Table The table to be encoded * @return array */ protected function encodeTable($Table) { if (!$Table) return $Table; $new_table = array(); foreach($Table as $row) { if (is_array($row)) { $new_row = array(); foreach($row as $item) { $new_row[] = $this->encodeObject($item); } $new_table[] = $new_row; } } return $new_table; } /** * Encodes an object including members with * protected and private visibility * * @param Object $Object The object to be encoded * @param int $Depth The current traversal depth * @return array All members of the object */ protected function encodeObject($Object, $ObjectDepth = 1, $ArrayDepth = 1, $MaxDepth = 1) { if ($MaxDepth > $this->options['maxDepth']) { return '** Max Depth ('.$this->options['maxDepth'].') **'; } $return = array(); if (is_resource($Object)) { return '** '.(string)$Object.' **'; } else if (is_object($Object)) { if ($ObjectDepth > $this->options['maxObjectDepth']) { return '** Max Object Depth ('.$this->options['maxObjectDepth'].') **'; } foreach ($this->objectStack as $refVal) { if ($refVal === $Object) { return '** Recursion ('.get_class($Object).') **'; } } array_push($this->objectStack, $Object); $return['__className'] = $class = get_class($Object); $class_lower = strtolower($class); $reflectionClass = new ReflectionClass($class); $properties = array(); foreach( $reflectionClass->getProperties() as $property) { $properties[$property->getName()] = $property; } $members = (array)$Object; foreach( $properties as $plain_name => $property ) { $name = $raw_name = $plain_name; if ($property->isStatic()) { $name = 'static:'.$name; } if ($property->isPublic()) { $name = 'public:'.$name; } else if ($property->isPrivate()) { $name = 'private:'.$name; $raw_name = "\0".$class."\0".$raw_name; } else if ($property->isProtected()) { $name = 'protected:'.$name; $raw_name = "\0".'*'."\0".$raw_name; } if (!(isset($this->objectFilters[$class_lower]) && is_array($this->objectFilters[$class_lower]) && in_array($plain_name,$this->objectFilters[$class_lower]))) { if (array_key_exists($raw_name,$members) && !$property->isStatic()) { $return[$name] = $this->encodeObject($members[$raw_name], $ObjectDepth + 1, 1, $MaxDepth + 1); } else { if (method_exists($property,'setAccessible')) { $property->setAccessible(true); $return[$name] = $this->encodeObject($property->getValue($Object), $ObjectDepth + 1, 1, $MaxDepth + 1); } else if ($property->isPublic()) { $return[$name] = $this->encodeObject($property->getValue($Object), $ObjectDepth + 1, 1, $MaxDepth + 1); } else { $return[$name] = '** Need PHP 5.3 to get value **'; } } } else { $return[$name] = '** Excluded by Filter **'; } } // Include all members that are not defined in the class // but exist in the object foreach( $members as $raw_name => $value ) { $name = $raw_name; if ($name{0} == "\0") { $parts = explode("\0", $name); $name = $parts[2]; } $plain_name = $name; if (!isset($properties[$name])) { $name = 'undeclared:'.$name; if (!(isset($this->objectFilters[$class_lower]) && is_array($this->objectFilters[$class_lower]) && in_array($plain_name,$this->objectFilters[$class_lower]))) { $return[$name] = $this->encodeObject($value, $ObjectDepth + 1, 1, $MaxDepth + 1); } else { $return[$name] = '** Excluded by Filter **'; } } } array_pop($this->objectStack); } elseif (is_array($Object)) { if ($ArrayDepth > $this->options['maxArrayDepth']) { return '** Max Array Depth ('.$this->options['maxArrayDepth'].') **'; } foreach ($Object as $key => $val) { // Encoding the $GLOBALS PHP array causes an infinite loop // if the recursion is not reset here as it contains // a reference to itself. This is the only way I have come up // with to stop infinite recursion in this case. if ($key=='GLOBALS' && is_array($val) && array_key_exists('GLOBALS',$val)) { $val['GLOBALS'] = '** Recursion (GLOBALS) **'; } $return[$key] = $this->encodeObject($val, 1, $ArrayDepth + 1, $MaxDepth + 1); } } else { if (self::is_utf8($Object)) { return $Object; } else { return utf8_encode($Object); } } return $return; } /** * Returns true if $string is valid UTF-8 and false otherwise. * * @param mixed $str String to be tested * @return boolean */ protected static function is_utf8($str) { if(function_exists('mb_detect_encoding')) { return (mb_detect_encoding($str) == 'UTF-8'); } $c=0; $b=0; $bits=0; $len=strlen($str); for($i=0; $i<$len; $i++){ $c=ord($str[$i]); if ($c > 128){ if (($c >= 254)) return false; elseif ($c >= 252) $bits=6; elseif ($c >= 248) $bits=5; elseif ($c >= 240) $bits=4; elseif ($c >= 224) $bits=3; elseif ($c >= 192) $bits=2; else return false; if (($i+$bits) > $len) return false; while($bits > 1){ $i++; $b=ord($str[$i]); if ($b < 128 || $b > 191) return false; $bits--; } } } return true; } /** * Converts to and from JSON format. * * JSON (JavaScript Object Notation) is a lightweight data-interchange * format. It is easy for humans to read and write. It is easy for machines * to parse and generate. It is based on a subset of the JavaScript * Programming Language, Standard ECMA-262 3rd Edition - December 1999. * This feature can also be found in Python. JSON is a text format that is * completely language independent but uses conventions that are familiar * to programmers of the C-family of languages, including C, C++, C#, Java, * JavaScript, Perl, TCL, and many others. These properties make JSON an * ideal data-interchange language. * * This package provides a simple encoder and decoder for JSON notation. It * is intended for use with client-side Javascript applications that make * use of HTTPRequest to perform server communication functions - data can * be encoded into JSON notation for use in a client-side javascript, or * decoded from incoming Javascript requests. JSON format is native to * Javascript, and can be directly eval()'ed with no further parsing * overhead * * All strings should be in ASCII or UTF-8 format! * * LICENSE: Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: Redistributions of source code must retain the * above copyright notice, this list of conditions and the following * disclaimer. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * @category * @package Services_JSON * @author Michal Migurski <mike-json@teczno.com> * @author Matt Knapp <mdknapp[at]gmail[dot]com> * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com> * @author Christoph Dorn <christoph@christophdorn.com> * @copyright 2005 Michal Migurski * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $ * @license http://www.opensource.org/licenses/bsd-license.php * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 */ /** * Keep a list of objects as we descend into the array so we can detect recursion. */ private $json_objectStack = array(); /** * convert a string from one UTF-8 char to one UTF-16 char * * Normally should be handled by mb_convert_encoding, but * provides a slower PHP-only method for installations * that lack the multibye string extension. * * @param string $utf8 UTF-8 character * @return string UTF-16 character * @access private */ private function json_utf82utf16($utf8) { // oh please oh please oh please oh please oh please if (function_exists('mb_convert_encoding')) { return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); } switch(strlen($utf8)) { case 1: // this case should never be reached, because we are in ASCII range // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return $utf8; case 2: // return a UTF-16 character from a 2-byte UTF-8 char // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0x07 & (ord($utf8{0}) >> 2)) . chr((0xC0 & (ord($utf8{0}) << 6)) | (0x3F & ord($utf8{1}))); case 3: // return a UTF-16 character from a 3-byte UTF-8 char // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr((0xF0 & (ord($utf8{0}) << 4)) | (0x0F & (ord($utf8{1}) >> 2))) . chr((0xC0 & (ord($utf8{1}) << 6)) | (0x7F & ord($utf8{2}))); } // ignoring UTF-32 for now, sorry return ''; } /** * encodes an arbitrary variable into JSON format * * @param mixed $var any number, boolean, string, array, or object to be encoded. * see argument 1 to Services_JSON() above for array-parsing behavior. * if var is a strng, note that encode() always expects it * to be in ASCII or UTF-8 format! * * @return mixed JSON string representation of input var or an error if a problem occurs * @access public */ private function json_encode($var) { if (is_object($var)) { if (in_array($var,$this->json_objectStack)) { return '"** Recursion **"'; } } switch (gettype($var)) { case 'boolean': return $var ? 'true' : 'false'; case 'NULL': return 'null'; case 'integer': return (int) $var; case 'double': case 'float': return (float) $var; case 'string': // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT $ascii = ''; $strlen_var = strlen($var); /* * Iterate over every character in the string, * escaping with a slash or encoding to UTF-8 where necessary */ for ($c = 0; $c < $strlen_var; ++$c) { $ord_var_c = ord($var{$c}); switch (true) { case $ord_var_c == 0x08: $ascii .= '\b'; break; case $ord_var_c == 0x09: $ascii .= '\t'; break; case $ord_var_c == 0x0A: $ascii .= '\n'; break; case $ord_var_c == 0x0C: $ascii .= '\f'; break; case $ord_var_c == 0x0D: $ascii .= '\r'; break; case $ord_var_c == 0x22: case $ord_var_c == 0x2F: case $ord_var_c == 0x5C: // double quote, slash, slosh $ascii .= '\\'.$var{$c}; break; case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): // characters U-00000000 - U-0000007F (same as ASCII) $ascii .= $var{$c}; break; case (($ord_var_c & 0xE0) == 0xC0): // characters U-00000080 - U-000007FF, mask 110XXXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1})); $c += 1; $utf16 = $this->json_utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xF0) == 0xE0): // characters U-00000800 - U-0000FFFF, mask 1110XXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2})); $c += 2; $utf16 = $this->json_utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xF8) == 0xF0): // characters U-00010000 - U-001FFFFF, mask 11110XXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3})); $c += 3; $utf16 = $this->json_utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xFC) == 0xF8): // characters U-00200000 - U-03FFFFFF, mask 111110XX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3}), ord($var{$c + 4})); $c += 4; $utf16 = $this->json_utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xFE) == 0xFC): // characters U-04000000 - U-7FFFFFFF, mask 1111110X // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3}), ord($var{$c + 4}), ord($var{$c + 5})); $c += 5; $utf16 = $this->json_utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; } } return '"'.$ascii.'"'; case 'array': /* * As per JSON spec if any array key is not an integer * we must treat the the whole array as an object. We * also try to catch a sparsely populated associative * array with numeric keys here because some JS engines * will create an array with empty indexes up to * max_index which can cause memory issues and because * the keys, which may be relevant, will be remapped * otherwise. * * As per the ECMA and JSON specification an object may * have any string as a property. Unfortunately due to * a hole in the ECMA specification if the key is a * ECMA reserved word or starts with a digit the * parameter is only accessible using ECMAScript's * bracket notation. */ // treat as a JSON object if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { $this->json_objectStack[] = $var; $properties = array_map(array($this, 'json_name_value'), array_keys($var), array_values($var)); array_pop($this->json_objectStack); foreach($properties as $property) { if ($property instanceof Exception) { return $property; } } return '{' . join(',', $properties) . '}'; } $this->json_objectStack[] = $var; // treat it like a regular array $elements = array_map(array($this, 'json_encode'), $var); array_pop($this->json_objectStack); foreach($elements as $element) { if ($element instanceof Exception) { return $element; } } return '[' . join(',', $elements) . ']'; case 'object': $vars = self::encodeObject($var); $this->json_objectStack[] = $var; $properties = array_map(array($this, 'json_name_value'), array_keys($vars), array_values($vars)); array_pop($this->json_objectStack); foreach($properties as $property) { if ($property instanceof Exception) { return $property; } } return '{' . join(',', $properties) . '}'; default: return null; } } /** * array-walking function for use in generating JSON-formatted name-value pairs * * @param string $name name of key to use * @param mixed $value reference to an array element to be encoded * * @return string JSON-formatted name-value pair, like '"name":value' * @access private */ private function json_name_value($name, $value) { // Encoding the $GLOBALS PHP array causes an infinite loop // if the recursion is not reset here as it contains // a reference to itself. This is the only way I have come up // with to stop infinite recursion in this case. if ($name=='GLOBALS' && is_array($value) && array_key_exists('GLOBALS',$value)) { $value['GLOBALS'] = '** Recursion **'; } $encoded_value = $this->json_encode($value); if ($encoded_value instanceof Exception) { return $encoded_value; } return $this->json_encode(strval($name)) . ':' . $encoded_value; } /** * @deprecated */ public function setProcessorUrl($URL) { trigger_error("The FirePHP::setProcessorUrl() method is no longer supported", E_USER_DEPRECATED); } /** * @deprecated */ public function setRendererUrl($URL) { trigger_error("The FirePHP::setRendererUrl() method is no longer supported", E_USER_DEPRECATED); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Behavior/FireShowPageTraceBehavior.class.php
PHP
art
72,118
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: AgentCheckBehavior.class.php 2616 2012-01-16 08:36:46Z liu21st $ class AgentCheckBehavior extends Behavior { protected $options = array( 'LIMIT_PROXY_VISIT'=>true, ); public function run(&$params) { // 代理访问检测 if(C('LIMIT_PROXY_VISIT') && ($_SERVER['HTTP_X_FORWARDED_FOR'] || $_SERVER['HTTP_VIA'] || $_SERVER['HTTP_PROXY_CONNECTION'] || $_SERVER['HTTP_USER_AGENT_VIA'])) { // 禁止代理访问 exit('Access Denied'); } } } ?>
zzgcms
ZGCMS/ThinkPHP/Extend/Behavior/AgentCheckBehavior.class.php
PHP
art
1,145
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: BrowserCheckBehavior.class.php 2616 2012-01-16 08:36:46Z liu21st $ class BrowserCheckBehavior extends Behavior { protected $options = array( 'LIMIT_REFLESH_TIMES'=>10, ); public function run(&$params) { if($_SERVER['REQUEST_METHOD'] == 'GET') { // 启用页面防刷新机制 $guid = md5($_SERVER['PHP_SELF']); // 检查页面刷新间隔 if(Cookie::is_set('_last_visit_time_'.$guid) && Cookie::get('_last_visit_time_'.$guid)>time()-C('LIMIT_REFLESH_TIMES')) { // 页面刷新读取浏览器缓存 header('HTTP/1.1 304 Not Modified'); exit; }else{ // 缓存当前地址访问时间 Cookie::set('_last_visit_time_'.$guid, $_SERVER['REQUEST_TIME'],$_SERVER['REQUEST_TIME']+3600); //header('Last-Modified:'.(date('D,d M Y H:i:s',$_SERVER['REQUEST_TIME']-C('LIMIT_REFLESH_TIMES'))).' GMT'); } } } }
zzgcms
ZGCMS/ThinkPHP/Extend/Behavior/BrowserCheckBehavior.class.php
PHP
art
1,646
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: CheckLangBehavior.class.php 2735 2012-02-15 03:11:13Z liu21st $ /** +------------------------------------------------------------------------------ * 系统行为扩展 语言检测 并自动加载语言包 +------------------------------------------------------------------------------ */ class CheckLangBehavior extends Behavior { // 行为参数定义(默认值) 可在项目配置中覆盖 protected $options = array( 'LANG_SWITCH_ON' => false, // 默认关闭语言包功能 'LANG_AUTO_DETECT' => true, // 自动侦测语言 开启多语言功能后有效 'LANG_LIST' => 'zh-cn', // 允许切换的语言列表 用逗号分隔 'VAR_LANGUAGE' => 'l', // 默认语言切换变量 ); // 行为扩展的执行入口必须是run public function run(&$params){ // 开启静态缓存 $this->checkLanguage(); } /** +---------------------------------------------------------- * 语言检查 * 检查浏览器支持语言,并自动加载语言包 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ private function checkLanguage() { // 不开启语言包功能,仅仅加载框架语言文件直接返回 if (!C('LANG_SWITCH_ON')){ return; } $langSet = C('DEFAULT_LANG'); // 启用了语言包功能 // 根据是否启用自动侦测设置获取语言选择 if (C('LANG_AUTO_DETECT')){ if(isset($_GET[C('VAR_LANGUAGE')])){ $langSet = $_GET[C('VAR_LANGUAGE')];// url中设置了语言变量 cookie('think_language',$langSet,3600); }elseif(cookie('think_language')){// 获取上次用户的选择 $langSet = cookie('think_language'); }elseif(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){// 自动侦测浏览器语言 preg_match('/^([a-z\-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches); $langSet = $matches[1]; cookie('think_language',$langSet,3600); } if(false === stripos(C('LANG_LIST'),$langSet)) { // 非法语言参数 $langSet = C('DEFAULT_LANG'); } } // 定义当前语言 define('LANG_SET',strtolower($langSet)); // 读取项目公共语言包 if (is_file(LANG_PATH.LANG_SET.'/common.php')) L(include LANG_PATH.LANG_SET.'/common.php'); $group = ''; // 读取当前分组公共语言包 if (defined('GROUP_NAME')){ if (is_file(LANG_PATH.LANG_SET.'/'.GROUP_NAME.'.php')) L(include LANG_PATH.LANG_SET.'/'.GROUP_NAME.'.php'); $group = GROUP_NAME.C('TMPL_FILE_DEPR'); } // 读取当前模块语言包 if (is_file(LANG_PATH.LANG_SET.'/'.$group.strtolower(MODULE_NAME).'.php')) L(include LANG_PATH.LANG_SET.'/'.$group.strtolower(MODULE_NAME).'.php'); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Behavior/CheckLangBehavior.class.php
PHP
art
3,896
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: CronRunBehavior.class.php 2616 2012-01-16 08:36:46Z liu21st $ class CronRunBehavior extends Behavior { protected $options = array( 'CRON_MAX_TIME'=>60, ); public function run(&$params) { // 锁定自动执行 $lockfile = RUNTIME_PATH.'cron.lock'; if(is_writable($lockfile) && filemtime($lockfile) > $_SERVER['REQUEST_TIME'] - C('CRON_MAX_TIME')) { return ; } else { touch($lockfile); } set_time_limit(1000); ignore_user_abort(true); // 载入cron配置文件 // 格式 return array( // 'cronname'=>array('filename',intervals,nextruntime),... // ); if(is_file(RUNTIME_PATH.'~crons.php')) { $crons = include RUNTIME_PATH.'~crons.php'; }elseif(is_file(CONF_PATH.'crons.php')){ $crons = include CONF_PATH.'crons.php'; } if(isset($crons) && is_array($crons)) { $update = false; $log = array(); foreach ($crons as $key=>$cron){ if(empty($cron[2]) || $_SERVER['REQUEST_TIME']>=$cron[2]) { // 到达时间 执行cron文件 G('cronStart'); include LIB_PATH.'Cron/'.$cron[0].'.php'; $_useTime = G('cronStart','cronEnd', 6); // 更新cron记录 $cron[2] = $_SERVER['REQUEST_TIME']+$cron[1]; $crons[$key] = $cron; $log[] = "Cron:$key Runat ".date('Y-m-d H:i:s')." Use $_useTime s\n"; $update = true; } } if($update) { // 记录Cron执行日志 Log::write(implode('',$log)); // 更新cron文件 $content = "<?php\nreturn ".var_export($crons,true).";\n?>"; file_put_contents(RUNTIME_PATH.'~crons.php',$content); } } // 解除锁定 unlink($lockfile); return ; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Behavior/CronRunBehavior.class.php
PHP
art
2,723
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: RelationModel.class.php 2702 2012-02-02 12:35:01Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP 关联模型类扩展 +------------------------------------------------------------------------------ */ define('HAS_ONE',1); define('BELONGS_TO',2); define('HAS_MANY',3); define('MANY_TO_MANY',4); 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(); 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 = D($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 = D($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); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Model/RelationModel.class.php
PHP
art
21,601
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: AdvModel.class.php 2702 2012-02-02 12:35:01Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP 高级模型类扩展 +------------------------------------------------------------------------------ */ class AdvModel extends Model { 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='',$tablePrefix='',$connection='') { if('' !== $name || is_subclass_of($this,'AdvModel') ){ // 如果是AdvModel子类或者有传入模型名称则获取字段缓存 }else{ // 空的模型 关闭字段缓存 $this->autoCheckFields = false; } parent::__construct($name,$tablePrefix,$connection); } /** +---------------------------------------------------------- * 利用__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 integer $step 增长值 * @param integer $lazyTime 延时时间(s) +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setLazyInc($field,$step=1,$lazyTime=0) { $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)); } /** +---------------------------------------------------------- * 字段值延迟减少 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param integer $step 减少值 * @param integer $lazyTime 延时时间(s) +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setLazyDec($field,$step=1,$lazyTime=0) { $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)); } /** +---------------------------------------------------------- * 延时更新检查 返回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]); } } if(!empty($serialize)) { $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; } /** +---------------------------------------------------------- * 批处理执行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; } } }
zzgcms
ZGCMS/ThinkPHP/Extend/Model/AdvModel.class.php
PHP
art
31,282
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: ViewModel.class.php 2795 2012-03-02 15:34:18Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP 视图模型类扩展 +------------------------------------------------------------------------------ */ 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){ // 获取数据表名称 if(isset($view['_table'])) { // 2011/10/17 添加实际表名定义支持 可以实现同一个表的视图 $tableName .= $view['_table']; }else{ $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(is_string($order) && !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; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Model/ViewModel.class.php
PHP
art
12,282
<?php // +---------------------------------------------------------------------- // | TOPThink [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2010 http://topthink.com All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: MongoModel.class.php 2576 2012-01-12 15:09:01Z liu21st $ /** +------------------------------------------------------------------------------ * TOPThink MongoModel模型类 * 实现了ODM和ActiveRecords模式 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id: MongoModel.class.php 2576 2012-01-12 15:09:01Z liu21st $ +------------------------------------------------------------------------------ */ class MongoModel extends Model{ // 主键类型 const TYPE_OBJECT = 1; const TYPE_INT = 2; const TYPE_STRING = 3; // 主键名称 protected $pk = '_id'; // _id 类型 1 Object 采用MongoId对象 2 Int 整形 支持自动增长 3 String 字符串Hash protected $_idType = self::TYPE_OBJECT; // 主键是否自动增长 支持Int型主键 protected $_autoInc = false; // Mongo默认关闭字段检测 可以动态追加字段 protected $autoCheckFields = false; /** +---------------------------------------------------------- * 利用__call方法实现一些特殊的Model方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名称 * @param array $args 调用参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$args) { if(in_array(strtolower($method),array('table','where','order','limit','page'),true)) { // 连贯操作的实现 $this->options[strtolower($method)] = $args[0]; return $this; }elseif(strtolower(substr($method,0,5))=='getby') { // 根据某个字段获取记录 $field = parse_name(substr($method,5)); $where[$field] =$args[0]; return $this->where($where)->find(); }elseif(strtolower(substr($method,0,10))=='getfieldby') { // 根据某个字段获取记录的某个值 $name = parse_name(substr($method,10)); $where[$name] =$args[0]; return $this->where($where)->getField($args[1]); }else{ throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); return; } } /** +---------------------------------------------------------- * 获取字段信息并缓存 主键和自增信息直接配置 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function flush() { // 缓存不存在则查询数据表信息 $fields = $this->db->getFields(); if(!$fields) { // 暂时没有数据无法获取字段信息 下次查询 return false; } $this->fields = array_keys($fields); $this->fields['_pk'] = $this->pk; $this->fields['_autoinc'] = $this->_autoInc; foreach ($fields as $key=>$val){ // 记录字段类型 $type[$key] = $val['type']; } // 记录字段类型信息 if(C('DB_FIELDTYPE_CHECK')) $this->fields['_type'] = $type; // 2008-3-7 增加缓存开关控制 if(C('DB_FIELDS_CACHE')){ // 永久缓存数据表信息 $db = $this->dbName?$this->dbName:C('DB_NAME'); F('_fields/'.$db.'.'.$this->name,$this->fields); } } // 写入数据前的回调方法 包括新增和更新 protected function _before_write(&$data) { $pk = $this->getPk(); // 根据主键类型处理主键数据 if(isset($data[$pk]) && $this->_idType == self::TYPE_OBJECT) { $data[$pk] = new MongoId($data[$pk]); } } /** +---------------------------------------------------------- * count统计 配合where连贯操作 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return integer +---------------------------------------------------------- */ public function count(){ // 分析表达式 $options = $this->_parseOptions(); return $this->db->count($options); } /** +---------------------------------------------------------- * 获取下一ID 用于自动增长型 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $pk 字段名 默认为主键 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function getMongoNextId($pk=''){ if(empty($pk)) { $pk = $this->getPk(); } return $this->db->mongo_next_id($pk); } // 插入数据前的回调方法 protected function _before_insert(&$data,$options) { // 写入数据到数据库 if($this->_autoInc && $this->_idType== self::TYPE_INT) { // 主键自动增长 $pk = $this->getPk(); if(!isset($data[$pk])) { $data[$pk] = $this->db->mongo_next_id($pk); } } } public function clear(){ return $this->db->clear(); } // 查询成功后的回调方法 protected function _after_select(&$resultSet,$options) { array_walk($resultSet,array($this,'checkMongoId')); } /** +---------------------------------------------------------- * 获取MongoId +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $result 返回数据 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ protected function checkMongoId(&$result){ if(is_object($result['_id'])) { $result['_id'] = $result['_id']->__toString(); } return $result; } // 表达式过滤回调方法 protected function _options_filter(&$options) { $id = $this->getPk(); if(isset($options['where'][$id]) && $this->_idType== self::TYPE_OBJECT) { $options['where'][$id] = new MongoId($options['where'][$id]); } } /** +---------------------------------------------------------- * 查询数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $options 表达式参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function find($options=array()) { if( is_numeric($options) || is_string($options)) { $id = $this->getPk(); $where[$id] = $options; $options = array(); $options['where'] = $where; } // 分析表达式 $options = $this->_parseOptions($options); $result = $this->db->find($options); if(false === $result) { return false; } if(empty($result)) {// 查询结果为空 return null; }else{ $this->checkMongoId($result); } $this->data = $result; $this->_after_find($this->data,$options); return $this->data; } /** +---------------------------------------------------------- * 字段值增长 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param integer $step 增长值 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setInc($field,$step=1) { return $this->setField($field,array('inc',$step)); } /** +---------------------------------------------------------- * 字段值减少 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param integer $step 减少值 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setDec($field,$step=1) { return $this->setField($field,array('inc','-'.$step)); } /** +---------------------------------------------------------- * 获取一条记录的某个字段值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param string $spea 字段数据间隔符号 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function getField($field,$sepa=null) { $options['field'] = $field; $options = $this->_parseOptions($options); if(strpos($field,',')) { // 多字段 $resultSet = $this->db->select($options); if(!empty($resultSet)) { $_field = explode(',', $field); $field = array_keys($resultSet[0]); $move = $_field[0]==$_field[1]?false:true; $key = array_shift($field); $key2 = array_shift($field); $cols = array(); $count = count($_field); foreach ($resultSet as $result){ $name = $result[$key]; if($move) { // 删除键值记录 unset($result[$key]); } if(2==$count) { $cols[$name] = $result[$key2]; }else{ $cols[$name] = is_null($sepa)?$result:implode($sepa,$result); } } return $cols; } }else{ // 查找一条记录 $result = $this->db->find($options); if(!empty($result)) { return $result[$field]; } } return null; } /** +---------------------------------------------------------- * 执行Mongo指令 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $command 指令 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function command($command) { return $this->db->command($command); } /** +---------------------------------------------------------- * 执行MongoCode +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $code MongoCode * @param array $args 参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function mongoCode($code,$args=array()) { return $this->db->execute($code,$args); } // 数据库切换后回调方法 protected function _after_db() { // 切换Collection $this->db->switchCollection($this->getTableName(),$this->dbName?$this->dbName:C('db_name')); } /** +---------------------------------------------------------- * 得到完整的数据表名 Mongo表名不带dbName +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getTableName() { if(empty($this->trueTableName)) { $tableName = !empty($this->tablePrefix) ? $this->tablePrefix : ''; if(!empty($this->tableName)) { $tableName .= $this->tableName; }else{ $tableName .= parse_name($this->name); } $this->trueTableName = strtolower($tableName); } return $this->trueTableName; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Model/MongoModel.class.php
PHP
art
14,197
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: functions.php 2821 2012-03-16 06:17:49Z luofei614@gmail.com $ /** +------------------------------------------------------------------------------ * Think 标准模式公共函数库 +------------------------------------------------------------------------------ * @category Think * @package Common * @author liu21st <liu21st@gmail.com> * @version $Id: functions.php 2821 2012-03-16 06:17:49Z luofei614@gmail.com $ +------------------------------------------------------------------------------ */ // 错误输出 function halt($error) { $e = array(); if (APP_DEBUG) { //调试模式下输出错误信息 if (!is_array($error)) { $trace = debug_backtrace(); $e['message'] = $error; $e['file'] = $trace[0]['file']; $e['class'] = $trace[0]['class']; $e['function'] = $trace[0]['function']; $e['line'] = $trace[0]['line']; $traceInfo = ''; $time = date('y-m-d H:i:m'); foreach ($trace as $t) { $traceInfo .= '[' . $time . '] ' . $t['file'] . ' (' . $t['line'] . ') '; $traceInfo .= $t['class'] . $t['type'] . $t['function'] . '('; $traceInfo .= implode(', ', $t['args']); $traceInfo .=')<br/>'; } $e['trace'] = $traceInfo; } else { $e = $error; } // 包含异常页面模板 include C('TMPL_EXCEPTION_FILE'); } else { //否则定向到错误页面 $error_page = C('ERROR_PAGE'); if (!empty($error_page)) { redirect($error_page); } else { if (C('SHOW_ERROR_MSG')) $e['message'] = is_array($error) ? $error['message'] : $error; else $e['message'] = C('ERROR_MESSAGE'); // 包含异常页面模板 include C('TMPL_EXCEPTION_FILE'); } } exit; } // 自定义异常处理 function throw_exception($msg, $type='ThinkException', $code=0) { if (class_exists($type, false)) throw new $type($msg, $code, true); else halt($msg); // 异常类型不存在则输出错误信息字串 } // 浏览器友好的变量输出 function dump($var, $echo=true, $label=null, $strict=true) { $label = ($label === null) ? '' : rtrim($label) . ' '; if (!$strict) { if (ini_get('html_errors')) { $output = print_r($var, true); $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>'; } else { $output = $label . print_r($var, true); } } else { ob_start(); var_dump($var); $output = ob_get_clean(); if (!extension_loaded('xdebug')) { $output = preg_replace("/\]\=\>\n(\s+)/m", '] => ', $output); $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>'; } } if ($echo) { echo($output); return null; }else return $output; } // 区间调试开始 function debug_start($label='') { $GLOBALS[$label]['_beginTime'] = microtime(TRUE); if (MEMORY_LIMIT_ON) $GLOBALS[$label]['_beginMem'] = memory_get_usage(); } // 区间调试结束,显示指定标记到当前位置的调试 function debug_end($label='') { $GLOBALS[$label]['_endTime'] = microtime(TRUE); echo '<div style="text-align:center;width:100%">Process ' . $label . ': Times ' . number_format($GLOBALS[$label]['_endTime'] - $GLOBALS[$label]['_beginTime'], 6) . 's '; if (MEMORY_LIMIT_ON) { $GLOBALS[$label]['_endMem'] = memory_get_usage(); echo ' Memories ' . number_format(($GLOBALS[$label]['_endMem'] - $GLOBALS[$label]['_beginMem']) / 1024) . ' k'; } echo '</div>'; } // 添加和获取页面Trace记录 function trace($title='',$value='') { if(!C('SHOW_PAGE_TRACE')) return; static $_trace = array(); if(is_array($title)) { // 批量赋值 $_trace = array_merge($_trace,$title); }elseif('' !== $value){ // 赋值 $_trace[$title] = $value; }elseif('' !== $title){ // 取值 return $_trace[$title]; }else{ // 获取全部Trace数据 return $_trace; } } // 设置当前页面的布局 function layout($layout) { if(false !== $layout) { // 开启布局 C('LAYOUT_ON',true); if(is_string($layout)) { C('LAYOUT_NAME',$layout); } } } // URL组装 支持不同模式 // 格式:U('[分组/模块/操作]?参数','参数','伪静态后缀','是否跳转','显示域名') function U($url,$vars='',$suffix=true,$redirect=false,$domain=false) { // 解析URL $info = parse_url($url); $url = !empty($info['path'])?$info['path']:ACTION_NAME; // 解析子域名 if($domain===true){ $domain = $_SERVER['HTTP_HOST']; if(C('APP_SUB_DOMAIN_DEPLOY') ) { // 开启子域名部署 $domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.'); // '子域名'=>array('项目[/分组]'); foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) { if(false === strpos($key,'*') && 0=== strpos($url,$rule[0])) { $domain = $key.strstr($domain,'.'); // 生成对应子域名 $url = substr_replace($url,'',0,strlen($rule[0])); break; } } } } // 解析参数 if(is_string($vars)) { // aaa=1&bbb=2 转换成数组 parse_str($vars,$vars); }elseif(!is_array($vars)){ $vars = array(); } if(isset($info['query'])) { // 解析地址里面参数 合并到vars parse_str($info['query'],$params); $vars = array_merge($params,$vars); } // URL组装 $depr = C('URL_PATHINFO_DEPR'); if($url) { if(0=== strpos($url,'/')) {// 定义路由 $route = true; $url = substr($url,1); if('/' != $depr) { $url = str_replace('/',$depr,$url); } }else{ if('/' != $depr) { // 安全替换 $url = str_replace('/',$depr,$url); } // 解析分组、模块和操作 $url = trim($url,$depr); $path = explode($depr,$url); $var = array(); $var[C('VAR_ACTION')] = !empty($path)?array_pop($path):ACTION_NAME; $var[C('VAR_MODULE')] = !empty($path)?array_pop($path):MODULE_NAME; if(C('URL_CASE_INSENSITIVE')) { $var[C('VAR_MODULE')] = parse_name($var[C('VAR_MODULE')]); } if(C('APP_GROUP_LIST')) { if(!empty($path)) { $group = array_pop($path); $var[C('VAR_GROUP')] = $group; }else{ if(GROUP_NAME != C('DEFAULT_GROUP')) { $var[C('VAR_GROUP')] = GROUP_NAME; } } } } } if(C('URL_MODEL') == 0) { // 普通模式URL转换 $url = __APP__.'?'.http_build_query($var); if(!empty($vars)) { $vars = http_build_query($vars); $url .= '&'.$vars; } }else{ // PATHINFO模式或者兼容URL模式 if(isset($route)) { $url = __APP__.'/'.$url; }else{ $url = __APP__.'/'.implode($depr,array_reverse($var)); } if(!empty($vars)) { // 添加参数 $vars = http_build_query($vars); $url .= $depr.str_replace(array('=','&'),$depr,$vars); } if($suffix) { $suffix = $suffix===true?C('URL_HTML_SUFFIX'):$suffix; if($suffix) { $url .= '.'.ltrim($suffix,'.'); } } } if($domain) { $url = 'http://'.$domain.$url; } if($redirect) // 直接跳转URL redirect($url); else return $url; } // URL重定向 function redirect($url, $time=0, $msg='') { //多行URL地址支持 $url = str_replace(array("\n", "\r"), '', $url); if (empty($msg)) $msg = "系统将在{$time}秒之后自动跳转到{$url}!"; if (!headers_sent()) { // redirect if (0 === $time) { header('Location: ' . $url); } else { header("refresh:{$time};url={$url}"); echo($msg); } exit(); } else { $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>"; if ($time != 0) $str .= $msg; exit($str); } } // 全局缓存设置和读取 //[sae] 在sae下S缓存固定用memcache实现。 function S($name, $value='', $expire=0, $type='', $options=null) { static $_cache = array(); static $mc; //取得缓存对象实例 if (!is_object($mc)) { $mc = memcache_init(); } if ('' !== $value) { if (is_null($value)) { // 删除缓存 $result = $mc->delete($_SERVER['HTTP_APPVERSION'] . '/' . $name); if ($result) unset($_cache[$name]); return $result; }else { // 缓存数据 $mc->set($_SERVER['HTTP_APPVERSION'] . '/' . $name, $value, MEMCACHE_COMPRESSED, $expire); $_cache[$name] = $value; //[sae] 实现列队 if (!is_null($options['length']) && $options['length'] > 0) { $queue = F('think_queue'); if (!$queue) { $queue = array(); } array_push($queue, $name); if (count($queue) > $options['length']) { $key = array_shift($queue); $mc->delete($key); //[sae] 在调试模式下,统计出队次数 if (APP_DEBUG) { $counter = Think::instance('SaeCounter'); if ($counter->exists('think_queue_out_times')) $counter->incr('think_queue_out_times'); else $counter->create('think_queue_out_times', 1); } } F('think_queue', $queue); } } return; } if (isset($_cache[$name])) return $_cache[$name]; // 获取缓存数据 $value = $mc->get($_SERVER['HTTP_APPVERSION'] . '/' . $name); $_cache[$name] = $value; return $value; } // 快速文件数据读取和保存 针对简单类型数据 字符串、数组 //[sae] 在sae下F缓存使用KVDB实现 function F($name, $value='', $path=DATA_PATH) { //sae使用KVDB实现F缓存 static $_cache = array(); static $kv; if (!is_object($kv)) { $kv = Think::instance('SaeKVClient'); if(!$kv->init()) halt('您没有初始化KVDB,请在SAE平台进行初始化'); } if ('' !== $value) { if (is_null($value)) { // 删除缓存 return $kv->delete($_SERVER['HTTP_APPVERSION'] . '/' . $name); } else { return $kv->set($_SERVER['HTTP_APPVERSION'] . '/' . $name, $value); } } if (isset($_cache[$name])) return $_cache[$name]; // 获取缓存数据 $value = $kv->get($_SERVER['HTTP_APPVERSION'] . '/' . $name); return $value; } // 取得对象实例 支持调用类的静态方法 function get_instance_of($name, $method='', $args=array()) { static $_instance = array(); $identify = empty($args) ? $name . $method : $name . $method . to_guid_string($args); if (!isset($_instance[$identify])) { if (class_exists($name)) { $o = new $name(); if (method_exists($o, $method)) { if (!empty($args)) { $_instance[$identify] = call_user_func_array(array(&$o, $method), $args); } else { $_instance[$identify] = $o->$method(); } } else $_instance[$identify] = $o; } else halt(L('_CLASS_NOT_EXIST_') . ':' . $name); } return $_instance[$identify]; } // 根据PHP各种类型变量生成唯一标识号 function to_guid_string($mix) { if (is_object($mix) && function_exists('spl_object_hash')) { return spl_object_hash($mix); } elseif (is_resource($mix)) { $mix = get_resource_type($mix) . strval($mix); } else { $mix = serialize($mix); } return md5($mix); } // xml编码 function xml_encode($data, $encoding='utf-8', $root='think') { $xml = '<?xml version="1.0" encoding="' . $encoding . '"?>'; $xml.= '<' . $root . '>'; $xml.= data_to_xml($data); $xml.= '</' . $root . '>'; return $xml; } function data_to_xml($data) { $xml = ''; foreach ($data as $key => $val) { is_numeric($key) && $key = "item id=\"$key\""; $xml.="<$key>"; $xml.= ( is_array($val) || is_object($val)) ? data_to_xml($val) : $val; list($key, ) = explode(' ', $key); $xml.="</$key>"; } return $xml; } // session管理函数 function session($name,$value='') { $prefix = C('SESSION_PREFIX'); if(is_array($name)) { // session初始化 在session_start 之前调用 if(isset($name['prefix'])) C('SESSION_PREFIX',$name['prefix']); if(isset($_REQUEST[C('VAR_SESSION_ID')])){ session_id($_REQUEST[C('VAR_SESSION_ID')]); }elseif(isset($name['id'])) { session_id($name['id']); } //ini_set('session.auto_start', 0);//[sae] 在sae平台不用设置 if(isset($name['name'])) session_name($name['name']); if(isset($name['path'])) session_save_path($name['path']); if(isset($name['domain'])) ini_set('session.cookie_domain', $name['domain']); if(isset($name['expire'])) ini_set('session.gc_maxlifetime', $name['expire']); if(isset($name['use_trans_sid'])) ini_set('session.use_trans_sid', $name['use_trans_sid']?1:0); if(isset($name['use_cookies'])) ini_set('session.use_cookies', $name['use_cookies']?1:0); if(isset($name['type'])) C('SESSION_TYPE',$name['type']); if(C('SESSION_TYPE')) { // 读取session驱动 $class = 'Session'. ucwords(strtolower(C('SESSION_TYPE'))); // 检查驱动类 if(require_cache(EXTEND_PATH.'Driver/Session/'.$class.'.class.php')) { $hander = new $class(); $hander->execute(); }else { // 类没有定义 throw_exception(L('_CLASS_NOT_EXIST_').': ' . $class); } } // 启动session if(C('SESSION_AUTO_START')) session_start(); }elseif('' === $value){ if(0===strpos($name,'[')) { // session 操作 if('[pause]'==$name){ // 暂停session session_write_close(); }elseif('[start]'==$name){ // 启动session session_start(); }elseif('[destroy]'==$name){ // 销毁session $_SESSION = array(); session_unset(); session_destroy(); }elseif('[regenerate]'==$name){ // 重新生成id session_regenerate_id(); } }elseif(0===strpos($name,'?')){ // 检查session $name = substr($name,1); if($prefix) { return isset($_SESSION[$prefix][$name]); }else{ return isset($_SESSION[$name]); } }elseif(is_null($name)){ // 清空session if($prefix) { unset($_SESSION[$prefix]); }else{ $_SESSION = array(); } }elseif($prefix){ // 获取session return $_SESSION[$prefix][$name]; }else{ return $_SESSION[$name]; } }elseif(is_null($value)){ // 删除session if($prefix){ unset($_SESSION[$prefix][$name]); }else{ unset($_SESSION[$name]); } }else{ // 设置session if($prefix){ if (!is_array($_SESSION[$prefix])) { $_SESSION[$prefix] = array(); } $_SESSION[$prefix][$name] = $value; }else{ $_SESSION[$name] = $value; } } } // Cookie 设置、获取、删除 function cookie($name, $value='', $option=null) { // 默认设置 $config = array( 'prefix' => C('COOKIE_PREFIX'), // cookie 名称前缀 'expire' => C('COOKIE_EXPIRE'), // cookie 保存时间 'path' => C('COOKIE_PATH'), // cookie 保存路径 'domain' => C('COOKIE_DOMAIN'), // cookie 有效域名 ); // 参数设置(会覆盖黙认设置) if (!empty($option)) { if (is_numeric($option)) $option = array('expire' => $option); elseif (is_string($option)) parse_str($option, $option); $config = array_merge($config, array_change_key_case($option)); } // 清除指定前缀的所有cookie if (is_null($name)) { if (empty($_COOKIE)) return; // 要删除的cookie前缀,不指定则删除config设置的指定前缀 $prefix = empty($value) ? $config['prefix'] : $value; if (!empty($prefix)) {// 如果前缀为空字符串将不作处理直接返回 foreach ($_COOKIE as $key => $val) { if (0 === stripos($key, $prefix)) { setcookie($key, '', time() - 3600, $config['path'], $config['domain']); unset($_COOKIE[$key]); } } } return; } $name = $config['prefix'] . $name; if ('' === $value) { return isset($_COOKIE[$name]) ? $_COOKIE[$name] : null; // 获取指定Cookie } else { if (is_null($value)) { setcookie($name, '', time() - 3600, $config['path'], $config['domain']); unset($_COOKIE[$name]); // 删除指定cookie } else { // 设置cookie $expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0; setcookie($name, $value, $expire, $config['path'], $config['domain']); $_COOKIE[$name] = $value; } } } // 加载扩展配置文件 function load_ext_file() { // 加载自定义外部文件 if(C('LOAD_EXT_FILE')) { $files = explode(',',C('LOAD_EXT_FILE')); foreach ($files as $file){ $file = COMMON_PATH.$file.'.php'; if(is_file($file)) include $file; } } // 加载自定义的动态配置文件 if(C('LOAD_EXT_CONFIG')) { $configs = C('LOAD_EXT_CONFIG'); if(is_string($configs)) $configs = explode(',',$configs); foreach ($configs as $key=>$config){ $file = CONF_PATH.$config.'.php'; if(is_file($file)) { is_numeric($key)?C(include $file):C($key,include $file); } } } } // 获取客户端IP地址 function get_client_ip() { static $ip = NULL; if ($ip !== NULL) return $ip; if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $pos = array_search('unknown',$arr); if(false !== $pos) unset($arr[$pos]); $ip = trim($arr[0]); }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; }elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } // IP地址合法验证 $ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0'; return $ip; } function send_http_status($code) { static $_status = array( // Success 2xx 200 => 'OK', // Redirection 3xx 301 => 'Moved Permanently', 302 => 'Moved Temporarily ', // 1.1 // Client Error 4xx 400 => 'Bad Request', 403 => 'Forbidden', 404 => 'Not Found', // Server Error 5xx 500 => 'Internal Server Error', 503 => 'Service Unavailable', ); if(isset($_status[$code])) { header('HTTP/1.1 '.$code.' '.$_status[$code]); // 确保FastCGI模式下正常 header('Status:'.$code.' '.$_status[$code]); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Common/functions.php
PHP
art
21,598
<?php //平滑函数,sae和本地都可以用,增加系统平滑性 function sae_unlink($filePath) { if (IS_SAE) { $arr = explode('/', ltrim($filePath, './')); $domain = array_shift($arr); $filePath = implode('/', $arr); $s = Think::instance('SaeStorage'); return $s->delete($domain, $filePath); } else { return unlink($filePath); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Common/sae_functions.php
PHP
art
398
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: common.php 2821 2012-03-16 06:17:49Z luofei614@gmail.com $ /** +------------------------------------------------------------------------------ * Think 基础函数库 +------------------------------------------------------------------------------ * @category Think * @package Common * @author liu21st <liu21st@gmail.com> * @version $Id: common.php 2821 2012-03-16 06:17:49Z luofei614@gmail.com $ +------------------------------------------------------------------------------ */ // 记录和统计时间(微秒) function G($start,$end='',$dec=4) { static $_info = array(); if(is_float($end)) { // 记录时间 $_info[$start] = $end; }elseif(!empty($end)){ // 统计时间 if(!isset($_info[$end])) $_info[$end] = microtime(TRUE); return number_format(($_info[$end]-$_info[$start]),$dec); }else{ // 记录时间 $_info[$start] = microtime(TRUE); } } // 设置和获取统计数据 function N($key, $step=0) { static $_num = array(); if (!isset($_num[$key])) { $_num[$key] = 0; } if (empty($step)) return $_num[$key]; else $_num[$key] = $_num[$key] + (int) $step; } /** +---------------------------------------------------------- * 字符串命名风格转换 * type * =0 将Java风格转换为C的风格 * =1 将C风格转换为Java的风格 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $name 字符串 * @param integer $type 转换类型 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ function parse_name($name, $type=0) { if ($type) { return ucfirst(preg_replace("/_([a-zA-Z])/e", "strtoupper('\\1')", $name)); } else { return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_")); } } // 优化的require_once //[sae], 在sae下可以导入sae专用文件 function require_cache($filename) { static $_importFiles = array(); if (!isset($_importFiles[$filename])) { //sae专属文件的文件名为 name_sae.class.php 或 name_sae.php $sae_filename = strpos($filename, 'class.php') ? str_replace('.class.php', '_sae.class.php', $filename) : str_replace('.php', '_sae.php', $filename); $sae_files=C('SAE_SPECIALIZED_FILES');//[sae]读取系统专属文件列表 if (is_file($sae_filename)) { require $sae_filename; $_importFiles[$filename] = true; }elseif(isset($sae_files[basename($filename)])){ require $sae_files[basename($filename)]; $_importFiles[$filename] = true; }elseif (file_exists_case($filename)) { require $filename; $_importFiles[$filename] = true; } else { $_importFiles[$filename] = false; } } return $_importFiles[$filename]; } // 区分大小写的文件存在判断 function file_exists_case($filename) { if (is_file($filename)) { if (IS_WIN && C('APP_FILE_CASE')) { if (basename(realpath($filename)) != basename($filename)) return false; } return true; } return false; } /** +---------------------------------------------------------- * 导入所需的类库 同java的Import * 本函数有缓存功能 +---------------------------------------------------------- * @param string $class 类库命名空间字符串 * @param string $baseUrl 起始路径 * @param string $ext 导入的文件扩展名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ function import($class, $baseUrl = '', $ext='.class.php') { static $_file = array(); $class = str_replace(array('.', '#'), array('/', '.'), $class); if ('' === $baseUrl && false === strpos($class, '/')) { // 检查别名导入 return alias_import($class); } if (isset($_file[$class . $baseUrl])) return true; else $_file[$class . $baseUrl] = true; $class_strut = explode('/', $class); if (empty($baseUrl)) { if ('@' == $class_strut[0] || APP_NAME == $class_strut[0]) { //加载当前项目应用类库 $baseUrl = dirname(LIB_PATH); $class = substr_replace($class, basename(LIB_PATH).'/', 0, strlen($class_strut[0]) + 1); }elseif ('think' == strtolower($class_strut[0])){ // think 官方基类库 $baseUrl = CORE_PATH; $class = substr($class,6); }elseif (in_array(strtolower($class_strut[0]), array('org', 'com'))) { // org 第三方公共类库 com 企业公共类库 $baseUrl = LIBRARY_PATH; }else { // 加载其他项目应用类库 $class = substr_replace($class, '', 0, strlen($class_strut[0]) + 1); $baseUrl = APP_PATH . '../' . $class_strut[0] . '/'.basename(LIB_PATH).'/'; } } if (substr($baseUrl, -1) != '/') $baseUrl .= '/'; $classfile = $baseUrl . $class . $ext; if (!class_exists(basename($class),false)) { // 如果类不存在 则导入类库文件 return require_cache($classfile); } } /** +---------------------------------------------------------- * 基于命名空间方式导入函数库 * load('@.Util.Array') +---------------------------------------------------------- * @param string $name 函数库命名空间字符串 * @param string $baseUrl 起始路径 * @param string $ext 导入的文件扩展名 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ function load($name, $baseUrl='', $ext='.php') { $name = str_replace(array('.', '#'), array('/', '.'), $name); if (empty($baseUrl)) { if (0 === strpos($name, '@/')) { //加载当前项目函数库 $baseUrl = COMMON_PATH; $name = substr($name, 2); } else { //加载ThinkPHP 系统函数库 $baseUrl = EXTEND_PATH . 'Function/'; } } if (substr($baseUrl, -1) != '/') $baseUrl .= '/'; require_cache($baseUrl . $name . $ext); } // 快速导入第三方框架类库 // 所有第三方框架的类库文件统一放到 系统的Vendor目录下面 // 并且默认都是以.php后缀导入 function vendor($class, $baseUrl = '', $ext='.php') { if (empty($baseUrl)) $baseUrl = VENDOR_PATH; return import($class, $baseUrl, $ext); } // 快速定义和导入别名 function alias_import($alias, $classfile='') { static $_alias = array(); if (is_string($alias)) { if(isset($_alias[$alias])) { return require_cache($_alias[$alias]); }elseif ('' !== $classfile) { // 定义别名导入 $_alias[$alias] = $classfile; return; } }elseif (is_array($alias)) { $_alias = array_merge($_alias,$alias); return; } return false; } /** +---------------------------------------------------------- * D函数用于实例化Model 格式 项目://分组/模块 +---------------------------------------------------------- * @param string name Model资源地址 +---------------------------------------------------------- * @return Model +---------------------------------------------------------- */ function D($name='') { if(empty($name)) return new Model; static $_model = array(); if(isset($_model[$name])) return $_model[$name]; if(strpos($name,'://')) {// 指定项目 $name = str_replace('://','/Model/',$name); }else{ $name = C('DEFAULT_APP').'/Model/'.$name; } import($name.'Model'); $class = basename($name.'Model'); if(class_exists($class)) { $model = new $class(); }else { $model = new Model(basename($name)); } $_model[$name] = $model; return $model; } /** +---------------------------------------------------------- * M函数用于实例化一个没有模型文件的Model +---------------------------------------------------------- * @param string name Model名称 支持指定基础模型 例如 MongoModel:User * @param string tablePrefix 表前缀 * @param mixed $connection 数据库连接信息 +---------------------------------------------------------- * @return Model +---------------------------------------------------------- */ function M($name='', $tablePrefix='',$connection='') { static $_model = array(); if(strpos($name,':')) { list($class,$name) = explode(':',$name); }else{ $class = 'Model'; } if (!isset($_model[$name . '_' . $class])) $_model[$name . '_' . $class] = new $class($name,$tablePrefix,$connection); return $_model[$name . '_' . $class]; } /** +---------------------------------------------------------- * A函数用于实例化Action 格式:[项目://][分组/]模块 +---------------------------------------------------------- * @param string name Action资源地址 +---------------------------------------------------------- * @return Action +---------------------------------------------------------- */ function A($name) { static $_action = array(); if(isset($_action[$name])) return $_action[$name]; if(strpos($name,'://')) {// 指定项目 $name = str_replace('://','/Action/',$name); }else{ $name = '@/Action/'.$name; } import($name.'Action'); $class = basename($name.'Action'); if(class_exists($class,false)) { $action = new $class(); $_action[$name] = $action; return $action; }else { return false; } } // 远程调用模块的操作方法 // URL 参数格式 [项目://][分组/]模块/操作 function R($url,$vars=array()) { $info = pathinfo($url); $action = $info['basename']; $module = $info['dirname']; $class = A($module); if($class) return call_user_func_array(array(&$class,$action),$vars); else return false; } // 获取和设置语言定义(不区分大小写) function L($name=null, $value=null) { static $_lang = array(); // 空参数返回所有定义 if (empty($name)) return $_lang; // 判断语言获取(或设置) // 若不存在,直接返回全大写$name if (is_string($name)) { $name = strtoupper($name); if (is_null($value)) return isset($_lang[$name]) ? $_lang[$name] : $name; $_lang[$name] = $value; // 语言定义 return; } // 批量定义 if (is_array($name)) $_lang = array_merge($_lang, array_change_key_case($name, CASE_UPPER)); return; } // 获取配置值 function C($name=null, $value=null) { static $_config = array(); // 无参数时获取所有 if (empty($name)) return $_config; // 优先执行设置获取或赋值 if (is_string($name)) { if (!strpos($name, '.')) { $name = strtolower($name); if (is_null($value)) return isset($_config[$name]) ? $_config[$name] : null; $_config[$name] = is_array($value)?array_change_key_case($value):$value; return; } // 二维数组设置和获取支持 $name = explode('.', $name); $name[0] = strtolower($name[0]); if (is_null($value)) return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null; $_config[$name[0]][$name[1]] = $value; return; } // 批量设置 if (is_array($name)){ return $_config = array_merge($_config, array_change_key_case($name)); } return null; // 避免非法参数 } // 处理标签扩展 function tag($tag, &$params=NULL) { // 系统标签扩展 $extends = C('extends.' . $tag); // 应用标签扩展 $tags = C('tags.' . $tag); if (!empty($tags)) { if(empty($tags['_overlay']) && !empty($extends)) { // 合并扩展 $tags = array_unique(array_merge($extends,$tags)); }elseif(isset($tags['_overlay'])){ // 通过设置 '_overlay'=>1 覆盖系统标签 unset($tags['_overlay']); } }elseif(!empty($extends)) { $tags = $extends; } if($tags) { if(APP_DEBUG) { G($tag.'Start'); Log::record('Tag[ '.$tag.' ] --START--',Log::INFO); } // 执行扩展 foreach ($tags as $key=>$name) { if(!is_int($key)) { // 指定行为类的完整路径 用于模式扩展 $name = $key; } B($name, $params); } if(APP_DEBUG) { // 记录行为的执行日志 Log::record('Tag[ '.$tag.' ] --END-- [ RunTime:'.G($tag.'Start',$tag.'End',6).'s ]',Log::INFO); } }else{ // 未执行任何行为 返回false return false; } } // 动态添加行为扩展到某个标签 function add_tag_behavior($tag,$behavior,$path='') { $array = C('tags.'.$tag); if(!$array) { $array = array(); } if($path) { $array[$behavior] = $path; }else{ $array[] = $behavior; } C('tags.'.$tag,$array); } // 过滤器方法 function filter($name, &$content) { $class = $name . 'Filter'; require_cache(LIB_PATH . 'Filter/' . $class . '.class.php'); $filter = new $class(); $content = $filter->run($content); } // 执行行为 function B($name, &$params=NULL) { $class = $name.'Behavior'; G('behaviorStart'); $behavior = new $class(); $behavior->run($params); if(APP_DEBUG) { // 记录行为的执行日志 G('behaviorEnd'); Log::record('Run '.$name.' Behavior [ RunTime:'.G('behaviorStart','behaviorEnd',6).'s ]',Log::INFO); } } // 渲染输出Widget function W($name, $data=array(), $return=false) { $class = $name . 'Widget'; require_cache(LIB_PATH . 'Widget/' . $class . '.class.php'); if (!class_exists($class)) throw_exception(L('_CLASS_NOT_EXIST_') . ':' . $class); $widget = Think::instance($class); $content = $widget->render($data); if ($return) return $content; else echo $content; } // 去除代码中的空白和注释 function strip_whitespace($content) { $stripStr = ''; //分析php源码 $tokens = token_get_all($content); $last_space = false; for ($i = 0, $j = count($tokens); $i < $j; $i++) { if (is_string($tokens[$i])) { $last_space = false; $stripStr .= $tokens[$i]; } else { switch ($tokens[$i][0]) { //过滤各种PHP注释 case T_COMMENT: case T_DOC_COMMENT: break; //过滤空格 case T_WHITESPACE: if (!$last_space) { $stripStr .= ' '; $last_space = true; } break; case T_START_HEREDOC: $stripStr .= "<<<THINK\n"; break; case T_END_HEREDOC: $stripStr .= "THINK;\n"; for($k = $i+1; $k < $j; $k++) { if(is_string($tokens[$k]) && $tokens[$k] == ';') { $i = $k; break; } else if($tokens[$k][0] == T_CLOSE_TAG) { break; } } break; default: $last_space = false; $stripStr .= $tokens[$i][1]; } } } return $stripStr; } // 循环创建目录 function mk_dir($dir, $mode = 0777) { if (is_dir($dir) || @mkdir($dir, $mode)) return true; if (!mk_dir(dirname($dir), $mode)) return false; return @mkdir($dir, $mode); } //[RUNTIME] //[sae] 在sae下能编译sae专用文件 function compile($filename) { $sae_filename = strpos($filename, 'class.php') ? str_replace('.class.php', '_sae.class.php', $filename) : str_replace('.php', '_sae.php', $filename); $content = is_file($sae_filename) ? file_get_contents($sae_filename) : file_get_contents($filename); // 替换预编译指令 $content = preg_replace('/\/\/\[RUNTIME\](.*?)\/\/\[\/RUNTIME\]/s', '', $content); $content = substr(trim($content), 5); if ('?>' == substr($content, -2)) $content = substr($content, 0, -2); return $content; } // 根据数组生成常量定义 function array_define($array,$check=true) { $content = "\n"; foreach ($array as $key => $val) { $key = strtoupper($key); if($check) $content .= 'defined(\'' . $key . '\') or '; if (is_int($val) || is_float($val)) { $content .= "define('" . $key . "'," . $val . ');'; } elseif (is_bool($val)) { $val = ($val) ? 'true' : 'false'; $content .= "define('" . $key . "'," . $val . ');'; } elseif (is_string($val)) { $content .= "define('" . $key . "','" . addslashes($val) . "');"; } $content .= "\n"; } return $content; } //[/RUNTIME]
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Common/common.php
PHP
art
18,590
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: runtime.php 2821 2012-03-16 06:17:49Z luofei614@gmail.com $ /** +------------------------------------------------------------------------------ * ThinkPHP 运行时文件 编译后不再加载 +------------------------------------------------------------------------------ */ if (!defined('THINK_PATH')) exit(); if (version_compare(PHP_VERSION, '5.2.0', '<')) die('require PHP > 5.2.0 !'); // 版本信息 define('THINK_VERSION', '3.0'); define('THINK_RELEASE', '20120313'); // 系统信息 if(version_compare(PHP_VERSION,'5.4.0','<') ) { //[sae]下不支持这个函数 //@set_magic_quotes_runtime (0); define('MAGIC_QUOTES_GPC',get_magic_quotes_gpc()?True:False); } define('IS_CGI',substr(PHP_SAPI, 0,3)=='cgi' ? 1 : 0 ); define('IS_WIN',strstr(PHP_OS, 'WIN') ? 1 : 0 ); define('IS_CLI',PHP_SAPI=='cli'? 1 : 0); // 项目名称 defined('APP_NAME') or define('APP_NAME', basename(dirname($_SERVER['SCRIPT_FILENAME']))); if(!IS_CLI) { // 当前文件名 if(!defined('_PHP_FILE_')) { if(IS_CGI) { //CGI/FASTCGI模式下 $_temp = explode('.php',$_SERVER['PHP_SELF']); define('_PHP_FILE_', rtrim(str_replace($_SERVER['HTTP_HOST'],'',$_temp[0].'.php'),'/')); }else { define('_PHP_FILE_', rtrim($_SERVER['SCRIPT_NAME'],'/')); } } if(!defined('__ROOT__')) { // 网站URL根目录 if( strtoupper(APP_NAME) == strtoupper(basename(dirname(_PHP_FILE_))) ) { $_root = dirname(dirname(_PHP_FILE_)); }else { $_root = dirname(_PHP_FILE_); } define('__ROOT__', (($_root=='/' || $_root=='\\')?'':$_root)); } //支持的URL模式 define('URL_COMMON', 0); //普通模式 define('URL_PATHINFO', 1); //PATHINFO模式 define('URL_REWRITE', 2); //REWRITE模式 define('URL_COMPAT', 3); // 兼容模式 } // 路径设置 可在入口文件中重新定义 所有路径常量都必须以/ 结尾 defined('CORE_PATH') or define('CORE_PATH',THINK_PATH.'Lib/'); // 系统核心类库目录 defined('EXTEND_PATH') or define('EXTEND_PATH',THINK_PATH.'Extend/'); // 系统扩展目录 defined('MODE_PATH') or define('MODE_PATH',EXTEND_PATH.'Mode/'); // 模式扩展目录 defined('ENGINE_PATH') or define('ENGINE_PATH',EXTEND_PATH.'Engine/'); // 引擎扩展目录// 系统模式目录 defined('VENDOR_PATH') or define('VENDOR_PATH',EXTEND_PATH.'Vendor/'); // 第三方类库目录 defined('LIBRARY_PATH') or define('LIBRARY_PATH',EXTEND_PATH.'Library/'); // 扩展类库目录 defined('COMMON_PATH') or define('COMMON_PATH', APP_PATH.'Common/'); // 项目公共目录 defined('LIB_PATH') or define('LIB_PATH', APP_PATH.'Lib/'); // 项目类库目录 defined('CONF_PATH') or define('CONF_PATH', APP_PATH.'Conf/'); // 项目配置目录 defined('LANG_PATH') or define('LANG_PATH', APP_PATH.'Lang/'); // 项目语言包目录 defined('TMPL_PATH') or define('TMPL_PATH',APP_PATH.'Tpl/'); // 项目模板目录 defined('HTML_PATH') or define('HTML_PATH',$_SERVER['HTTP_APPVERSION'].'/html/'); //[sae] 项目静态目录,静态文件会存到KVDB defined('LOG_PATH') or define('LOG_PATH', RUNTIME_PATH.'Logs/'); // 项目日志目录 defined('TEMP_PATH') or define('TEMP_PATH', RUNTIME_PATH.'Temp/'); // 项目缓存目录 defined('DATA_PATH') or define('DATA_PATH', RUNTIME_PATH.'Data/'); // 项目数据目录 defined('CACHE_PATH') or define('CACHE_PATH', RUNTIME_PATH.'Cache/'); // 项目模板缓存目录 // 为了方便导入第三方类库 设置Vendor目录到include_path set_include_path(get_include_path() . PATH_SEPARATOR . VENDOR_PATH); // 加载运行时所需要的文件 并负责自动目录生成 function load_runtime_file() { //[sae] 加载系统基础函数库 require SAE_PATH.'Common/common.php'; //[sae] 读取核心编译文件列表 $list = array( SAE_PATH.'Lib/Core/Think.class.php', CORE_PATH.'Core/ThinkException.class.php', // 异常处理类 CORE_PATH.'Core/Behavior.class.php', ); // 加载模式文件列表 foreach ($list as $key=>$file){ if(is_file($file)) require_cache($file); } //[sae] 加载系统类库别名定义 alias_import(include SAE_PATH.'Conf/alias.php'); //[sae]在sae下不对目录结构进行检查 if(APP_DEBUG){ //[sae] 调试模式切换删除编译缓存 if(SaeMC::file_exists(RUNTIME_FILE)) SaeMC::unlink(RUNTIME_FILE) ; } } //[sae]下,不需要生成检查runtime目录函数 // 创建编译缓存 function build_runtime_cache($append='') { // 生成编译文件 $defs = get_defined_constants(TRUE); $content = '$GLOBALS[\'_beginTime\'] = microtime(TRUE);'; //[sae]编译SaeMC核心 $content.=compile(SAE_PATH.'Lib/Core/SaeMC.class.php'); if(defined('RUNTIME_DEF_FILE')) { //[sae] 编译后的常量文件外部引入 SaeMC::set(RUNTIME_DEF_FILE, '<?php '.array_define($defs['user'])); $content .= 'SaeMC::include_file(\''.RUNTIME_DEF_FILE.'\');'; }else{ $content .= array_define($defs['user']); } $content .= 'set_include_path(get_include_path() . PATH_SEPARATOR . VENDOR_PATH);'; //[sae] 读取核心编译文件列表 $list = array( SAE_PATH.'Common/common.php', SAE_PATH.'Lib/Core/Think.class.php', CORE_PATH.'Core/ThinkException.class.php', CORE_PATH.'Core/Behavior.class.php', ); foreach ($list as $file){ $content .= compile($file); } // 系统行为扩展文件统一编译 if(C('APP_TAGS_ON')) { $content .= build_tags_cache(); } //[sae] 编译SAE的alias $alias = include SAE_PATH.'Conf/alias.php'; $content .= 'alias_import('.var_export($alias,true).');'; // 编译框架默认语言包和配置参数 $content .= $append."\nL(".var_export(L(),true).");C(".var_export(C(),true).');G(\'loadTime\');Think::Start();'; //[sae] 生成编译缓存文件 SaeMC::set(RUNTIME_FILE, strip_whitespace('<?php '.$content)); } // 编译系统行为扩展类库 function build_tags_cache() { $tags = C('extends'); $content = ''; foreach ($tags as $tag=>$item){ foreach ($item as $key=>$name) { $content .= is_int($key)?compile(CORE_PATH.'Behavior/'.$name.'Behavior.class.php'):compile($name); } } return $content; } //[sae]下,不需要生成目录结构函数 // 加载运行时所需文件 load_runtime_file(); // 记录加载文件时间 G('loadTime'); // 执行入口 Think::Start();
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Common/runtime.php
PHP
art
7,359
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: ThinkTemplate.class.php 2821 2012-03-16 06:17:49Z luofei614@gmail.com $ /** +------------------------------------------------------------------------------ * ThinkPHP内置模板引擎类 * 支持XML标签和普通标签的模板解析 * 编译型模板引擎 支持动态缓存 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Template * @author liu21st <liu21st@gmail.com> * @version $Id: ThinkTemplate.class.php 2821 2012-03-16 06:17:49Z luofei614@gmail.com $ +------------------------------------------------------------------------------ */ class ThinkTemplate { // 模板页面中引入的标签库列表 protected $tagLib = array(); // 当前模板文件 protected $templateFile = ''; // 模板变量 public $tVar = array(); public $config = array(); private $literal = array(); /** +---------------------------------------------------------- * 取得模板实例对象 * 静态方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return ThinkTemplate +---------------------------------------------------------- */ static public function getInstance() { return get_instance_of(__CLASS__); } /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $config 模板引擎配置数组 +---------------------------------------------------------- */ public function __construct(){ //[sae] 不用此项 $this->config['cache_path'] = C('CACHE_PATH'); $this->config['template_suffix'] = C('TMPL_TEMPLATE_SUFFIX'); $this->config['cache_suffix'] = C('TMPL_CACHFILE_SUFFIX'); $this->config['tmpl_cache'] = C('TMPL_CACHE_ON'); $this->config['cache_time'] = C('TMPL_CACHE_TIME'); $this->config['taglib_begin'] = $this->stripPreg(C('TAGLIB_BEGIN')); $this->config['taglib_end'] = $this->stripPreg(C('TAGLIB_END')); $this->config['tmpl_begin'] = $this->stripPreg(C('TMPL_L_DELIM')); $this->config['tmpl_end'] = $this->stripPreg(C('TMPL_R_DELIM')); $this->config['default_tmpl'] = C('TEMPLATE_NAME'); $this->config['layout_item'] = C('TMPL_LAYOUT_ITEM'); } private function stripPreg($str) { return str_replace(array('{','}','(',')','|','[',']'),array('\{','\}','\(','\)','\|','\[','\]'),$str); } // 模板变量获取和设置 public function get($name) { if(isset($this->tVar[$name])) return $this->tVar[$name]; else return false; } public function set($name,$value) { $this->tVar[$name]= $value; } // 加载模板 public function fetch($templateFile,$templateVar) { $this->tVar = $templateVar; $templateCacheFile = $this->loadTemplate($templateFile); //[sae]载入模版缓存文件 SaeMC::include_file($templateCacheFile,$templateVar); } /** +---------------------------------------------------------- * 加载主模板并缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $tmplTemplateFile 模板文件 +---------------------------------------------------------- * @return string +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function loadTemplate ($tmplTemplateFile) { $this->templateFile = $tmplTemplateFile; //[sae] 根据模版文件名定位缓存文件 $tmplCacheFile = md5($tmplTemplateFile).$this->config['cache_suffix']; // 读取模板文件内容 $tmplContent = file_get_contents($tmplTemplateFile); // 判断是否启用布局 if(C('LAYOUT_ON')) { if(false !== strpos($tmplContent,'{__NOLAYOUT__}')) { // 可以单独定义不使用布局 $tmplContent = str_replace('{__NOLAYOUT__}','',$tmplContent); }else{ // 替换布局的主体内容 $layoutFile = THEME_PATH.C('LAYOUT_NAME').$this->config['template_suffix']; $tmplContent = str_replace($this->config['layout_item'],$tmplContent,file_get_contents($layoutFile)); } } //编译模板内容 $tmplContent = $this->compiler($tmplContent); //[sae]去掉检测分组目录 //[sae]重写Cache文件 SaeMC::set($tmplCacheFile, trim($tmplContent)); return $tmplCacheFile; } /** +---------------------------------------------------------- * 编译模板文件内容 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $tmplContent 模板内容 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function compiler($tmplContent) { //模板解析 $tmplContent = $this->parse($tmplContent); // 还原被替换的Literal标签 $tmplContent = preg_replace('/<!--###literal(\d)###-->/eis',"\$this->restoreLiteral('\\1')",$tmplContent); // 添加安全代码 $tmplContent = '<?php if (!defined(\'THINK_PATH\')) exit();?>'.$tmplContent; if(C('TMPL_STRIP_SPACE')) { /* 去除html空格与换行 */ $find = array("~>\s+<~","~>(\s+\n|\r)~"); $replace = array('><','>'); $tmplContent = preg_replace($find, $replace, $tmplContent); } // 优化生成的php代码 $tmplContent = str_replace('?><?php','',$tmplContent); return strip_whitespace($tmplContent); } /** +---------------------------------------------------------- * 模板解析入口 * 支持普通标签和TagLib解析 支持自定义标签库 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $content 要解析的模板内容 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function parse($content) { // 内容为空不解析 if(empty($content)) return ''; $begin = $this->config['taglib_begin']; $end = $this->config['taglib_end']; // 首先替换literal标签内容 $content = preg_replace('/'.$begin.'literal'.$end.'(.*?)'.$begin.'\/literal'.$end.'/eis',"\$this->parseLiteral('\\1')",$content); // 检查include语法 $content = $this->parseInclude($content); // 检查PHP语法 $content = $this->parsePhp($content); // 获取需要引入的标签库列表 // 标签库只需要定义一次,允许引入多个一次 // 一般放在文件的最前面 // 格式:<taglib name="html,mytag..." /> // 当TAGLIB_LOAD配置为true时才会进行检测 if(C('TAGLIB_LOAD')) { $this->getIncludeTagLib($content); if(!empty($this->tagLib)) { // 对导入的TagLib进行解析 foreach($this->tagLib as $tagLibName) { $this->parseTagLib($tagLibName,$content); } } } // 预先加载的标签库 无需在每个模板中使用taglib标签加载 但必须使用标签库XML前缀 if(C('TAGLIB_PRE_LOAD')) { $tagLibs = explode(',',C('TAGLIB_PRE_LOAD')); foreach ($tagLibs as $tag){ $this->parseTagLib($tag,$content); } } // 内置标签库 无需使用taglib标签导入就可以使用 并且不需使用标签库XML前缀 $tagLibs = explode(',',C('TAGLIB_BUILD_IN')); foreach ($tagLibs as $tag){ $this->parseTagLib($tag,$content,true); } //解析普通模板标签 {tagName} $content = preg_replace('/('.$this->config['tmpl_begin'].')(\S.+?)('.$this->config['tmpl_end'].')/eis',"\$this->parseTag('\\2')",$content); return $content; } // 检查PHP语法 protected function parsePhp($content) { // PHP语法检查 if(C('TMPL_DENY_PHP') && false !== strpos($content,'<?php')) { throw_exception(L('_NOT_ALLOW_PHP_')); }elseif(ini_get('short_open_tag')){ // 开启短标签的情况要将<?标签用echo方式输出 否则无法正常输出xml标识 $content = preg_replace('/(<\?(?!php|=|$))/i', '<?php echo \'\\1\'; ?>'."\n", $content ); } return $content; } // 解析模板中的布局标签 protected function parseLayout($content) { // 读取模板中的布局标签 $find = preg_match('/'.$this->config['taglib_begin'].'layout\s(.+?)\s*?\/'.$this->config['taglib_end'].'/is',$content,$matches); if($find) { //替换Layout标签 $content = str_replace($matches[0],'',$content); //解析Layout标签 $layout = $matches[1]; $xml = '<tpl><tag '.$layout.' /></tpl>'; $xml = simplexml_load_string($xml); if(!$xml) throw_exception(L('_XML_TAG_ERROR_')); $xml = (array)($xml->tag->attributes()); $array = array_change_key_case($xml['@attributes']); if(!C('LAYOUT_ON') || C('LAYOUT_NAME') !=$array['name'] ) { // 读取布局模板 $layoutFile = THEME_PATH.$array['name'].$this->config['template_suffix']; $replace = isset($array['replace'])?$array['replace']:$this->config['layout_item']; // 替换布局的主体内容 $content = str_replace($replace,$content,file_get_contents($layoutFile)); } } return $content; } // 解析模板中的include标签 protected function parseInclude($content) { // 解析布局 $content = $this->parseLayout($content); // 读取模板中的布局标签 $find = preg_match_all('/'.$this->config['taglib_begin'].'include\s(.+?)\s*?\/'.$this->config['taglib_end'].'/is',$content,$matches); if($find) { for($i=0;$i<$find;$i++) { $include = $matches[1][$i]; $xml = '<tpl><tag '.$include.' /></tpl>'; $xml = simplexml_load_string($xml); if(!$xml) throw_exception(L('_XML_TAG_ERROR_')); $xml = (array)($xml->tag->attributes()); $array = array_change_key_case($xml['@attributes']); $file = $array['file']; unset($array['file']); $content = str_replace($matches[0][$i],$this->parseIncludeItem($file,$array),$content); } } return $content; } /** +---------------------------------------------------------- * 替换页面中的literal标签 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param string $content 模板内容 +---------------------------------------------------------- * @return string|false +---------------------------------------------------------- */ private function parseLiteral($content) { if(trim($content)=='') return ''; $content = stripslashes($content); $i = count($this->literal); $parseStr = "<!--###literal{$i}###-->"; $this->literal[$i] = $content; return $parseStr; } /** +---------------------------------------------------------- * 还原被替换的literal标签 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param string $tag literal标签序号 +---------------------------------------------------------- * @return string|false +---------------------------------------------------------- */ private function restoreLiteral($tag) { // 还原literal标签 $parseStr = $this->literal[$tag]; // 销毁literal记录 unset($this->literal[$tag]); return $parseStr; } /** +---------------------------------------------------------- * 搜索模板页面中包含的TagLib库 * 并返回列表 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $content 模板内容 +---------------------------------------------------------- * @return string|false +---------------------------------------------------------- */ public function getIncludeTagLib(& $content) { //搜索是否有TagLib标签 $find = preg_match('/'.$this->config['taglib_begin'].'taglib\s(.+?)(\s*?)\/'.$this->config['taglib_end'].'\W/is',$content,$matches); if($find) { //替换TagLib标签 $content = str_replace($matches[0],'',$content); //解析TagLib标签 $tagLibs = $matches[1]; $xml = '<tpl><tag '.$tagLibs.' /></tpl>'; $xml = simplexml_load_string($xml); if(!$xml) throw_exception(L('_XML_TAG_ERROR_')); $xml = (array)($xml->tag->attributes()); $array = array_change_key_case($xml['@attributes']); $this->tagLib = explode(',',$array['name']); } return; } /** +---------------------------------------------------------- * TagLib库解析 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $tagLib 要解析的标签库 * @param string $content 要解析的模板内容 * @param boolen $hide 是否隐藏标签库前缀 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function parseTagLib($tagLib,&$content,$hide=false) { $begin = $this->config['taglib_begin']; $end = $this->config['taglib_end']; $className = 'TagLib'.ucwords($tagLib); if(!import($className)) { if(is_file(EXTEND_PATH.'Driver/TagLib/'.$className.'.class.php')) { // 扩展标签库优先识别 $file = EXTEND_PATH.'Driver/TagLib/'.$className.'.class.php'; }else{ // 系统目录下面的标签库 $file = CORE_PATH.'Driver/TagLib/'.$className.'.class.php'; } require_cache($file); } $tLib = Think::instance($className); foreach ($tLib->getTags() as $name=>$val){ $tags = array($name); if(isset($val['alias'])) {// 别名设置 $tags = explode(',',$val['alias']); $tags[] = $name; } $level = isset($val['level'])?$val['level']:1; $closeTag = isset($val['close'])?$val['close']:true; foreach ($tags as $tag){ $parseTag = !$hide? $tagLib.':'.$tag: $tag;// 实际要解析的标签名称 if(!method_exists($tLib,'_'.$tag)) { // 别名可以无需定义解析方法 $tag = $name; } $n1 = empty($val['attr'])?'(\s*?)':'\s(.*?)'; if (!$closeTag){ $patterns = '/'.$begin.$parseTag.$n1.'\/(\s*?)'.$end.'/eis'; $replacement = "\$this->parseXmlTag('$tagLib','$tag','$1','')"; $content = preg_replace($patterns, $replacement,$content); }else{ $patterns = '/'.$begin.$parseTag.$n1.$end.'(.*?)'.$begin.'\/'.$parseTag.'(\s*?)'.$end.'/eis'; $replacement = "\$this->parseXmlTag('$tagLib','$tag','$1','$2')"; for($i=0;$i<$level;$i++) $content=preg_replace($patterns,$replacement,$content); } } } } /** +---------------------------------------------------------- * 解析标签库的标签 * 需要调用对应的标签库文件解析类 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $tagLib 标签库名称 * @param string $tag 标签名 * @param string $attr 标签属性 * @param string $content 标签内容 +---------------------------------------------------------- * @return string|false +---------------------------------------------------------- */ public function parseXmlTag($tagLib,$tag,$attr,$content) { //if (MAGIC_QUOTES_GPC) { $attr = stripslashes($attr); $content = stripslashes($content); //} if(ini_get('magic_quotes_sybase')) $attr = str_replace('\"','\'',$attr); $tLib = Think::instance('TagLib'.ucwords(strtolower($tagLib))); $parse = '_'.$tag; $content = trim($content); return $tLib->$parse($attr,$content); } /** +---------------------------------------------------------- * 模板标签解析 * 格式: {TagName:args [|content] } +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $tagStr 标签内容 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function parseTag($tagStr){ //if (MAGIC_QUOTES_GPC) { $tagStr = stripslashes($tagStr); //} //还原非模板标签 if(preg_match('/^[\s|\d]/is',$tagStr)) //过滤空格和数字打头的标签 return C('TMPL_L_DELIM') . $tagStr .C('TMPL_R_DELIM'); $flag = substr($tagStr,0,1); $name = substr($tagStr,1); if('$' == $flag){ //解析模板变量 格式 {$varName} return $this->parseVar($name); }elseif('-' == $flag || '+'== $flag){ // 输出计算 return '<?php echo '.$flag.$name.';?>'; }elseif(':' == $flag){ // 输出某个函数的结果 return '<?php echo '.$name.';?>'; }elseif('~' == $flag){ // 执行某个函数 return '<?php '.$name.';?>'; }elseif(substr($tagStr,0,2)=='//' || (substr($tagStr,0,2)=='/*' && substr($tagStr,-2)=='*/')){ //注释标签 return ''; } // 未识别的标签直接返回 return C('TMPL_L_DELIM') . $tagStr .C('TMPL_R_DELIM'); } /** +---------------------------------------------------------- * 模板变量解析,支持使用函数 * 格式: {$varname|function1|function2=arg1,arg2} +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $varStr 变量数据 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function parseVar($varStr){ $varStr = trim($varStr); static $_varParseList = array(); //如果已经解析过该变量字串,则直接返回变量值 if(isset($_varParseList[$varStr])) return $_varParseList[$varStr]; $parseStr =''; $varExists = true; if(!empty($varStr)){ $varArray = explode('|',$varStr); //取得变量名称 $var = array_shift($varArray); //非法变量过滤 不允许在变量里面使用 -> //TODO:还需要继续完善 if(preg_match('/->/is',$var)) return ''; if('Think.' == substr($var,0,6)){ // 所有以Think.打头的以特殊变量对待 无需模板赋值就可以输出 $name = $this->parseThinkVar($var); }elseif( false !== strpos($var,'.')) { //支持 {$var.property} $vars = explode('.',$var); $var = array_shift($vars); switch(strtolower(C('TMPL_VAR_IDENTIFY'))) { case 'array': // 识别为数组 $name = '$'.$var; foreach ($vars as $key=>$val) $name .= '["'.$val.'"]'; break; case 'obj': // 识别为对象 $name = '$'.$var; foreach ($vars as $key=>$val) $name .= '->'.$val; break; default: // 自动判断数组或对象 只支持二维 $name = 'is_array($'.$var.')?$'.$var.'["'.$vars[0].'"]:$'.$var.'->'.$vars[0]; } }elseif(false !==strpos($var,':')){ //支持 {$var:property} 方式输出对象的属性 $vars = explode(':',$var); $var = str_replace(':','->',$var); $name = "$".$var; $var = $vars[0]; }elseif(false !== strpos($var,'[')) { //支持 {$var['key']} 方式输出数组 $name = "$".$var; preg_match('/(.+?)\[(.+?)\]/is',$var,$match); $var = $match[1]; }else { $name = "$$var"; } //对变量使用函数 if(count($varArray)>0) $name = $this->parseVarFunction($name,$varArray); $parseStr = '<?php echo ('.$name.'); ?>'; } $_varParseList[$varStr] = $parseStr; return $parseStr; } /** +---------------------------------------------------------- * 对模板变量使用函数 * 格式 {$varname|function1|function2=arg1,arg2} +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 变量名 * @param array $varArray 函数列表 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function parseVarFunction($name,$varArray){ //对变量使用函数 $length = count($varArray); //取得模板禁止使用函数列表 $template_deny_funs = explode(',',C('TMPL_DENY_FUNC_LIST')); for($i=0;$i<$length ;$i++ ){ $args = explode('=',$varArray[$i],2); //模板函数过滤 $fun = strtolower(trim($args[0])); switch($fun) { case 'default': // 特殊模板函数 $name = '('.$name.')?('.$name.'):'.$args[1]; break; default: // 通用模板函数 if(!in_array($fun,$template_deny_funs)){ if(isset($args[1])){ if(strstr($args[1],'###')){ $args[1] = str_replace('###',$name,$args[1]); $name = "$fun($args[1])"; }else{ $name = "$fun($name,$args[1])"; } }else if(!empty($args[0])){ $name = "$fun($name)"; } } } } return $name; } /** +---------------------------------------------------------- * 特殊模板变量解析 * 格式 以 $Think. 打头的变量属于特殊模板变量 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $varStr 变量字符串 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function parseThinkVar($varStr){ $vars = explode('.',$varStr); $vars[1] = strtoupper(trim($vars[1])); $parseStr = ''; if(count($vars)>=3){ $vars[2] = trim($vars[2]); switch($vars[1]){ case 'SERVER': $parseStr = '$_SERVER[\''.strtoupper($vars[2]).'\']';break; case 'GET': $parseStr = '$_GET[\''.$vars[2].'\']';break; case 'POST': $parseStr = '$_POST[\''.$vars[2].'\']';break; case 'COOKIE': if(isset($vars[3])) { $parseStr = '$_COOKIE[\''.$vars[2].'\'][\''.$vars[3].'\']'; }else{ $parseStr = '$_COOKIE[\''.$vars[2].'\']'; }break; case 'SESSION': if(isset($vars[3])) { $parseStr = '$_SESSION[\''.$vars[2].'\'][\''.$vars[3].'\']'; }else{ $parseStr = '$_SESSION[\''.$vars[2].'\']'; } break; case 'ENV': $parseStr = '$_ENV[\''.strtoupper($vars[2]).'\']';break; case 'REQUEST': $parseStr = '$_REQUEST[\''.$vars[2].'\']';break; case 'CONST': $parseStr = strtoupper($vars[2]);break; case 'LANG': $parseStr = 'L("'.$vars[2].'")';break; case 'CONFIG': if(isset($vars[3])) { $vars[2] .= '.'.$vars[3]; } $parseStr = 'C("'.$vars[2].'")';break; default:break; } }else if(count($vars)==2){ switch($vars[1]){ case 'NOW': $parseStr = "date('Y-m-d g:i a',time())"; break; case 'VERSION': $parseStr = 'THINK_VERSION'; break; case 'TEMPLATE': $parseStr = "'".$this->templateFile."'";//'C("TEMPLATE_NAME")'; break; case 'LDELIM': $parseStr = 'C("TMPL_L_DELIM")'; break; case 'RDELIM': $parseStr = 'C("TMPL_R_DELIM")'; break; default: if(defined($vars[1])) $parseStr = $vars[1]; } } return $parseStr; } /** +---------------------------------------------------------- * 加载公共模板并缓存 和当前模板在同一路径,否则使用相对路径 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $tmplPublicName 公共模板文件名 * @param array $vars 要传递的变量列表 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseIncludeItem($tmplPublicName,$vars=array()){ if(substr($tmplPublicName,0,1)=='$') //支持加载变量文件名 $tmplPublicName = $this->get(substr($tmplPublicName,1)); if(false === strpos($tmplPublicName,$this->config['template_suffix'])) { // 解析规则为 模板主题:模块:操作 不支持 跨项目和跨分组调用 $path = explode(':',$tmplPublicName); $action = array_pop($path); $module = !empty($path)?array_pop($path):MODULE_NAME; if(!empty($path)) {// 设置模板主题 $path = dirname(THEME_PATH).'/'.array_pop($path).'/'; }else{ $path = THEME_PATH; } $depr = defined('GROUP_NAME')?C('TMPL_FILE_DEPR'):'/'; $tmplPublicName = $path.$module.$depr.$action.$this->config['template_suffix']; } // 获取模板文件内容 $parseStr = file_get_contents($tmplPublicName); foreach ($vars as $key=>$val) { $parseStr = str_replace('['.$key.']',$val,$parseStr); } //再次对包含文件进行模板分析 return $this->parseInclude($parseStr); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Lib/Template/ThinkTemplate.class.php
PHP
art
30,895
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: ParseTemplateBehavior.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ /** +------------------------------------------------------------------------------ * 系统行为扩展 模板解析 +------------------------------------------------------------------------------ */ class ParseTemplateBehavior extends Behavior { // 行为参数定义(默认值) 可在项目配置中覆盖 protected $options = array( // 布局设置 'TMPL_ENGINE_TYPE' => 'Think', // 默认模板引擎 以下设置仅对使用Think模板引擎有效 'TMPL_CACHFILE_SUFFIX' => '.php', // 默认模板缓存后缀 'TMPL_DENY_FUNC_LIST' => 'echo,exit', // 模板引擎禁用函数 'TMPL_DENY_PHP' =>false, // 默认模板引擎是否禁用PHP原生代码 'TMPL_L_DELIM' => '{', // 模板引擎普通标签开始标记 'TMPL_R_DELIM' => '}', // 模板引擎普通标签结束标记 'TMPL_VAR_IDENTIFY' => 'array', // 模板变量识别。留空自动判断,参数为'obj'则表示对象 'TMPL_STRIP_SPACE' => true, // 是否去除模板文件里面的html空格与换行 'TMPL_CACHE_ON' => true, // 是否开启模板编译缓存,设为false则每次都会重新编译 'TMPL_CACHE_TIME' => 0, // 模板缓存有效期 0 为永久,(以数字为值,单位:秒) 'TMPL_LAYOUT_ITEM' => '{__CONTENT__}', // 布局模板的内容替换标识 'LAYOUT_ON' => false, // 是否启用布局 'LAYOUT_NAME' => 'layout', // 当前布局名称 默认为layout // Think模板引擎标签库相关设定 'TAGLIB_BEGIN' => '<', // 标签库标签开始标记 'TAGLIB_END' => '>', // 标签库标签结束标记 'TAGLIB_LOAD' => true, // 是否使用内置标签库之外的其它标签库,默认自动检测 'TAGLIB_BUILD_IN' => 'cx', // 内置标签库名称(标签使用不必指定标签库名称),以逗号分隔 注意解析顺序 'TAGLIB_PRE_LOAD' => '', // 需要额外加载的标签库(须指定标签库名称),多个以逗号分隔 ); // 行为扩展的执行入口必须是run public function run(&$_data){ $engine = strtolower(C('TMPL_ENGINE_TYPE')); if('think'==$engine){ //[sae] 采用Think模板引擎 if($this->checkCache($_data['file'])) { // 缓存有效 SaeMC::include_file(md5($_data['file']).C('TMPL_CACHFILE_SUFFIX'),$_data['var']); }else{ $tpl = Think::instance('ThinkTemplate'); // 编译并加载模板文件 $tpl->fetch($_data['file'],$_data['var']); } }else{ // 调用第三方模板引擎解析和输出 $class = 'Template'.ucwords($engine); if(is_file(CORE_PATH.'Driver/Template/'.$class.'.class.php')) { // 内置驱动 $path = CORE_PATH; }else{ // 扩展驱动 $path = EXTEND_PATH; } if(require_cache($path.'Driver/Template/'.$class.'.class.php')) { $tpl = new $class; $tpl->fetch($_data['file'],$_data['var']); }else { // 类没有定义 throw_exception(L('_NOT_SUPPERT_').': ' . $class); } } //[sae] 添加trace信息。 trace(array( '[SAE]核心缓存'=>$_SERVER['HTTP_APPVERSION'].'/'.RUNTIME_FILE, '[SAE]模板缓存'=>$_SERVER['HTTP_APPVERSION'].'/'.md5($_data['file']).C('TMPL_CACHFILE_SUFFIX') )); } /** +---------------------------------------------------------- * 检查缓存文件是否有效 * 如果无效则需要重新编译 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $tmplTemplateFile 模板文件名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ //[sae] 检查模版 protected function checkCache($tmplTemplateFile) { if (!C('TMPL_CACHE_ON')) // 优先对配置设定检测 return false; //[sae] 不加模版目录,简化模版名称 $tmplCacheFile = md5($tmplTemplateFile).C('TMPL_CACHFILE_SUFFIX'); if(!SaeMC::file_exists($tmplCacheFile)){ return false; //}elseif (filemtime($tmplTemplateFile) > filemtime($tmplCacheFile)) { }elseif (filemtime($tmplTemplateFile) > SaeMC::filemtime($tmplCacheFile)) { // 模板文件如果有更新则缓存需要更新 return false; }elseif (C('TMPL_CACHE_TIME') != 0 && time() > SaeMC::filemtime($tmplCacheFile)+C('TMPL_CACHE_TIME')) { // 缓存是否在有效期 return false; } // 开启布局模板 if(C('LAYOUT_ON')) { $layoutFile = THEME_PATH.C('LAYOUT_NAME').C('TMPL_TEMPLATE_SUFFIX'); if(filemtime($layoutFile) > SaeMC::filemtime($tmplCacheFile)) { return false; } } // 缓存有效 return true; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Lib/Behavior/ParseTemplateBehavior.class.php
PHP
art
6,113
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: WriteHtmlCacheBehavior.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ /** +------------------------------------------------------------------------------ * 系统行为扩展 静态缓存写入 * 增加配置参数如下: +------------------------------------------------------------------------------ */ class WriteHtmlCacheBehavior extends Behavior { // 行为扩展的执行入口必须是run public function run(&$content){ if(C('HTML_CACHE_ON') && defined('HTML_FILE_NAME')) { //静态文件写入 // 如果开启HTML功能 检查并重写HTML文件 // 没有模版的操作不生成静态文件 //[sae] 生成静态缓存 $kv = Think::instance('SaeKVClient'); if (!$kv->init()) halt('您没有初始化KVDB,请在SAE平台进行初始化'); trace('[SAE]静态缓存',HTML_FILE_NAME); $kv->set(HTML_FILE_NAME,time().$content); } } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Lib/Behavior/WriteHtmlCacheBehavior.class.php
PHP
art
1,639
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: ReadHtmlCacheBehavior.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ /** +------------------------------------------------------------------------------ * 系统行为扩展 静态缓存读取 +------------------------------------------------------------------------------ */ class ReadHtmlCacheBehavior extends Behavior { protected $options = array( 'HTML_CACHE_ON'=>false, 'HTML_CACHE_TIME'=>60, 'HTML_CACHE_RULES'=>array(), 'HTML_FILE_SUFFIX'=>'.html', ); static protected $html_content='';//[sae] 存储html内容 // 行为扩展的执行入口必须是run public function run(&$params){ // 开启静态缓存 if(C('HTML_CACHE_ON')) { if(($cacheTime = $this->requireHtmlCache()) && $this->checkHTMLCache(HTML_FILE_NAME,$cacheTime)) { //静态页面有效 //[sae] 读取静态页面输出 exit(self::$html_content); } } } // 判断是否需要静态缓存 static private function requireHtmlCache() { // 分析当前的静态规则 $htmls = C('HTML_CACHE_RULES'); // 读取静态规则 if(!empty($htmls)) { // 静态规则文件定义格式 actionName=>array(‘静态规则’,’缓存时间’,’附加规则') // 'read'=>array('{id},{name}',60,'md5') 必须保证静态规则的唯一性 和 可判断性 // 检测静态规则 $moduleName = strtolower(MODULE_NAME); if(isset($htmls[$moduleName.':'.ACTION_NAME])) { $html = $htmls[$moduleName.':'.ACTION_NAME]; // 某个模块的操作的静态规则 }elseif(isset($htmls[$moduleName.':'])){// 某个模块的静态规则 $html = $htmls[$moduleName.':']; }elseif(isset($htmls[ACTION_NAME])){ $html = $htmls[ACTION_NAME]; // 所有操作的静态规则 }elseif(isset($htmls['*'])){ $html = $htmls['*']; // 全局静态规则 }elseif(isset($htmls['empty:index']) && !class_exists(MODULE_NAME.'Action')){ $html = $htmls['empty:index']; // 空模块静态规则 }elseif(isset($htmls[$moduleName.':_empty']) && $this->isEmptyAction(MODULE_NAME,ACTION_NAME)){ $html = $htmls[$moduleName.':_empty']; // 空操作静态规则 } if(!empty($html)) { // 解读静态规则 $rule = $html[0]; // 以$_开头的系统变量 $rule = preg_replace('/{\$(_\w+)\.(\w+)\|(\w+)}/e',"\\3(\$\\1['\\2'])",$rule); $rule = preg_replace('/{\$(_\w+)\.(\w+)}/e',"\$\\1['\\2']",$rule); // {ID|FUN} GET变量的简写 $rule = preg_replace('/{(\w+)\|(\w+)}/e',"\\2(\$_GET['\\1'])",$rule); $rule = preg_replace('/{(\w+)}/e',"\$_GET['\\1']",$rule); // 特殊系统变量 $rule = str_ireplace( array('{:app}','{:module}','{:action}','{:group}'), array(APP_NAME,MODULE_NAME,ACTION_NAME,defined('GROUP_NAME')?GROUP_NAME:''), $rule); // {|FUN} 单独使用函数 $rule = preg_replace('/{|(\w+)}/e',"\\1()",$rule); if(!empty($html[2])) $rule = $html[2]($rule); // 应用附加函数 $cacheTime = isset($html[1])?$html[1]:C('HTML_CACHE_TIME'); // 缓存有效期 // 当前缓存文件 define('HTML_FILE_NAME',HTML_PATH . $rule.C('HTML_FILE_SUFFIX')); return $cacheTime; } } // 无需缓存 return false; } /** +---------------------------------------------------------- * 检查静态HTML文件是否有效 * 如果无效需要重新更新 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $cacheFile 静态文件名 * @param integer $cacheTime 缓存有效期 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ //[sae] 检查静态缓存 static public function checkHTMLCache($cacheFile='',$cacheTime='') { $kv=Think::instance('SaeKVClient'); if(!$kv->init()) halt('您没有初始化KVDB,请在SAE平台进行初始化'); $content=$kv->get($cacheFile); if(!$content) return false; $mtime= substr($content,0,10); self::$html_content=substr($content,10); if (filemtime(C('TEMPLATE_NAME')) > $mtime) { // 模板文件如果更新静态文件需要更新 return false; }elseif(!is_numeric($cacheTime) && function_exists($cacheTime)){ return $cacheTime($cacheFile); }elseif ($cacheTime != 0 && time() > $mtime+$cacheTime) { // 文件是否在有效期 return false; } //静态文件有效 return true; } //检测是否是空操作 static private function isEmptyAction($module,$action) { $className = $module.'Action'; $class=new $className; return !method_exists($class,$action); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Lib/Behavior/ReadHtmlCacheBehavior.class.php
PHP
art
6,182
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Image_sae.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ /** +------------------------------------------------------------------------------ * 图像操作类库 +------------------------------------------------------------------------------ * @category ORG * @package ORG * @subpackage Util * @author liu21st <liu21st@gmail.com> * @version $Id: Image_sae.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ +------------------------------------------------------------------------------ */ class Image { /** +---------------------------------------------------------- * 取得图像信息 * +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param string $image 图像文件名 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ static function getImageInfo($img) { $imageInfo = getimagesize($img); if ($imageInfo !== false) { $imageType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1)); $imageSize = filesize($img); $info = array( "width" => $imageInfo[0], "height" => $imageInfo[1], "type" => $imageType, "size" => $imageSize, "mime" => $imageInfo['mime'] ); return $info; } else { return false; } } /** +---------------------------------------------------------- * 为图片添加水印 +---------------------------------------------------------- * @static public +---------------------------------------------------------- * @param string $source 原文件名 * @param string $water 水印图片 * @param string $$savename 添加水印后的图片名 * @param string $alpha 水印的透明度 +---------------------------------------------------------- * @return string +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ //[sae] 水印,使用saeimage实现 static public function water($source, $water, $savename=null, $alpha=80) { //检查文件是否存在 $arr = explode('/', ltrim($source, './')); $domain = array_shift($arr); $source = implode('/', $arr); $s = Think::instance('SaeStorage'); if (!$s->fileExists($domain, $source) || !file_exists($water)) return false; $source_url = $s->getUrl($domain, $source); $img = Think::instance('SaeImage'); $source_data = file_get_contents($source_url); $water_data = file_get_contents($water); $img->setData($source_data); $size = $img->getImageAttr(); //获得后缀 $ext = array( 1 => 'gif', 2 => 'jpg', 3 => 'png' ); $type = isset($ext[$size[2]]) ? $ext[$size[2]] : 'jpg'; $img->clean(); $alpha = $alpha * 0.01; $img->setData(array( array($source_data, 0, 0, 1, SAE_TOP_LEFT), array($water_data, 0, 0, $alpha, SAE_BOTTOM_RIGHT) )); $img->composite($size[0], $size[1]); $data = $img->exec($type); if (!$savename) { $savename = $source; } else { $arr = explode('/', ltrim($savename, './')); $domain = array_shift($arr); $savename = implode('/', $arr); } $s->write($domain, $savename, $data); } function showImg($imgFile, $text='', $x='10', $y='10', $alpha='50') { //获取图像文件信息 //2007/6/26 增加图片水印输出,$text为图片的完整路径即可 $info = Image::getImageInfo($imgFile); if ($info !== false) { $createFun = str_replace('/', 'createfrom', $info['mime']); $im = $createFun($imgFile); if ($im) { $ImageFun = str_replace('/', '', $info['mime']); //水印开始 if (!empty($text)) { $tc = imagecolorallocate($im, 0, 0, 0); if (is_file($text) && file_exists($text)) {//判断$text是否是图片路径 // 取得水印信息 $textInfo = Image::getImageInfo($text); $createFun2 = str_replace('/', 'createfrom', $textInfo['mime']); $waterMark = $createFun2($text); //$waterMark=imagecolorallocatealpha($text,255,255,0,50); $imgW = $info["width"]; $imgH = $info["width"] * $textInfo["height"] / $textInfo["width"]; //$y = ($info["height"]-$textInfo["height"])/2; //设置水印的显示位置和透明度支持各种图片格式 imagecopymerge($im, $waterMark, $x, $y, 0, 0, $textInfo['width'], $textInfo['height'], $alpha); } else { imagestring($im, 80, $x, $y, $text, $tc); } //ImageDestroy($tc); } //水印结束 if ($info['type'] == 'png' || $info['type'] == 'gif') { imagealphablending($im, FALSE); //取消默认的混色模式 imagesavealpha($im, TRUE); //设定保存完整的 alpha 通道信息 } Header("Content-type: " . $info['mime']); $ImageFun($im); @ImageDestroy($im); return; } //保存图像 $ImageFun($sImage, $savename); imagedestroy($sImage); //获取或者创建图像文件失败则生成空白PNG图片 $im = imagecreatetruecolor(80, 30); $bgc = imagecolorallocate($im, 255, 255, 255); $tc = imagecolorallocate($im, 0, 0, 0); imagefilledrectangle($im, 0, 0, 150, 30, $bgc); imagestring($im, 4, 5, 5, "no pic", $tc); Image::output($im); return; } } /** +---------------------------------------------------------- * 生成缩略图 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param string $image 原图 * @param string $type 图像格式 * @param string $thumbname 缩略图文件名 * @param string $maxWidth 宽度 * @param string $maxHeight 高度 * @param string $position 缩略图保存目录 * @param boolean $interlace 启用隔行扫描 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static function thumb($image, $thumbname, $type='', $maxWidth=200, $maxHeight=50, $interlace=true) { // 获取原图信息 $info = Image::getImageInfo($image); if ($info !== false) { $srcWidth = $info['width']; $srcHeight = $info['height']; $type = empty($type) ? $info['type'] : $type; $type = strtolower($type); $interlace = $interlace ? 1 : 0; unset($info); $scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight); // 计算缩放比例 if ($scale >= 1) { // 超过原图大小不再缩略 $width = $srcWidth; $height = $srcHeight; } else { // 缩略图尺寸 $width = (int) ($srcWidth * $scale); $height = (int) ($srcHeight * $scale); } // 载入原图 $createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type); $srcImg = $createFun($image); //创建缩略图 if ($type != 'gif' && function_exists('imagecreatetruecolor')) $thumbImg = imagecreatetruecolor($width, $height); else $thumbImg = imagecreate($width, $height); // 复制图片 if (function_exists("ImageCopyResampled")) imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight); else imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight); if ('gif' == $type || 'png' == $type) { //imagealphablending($thumbImg, false);//取消默认的混色模式 //imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息 $background_color = imagecolorallocate($thumbImg, 0, 255, 0); // 指派一个绿色 imagecolortransparent($thumbImg, $background_color); // 设置为透明色,若注释掉该行则输出绿色的图 } // 对jpeg图形设置隔行扫描 if ('jpg' == $type || 'jpeg' == $type) imageinterlace($thumbImg, $interlace); //$gray=ImageColorAllocate($thumbImg,255,0,0); //ImageString($thumbImg,2,5,5,"ThinkPHP",$gray); // 生成图片 $imageFun = 'image' . ($type == 'jpg' ? 'jpeg' : $type); $imageFun($thumbImg, $thumbname); imagedestroy($thumbImg); imagedestroy($srcImg); return $thumbname; } return false; } /** +---------------------------------------------------------- * 根据给定的字符串生成图像 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param string $string 字符串 * @param string $size 图像大小 width,height 或者 array(width,height) * @param string $font 字体信息 fontface,fontsize 或者 array(fontface,fontsize) * @param string $type 图像格式 默认PNG * @param integer $disturb 是否干扰 1 点干扰 2 线干扰 3 复合干扰 0 无干扰 * @param bool $border 是否加边框 array(color) +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static function buildString($string, $rgb=array(), $filename='', $type='png', $disturb=1, $border=true) { if (is_string($size)) $size = explode(',', $size); $width = $size[0]; $height = $size[1]; if (is_string($font)) $font = explode(',', $font); $fontface = $font[0]; $fontsize = $font[1]; $length = strlen($string); $width = ($length * 9 + 10) > $width ? $length * 9 + 10 : $width; $height = 22; if ($type != 'gif' && function_exists('imagecreatetruecolor')) { $im = @imagecreatetruecolor($width, $height); } else { $im = @imagecreate($width, $height); } if (empty($rgb)) { $color = imagecolorallocate($im, 102, 104, 104); } else { $color = imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]); } $backColor = imagecolorallocate($im, 255, 255, 255); //背景色(随机) $borderColor = imagecolorallocate($im, 100, 100, 100); //边框色 $pointColor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); //点颜色 @imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor); @imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor); @imagestring($im, 5, 5, 3, $string, $color); if (!empty($disturb)) { // 添加干扰 if ($disturb = 1 || $disturb = 3) { for ($i = 0; $i < 25; $i++) { imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $pointColor); } } elseif ($disturb = 2 || $disturb = 3) { for ($i = 0; $i < 10; $i++) { imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $pointColor); } } } Image::output($im, $type, $filename); } /** +---------------------------------------------------------- * 生成图像验证码 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param string $length 位数 * @param string $mode 类型 * @param string $type 图像格式 * @param string $width 宽度 * @param string $height 高度 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ //[sae]使用saevcode实现 static function buildImageVerify($length=4, $mode=1, $type='png', $width=48, $height=22, $verifyName='verify') { $vcode = Think::instance('SaeVcode'); $_SESSION[$verifyName] = md5($vcode->answer()); $question = $vcode->question(); header('Location:' . $question['img_url']); } // 中文验证码 static function GBVerify($length=4, $type='png', $width=180, $height=50, $fontface='simhei.ttf', $verifyName='verify') { import('ORG.Util.String'); $code = String::randString($length, 4); $width = ($length * 45) > $width ? $length * 45 : $width; $_SESSION[$verifyName] = md5($code); $im = imagecreatetruecolor($width, $height); $borderColor = imagecolorallocate($im, 100, 100, 100); //边框色 $bkcolor = imagecolorallocate($im, 250, 250, 250); imagefill($im, 0, 0, $bkcolor); @imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor); // 干扰 for ($i = 0; $i < 15; $i++) { $fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $fontcolor); } for ($i = 0; $i < 255; $i++) { $fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $fontcolor); } if (!is_file($fontface)) { $fontface = dirname(__FILE__) . "/" . $fontface; } for ($i = 0; $i < $length; $i++) { $fontcolor = imagecolorallocate($im, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120)); //这样保证随机出来的颜色较深。 $codex = String::msubstr($code, $i, 1); imagettftext($im, mt_rand(16, 20), mt_rand(-60, 60), 40 * $i + 20, mt_rand(30, 35), $fontcolor, $fontface, $codex); } Image::output($im, $type); } /** +---------------------------------------------------------- * 把图像转换成字符显示 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param string $image 要显示的图像 * @param string $type 图像类型,默认自动获取 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static function showASCIIImg($image, $string='', $type='') { $info = Image::getImageInfo($image); if ($info !== false) { $type = empty($type) ? $info['type'] : $type; unset($info); // 载入原图 $createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type); $im = $createFun($image); $dx = imagesx($im); $dy = imagesy($im); $i = 0; $out = '<span style="padding:0px;margin:0;line-height:100%;font-size:1px;">'; set_time_limit(0); for ($y = 0; $y < $dy; $y++) { for ($x = 0; $x < $dx; $x++) { $col = imagecolorat($im, $x, $y); $rgb = imagecolorsforindex($im, $col); $str = empty($string) ? '*' : $string[$i++]; $out .= sprintf('<span style="margin:0px;color:#%02x%02x%02x">' . $str . '</span>', $rgb['red'], $rgb['green'], $rgb['blue']); } $out .= "<br>\n"; } $out .= '</span>'; imagedestroy($im); return $out; } return false; } /** +---------------------------------------------------------- * 生成UPC-A条形码 +---------------------------------------------------------- * @static +---------------------------------------------------------- * @param string $type 图像格式 * @param string $type 图像格式 * @param string $lw 单元宽度 * @param string $hi 条码高度 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static function UPCA($code, $type='png', $lw=2, $hi=100) { static $Lencode = array('0001101', '0011001', '0010011', '0111101', '0100011', '0110001', '0101111', '0111011', '0110111', '0001011'); static $Rencode = array('1110010', '1100110', '1101100', '1000010', '1011100', '1001110', '1010000', '1000100', '1001000', '1110100'); $ends = '101'; $center = '01010'; /* UPC-A Must be 11 digits, we compute the checksum. */ if (strlen($code) != 11) { die("UPC-A Must be 11 digits."); } /* Compute the EAN-13 Checksum digit */ $ncode = '0' . $code; $even = 0; $odd = 0; for ($x = 0; $x < 12; $x++) { if ($x % 2) { $odd += $ncode[$x]; } else { $even += $ncode[$x]; } } $code.= ( 10 - (($odd * 3 + $even) % 10)) % 10; /* Create the bar encoding using a binary string */ $bars = $ends; $bars.=$Lencode[$code[0]]; for ($x = 1; $x < 6; $x++) { $bars.=$Lencode[$code[$x]]; } $bars.=$center; for ($x = 6; $x < 12; $x++) { $bars.=$Rencode[$code[$x]]; } $bars.=$ends; /* Generate the Barcode Image */ if ($type != 'gif' && function_exists('imagecreatetruecolor')) { $im = imagecreatetruecolor($lw * 95 + 30, $hi + 30); } else { $im = imagecreate($lw * 95 + 30, $hi + 30); } $fg = ImageColorAllocate($im, 0, 0, 0); $bg = ImageColorAllocate($im, 255, 255, 255); ImageFilledRectangle($im, 0, 0, $lw * 95 + 30, $hi + 30, $bg); $shift = 10; for ($x = 0; $x < strlen($bars); $x++) { if (($x < 10) || ($x >= 45 && $x < 50) || ($x >= 85)) { $sh = 10; } else { $sh = 0; } if ($bars[$x] == '1') { $color = $fg; } else { $color = $bg; } ImageFilledRectangle($im, ($x * $lw) + 15, 5, ($x + 1) * $lw + 14, $hi + 5 + $sh, $color); } /* Add the Human Readable Label */ ImageString($im, 4, 5, $hi - 5, $code[0], $fg); for ($x = 0; $x < 5; $x++) { ImageString($im, 5, $lw * (13 + $x * 6) + 15, $hi + 5, $code[$x + 1], $fg); ImageString($im, 5, $lw * (53 + $x * 6) + 15, $hi + 5, $code[$x + 6], $fg); } ImageString($im, 4, $lw * 95 + 17, $hi - 5, $code[11], $fg); /* Output the Header and Content. */ Image::output($im, $type); } static function output($im, $type='png', $filename='') { header("Content-type: image/" . $type); $ImageFun = 'image' . $type; if (empty($filename)) { $ImageFun($im); } else { $ImageFun($im, $filename); } imagedestroy($im); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Lib/Extend/Library/ORG/Util/Image_sae.class.php
PHP
art
21,676
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: UploadFile_sae.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ /** +------------------------------------------------------------------------------ * 文件上传类 +------------------------------------------------------------------------------ * @category ORG * @package ORG * @subpackage Net * @author liu21st <liu21st@gmail.com> * @version $Id: UploadFile_sae.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ +------------------------------------------------------------------------------ */ class UploadFile {//类定义开始 // 上传文件的最大值 public $maxSize = -1; // 是否支持多文件上传 public $supportMulti = true; // 允许上传的文件后缀 // 留空不作后缀检查 public $allowExts = array(); // 允许上传的文件类型 // 留空不做检查 public $allowTypes = array(); // 使用对上传图片进行缩略图处理 public $thumb = false; // 图库类包路径 public $imageClassPath = 'ORG.Util.Image'; // 缩略图最大宽度 public $thumbMaxWidth; // 缩略图最大高度 public $thumbMaxHeight; // 缩略图前缀 public $thumbPrefix = 'thumb_'; public $thumbSuffix = ''; // 缩略图保存路径 public $thumbPath = ''; // 缩略图文件名 public $thumbFile = ''; // 是否移除原图 public $thumbRemoveOrigin = false; // 压缩图片文件上传 public $zipImages = false; // 启用子目录保存文件 public $autoSub = false; // 子目录创建方式 可以使用hash date public $subType = 'hash'; public $dateFormat = 'Ymd'; public $hashLevel = 1; // hash的目录层次 // 上传文件保存路径 public $savePath = ''; public $autoCheck = true; // 是否自动检查附件 // 存在同名是否覆盖 public $uploadReplace = false; // 上传文件命名规则 // 例如可以是 time uniqid com_create_guid 等 // 必须是一个无需任何参数的函数名 可以使用自定义函数 public $saveRule = ''; // 上传文件Hash规则函数名 // 例如可以是 md5_file sha1_file 等 public $hashType = 'md5_file'; // 错误信息 private $error = ''; // 上传成功的文件信息 private $uploadFileInfo; //[sae] domain private $domain; private $thumbDomain; /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @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']; $s = Think::instance('SaeStorage'); if (!$this->uploadReplace && $s->fileExists($this->domain, $filename)) { // 不覆盖同名文件 $this->error = '文件已经存在!' . $filename; return false; } // 如果是图像文件 检测文件格式 if (in_array(strtolower($file['extension']), array('gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf')) && false === getimagesize($file['tmp_name'])) { $this->error = '非法图像文件'; return false; } //if(!move_uploaded_file($file['tmp_name'], $this->autoCharset($filename,'utf-8','gbk'))) { if (!$this->thumbRemoveOrigin && !$s->upload($this->domain, $filename, $file['tmp_name']) ) { $this->error = $s->errno() == -7 ? 'domain [ ' . $this->domain . ' ] 不存在!请在SAE控制台的Storage服务中添加一个domain' : '文件上传保存错误!'; return false; } if ($this->thumb && in_array(strtolower($file['extension']), array('gif', 'jpg', 'jpeg', 'bmp', 'png'))) { $image = getimagesize($file['tmp_name']); 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']; //[sae] 定义缩略图目录时,判断doamin $domain = $this->thumbPath ? $this->thumbDomain : $this->domain; //[sae] 用自带image类生成缩略图 $realFilename = $this->autoSub ? basename($file['savename']) : $file['savename']; $srcWidth = $image[0]; $srcHeight = $image[1]; $img = Think::instance('SaeImage'); for ($i = 0, $len = count($thumbWidth); $i < $len; $i++) { $scale = min($thumbWidth[$i] / $srcWidth, $thumbHeight[$i] / $srcHeight); // 计算缩放比例 if ($scale >= 1) { // 超过原图大小不再缩略 $width = $srcWidth; $height = $srcHeight; } else { // 缩略图尺寸 $width = (int) ($srcWidth * $scale); $height = (int) ($srcHeight * $scale); } $thumbname = $thumbPrefix[$i] . substr($realFilename, 0, strrpos($realFilename, '.')) . $thumbSuffix[$i] . '.' . $file['extension']; $img->setData(file_get_contents($file['tmp_name'])); $img->resize($width, $height); $new_data = $img->exec(); if (!$s->write($domain, $thumbPath . $thumbname, $new_data)) { $this->error = $s->errno() == -7 ? 'domain [ ' . $this->domain . ' ] 不存在!请在SAE控制台的Storage服务中添加一个domain' : '生成缩略图失败!'; return false; } } } } if ($this->zipImags) { // TODO 对图片压缩包在线解压 } return true; } //[sae]获得domain,改变path private function getDomain($filePath) { $arr = explode('/', ltrim($filePath, './')); $domain = array_shift($arr); $filePath = implode('/', $arr); return array($domain, $filePath); } /** +---------------------------------------------------------- * 上传所有文件 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $savePath 上传文件保存路径 +---------------------------------------------------------- * @return string +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function upload($savePath ='') { //如果不指定保存文件名,则由系统默认 if (empty($savePath)) $savePath = $this->savePath; //[sae] 去掉检查上传目录 $fileInfo = array(); $isUpload = false; //[sae] 分析出domain,第一个目录为domain list($this->domain, $savePath) = $this->getDomain($savePath); //[sae] 分析缩略图保存地址 if ($this->thumb && $this->thumbPath) list($this->thumbDomain, $this->thumbPath) = $this->getDomain($this->thumbPath); // 获取上传的文件信息 // 对$_FILES数组信息处理 $files = $this->dealFiles($_FILES); foreach ($files as $key => $file) { //过滤无效的上传 if (!empty($file['name'])) { //登记上传文件的扩展信息 $file['key'] = $key; $file['extension'] = $this->getExt($file['name']); $file['savepath'] = $savePath; $file['savename'] = $this->getSaveName($file); // 自动检查附件 if ($this->autoCheck) { if (!$this->check($file)) return false; } //保存上传文件 if (!$this->save($file)) return false; if (function_exists($this->hashType)) { $fun = $this->hashType; $file['hash'] = $fun($this->autoCharset($file['savepath'] . $file['savename'], 'utf-8', 'gbk')); } //上传成功后保存文件信息,供其他地方调用 unset($file['tmp_name'], $file['error']); $fileInfo[] = $file; $isUpload = true; } } if ($isUpload) { $this->uploadFileInfo = $fileInfo; return true; } else { $this->error = '没有选择上传文件'; return false; } } /** +---------------------------------------------------------- * 上传单个上传字段中的文件 支持多附件 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $file 上传文件信息 * @param string $savePath 上传文件保存路径 +---------------------------------------------------------- * @return string +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function uploadOne($file, $savePath='') { //如果不指定保存文件名,则由系统默认 if (empty($savePath)) $savePath = $this->savePath; //[sae] 不检查上传目录 //[sae] 分析出domain,第一个目录为domain list($this->domain, $savePath) = $this->getDomain($savePath); //[sae] 分析缩略图保存地址 if ($this->thumb && $this->thumbPath) list($this->thumbDomain, $this->thumbPath) = $this->getDomain($this->thumbPath); //过滤无效的上传 if (!empty($file['name'])) { $fileArray = array(); if (is_array($file['name'])) { $keys = array_keys($file); $count = count($file['name']); for ($i = 0; $i < $count; $i++) { foreach ($keys as $key) $fileArray[$i][$key] = $file[$key][$i]; } } else { $fileArray[] = $file; } $info = array(); foreach ($fileArray as $key => $file) { //登记上传文件的扩展信息 $file['extension'] = $this->getExt($file['name']); $file['savepath'] = $savePath; $file['savename'] = $this->getSaveName($file); // 自动检查附件 if ($this->autoCheck) { if (!$this->check($file)) return false; } //保存上传文件 if (!$this->save($file)) return false; if (function_exists($this->hashType)) { $fun = $this->hashType; $file['hash'] = $fun($this->autoCharset($file['savepath'] . $file['savename'], 'utf-8', 'gbk')); } unset($file['tmp_name'], $file['error']); $info[] = $file; } // 返回上传的文件信息 return $info; } else { $this->error = '没有选择上传文件'; return false; } } /** +---------------------------------------------------------- * 转换上传文件数组变量为正确的方式 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param array $files 上传的文件变量 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ private function dealFiles($files) { $fileArray = array(); $n = 0; foreach ($files as $file) { if (is_array($file['name'])) { $keys = array_keys($file); $count = count($file['name']); for ($i = 0; $i < $count; $i++) { foreach ($keys as $key) $fileArray[$n][$key] = $file[$key][$i]; $n++; } } else { $fileArray[$n] = $file; $n++; } } return $fileArray; } /** +---------------------------------------------------------- * 获取错误代码信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $errorNo 错误号码 +---------------------------------------------------------- * @return void +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ protected function error($errorNo) { switch ($errorNo) { case 1: $this->error = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值'; break; case 2: $this->error = '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值'; break; case 3: $this->error = '文件只有部分被上传'; break; case 4: $this->error = '没有文件被上传'; break; case 6: $this->error = '找不到临时文件夹'; break; case 7: $this->error = '文件写入失败'; break; default: $this->error = '未知上传错误!'; } return; } /** +---------------------------------------------------------- * 根据上传文件命名规则取得保存文件名 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param string $filename 数据 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ private function getSaveName($filename) { $rule = $this->saveRule; if (empty($rule)) {//没有定义命名规则,则保持文件名不变 $saveName = $filename['name']; } else { if (function_exists($rule)) { //使用函数生成一个唯一文件标识号 $saveName = $rule() . "." . $filename['extension']; } else { //使用给定的文件名作为标识号 $saveName = $rule . "." . $filename['extension']; } } if ($this->autoSub) { // 使用子目录保存文件 $filename['savename'] = $saveName; $saveName = $this->getSubName($filename) . '/' . $saveName; } return $saveName; } /** +---------------------------------------------------------- * 获取子目录的名称 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param array $file 上传的文件信息 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ private function getSubName($file) { switch ($this->subType) { case 'date': $dir = date($this->dateFormat, time()); break; case 'hash': default: $name = md5($file['savename']); $dir = ''; for ($i = 0; $i < $this->hashLevel; $i++) { $dir .= $name{$i} . '/'; } break; } if (!is_dir($file['savepath'] . $dir)) { mk_dir($file['savepath'] . $dir); } return $dir; } /** +---------------------------------------------------------- * 检查上传的文件 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param array $file 文件信息 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ private function check($file) { if ($file['error'] !== 0) { //文件上传失败 //捕获错误代码 $this->error($file['error']); return false; } //文件上传成功,进行自定义规则检查 //检查文件大小 if (!$this->checkSize($file['size'])) { $this->error = '上传文件大小不符!'; return false; } //检查文件Mime类型 if (!$this->checkType($file['type'])) { $this->error = '上传文件MIME类型不允许!'; return false; } //检查文件类型 if (!$this->checkExt($file['extension'])) { $this->error = '上传文件类型不允许'; return false; } //检查是否合法上传 if (!$this->checkUpload($file['tmp_name'])) { $this->error = '非法上传文件!'; return false; } return true; } // 自动转换字符集 支持数组转换 private function autoCharset($fContents, $from='gbk', $to='utf-8') { $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from; $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to; if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) { //如果编码相同或者非字符串标量则不转换 return $fContents; } if (function_exists('mb_convert_encoding')) { return mb_convert_encoding($fContents, $to, $from); } elseif (function_exists('iconv')) { return iconv($from, $to, $fContents); } else { return $fContents; } } /** +---------------------------------------------------------- * 检查上传的文件类型是否合法 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param string $type 数据 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ private function checkType($type) { if (!empty($this->allowTypes)) return in_array(strtolower($type), $this->allowTypes); return true; } /** +---------------------------------------------------------- * 检查上传的文件后缀是否合法 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param string $ext 后缀名 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ private function checkExt($ext) { if (!empty($this->allowExts)) return in_array(strtolower($ext), $this->allowExts, true); return true; } /** +---------------------------------------------------------- * 检查文件大小是否合法 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param integer $size 数据 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ private function checkSize($size) { return!($size > $this->maxSize) || (-1 == $this->maxSize); } /** +---------------------------------------------------------- * 检查文件是否非法提交 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param string $filename 文件名 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ private function checkUpload($filename) { return is_uploaded_file($filename); } /** +---------------------------------------------------------- * 取得上传文件的后缀 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param string $filename 文件名 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ private function getExt($filename) { $pathinfo = pathinfo($filename); return $pathinfo['extension']; } /** +---------------------------------------------------------- * 取得上传文件的信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function getUploadFileInfo() { return $this->uploadFileInfo; } /** +---------------------------------------------------------- * 取得最后一次错误信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getErrorMsg() { return $this->error; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Lib/Extend/Library/ORG/Net/UploadFile_sae.class.php
PHP
art
25,721
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Action.class.php 2793 2012-03-02 05:34:40Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP Action控制器基类 抽象类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id: Action.class.php 2793 2012-03-02 05:34:40Z liu21st $ +------------------------------------------------------------------------------ */ abstract class Action { // 视图实例对象 protected $view = null; // 当前Action名称 private $name = ''; /** +---------------------------------------------------------- * 架构函数 取得模板对象实例 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct() { tag('action_begin'); //实例化视图类 $this->view = Think::instance('View'); //控制器初始化 if(method_exists($this,'_initialize')) $this->_initialize(); } /** +---------------------------------------------------------- * 获取当前Action名称 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- */ protected function getActionName() { if(empty($this->name)) { // 获取Action名称 $this->name = substr(get_class($this),0,-6); } return $this->name; } /** +---------------------------------------------------------- * 是否AJAX请求 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @return bool +---------------------------------------------------------- */ protected function isAjax() { if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) ) { if('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])) return true; } if(!empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')])) // 判断Ajax方式提交 return true; return false; } /** +---------------------------------------------------------- * 模板显示 * 调用内置的模板引擎显示方法, +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $templateFile 指定要调用的模板文件 * 默认为空 由系统自动定位模板文件 * @param string $charset 输出编码 * @param string $contentType 输出类型 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function display($templateFile='',$charset='',$contentType='') { $this->view->display($templateFile,$charset,$contentType); } /** +---------------------------------------------------------- * 获取输出页面内容 * 调用内置的模板引擎fetch方法, +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $templateFile 指定要调用的模板文件 * 默认为空 由系统自动定位模板文件 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function fetch($templateFile='') { return $this->view->fetch($templateFile); } /** +---------------------------------------------------------- * 创建静态页面 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @htmlfile 生成的静态文件名称 * @htmlpath 生成的静态文件路径 * @param string $templateFile 指定要调用的模板文件 * 默认为空 由系统自动定位模板文件 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ //[sae] 生成静态文件 protected function buildHtml($htmlfile='',$htmlpath='',$templateFile='') { $content = $this->fetch($templateFile); $kv=Think::instance('SaeKVClient'); if(!$kv->init()) halt('您没有初始化KVDB,请在SAE平台进行初始化'); $htmlpath = !empty($htmlpath)?$htmlpath:HTML_PATH; $htmlfile = $htmlpath.$htmlfile.C('HTML_FILE_SUFFIX'); trace('[SAE]静态缓存',$htmlfile); $kv->set($htmlfile,$content);//[sae] 注意buildHtml生成的静态数据没有记录生成时间 return $content; } /** +---------------------------------------------------------- * 模板变量赋值 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $name 要显示的模板变量 * @param mixed $value 变量的值 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function assign($name,$value='') { $this->view->assign($name,$value); } public function __set($name,$value) { $this->view->assign($name,$value); } /** +---------------------------------------------------------- * 取得模板显示变量的值 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $name 模板显示变量 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __get($name) { return $this->view->get($name); } /** +---------------------------------------------------------- * 魔术方法 有不存在的操作的时候执行 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名 * @param array $args 参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$args) { if( 0 === strcasecmp($method,ACTION_NAME)) { if(method_exists($this,'_empty')) { // 如果定义了_empty操作 则调用 $this->_empty($method,$args); }elseif(file_exists_case(C('TEMPLATE_NAME'))){ // 检查是否存在默认模版 如果有直接输出模版 $this->display(); }elseif(function_exists('__hack_action')) { // hack 方式定义扩展操作 __hack_action(); }elseif(APP_DEBUG) { // 抛出异常 throw_exception(L('_ERROR_ACTION_').ACTION_NAME); }else{ if(C('LOG_EXCEPTION_RECORD')) Log::write(L('_ERROR_ACTION_').ACTION_NAME); send_http_status(404); exit; } }else{ switch(strtolower($method)) { // 判断提交方式 case 'ispost': case 'isget': case 'ishead': case 'isdelete': case 'isput': return strtolower($_SERVER['REQUEST_METHOD']) == strtolower(substr($method,2)); // 获取变量 支持过滤和默认值 调用方式 $this->_post($key,$filter,$default); case '_get': $input =& $_GET;break; case '_post':$input =& $_POST;break; case '_put': parse_str(file_get_contents('php://input'), $input);break; case '_request': $input =& $_REQUEST;break; case '_session': $input =& $_SESSION;break; case '_cookie': $input =& $_COOKIE;break; case '_server': $input =& $_SERVER;break; case '_globals': $input =& $GLOBALS;break; default: throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); } if(isset($input[$args[0]])) { // 取值操作 $data = $input[$args[0]]; $fun = $args[1]?$args[1]:C('DEFAULT_FILTER'); $data = $fun($data); // 参数过滤 }else{ // 变量默认值 $data = isset($args[2])?$args[2]:NULL; } return $data; } } /** +---------------------------------------------------------- * 操作错误跳转的快捷方法 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $message 错误信息 * @param string $jumpUrl 页面跳转地址 * @param Boolean $ajax 是否为Ajax方式 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function error($message,$jumpUrl='',$ajax=false) { $this->dispatchJump($message,0,$jumpUrl,$ajax); } /** +---------------------------------------------------------- * 操作成功跳转的快捷方法 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $message 提示信息 * @param string $jumpUrl 页面跳转地址 * @param Boolean $ajax 是否为Ajax方式 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function success($message,$jumpUrl='',$ajax=false) { $this->dispatchJump($message,1,$jumpUrl,$ajax); } /** +---------------------------------------------------------- * Ajax方式返回数据到客户端 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $data 要返回的数据 * @param String $info 提示信息 * @param boolean $status 返回状态 * @param String $status ajax返回类型 JSON XML +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function ajaxReturn($data,$info='',$status=1,$type='') { $result = array(); $result['status'] = $status; $result['info'] = $info; $result['data'] = $data; //扩展ajax返回数据, 在Action中定义function ajaxAssign(&$result){} 方法 扩展ajax返回数据。 if(method_exists($this,'ajaxAssign')) $this->ajaxAssign($result); if(empty($type)) $type = C('DEFAULT_AJAX_RETURN'); if(strtoupper($type)=='JSON') { // 返回JSON数据格式到客户端 包含状态信息 header('Content-Type:text/html; charset=utf-8'); exit(json_encode($result)); }elseif(strtoupper($type)=='XML'){ // 返回xml格式数据 header('Content-Type:text/xml; charset=utf-8'); exit(xml_encode($result)); }elseif(strtoupper($type)=='EVAL'){ // 返回可执行的js脚本 header('Content-Type:text/html; charset=utf-8'); exit($data); }else{ // TODO 增加其它格式 } } /** +---------------------------------------------------------- * Action跳转(URL重定向) 支持指定模块和延时跳转 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $url 跳转的URL表达式 * @param array $params 其它URL参数 * @param integer $delay 延时跳转的时间 单位为秒 * @param string $msg 跳转提示信息 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function redirect($url,$params=array(),$delay=0,$msg='') { $url = U($url,$params); redirect($url,$delay,$msg); } /** +---------------------------------------------------------- * 默认跳转操作 支持错误导向和正确跳转 * 调用模板显示 默认为public目录下面的success页面 * 提示页面为可配置 支持模板标签 +---------------------------------------------------------- * @param string $message 提示信息 * @param Boolean $status 状态 * @param string $jumpUrl 页面跳转地址 * @param Boolean $ajax 是否为Ajax方式 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ private function dispatchJump($message,$status=1,$jumpUrl='',$ajax=false) { // 判断是否为AJAX返回 if($ajax || $this->isAjax()) $this->ajaxReturn($ajax,$message,$status); if(!empty($jumpUrl)) $this->assign('jumpUrl',$jumpUrl); // 提示标题 $this->assign('msgTitle',$status? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_')); //如果设置了关闭窗口,则提示完毕后自动关闭窗口 if($this->view->get('closeWin')) $this->assign('jumpUrl','javascript:window.close();'); $this->assign('status',$status); // 状态 //保证输出不受静态缓存影响 C('HTML_CACHE_ON',false); if($status) { //发送成功信息 $this->assign('message',$message);// 提示信息 // 成功操作后默认停留1秒 if(!$this->view->get('waitSecond')) $this->assign('waitSecond','1'); // 默认操作成功自动返回操作前页面 if(!$this->view->get('jumpUrl')) $this->assign('jumpUrl',$_SERVER['HTTP_REFERER']); $this->display(C('TMPL_ACTION_SUCCESS')); }else{ $this->assign('error',$message);// 提示信息 //发生错误时候默认停留3秒 if(!$this->view->get('waitSecond')) $this->assign('waitSecond','3'); // 默认发生错误的话自动返回上页 if(!$this->view->get('jumpUrl')) $this->assign('jumpUrl','javascript:history.back(-1);'); $this->display(C('TMPL_ACTION_ERROR')); // 中止执行 避免出错后继续执行 exit ; } } /** +---------------------------------------------------------- * 析构方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __destruct() { // 保存日志 if(C('LOG_RECORD')) Log::save(); // 执行后续操作 tag('action_end'); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Lib/Core/Action.class.php
PHP
art
16,959
<?php /** * +--------------------------------------------------- * | 对Memcache操作的封装,用于文件缓存 * +--------------------------------------------------- * @author luofei614<www.3g4k.com> */ if (!class_exists('SaeMC')) { //[sae]对Memcache操作的封装,编译缓存,模版缓存存入Memcache中(非wrappers的形式) class SaeMC { static public $handler; static private $current_include_file = null; static private $contents = array(); static private $filemtimes = array(); //设置文件内容 static public function set($filename, $content) { $time=time(); self::$handler->set($_SERVER['HTTP_APPVERSION'] . '/' . $filename, $time . $content, MEMCACHE_COMPRESSED, 0); self::$contents[$filename]=$content; self::$filemtimes[$filename]=$time; } //载入文件 static public function include_file($_filename,$_vars=null) { self::$current_include_file = 'saemc://' . $_SERVER['HTTP_APPVERSION'] . '/' . $_filename; $_content = isset(self::$contents[$_filename]) ? self::$contents[$_filename] : self::getValue($_filename, 'content'); if(!is_null($_vars)) extract($_vars, EXTR_OVERWRITE); if (!$_content) exit('<br /><b>SAE_Parse_error</b>: failed to open stream: No such file ' . self::$current_include_file); if (@(eval(' ?>' . $_content)) === false) self::error(); self::$current_include_file = null; unset(self::$contents[$_filename]); //释放内存 } static private function getValue($filename, $type='mtime') { $content = self::$handler->get($_SERVER['HTTP_APPVERSION'] . '/' . $filename); if (!$content) return false; $ret = array( 'mtime' => substr($content, 0, 10), 'content' => substr($content, 10) ); self::$contents[$filename] = $ret['content']; self::$filemtimes[$filename] = $ret['mtime']; return $ret[$type]; } //获得文件修改时间 static public function filemtime($filename) { if (!isset(self::$filemtimes[$filename])) return self::getValue($filename, 'mtime'); return self::$filemtimes[$filename]; } //删除文件 static public function unlink($filename) { if (isset(self::$contents[$filename])) unset(self::$contents[$filename]); if (isset(self::$filemtimes[$filename])) unset(self::$filemtimes[$filename]); return self::$handler->delete($_SERVER['HTTP_APPVERSION'] . '/' . $filename); } static public function file_exists($filename) { return self::filemtime($filename) === false ? false : true; } static function error() { $error = error_get_last(); if (!is_null($error)) { $file = strpos($error['file'], 'eval()') !== false ? self::$current_include_file : $error['file']; exit("<br /><b>SAE_error</b>: {$error['message']} in <b>" . $file . "</b> on line <b>{$error['line']}</b><br />"); } } } register_shutdown_function(array('SaeMC', 'error')); //[sae] 初始化memcache if (!(SaeMC::$handler = @(memcache_init()))) { header('Content-Type:text/html; charset=utf-8'); exit('<div style=\'font-weight:bold;float:left;width:430px;text-align:center;border:1px solid silver;background:#E8EFFF;padding:8px;color:red;font-size:14px;font-family:Tahoma\'>您的Memcache还没有初始化,请登录SAE平台进行初始化~</div>'); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Lib/Core/SaeMC.class.php
PHP
art
3,818
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Think.class.php 2793 2012-03-02 05:34:40Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP Portal类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id: Think.class.php 2793 2012-03-02 05:34:40Z liu21st $ +------------------------------------------------------------------------------ */ class Think { private static $_instance = array(); /** +---------------------------------------------------------- * 应用程序初始化 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function Start() { // 设定错误和异常处理 set_error_handler(array('Think','appError')); set_exception_handler(array('Think','appException')); // 注册AUTOLOAD方法 spl_autoload_register(array('Think', 'autoload')); //[RUNTIME] Think::buildApp(); // 预编译项目 //[/RUNTIME] // 运行应用 App::run(); return ; } //[RUNTIME] /** +---------------------------------------------------------- * 读取配置信息 编译项目 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static private function buildApp() { // 加载底层惯例配置文件 C(include THINK_PATH.'Conf/convention.php'); // 读取运行模式 if(defined('MODE_NAME')) { // 模式的设置并入核心模式 $mode = include MODE_PATH.strtolower(MODE_NAME).'.php'; }else{ $mode = array(); } // 加载模式配置文件 if(isset($mode['config'])) { C( is_array($mode['config'])?$mode['config']:include $mode['config'] ); } // 加载项目配置文件 if(is_file(CONF_PATH.'config.php')) C(include CONF_PATH.'config.php'); //[sae]惯例配置 C(include SAE_PATH.'Conf/convention_sae.php'); //[sae]专有配置 if (is_file(CONF_PATH . 'config_sae.php')) C(include CONF_PATH . 'config_sae.php'); // 加载框架底层语言包 L(include THINK_PATH.'Lang/'.strtolower(C('DEFAULT_LANG')).'.php'); // 加载模式系统行为定义 if(C('APP_TAGS_ON')) { if(isset($mode['extends'])) { C('extends',is_array($mode['extends'])?$mode['extends']:include $mode['extends']); }else{ //[sae] 默认加载系统行为扩展定义 C('extends', include SAE_PATH.'Conf/tags.php'); } } // 加载应用行为定义 if(isset($mode['tags'])) { C('tags', is_array($mode['tags'])?$mode['tags']:include $mode['tags']); }elseif(is_file(CONF_PATH.'tags.php')){ // 默认加载项目配置目录的tags文件定义 C('tags', include CONF_PATH.'tags.php'); } $compile = ''; // 读取核心编译文件列表 if(isset($mode['core'])) { $list = $mode['core']; }else{ $list = array( SAE_PATH.'Common/functions.php', //[sae] 标准模式函数库 SAE_PATH.'Common/sae_functions.php',//[sae]新增sae专用函数 SAE_PATH.'Lib/Core/Log.class.php', // 日志处理类 CORE_PATH.'Core/Dispatcher.class.php', // URL调度类 CORE_PATH.'Core/App.class.php', // 应用程序类 SAE_PATH.'Lib/Core/Action.class.php', //[sae] 控制器类 CORE_PATH.'Core/View.class.php', // 视图类 ); } // 项目追加核心编译列表文件 if(is_file(CONF_PATH.'core.php')) { $list = array_merge($list,include CONF_PATH.'core.php'); } foreach ($list as $file){ if(is_file($file)) { require_cache($file); if(!APP_DEBUG) $compile .= compile($file); } } // 加载项目公共文件 if(is_file(COMMON_PATH.'common.php')) { include COMMON_PATH.'common.php'; // 编译文件 if(!APP_DEBUG) $compile .= compile(COMMON_PATH.'common.php'); } // 加载模式别名定义 if(isset($mode['alias'])) { $alias = is_array($mode['alias'])?$mode['alias']:include $mode['alias']; alias_import($alias); if(!APP_DEBUG) $compile .= 'alias_import('.var_export($alias,true).');'; } // 加载项目别名定义 if(is_file(CONF_PATH.'alias.php')){ $alias = include CONF_PATH.'alias.php'; alias_import($alias); if(!APP_DEBUG) $compile .= 'alias_import('.var_export($alias,true).');'; } if(APP_DEBUG) { // 调试模式加载系统默认的配置文件 C(include THINK_PATH.'Conf/debug.php'); // 读取调试模式的应用状态 $status = C('APP_STATUS'); // 加载对应的项目配置文件 if(is_file(CONF_PATH.$status.'.php')) // 允许项目增加开发模式配置定义 C(include CONF_PATH.$status.'.php'); }else{ // 部署模式下面生成编译文件 build_runtime_cache($compile); } return ; } //[/RUNTIME] /** +---------------------------------------------------------- * 系统自动加载ThinkPHP类库 * 并且支持配置自动加载路径 +---------------------------------------------------------- * @param string $class 对象类名 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public static function autoload($class) { // 检查是否存在别名定义 if(alias_import($class)) return ; if(substr($class,-8)=='Behavior') { // 加载行为 if(require_cache(CORE_PATH.'Behavior/'.$class.'.class.php') || require_cache(EXTEND_PATH.'Behavior/'.$class.'.class.php') || require_cache(LIB_PATH.'Behavior/'.$class.'.class.php') || (defined('MODE_NAME') && require_cache(MODE_PATH.ucwords(MODE_NAME).'/Behavior/'.$class.'.class.php'))) { return ; } }elseif(substr($class,-5)=='Model'){ // 加载模型 if(require_cache(LIB_PATH.'Model/'.$class.'.class.php') || require_cache(EXTEND_PATH.'Model/'.$class.'.class.php') ) { return ; } }elseif(substr($class,-6)=='Action'){ // 加载控制器 if((defined('GROUP_NAME') && require_cache(LIB_PATH.'Action/'.GROUP_NAME.'/'.$class.'.class.php')) || require_cache(LIB_PATH.'Action/'.$class.'.class.php') || require_cache(EXTEND_PATH.'Action/'.$class.'.class.php') ) { return ; } } // 根据自动加载路径设置进行尝试搜索 $paths = explode(',',C('APP_AUTOLOAD_PATH')); foreach ($paths as $path){ if(import($path.'.'.$class)) // 如果加载类成功则返回 return ; } } /** +---------------------------------------------------------- * 取得对象实例 支持调用类的静态方法 +---------------------------------------------------------- * @param string $class 对象类名 * @param string $method 类的静态方法名 +---------------------------------------------------------- * @return object +---------------------------------------------------------- */ static public function instance($class,$method='') { $identify = $class.$method; if(!isset(self::$_instance[$identify])) { if(class_exists($class)){ $o = new $class(); if(!empty($method) && method_exists($o,$method)) self::$_instance[$identify] = call_user_func_array(array(&$o, $method)); else self::$_instance[$identify] = $o; } else halt(L('_CLASS_NOT_EXIST_').':'.$class); } return self::$_instance[$identify]; } /** +---------------------------------------------------------- * 自定义异常处理 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $e 异常对象 +---------------------------------------------------------- */ static public function appException($e) { halt($e->__toString()); } /** +---------------------------------------------------------- * 自定义错误处理 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param int $errno 错误类型 * @param string $errstr 错误信息 * @param string $errfile 错误文件 * @param int $errline 错误行数 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function appError($errno, $errstr, $errfile, $errline) { switch ($errno) { case E_ERROR: case E_USER_ERROR: $errorStr = "[$errno] $errstr ".basename($errfile)." 第 $errline 行."; if(C('LOG_RECORD')) Log::write($errorStr,Log::ERR); halt($errorStr); break; case E_STRICT: case E_USER_WARNING: case E_USER_NOTICE: default: $errorStr = "[$errno] $errstr ".basename($errfile)." 第 $errline 行."; Log::record($errorStr,Log::NOTICE); break; } } /** +---------------------------------------------------------- * 自动变量设置 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param $name 属性名称 * @param $value 属性值 +---------------------------------------------------------- */ public function __set($name ,$value) { if(property_exists($this,$name)) $this->$name = $value; } /** +---------------------------------------------------------- * 自动变量获取 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param $name 属性名称 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __get($name) { return isset($this->$name)?$this->$name:null; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Lib/Core/Think.class.php
PHP
art
12,476
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Log.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ /** +------------------------------------------------------------------------------ * 日志处理类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id: Log.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ +------------------------------------------------------------------------------ */ class Log { // 日志级别 从上到下,由低到高 const EMERG = 'EMERG'; // 严重错误: 导致系统崩溃无法使用 const ALERT = 'ALERT'; // 警戒性错误: 必须被立即修改的错误 const CRIT = 'CRIT'; // 临界值错误: 超过临界值的错误,例如一天24小时,而输入的是25小时这样 const ERR = 'ERR'; // 一般错误: 一般性错误 const WARN = 'WARN'; // 警告性错误: 需要发出警告的错误 const NOTICE = 'NOTIC'; // 通知: 程序可以运行但是还不够完美的错误 const INFO = 'INFO'; // 信息: 程序输出信息 const DEBUG = 'DEBUG'; // 调试: 调试信息 const SQL = 'SQL'; // SQL:SQL语句 注意只在调试模式开启时有效 // 日志记录方式 const SYSTEM = 0; const MAIL = 1; const FILE = 3; const SAPI = 4; // 日志信息 static $log = array(); // 日期格式 static $format = '[ c ]'; /** +---------------------------------------------------------- * 记录日志 并且会过滤未经设置的级别 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param string $message 日志信息 * @param string $level 日志级别 * @param boolean $record 是否强制记录 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static function record($message,$level=self::ERR,$record=false) { if($record || strpos(C('LOG_LEVEL'),$level)) { //[sae] 下不记录时间 sae_debug会记录 self::$log[] = '###'.$_SERVER['REQUEST_URI'] . " | {$level}: {$message}###"; } } /** +---------------------------------------------------------- * 日志保存 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param integer $type 日志记录方式 * @param string $destination 写入目标 * @param string $extra 额外参数 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ //[sae]保存日志 static function save($type='',$destination='',$extra='') { self::sae_set_display_errors(false); foreach (self::$log as $log) sae_debug($log); // 保存后清空日志缓存 self::$log = array(); self::sae_set_display_errors(true); //clearstatcache(); } /** +---------------------------------------------------------- * 日志直接写入 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param string $message 日志信息 * @param string $level 日志级别 * @param integer $type 日志记录方式 * @param string $destination 写入目标 * @param string $extra 额外参数 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ //[sae]下写入日志。 static function write($message,$level=self::ERR,$type='',$destination='',$extra='') { self::sae_set_display_errors(false); sae_debug('###'.$_SERVER['REQUEST_URI'] . " | {$level}: {$message}###"); self::sae_set_display_errors(true); //clearstatcache(); } //[sae] 增加错误信息显示控制,弥补SAE平台字段的sae_set_display_errors的不足。 static function sae_set_display_errors($bool){ static $is_debug=null; if (is_null($is_debug)) { preg_replace('@(\w+)\=([^;]*)@e', '$appSettings[\'\\1\']="\\2";', $_SERVER['HTTP_APPCOOKIE']); $is_debug = in_array($_SERVER['HTTP_APPVERSION'], explode(',', $appSettings['debug'])) ? true : false; } if($is_debug) sae_set_display_errors ($bool); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Lib/Core/Log.class.php
PHP
art
5,535
<?php /** * +--------------------------------------------------- * | SAE本地开发环境, 模拟sae服务 * +--------------------------------------------------- * @author luofei614<www.3g4k.com> */ @(ini_set('post_max_size', '10M')); // sae下最大上传文件为10M @(ini_set('upload_max_filesize', '10M')); $sae_config = include(SAE_PATH.'SaeImit/config.php');//读取配置文件 include_once SAE_PATH.'SaeImit/defines.php'; include_once SAE_PATH.'SaeImit/sae_functions.php'; include_once SAE_PATH.'SaeImit/imit_functions.php'; include_once SAE_PATH.'SaeImit/Lang.php'; spl_autoload_register('sae_auto_load'); function sae_auto_load($class){ $files=array( 'SaeObject'=>SAE_PATH.'SaeImit/SaeObject.class.php', 'SaeCounter'=> SAE_PATH.'SaeImit/SaeCounter.class.php', 'SaeRank'=>SAE_PATH.'SaeImit/SaeRank.class.php', 'SaeTaskQueue'=>SAE_PATH.'SaeImit/SaeTaskQueue.class.php', 'SaeStorage'=>SAE_PATH.'SaeImit/SaeStorage.class.php', 'SaeKVClient'=>SAE_PATH.'SaeImit/SaeKVClient.class.php', 'Memcache'=>SAE_PATH.'SaeImit/Memcache.class.php', 'CacheFile'=>THINK_PATH.'Lib/Driver/Cache/CacheFile.class.php', 'SaeMail'=>SAE_PATH.'SaeImit/SaeMail.class.php', 'SaeMysql'=>SAE_PATH.'SaeImit/SaeMysql.class.php', 'ImitSqlite'=>SAE_PATH.'SaeImit/ImitSqlite.class.php', 'SaeFetchurl'=>SAE_PATH.'SaeImit/SaeFetchurl.class.php', 'SaeImage'=>SAE_PATH.'SaeImit/SaeImage.class.php' ); if(isset($files[$class])) require $files[$class]; } ?>
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit.php
PHP
art
1,544
<?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: luofei614 <www.3g4k.com> // +---------------------------------------------------------------------- // $Id: Memcache.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ /** *memcache模拟器。 *当本地环境不支持memcache时被调用。 *当你本地环境支持memcache时,会使用原始的memcache,此类将不起作用。 */ class Memcache extends Think{ private static $handler; public function __construct(){ if(!is_object(self::$handler)){ self::$handler=new CacheFile(); } } public static function add($key, $var, $flag=null, $expire=-1){ if(self::$handler->get($key)!==false) return false; return self::$handler->set($key,$var,$expire); } public static function addServer($host,$port=11211,$persistent=null,$weight=null,$timeout=null,$retry_interval=null,$status=null,$failure_back=null,$timeoutms=null){ return true; } public static function close(){ return true; } public static function connect($host,$port=11211,$timeout=null){ return true; } public static function decrement($key,$value=1){ return self::$handler->decrement($key,$value); } public static function increment($key,$value=1){ return self::$handler->increment($key,$value); } public static function delete($key,$timeout=0){ $v=S($key); if($v===false) return false; if($timeout!==0){ return self::$handler->set($key,$v,$timeout); }else{ return self::$handler->rm($key); } } public static function flush(){ return self::$handler->clear(); } public static function get($key,$flag=null){ if(is_string($key)){ return self::$handler->get($key); }else{ //返回数组形式 array('k1'=>'v1','k2'=>'v2') $ret=array(); foreach($key as $k){ $ret[$k]=self::$handler->get($k); } return $ret; } } public static function getExtendedStats($type=null,$slabid=null,$limit=100){ //pass return true; } public static function getServerStatus($host,$port=11211){ return 1; } public static function getStats($type,$stabid=null,$limit=100){ //pass return true; } public static function getVersion(){ //todu 待完善 return true; } public static function pconnect($host,$port=11211,$timeout=null){ //pass return true; } public static function replace($key,$var,$flag=null,$expire=-1){ if(self::$handler->get($key)===false) return false; return self::$handler->set($key,$var,$flag,$expire); } public static function set($key,$var,$flag=null,$expire=-1){ return self::$handler->set($key,$var,$expire); } public static function setCompressThreshold($threshold,$min_savings=null){ //pass return true; } public static function setServerParams($host,$port=11211,$timeout=-1,$retry_interval=false,$status=null,$retry_interval=false){ return true; } //todu memcache_debug 函数 } function memcache_add($m,$key, $var, $flag=null, $expire=-1){ return Memcache::add($key,$var,$flag,$expire); } function memcache_add_server($host,$port=11211,$persistent=null,$weight=null,$timeout=null,$retry_interval=null,$status=null,$failure_back=null,$timeoutms=null){ return true; } function memcache_close(){ return true; } function memcache_decrement($m,$key,$value=1){ return Memcache::decrement($m,$key,$value); } function memcache_increment($m,$key,$value=1){ return Memcache::increment($key,$value); } function memcache_delete($m,$key,$timeout=0){ return Memcache::delete($key,$timeout); } function memcache_flush($m){ return Memcache::flush(); } function memcache_get_extended_stats($m,$type=null,$slabid=null,$limit=100){ return true; } function memcache_get_server_status($m,$host,$port=11211){ return 1; } function memcache_get_stats($m,$type,$stabid=null,$limit=100){ return true; } function memcache_get_version($m){ return true; } function memcache_pconnect($host,$port=11211,$timeout=null){ return true; } function memcache_replace($m,$key,$var,$flag=null,$expire){ return Memcache::replace($key,$var,$flag,$expire); } function memcache_set_compress_threshold($m,$threshold,$min_savings=null){ return true; } function memcache_set_server_params($host,$port=11211,$timeout=-1,$retry_interval=false,$status=null,$retry_interval=false){ return true; } function memcache_set($m,$key,$value){ return $mmc->set($key,$value); } function memcache_get($m,$key){ return $mmc->get($key); }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/Memcache.class.php
PHP
art
4,969
<?php // +---------------------------------------------------------------------- // | 模拟器数据库采用sqlite3 // +---------------------------------------------------------------------- // | Author: luofei614<www.3g4k.com> // +---------------------------------------------------------------------- // $Id: ImitSqlite.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ class ImitSqlite extends SQLite3{ function __construct() { $this->open(dirname(__FILE__).'/sae.db'); } //获得数据,返回数组 public function getData($sql){ $this->last_sql = $sql; $result=$this->query($sql); if(!$result){ return false; } $data=array(); while($arr=$result->fetchArray(SQLITE3_ASSOC)){ $data[]=$arr; } return $data; } //返回第一条数据 public function getLine($sql) { $data = $this->getData($sql); if ($data) { return @reset($data); } else { return false; } } //返回第一条记录的第一个字段值 public function getVar($sql) { $data = $this->getLine($sql); if ($data) { return $data[@reset(@array_keys($data))]; } else { return false; } } //运行sql语句 public function runSql($sql) { return $this->exec($sql); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/ImitSqlite.class.php
PHP
art
1,474
<?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: luofei614 <www.3g4k.com> // +---------------------------------------------------------------------- // $Id: SaeObject.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ class SaeObject { protected $errno = SAE_Success; protected $errmsg; static $db; //实现自动建表 public function __construct() { $this->errmsg = Imit_L("_SAE_OK_"); static $inited = false; //只初始化一次 if ($inited) return; if (extension_loaded('sqlite3')) { self::$db = new ImitSqlite(); } else { self::$db = get_class($this) == "SaeMysql" ? $this : new SaeMysql(); $this->createTable(); } $inited = true; } //获得错误代码 public function errno() { return $this->errno; } //获得错误信息 public function errmsg() { return $this->errmsg; } public function setAuth($accesskey, $secretkey) { } protected function createTable() { $sql = file_get_contents(dirname(__FILE__).'/sae.sql'); $tablepre = C('DB_PREFIX'); $tablesuf = C('DB_SUFFIX'); $dbcharset = C('DB_CHARSET'); $sql = str_replace("\r", "\n",$sql); $ret = array(); $num = 0; foreach (explode(";\n", trim($sql)) as $query) { $queries = explode("\n", trim($query)); foreach ($queries as $query) { $ret[$num] .= $query[0] == '#' || $query[0] . $query[1] == '--' ? '' : $query; } $num++; } unset($sql); foreach ($ret as $query) { $query = trim($query); if ($query) { if (substr($query, 0, 12) == 'CREATE TABLE') { $name = preg_replace("/CREATE TABLE ([a-z0-9_]+) .*/is", "\\1", $query); $type = strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $query)); $type = in_array($type, array('MYISAM', 'HEAP')) ? $type : 'MYISAM'; $query = preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $query) . (mysql_get_server_info() > '4.1' ? " ENGINE=$type DEFAULT CHARSET=$dbcharset" : " TYPE=$type"); } self::$db->runSql($query); } } } } ?>
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/SaeObject.class.php
PHP
art
2,982
<?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: luofei614 <www.3g4k.com> // +---------------------------------------------------------------------- // $Id: SaeRank.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ class SaeRank extends SaeObject{ public function __construct(){ parent::__construct(); } public function clear($namespace){ if($this->emptyName($namespace)) return false; self::$db->runSql("delete from sae_rank where namespace='$namespace'"); self::$db->runSql("delete from sae_rank_list where namespace='$namespace'"); return true; } //创建 //expire过期时间的单位为分钟 public function create($namespace,$number,$expire=0){ //判断是否存在 if(!$this->emptyName($namespace)){ $this->errno=-10; $this->errmsg=Imit_L("_SAE_THE_RANK_IS_EXISTED_"); return false; } $ret=self::$db->runSql("insert into sae_rank(namespace,num,expire,createtime) values('$namespace','$number','$expire','".time()."')"); if($ret===false){ $this->errno=-6; $this->errmsg=Imit_L("_SAE_ERR_"); return false; }else{ return true; } } //减去 public function decrease($namespace,$key,$value,$renkReurn=false){ if($this->emptyName($namespace)) return false; $this->check($namespace); if(self::$db->getVar("select count(*) from sae_rank_list where namespace='$namespace' and k='$key'")==0){ //如果不存在 $this->errno=-3; $this->errmsg=Imit_L("_SAE_NOT_IN_BILLBOARD_"); return false; }else{ $ret=self::$db->runSql("update sae_rank_list set v=v-$value where namespace='$namespace' and k='$key'"); if($ret===false) return false; if(rankReturn){ return $this->getRank($namespace,$key); } return true; } } //删除键 public function delete($namespace,$key,$rankReturn=false){ if($this->emptyName($namespace)) return false; if($rankReturn) $r=$this->getRank($namespace,$key); $ret=self::$db->runSql("delete from sae_rank_list where namespace='$namespace' and k='$key'"); if($ret===false){ $this->errno=-6; $this->errmsg=Imit_L("_SAE_ERR_"); return false; }else{ if($rankReturn) return $r; return true; } } //获得排行榜 public function getList($namespace,$order=false,$offsetFrom=0,$offsetTo=PHP_INT_MAX){ //判断是否存在 if($this->emptyName($namespace)) return false; $ord="v asc"; //获得列表 if($order) $ord="v desc"; //判断是否有长度限制 $num=self::$db->getVar("select num from sae_rank where namespace='$namespace'"); if($num!=0){ $ord="v desc";//todu,完善和sae数据一致。 if($offsetTo>$num) $offsetTo=$num; } $data=self::$db->getData("select * from sae_rank_list where namespace='$namespace' order by $ord limit $offsetFrom,$offsetTo"); $ret=array(); foreach($data as $r){ $ret[$r['k']]=$r['v']; } $this->check($namespace);//检查过期 if($data===false){ $this->errno=-6; $this->errmsg=Imit_L("_SAE_ERR_"); return false; }else{ return $ret; } } //获得某个键的排名 //注意排名是从0开始的 public function getRank($namespace,$key){ if($this->emptyName($namespace)) return false; $v=self::$db->getVar("select v from sae_rank_list where namespace='$namespace' and k='$key'"); $ret=self::$db->getVar("select count(*) from sae_rank_list where namespace='$namespace' and v>=$v"); if(!$ret){ $this->errno=-3; $this->errmsg=Imit_L("_SAE_NOT_IN_BILLBOARD_"); return false; } return $ret-1; } //增加值 public function increase($namespace,$key,$value,$rankReturn=false){ if($this->emptyName($namespace)) return false; $this->check($namespace); if(self::$db->getVar("select count(*) from sae_rank_list where namespace='$namespace' and k='$key'")==0){ //如果不存在 $this->errno=-3; $this->errmsg=Imit_L("_SAE_NOT_IN_BILLBOARD_"); return false; }else{ $ret=self::$db->runSql("update sae_rank_list set v=v+$value where namespace='$namespace' and k='$key'"); if($ret===false) return false; if(rankReturn){ return $this->getRank($namespace,$key); } return true; } } //设置值 public function set($namespace,$key,$value,$rankReturn=false){ //判断是否存在 if($this->emptyName($namespace)) return false; //检查是否过期 $this->check($namespace); //设置值 //判断是否有此key if(self::$db->getVar("select count(*) from sae_rank_list where namespace='$namespace' and k='$key'")==0){ $setarr=array( 'namespace'=>$namespace, 'k'=>$key, 'v'=>$value ); $ret=self::$db->runSql("insert into sae_rank_list(namespace,k,v) values('$namespace','$key','$value')"); }else{ $ret=self::$db->runSql("update sae_rank_list set v='$value' where namespace='$namespace' and k='$key'"); } if($ret===false) return false; if($rankReturn){ //返回排名 return $this->getRank($namespace,$key); } return true; } //判断是否为空 private function emptyName($name){ $num=self::$db->getVar("select count(*) from sae_rank where namespace='$name'"); if($num==0){ return true; }else{ $this->errno=-4; $this->errmsg=Imit_L("_SAE_BILLBOARD_NOT_EXISTS_"); return false; } } //检查是否过期 private function check($name){ $data=self::$db->getLine("select * from sae_rank where namespace='$name'"); if($data['expire'] && $data['createtime']+$data['expire']*60<=time()){ self::$db->runSql("delete from sae_rank_list where namespace='$name'"); //重新设置创建时间 self::$db->runSql("update sae_rank set createtime='".time()."' where namespace='$name'"); } } } ?>
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/SaeRank.class.php
PHP
art
6,491
<?php class SaeImage extends SaeObject { private $_img_data = ''; //图片数据 private $_options = array(); //图片选项 private $_width = 0; private $_height = 0; private $_image = null; //存储image资源 const image_limitsize = 2097152; public function __construct($img_data='') { parent::__construct(); return $this->setData($img_data); } //添加文字注释 public function annotate($txt, $opacity=0.5, $gravity=SAE_Static, $font=array()) { $opacity = floatval($opacity); if ($this->imageNull()) return false; //设置默认字体样式 $font_default = array('name' => SAE_SimSun, 'size' => 15, 'weight' => 300, 'color' => 'black'); $font = array_merge($font_default, $font); array_push($this->_options, array('act' => 'annotate', "txt" => $txt, "opacity" => $opacity, "gravity" => $gravity, "font" => array("name" => $font['name'], "size" => $font["size"], "weight" => $font["weight"], "color" => $font["color"]))); return true; } //数据重新初始化 public function clean() { $this->_img_data = ''; $this->_options = array(); $this->_width = 0; $this->_height = 0; $this->_image = null; } //图片合成, data为数组,在其他操作执行前进行操作 public function composite($width, $height, $color="black") { $width = intval($width); $height = intval($height); if ($this->imageNull()) return false; array_push($this->_options, array('act' => 'composite', "width" => $width, "height" => $height, "color" => $color)); return true; } //裁剪图片 public function crop($lx=0.25, $rx=0.75, $by=0.25, $ty=0.75) { $lx = floatval($lx); $rx = floatval($rx); $by = floatval($by); $ty = floatval($ty); if ($this->imageNull()) return false; array_push($this->_options, array('act' => 'crop', "lx" => $lx, "rx" => $rx, "by" => $by, "ty" => $ty)); return true; } //进行图片处理操作 public function exec($format='jpg', $display=false) { if ($this->imageNull()) return false; if (!in_array($format, array('jpg', 'gif', 'png'))) { $this->errno = SAE_ErrParameter; $this->errmsg = "format must be one of 'jpg', 'gif' and 'png'"; return false; } if ($format == "jpg") $format = "jpeg"; if ($this->_options[0]["act"] == "composite" && !is_array($this->_img_data)) { $this->errno = SAE_ErrParameter; $this->errmsg = "composite imagedata must be an array, pls see doc:"; return false; } if ($this->_options[0]["act"] != "composite" && is_array($this->_img_data)) { $this->errno = SAE_ErrParameter; $this->errmsg = "imagedata is array only when composite image and composite must be the first operation"; return false; } if (!$this->_image_create()) return false; //循环处理 foreach ($this->_options as $options) { call_user_func(array($this, "_" . $options['act']), $options); } $imgFun = 'image' . $format; if ($display) { header("Content-Type: image/" . $format); $imgFun($this->_image); } else { ob_start(); $imgFun($this->_image); return ob_get_clean(); } imagedestroy($this->_image); } //创建画布 private function _image_create() { if ($this->_options[0]["act"] == "composite") { //合并多张图片 $w = $this->_options[0]["width"]; $h = $this->_options[0]["height"]; $this->_width=$w; $this->_height=$h; $_image = imagecreatetruecolor($w, $h); //设置背景颜色 $color = $this->toRGB($this->_options[0]['color']); $bg = imagecolorallocate($_image, $color['r'], $color['g'], $color['b']); imagefill($_image, 0, 0, $bg); foreach ($this->_img_data as $data) { $img_data = $data[0]; $x = isset($data[1]) ? $data[1] : 0; $y = isset($data[2]) ? $data[2] : 0; $o = isset($data[3]) ? $data[3] * 100 : 100; $p = isset($data[4]) ? $data[4] : SAE_TOP_LEFT; $tmp_file = tempnam(SAE_TMP_PATH, "SAE_IMAGE"); if (!file_put_contents($tmp_file, $img_data)) { $this->errmsg = "file_put_contents to SAETMP_PATH failed when getImageAttr"; return false; } $info = getimagesize($tmp_file); $sw = $info[0]; $sh = $info[1]; $image_type = strtolower(substr(image_type_to_extension($info[2]), 1)); $createFun = "imagecreatefrom" . $image_type; $sImage = $createFun($tmp_file); //设置位置 switch ($p) { case SAE_TOP_LEFT: $dst_x = $x; $dst_y = -$y; break; case SAE_TOP_CENTER: $dst_x = ($w - $sw) / 2 + $x; $dst_y = -$y; break; case SAE_TOP_RIGHT: $dst_x = $w - $sw + $x; $dst_y = -$y; break; case SAE_CENTER_LEFT: $dst_x = $x; $dst_y = ($h - $sh) / 2 - $y; break; case SAE_CENTER_CENTER: $dst_x = ($w - $sw) / 2 + $x; $dst_y = ($h - $sh) / 2 - $y; break; case SAE_CENTER_RIGHT: $dst_x = $w - $sw + $x; $dst_y = ($h - $sh) / 2 - $y; break; case SAE_BOTTOM_LEFT: $dst_x = $x; $dst_y = $h - $sh - $y; break; case SAE_BOTTOM_CENTER: $dst_x = ($w - $sw) / 2 + $x; $dst_y = $h - $sh - $y; break; case SAE_BOTTOM_RIGHT: $dst_x = $w - $sw + $x; $dst_y = $h - $sh - $y; break; } $this->imagecopymerge_alpha($_image, $sImage, $dst_x, $dst_y, 0, 0, $sw, $sh, $o); unlink($tmp_file); } $this->_image = $_image; unset($this->_options[0]); } else { if (is_null($this->_image)) $this->getImageAttr(); } return true; } //修复合并时png透明问题 private function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){ $w = imagesx($src_im); $h = imagesy($src_im); $cut = imagecreatetruecolor($src_w, $src_h); imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h); imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h); imagecopymerge($dst_im, $cut, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h,$pct); } //水平翻转 public function flipH() { if ($this->imageNull()) return false; array_push($this->_options, array('act' => 'flipH')); return true; } //垂直翻转 public function flipV() { if ($this->imageNull()) return false; array_push($this->_options, array('act' => 'flipV')); return true; } //获取图像属性 public function getImageAttr() { if ($this->imageNull()) return false; $fn = tempnam(SAE_TMP_PATH, "SAE_IMAGE"); if ($fn == false) { $this->errmsg = "tempnam call failed when getImageAttr"; return false; } if (!file_put_contents($fn, $this->_img_data)) { $this->errmsg = "file_put_contents to SAETMP_PATH failed when getImageAttr"; return false; } if (!($size = getimagesize($fn, $info))) { $this->errmsg = "getimagesize failed when getImageAttr"; return false; } foreach ($info as $k => $v) { $size[$k] = $v; } $this->_width = $size[0]; $this->_height = $size[1]; //建立图片资源 $image_type = strtolower(substr(image_type_to_extension($size[2]), 1)); $createFun = "imagecreatefrom" . $image_type; $this->_image = $createFun($fn); unlink($fn); //删除临时文件 return $size; } //去噪点,改善图片质量,通常用于exec之前 public function improve() { if ($this->imageNull()) return false; array_push($this->_options, array('act' => 'improve')); return true; } //等比例缩放 public function resize($width=0, $height=0) { $width = intval($width); $height = intval($height); if ($this->imageNull()) return false; array_push($this->_options, array('act' => 'resize', "width" => $width, "height" => $height)); return true; } //按比例缩放 public function resizeRatio($ratio=0.5) { $ratio = floatval($ratio); if ($this->imageNull()) return false; if ($this->_width == 0) { $attr = $this->getImageAttr(); if (!$attr) return false; } array_push($this->_options, array('act' => 'resize', "width" => $this->_width * $ratio, "height" => $this->_height * $ratio)); return true; } //顺时针旋转图片 public function rotate($degree=90) { $degree = intval($degree); if ($this->imageNull()) return false; array_push($this->_options, array('act' => 'rotate', "degree" => $degree)); return true; } //设置数据 public function setData($img_data) { if (is_array($img_data)) { $_size = 0; foreach ($img_data as $k => $i) { if (count($i) < 1 || count($i) > 5) { $this->errno = SAE_ErrParameter; $this->errmsg = "image data array you supplied invalid"; return false; } if (is_null($i[1]) || $i[1] === false) $img_data[$k][1] = 0; if (is_null($i[2]) || $i[1] === false) $img_data[$k][2] = 0; if (is_null($i[3]) || $i[1] === false) $img_data[$k][3] = 1; if (is_null($i[4]) || $i[1] === false) $img_data[$k][4] = SAE_TOP_LEFT; $_size += strlen($i[0]); } if ($_size > self::image_limitsize) { $this->errno = SAE_ErrParameter; $this->errmsg = "image datas length more than 2M"; return false; } } else if (strlen($img_data) > self::image_limitsize) { $this->errno = SAE_ErrParameter; $this->errmsg = "image data length more than 2M"; return false; } $this->_img_data = $img_data; return true; } //判断图片数据是否可用 private function imageNull() { if (empty($this->_img_data)) { $this->errno = SAE_ErrParameter; $this->errmsg = "image data cannot be empty"; return true; } else { return false; } } //将颜色转换为RGB格式 private function toRGB($color) { $color = trim($color); if (preg_match('/^rgb\((\d+),(\d+),(\d+)\)$/i', $color, $arr)) { //支持rgb(r,g,b)格式 return array( 'r' => $arr[1], 'g' => $arr[2], 'b' => $arr[3] ); } $e_color = array( //支持英文颜色名 'black' => '#000', 'red' => '#f00', 'blue'=>'#00f' //TODU 增加其他 ); $hexColor = str_replace(array_keys($e_color), array_values($e_color), $color); $color = str_replace('#', '', $hexColor); if (strlen($color) > 3) { $rgb = array( 'r' => hexdec(substr($color, 0, 2)), 'g' => hexdec(substr($color, 2, 2)), 'b' => hexdec(substr($color, 4, 2)) ); } else { $color = str_replace('#', '', $hexColor); $r = substr($color, 0, 1) . substr($color, 0, 1); $g = substr($color, 1, 1) . substr($color, 1, 1); $b = substr($color, 2, 1) . substr($color, 2, 1); $rgb = array( 'r' => hexdec($r), 'g' => hexdec($g), 'b' => hexdec($b) ); } return $rgb; } /** * 添加文字 * 参数格式 * array("txt" => $txt, "opacity" => $opacity, "gravity" => $gravity, "font" => array("name" => $font['name'], "size" => $font["size"], "weight" => $font["weight"], "color" => $font["color"])) * @param array $args */ private function _annotate($args) { $font = $args['font']; $rgb = $this->toRGB($font['color']); $color = imagecolorclosestalpha($this->_image, $rgb['r'], $rgb['g'], $rgb['b'], (1 - $args['opacity']) * 100); //设置位置 $fontSize = imagettfbbox($font['size'], 0, $font['name'], $args['txt']); $textWidth = $fontSize [4]; //取出宽 $textHeight = abs($fontSize[7]); //取出高 switch ($args['gravity']) { case SAE_NorthWest: $x=0; $y=$textHeight; break; case SAE_North: $x=($this->_width-$textWidth)/2;; $y=$textHeight; break; case SAE_NorthEast: $x=$this->_width-$textWidth;; $y=$textHeight; break; case SAE_West: $x=0; $y=($this->_height-$textHeight)/2; break; case SAE_East: $x=$this->_width-$textWidth; $y=($this->_height-$textHeight)/2; break; case SAE_SouthWest: $x=0; $y=$this->_height-$textHeight; break; case SAE_South: $x=($this->_width-$textWidth)/2; $y=$this->_height-$textHeight; break; case SAE_SouthEast: $x=$this->_width-$textWidth; $y=$this->_height-$textHeight; break; case SAE_Static: default : $x=($this->_width-$textWidth)/2; $y=($this->_height-$textHeight)/2; break; } imagettftext($this->_image, $font['size'], 0, $x, $y, $color, $font['name'], $args['txt']); } /** *截取图片 * 参数 array("lx" => $lx, "rx" => $rx, "by" => $by, "ty" => $ty) * @param array $args */ private function _crop($args){ $width=($args['rx']-$args['lx'])*$this->_width; $height=($args['ty']-$args['by'])*$this->_height; $x=$args['lx']*$this->_width; $y=$args['by']*$this->_height; $_image=imagecreatetruecolor($width, $height); imagecopyresampled($_image,$this->_image,0,0,$x,$y, $width,$height,$width,$height); $this->_image=$_image; } /** *图片放缩 * 参数:array( "width" => $width, "height" => $height) * @param array $args */ private function _resize($args){ if($args['width']==0 && $args['heigth']==0) return ; if($args['width']==0){ //高度固定等比例放缩 $h=$args['heigth']; $w=$h/$this->_height*$this->_width; }elseif($args['heigth']==0){ //宽度固定等比例放缩 $w=$args['width']; $h=$w/$this->_width*$this->_height; }else{ $w=$args['width']; $h=$args['height']; } $_image=imagecreatetruecolor($w, $h); imagecopyresampled($_image, $this->_image, 0, 0, 0, 0, $w, $h, $this->_width, $this->_height); $this->_image=$_image; } /** *旋转角度 * @param array $args */ private function _rotate($args){ $this->_image=imagerotate($this->_image, 360-$args['degree'],0); } //水平翻转 private function _flipH($args) { $_image=imagecreatetruecolor($this->_width, $this->_height); for ($i = 0; $i < $this->_width; $i++) { imagecopyresampled($_image, $this->_image, ($this->_width - $i), 0, $i, 0, 1, $this->_height, 1, $this->_height); } $this->_image=$_image; } //垂直翻转 private function _flipV($args) { $this->_flipH(array()); $this->_rotate(array('degree'=>180)); } //去除噪点 private function _improve($args){ //本地不做任何处理 } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/SaeImage.class.php
PHP
art
18,057
<?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: luofei614 <www.3g4k.com> // +---------------------------------------------------------------------- // $Id: SaeStorage.class.php 2803 2012-03-06 14:57:17Z luofei614@gmail.com $ /** * storage模拟器 * 在本地环境时,domain对应了Public文件夹下以domain名命名的的文件夹 */ //本地默认的域在public中, 建立的文件夹名为域名。 class SaeStorage extends SaeObject { private $domainDir; //域的根目录 private $filterPath; private $url; private $domainSize = array(); //记录域大小 private $domainSizeFlag = ""; //todu 增加api文档没有的函数 public function __construct($_accessKey='', $_secretKey='') { global $sae_config; $this->domainDir = $sae_config['storage_dir']; $this->url = $sae_config['storage_url']; parent::__construct(); } public function delete($domain, $filename) { $domain = trim($domain); $filename = $this->formatFilename($filename); if (Empty($domain) || Empty($filename)) { $this->errMsg = Imit_L("_SAE_STORAGE_PARAM_EMPTY_") . '[the value of parameter (domain,filename) can not be empty!]'; $this->errNum = -101; return false; } $filepath = $this->domainDir . $domain . "/" . $filename; if (unlink($filepath)) { return true; } else { $this->errno = -1; $this->errmsg = Imit_L("_SAE_STORAGE_DELETE_ERR_"); return false; } } public function deleteFolder($domain, $path) { $domain = trim($domain); $path = $this->formatFilename($path); if (Empty($domain) || Empty($path)) { $this->errmsg = Imit_L("_SAE_STORAGE_PARAM_EMPTY_") . '[the value of parameter (domain,path) can not be empty!]'; $this->errno = -101; return false; } $folder = $this->domainDir . $domain . "/" . $path; $this->delDir($folder); return true; } private function delDir($directory) { if (is_dir($directory) == false) { exit("The Directory Is Not Exist!"); } $handle = opendir($directory); while (($file = readdir($handle)) !== false) { if ($file != "." && $file != "..") { is_dir("$directory/$file") ? $this->delDir("$directory/$file") : unlink("$directory/$file"); } } if (readdir($handle) == false) { closedir($handle); rmdir($directory); } } public function fileExists($domain, $filename) { $domain = trim($domain); $filename = $this->formatFilename($filename); if (Empty($domain) || Empty($filename)) { $this->errmsg = Imit_L("_SAE_STORAGE_PARAM_EMPTY_") . '[the value of parameter (domain,filename) can not be empty!]'; $this->errno = -101; return false; } $filepath = $this->domainDir . $domain . "/" . $filename; return file_exists($filepath); } public function getAttr($domain, $filename, $attrKey=array()) { $filepath = $this->domainDir . $domain . "/" . $filename; if (!is_file($filepath)) { $this->errno = -1; $this->errmsg = Imit_L("_SAE_STORAGE_FILE_NOT_EXISTS_"); return false; } if (empty($attrKey)) $attrKey = array('fileName', 'length', 'datetime'); $ret = array(); foreach ($attrKey as $key) { switch ($key) { case "fileName": $ret['fileName'] = $filename; break; case "length": $ret['length'] = filesize($filepath); break; case "datetime": $ret['datetime'] = filemtime($filepath); //todu 需要验证一下 break; } } return $ret; } public function getDomainCapacity($domain) { if (!isset($this->domainSize[$domain])) $this->getList($domain); return $this->domainSize[$domain]; } public function getFilesNum($domain, $path=NULL) { static $filesNum = array(); if (isset($filesNum[md5($domin . $path)])) return $filesNum[md5($domin . $path)]; if ($path == NULL) $path = "*"; $filesNum[md5($domin . $path)] = count($this->getList($domain, $path)); return $filesNum[md5($domin . $path)]; } public function getList($domain, $prefix='*', $limit=10, $offset=0) { $domain = trim($domain); if (Empty($domain)) { $this->errMsg = Imit_L("_SAE_STORAGE_PARAM_EMPTY_") . '[the value of parameter (domain) can not be empty!]'; $this->errNum = -101; return false; } $path = $this->domainDir . $domain; $this->filterPath = $path . "/"; //记录域的大小 if ($prefix == "*" && !isset($this->domainSize[$domain])) $this->domainSizeFlag = $domain; $files = $this->getAllList($path, $prefix); $this->domainSizeFlag = ""; //偏移 return array_slice($files, $offset, $limit); } //获得所有文件 private function getAllList($path, $prefix, &$files=array()) { $list = glob($path . "/" . $prefix); //循环处理,创建数组 $dirs = array(); $_files = array(); foreach ($list as $i => $file) { if (is_dir($file) && !$this->isEmpty($file)) {//如果不是空文件夹 $dirs[] = $file; continue; }; if (!empty($this->domainSizeFlag)) $this->domainSize[$this->domainSizeFlag]+=filesize($file); //统计大小 $_files[$i]['name'] = str_replace($this->filterPath, '', $file); //不含域的名称 $_files[$i]['isDir'] = is_dir($file); } //排序$_files $cmp_func = create_function('$a,$b', ' $k="isDir"; if($a[$k] == $b[$k]) return 0; return $a[$k]>$b[$k]?-1:1; '); usort($_files, $cmp_func); foreach ($_files as $file) { //设置$files $files[] = $file['isDir'] ? $file['name'] . "/__________sae-dir-tag" : $file['name']; } //循环数组,读取二级目录 foreach ($dirs as $dir) { $this->getAllList($dir, "*", $files); } return $files; } //判断是否为空目录 private function isEmpty($directory) { $handle = opendir($directory); while (($file = readdir($handle)) !== false) { if ($file != "." && $file != "..") { closedir($handle); return false; } } closedir($handle); return true; } public function getListByPath($domain, $path=NULL, $limit=100, $offset=0, $fold=true) { $filepath = $this->domainDir . $domain . "/" . $path; $list = scandir($filepath); //读取非折叠数据 $files = array(); $dirnum = 0; $filenum = 0; foreach ($list as $file) { //统计 if ($file == '.' || $file == '..') continue; $fullfile = $filepath . "/" . $file; if (is_dir($fullfile)) { $dirnum++; $filename = $fullfile . "/__________sae-dir-tag"; } else { $filenum++; $filename = $fullfile; } $filename = str_replace($this->domainDir . $domain . "/", '', $filename); $files[] = array( 'name' => basename($filename), 'fullName' => $filename, 'length' => filesize($fullfile), 'uploadTime' => filectime($fullfile) ); } //偏移 $files = array_slice($files, $offset, $limit); if ($fold) { //折叠处理 $rets = array( 'dirNum' => $dirnum, 'fileNum' => $filenum ); foreach ($files as $file) { if ($file['name'] == "__________sae-dir-tag") { //文件夹 $rets['dirs'][] = array( 'name' => $file['name'], 'fullName' => $file['fullName'] ); } else { $rets['files'][] = $file; } } return $rets; } return $files; } public function getUrl($domain, $filename) { $domain = trim($domain); $filename = $this->formatFilename($filename); return $this->url. $domain . "/" . $filename; } public function read($domain, $filename) { $domain = trim($domain); $filename = $this->formatFilename($filename); if (Empty($domain) || Empty($filename)) { $this->errmsg = Imit_L("_SAE_STORAGE_PARAM_EMPTY_") . '[the value of parameter (domain,filename) can not be empty!]'; $this->errno = -101; return false; } $filepath = $this->domainDir . $domain . "/" . $filename; return file_get_contents($filepath); } public function setDomainAttr($domain, $attr=array()) { //pass return true; } public function setFileAttr($domain, $filename, $attr=array()) { //pass return true; } public function upload($domain, $destFileName, $srcFileName, $attr=array()) { $domain = trim($domain); $destFileName = $this->formatFilename($destFileName); if (Empty($domain) || Empty($destFileName) || Empty($srcFileName)) { $this->errmsg = Imit_L("_SAE_STORAGE_PARAM_EMPTY_") . '[the value of parameter (domain,destFile,srcFileName) can not be empty!]'; $this->errno = -101; return false; } return $this->write($domain,$destFileName,file_get_contents($srcFileName)); } public function write($domain, $destFileName, $content, $size=-1, $attr=array(), $compress=false) { if (Empty($domain) || Empty($destFileName)) { $this->errmsg = Imit_L("_SAE_STORAGE_PARAM_EMPTY_") . "[the value of parameter (domain,destFileName,content) can not be empty!]"; $this->errno = -101; return false; } //定义文件路径 $filepath = $this->domainDir . $domain . "/" . $destFileName; $this->mkdir(dirname($filepath)); //设置长度 if ($size > -1) $content = substr($content, 0, $size); //写入文件 if (file_put_contents($filepath, $content)) { return true; } else { $this->errmsg = Imit_L('_SAE_STORAGE_SERVER_ERR_'); $this->errno = -12; return false; } } //创建目录,无限层次。传递一个文件的 private function mkdir($dir) { static $_dir; // 记录需要建立的目录 if (!is_dir($dir)) { if (empty($_dir)) $_dir = $dir; if (!is_dir(dirname($dir))) { $this->mkdir(dirname($dir)); } else { mkdir($dir); if (!is_dir($_dir)) { $this->mkdir($_dir); } else { $_dir = ""; } } } } private function formatFilename($filename) { $filename = trim($filename); $encodings = array('UTF-8', 'GBK', 'BIG5'); $charset = mb_detect_encoding($filename, $encodings); if ($charset != 'UTF-8') { $filename = mb_convert_encoding($filename, "UTF-8", $charset); } return $filename; } } ?>
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/SaeStorage.class.php
PHP
art
12,417
<?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: luofei614 <www.3g4k.com> // +---------------------------------------------------------------------- // $Id: Lang.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ Imit_L(array( '_SAE_DATABASE_NOT_EXIST_'=>'数据库['.SAE_MYSQL_DB.']不存在', '_SAE_NOT_IN_BILLBOARD_'=>'查找元素没有在排行榜中[not in billboard]', '_SAE_BILLBOARD_NOT_EXISTS_'=>'排行榜不存在[billboard not exists]', '_SAE_THE_RANK_IS_EXISTED_'=>'排行榜已存在[the rank is existed]', '_SAE_ERR_'=>'SAE内部错误', '_SAE_OK_'=>'操作成功[OK]', '_SAE_ERRPARAMTER_'=>'参数错误[Unavailable tasks]', '_SAE_TASKQUEUE_SERVICE_FAULT_'=>'服务内部错误[taskqueue service segment fault]', '_SAE_TASKQUEUE_SERVICE_ERROR_'=>'服务内部错误[taskqueue service internal error]', '_SAE_UNKNOWN_ERROR_'=>'未知错误[unknown error]', '_SAE_STORAGE_PARAM_EMPTY_'=>'参数错误', '_SAE_STORAGE_SERVER_ERR_'=>'存储服务器返回错误', '_SAE_STORAGE_DELETE_ERR_'=>'删除失败[deleted failed!...]', '_SAE_STORAGE_FILE_NOT_EXISTS_'=>'文件不存在', '_SAE_MAIL_SIZE_lARGER_'=>'邮件内容过大[mail size cannot larger than 1048576 bytes]', '_SAE_CONNECT_DB_ERR_'=>'数据库连接失败', '_SAE_PLEASE_CONFIG_DB_'=>'请配置数据库' ) ); ?>
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/Lang.php
PHP
art
1,774
<?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: luofei614 <www.3g4k.com> // +---------------------------------------------------------------------- // $Id: SaeCounter.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ /** * SaeCounter模拟器 * 使用了数据库存储统计器信息, * 相关数据表:think_sae_counter */ class SaeCounter extends SaeObject { //创建统计器 public function create($name, $value=0) { //判断是否存在 if ($this->exists($name)) return false; return self::$db->runSql("insert into sae_counter(name,val) values('$name','$value')"); } //减法 public function decr($name, $value=1) { if (!$this->exists($name)) return false; self::$db->runSql("update sae_counter set val=val-$value where name='$name'"); return self::$db->getVar("select val from sae_counter where name='$name'"); } //是否存在 public function exists($name) { $num = self::$db->getVar("select count(*) from sae_counter where name='$name'"); return $num != 0 ? true : false; } public function get($name) { if (!$this->exists($name)) return false; return self::$db->getVar("select val from sae_counter where name='$name'"); } public function getall() { $data = self::$db->getData("select * from sae_counter where name='$name'"); $ret = array(); foreach ($data as $r) { $ret[$r['name']] = $r['val']; } return $ret; } //加法 public function incr($name, $value=1) { if (!$this->exists($name)) return false; self::$db->runSql("update sae_counter set val=val+$value where name='$name'"); return self::$db->getVar("select val from sae_counter where name='$name'"); } public function length() { return self::$db->getVar("select count(*) from sae_counter"); } //获得多个统计器,names为数组 public function mget($names) { array_walk($names, function(&$name) { $name = "'$name'"; }); $where = implode(',', $names); $data = self::$db->getData("select * from sae_counter where name in($where)"); $ret = array(); foreach ($data as $r) { $ret[$r['name']] = $r['val']; } return $ret; } public function remove($name) { if (!$this->exists($name)) return false; return self::$db->runSql("delete from sae_counter where name='$name'"); } //设置值 public function set($name, $value) { return self::$db->runSql("update sae_counter set val='$value' where name='$name'"); } } ?>
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/SaeCounter.class.php
PHP
art
3,296
<?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: luofei614 <www.3g4k.com> // +---------------------------------------------------------------------- // $Id: SaeMail.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ /** *Mail模拟器 *todu, 支持ssl和附件上传。 *现在暂不支持ssl,建议不用使用gmail测试。 */ class SaeMail extends SaeObject{ private $msp = array( "sina.com" => array("smtp.sina.com",25,0), "sina.cn" => array("smtp.sina.cn",25,0), "163.com" => array("smtp.163.com",25,0), "263.com" => array("smtp.263.com",25,0), "gmail.com" => array("smtp.gmail.com",587,1), "sohu.com" => array("smtp.sohu.com",25,0), "qq.com" => array("smtp.qq.com",25,0), "vip.qq.com" => array("smtp.qq.com",25,0), "126.com" => array("smtp.126.com",25,0), ); private $_post=array(); const mail_limitsize=1048576; const subject_limitsize=256; private $_count; private $_attachSize; private $_allowedAttachType = array("bmp","css","csv","gif","htm","html","jpeg","jpg","jpe","pdf","png","rss","text","txt","asc","diff","pot","tiff","tif","wbmp","ics","vcf"); public function __construct($options=array()){ $this->setOpt($options); } public function clean(){ $this->_post = array(); $this->_count = 0; $this->_attachSize = 0; return true; } public function quickSend($to,$subject,$msgbody,$smtp_user,$smtp_pass,$smtp_host='',$smtp_port=25,$smtp_tls=false){ $to = trim($to); $subject = trim($subject); $msgbody = trim($msgbody); $smtp_user = trim($smtp_user); $smtp_host = trim($smtp_host); $smtp_port = intval($smtp_port); $this->_count = strlen($msgbody) + $this->_attachSize; if(strlen($subject) > self::subject_limitsize) { $this->errno = SAE_ErrParameter; $this->errmsg = "subject cannot larger than ".self::subject_limitsize." bytes"; return false; } if($this->_count > self::mail_limitsize) { $this->errno = SAE_ErrParameter; $this->errmsg = "mail size cannot larger than ".self::subject_limitsize." bytes"; return false; } if (filter_var($smtp_user, FILTER_VALIDATE_EMAIL)) { preg_match('/([^@]+)@(.*)/', $smtp_user, $match); $user = $match[1]; $host = $match[2]; if(empty($smtp_host)) { //print_r($match); if(isset($this->msp[$host])) { $smtp_host = $this->msp[$host][0]; } else { $this->errno = SAE_ErrParameter; $this->errmsg = "you can set smtp_host explicitly or choose msp from sina,gmail,163,265,netease,qq,sohu,yahoo"; return false; } } if($smtp_port == 25 and isset($this->msp[$host])) { $smtp_port = $this->msp[$host][1]; } if(!$smtp_tls and isset($this->msp[$host])) { $smtp_tls = $this->msp[$host][2]; } $smtp_tls = ($smtp_tls == true); $username = $user; } else { $this->_errno = SAE_ErrParameter; $this->_errmsg = "invalid email address"; return false; } $this->_post = array_merge($this->_post, array("from"=>$smtp_user, "smtp_username"=>$username, "smtp_password"=>$smtp_pass, "smtp_host"=>$smtp_host, "smtp_port"=>$smtp_port, 'to'=>$to,'subject'=>$subject,'content'=>$msgbody, 'tls'=>$smtp_tls)); return $this->send(); } public function send(){ if ( empty($this->_post['from']) || empty($this->_post['to']) || empty($this->_post['smtp_host']) || empty($this->_post['smtp_username']) || empty($this->_post['smtp_password']) || empty($this->_post['subject']) ) { $this->_errno = SAE_ErrParameter; $this->_errmsg = "parameters from, to, subject, smtp_host, smtp_username, smtp_password can no be empty"; return false; } if($this->_count > self::mail_limitsize) { $this->_errno = SAE_ErrForbidden; $this->_errmsg = "mail size cannot larger than ".self::mail_limitsize." bytes"; return false; } //连接服务器 $fp = fsockopen ( $this->_post['smtp_host'], $this->_post['smtp_port'], $errno, $errstr, 60); if (!$fp ) return "联接服务器失败".__LINE__; stream_set_blocking($fp, true ); $lastmessage=fgets($fp,512); if ( substr($lastmessage,0,3) != 220 ) return "error1:".$lastmessage.__LINE__; //HELO $yourname = "YOURNAME"; $lastact="EHLO ".$yourname."\r\n"; fputs($fp, $lastact); $lastmessage == fgets($fp,512); if (substr($lastmessage,0,3) != 220 ) return "error2:$lastmessage".__LINE__; while (true) { $lastmessage = fgets($fp,512); if ( (substr($lastmessage,3,1) != "-") or (empty($lastmessage)) ) break; } //身份验证 //验证开始 $lastact="AUTH LOGIN"."\r\n"; fputs( $fp, $lastact); $lastmessage = fgets ($fp,512); if (substr($lastmessage,0,3) != 334) return "error3:$lastmessage".__LINE__; //用户姓名 $lastact=base64_encode($this->_post['smtp_username'])."\r\n"; fputs( $fp, $lastact); $lastmessage = fgets ($fp,512); if (substr($lastmessage,0,3) != 334) return "error4:$lastmessage".__LINE__; //用户密码 $lastact=base64_encode($this->_post['smtp_password'])."\r\n"; fputs( $fp, $lastact); $lastmessage = fgets ($fp,512); if (substr($lastmessage,0,3) != "235") return "error5:$lastmessage".__LINE__; //FROM: $lastact="MAIL FROM: ". $this->_post['from'] . "\r\n"; fputs( $fp, $lastact); $lastmessage = fgets ($fp,512); if (substr($lastmessage,0,3) != 250) return "error6:$lastmessage".__LINE__; //TO: $lastact="RCPT TO: ".$this->_post['to']. "\r\n"; fputs( $fp, $lastact); $lastmessage = fgets ($fp,512); if (substr($lastmessage,0,3) != 250) return "error7:$lastmessage".__LINE__; //DATA $lastact="DATA\r\n"; fputs($fp, $lastact); $lastmessage = fgets ($fp,512); if (substr($lastmessage,0,3) != 354) return "error8:$lastmessage".__LINE__; //处理Subject头 $head="Subject: ".$this->_post['subject']."\r\n"; $message = $head."\r\n".$this->_post['content']; //处理From头 $head="From: ".$this->_post['from']."\r\n"; $message = $head.$message; //处理To头 $head="To: ".$this->_post['to']."\r\n"; $message = $head.$message; //加上结束串 $message .= "\r\n.\r\n"; //发送信息 fputs($fp, $message); $lastact="QUIT\r\n"; fputs($fp,$lastact); fclose($fp); } public function setAttach($attach){ if(!is_array($attach)) { $this->errmsg = "attach parameter must be an array!"; $this->errno = SAE_ErrParameter; return false; } $this->_attachSize = 0; foreach($attach as $fn=>$blob) { $suffix = end(explode(".", $fn)); if(!in_array($suffix, $this->_allowedAttachType)) { $this->errno = SAE_ErrParameter; $this->errmsg = "Invalid attachment type"; return false; } $this->_attachSize += strlen($blob); $this->_count = $this->_attachSize + strlen($this->_post['content']); if($this->_count > self::mail_limitsize) { $this->errno = SAE_ErrForbidden; $this->errmsg = "mail size cannot larger than ".self::mail_limitsize." bytes"; return false; } //$this->_post = array_merge($this->_post, array("attach:$fn:B:".$this->_disposition[$suffix] => base64_encode($blob))); } return true; } public function setOpt($options){ if (isset($options['subject']) && strlen($options['subject']) > self::subject_limitsize) { $this->errno = SAE_ErrParameter; $this->errmsg = Imit_L("_SAE_MAIL_SIZE_lARGER_"); return false; } if(isset($options['content'])) $this->_count = $this->_attachSize + strlen($options['content']); if($this->_count > self::mail_limitsize) { $this->errno = SAE_ErrParameter; $this->errmsg = Imit_L("_SAE_MAIL_SIZE_lARGER_"); return false; } $this->_post = array_merge($this->_post, $options); return true; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/SaeMail.class.php
PHP
art
8,282
<?php /** * SAE数据抓取服务 * * @author zhiyong * @version $Id: SaeFetchurl.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ * @package sae * */ /** * SAE数据抓取class * * SaeFetchurl用于抓取外部数据。支持的协议为http/https。<br /> * 该类已被废弃,请直接使用curl抓取外部资源 * @deprecated 该类已被废弃,请直接使用curl抓取外部资源 * * 默认超时时间: * - 连接超时: 5秒 * - 发送数据超时: 30秒 * - 接收数据超时: 40秒 * * 抓取页面 * <code> * $f = new SaeFetchurl(); * $content = $f->fetch('http://sina.cn'); * </code> * * 发起POST请求 * <code> * $f = new SaeFetchurl(); * $f->setMethod('post'); * $f->setPostData( array('name'=> 'easychen' , 'email' => 'easychen@gmail.com' , 'file' => '文件的二进制内容') ); * $ret = $f->fetch('http://photo.sinaapp.com/save.php'); * * //抓取失败时输出错误码和错误信息 * if ($ret === false) * var_dump($f->errno(), $f->errmsg()); * </code> * * 错误码参考: * - errno: 0 成功 * - errno: 600 fetchurl 服务内部错误 * - errno: 601 accesskey 不存在 * - errno: 602 认证错误,可能是secretkey错误 * - errno: 603 超出fetchurl的使用配额 * - errno: 604 REST 协议错误,相关的header不存在或其它错误,建议使用SAE提供的fetch_url函数 * - errno: 605 请求的URI格式不合法 * - errno: 606 请求的URI,服务器不可达。 * * @author zhiyong * @version $Id: SaeFetchurl.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ * @package sae * */ class SaeFetchurl extends SaeObject { function __construct( $akey = NULL , $skey = NULL ) { if( $akey === NULL ) $akey = SAE_ACCESSKEY; if( $skey === NULL ) $skey = SAE_SECRETKEY; $this->impl_ = new FetchUrl($akey, $skey); $this->method_ = "get"; $this->cookies_ = array(); $this->opt_ = array(); $this->headers_ = array(); } /** * 设置acccesskey和secretkey * * 使用当前的应用的key时,不需要调用此方法 * * @param string $akey * @param string $skey * @return void * @author zhiyong * @ignore */ public function setAuth( $akey , $skey ) { $this->impl_->setAccesskey($akey); $this->impl_->setSecretkey($skey); } /** * @ignore */ public function setAccesskey( $akey ) { $this->impl_->setAccesskey($akey); } /** * @ignore */ public function setSecretkey( $skey ) { $this->impl_->setSecretkey($skey); } /** * 设置请求的方法(POST/GET/PUT... ) * * @param string $method * @return void * @author zhiyong */ public function setMethod( $method ) { $this->method_ = trim($method); $this->opt_['method'] = trim($method); } /** * 设置POST方法的数据 * * @param array|string $post_data 当格式为array时,key为变量名称,value为变量值,使用multipart方式提交。当格式为string时,直接做为post的content提交。与curl_setopt($ch, CURLOPT_POSTFIELDS, $data)中$data的格式相同。 * @param bool $multipart value是否为二进制数据 * @return bool * @author zhiyong */ public function setPostData( $post_data , $multipart = false ) { $this->opt_["post"] = $post_data; $this->opt_["multipart"] = $multipart; return true; } /** * 在发起的请求中,添加请求头 * * 不可以使用此方法设定的头: * - Content-Length * - Host * - Vary * - Via * - X-Forwarded-For * - FetchUrl * - AccessKey * - TimeStamp * - Signature * - AllowTruncated //可使用setAllowTrunc方法来进行设定 * - ConnectTimeout //可使用setConnectTimeout方法来进行设定 * - SendTimeout //可使用setSendTimeout方法来进行设定 * - ReadTimeout //可使用setReadTimeout方法来进行设定 * * * @param string $name * @param string $value * @return bool * @author zhiyong */ public function setHeader( $name , $value ) { $name = trim($name); if (!in_array(strtolower($name), FetchUrl::$disabledHeaders)) { $this->headers_[$name] = $value; return true; } else { trigger_error("Disabled FetchUrl Header:" . $name, E_USER_NOTICE); return false; } } /** * 设置FetchUrl参数 * * 参数列表: * - truncated 布尔 是否截断 * - redirect 布尔 是否支持重定向 * - username 字符串 http认证用户名 * - password 字符串 http认证密码 * - useragent 字符串 自定义UA * * @param string $name * @param string $value * @return void * @author Elmer Zhang * @ignore */ public function setOpt( $name , $value ) { $name = trim($name); $this->opt_[$name] = $value; } /** * 在发起的请求中,批量添加cookie数据 * * @param array $cookies 要添加的Cookies,格式:array('key1' => 'value1', 'key2' => 'value2', ....) * @return void * @author zhiyong */ public function setCookies( $cookies = array() ) { if ( is_array($cookies) and !empty($cookies) ) { foreach ( $cookies as $k => $v ) { $this->setCookie($k, $v); } } } /** * 在发起的请求中,添加cookie数据,此函数可多次调用,添加多个cookie * * @param string $name * @param string $value * @return void * @author zhiyong */ public function setCookie( $name , $value ) { $name = trim($name); array_push($this->cookies_, "$name=$value"); } /** * 是否允许截断,默认为不允许 * * 如果设置为true,当发送数据超过允许大小时,自动截取符合大小的部分;<br /> * 如果设置为false,当发送数据超过允许大小时,直接返回false; * * @param bool $allow * @return void * @author zhiyong */ public function setAllowTrunc($allow) { $this->opt_["truncated"] = $allow; } /** * 设置连接超时时间,此时间必须小于SAE系统设置的时间,否则以SAE系统设置为准(默认为5秒) * * @param int $ms 毫秒 * @return void * @author zhiyong */ public function setConnectTimeout($ms) { $this->opt_["connecttimeout"] = $ms; } /** * 设置发送超时时间,此时间必须小于SAE系统设置的时间,否则以SAE系统设置为准(默认为20秒) * * @param int $ms 毫秒 * @return void * @author zhiyong */ public function setSendTimeout($ms) { $this->opt_["sendtimeout"] = $ms; } /** * 设置读取超时时间,此时间必须小于SAE系统设置的时间,否则以SAE系统设置为准(默认为60秒) * * @param int $ms 毫秒 * @return void * @author zhiyong */ public function setReadTimeout($ms) { $this->opt_["ReadTimeout"] = $ms; } /** * 当请求页面是转向页时,是否允许跳转,SAE最大支持5次跳转(默认不跳转) * * @param bool $allow 是否允许跳转。true:允许,false:禁止,默认为true * @return void * @author zhiyong */ public function setAllowRedirect($allow = true) { $this->opt_["redirect"] = $allow; } /** * 设置HTTP认证用户名密码 * * @param string $username HTTP认证用户名 * @param string $password HTTP认证密码 * @return void * @author zhiyong */ public function setHttpAuth($username, $password) { $this->opt_["username"] = $username; $this->opt_["password"] = $password; } /** * 发起请求 * * <code> * <?php * echo "Use callback function\n"; * * function demo($content) { * echo strtoupper($content); * } * * $furl = new SaeFetchurl(); * $furl->fetch($url, $opt, 'demo'); * * echo "Use callback class\n"; * * class Ctx { * public function demo($content) { * $this->c .= $content; * } * public $c; * }; * * $ctx = new Ctx; * $furl = new SaeFetchurl(); * $furl->fetch($url, $opt, array($ctx, 'demo')); * echo $ctx->c; * ?> * </code> * * @param string $url * @param array $opt 请求参数,格式:array('key1'=>'value1', 'key2'=>'value2', ... )。参数列表: * - truncated 布尔 是否截断 * - redirect 布尔 是否支持重定向 * - username 字符串 http认证用户名 * - password 字符串 http认证密码 * - useragent 字符串 自定义UA * @param callback $callback 用来处理返回的数据的函数。可以为函数名或某个实例对象的方法。 * @return string 成功时读取到的内容,否则返回false * @author zhiyong */ public function fetch( $url, $opt = NULL, $callback=NULL ) { if (count($this->cookies_) != 0) { $this->opt_["cookie"] = join("; ", $this->cookies_); } $opt = ($opt) ? array_merge($this->opt_, $opt) : $this->opt_; return $this->impl_->fetch($url, $opt, $this->headers_, $callback); } /** * 返回数据的header信息 * * @param bool $parse 是否解析header,默认为true。 * @return array * @author zhiyong */ public function responseHeaders($parse = true) { $items = explode("\r\n", $this->impl_->headerContent()); if (!$parse) { return $items; } array_shift($items); $headers = array(); foreach ($items as $_) { $pos = strpos($_, ":"); $key = trim(substr($_, 0, $pos)); $value = trim(substr($_, $pos + 1)); if ($key == "Set-Cookie") { if (array_key_exists($key, $headers)) { array_push($headers[$key], trim($value)); } else { $headers[$key] = array(trim($value)); } } else { $headers[$key] = trim($value); } } return $headers; } /** * 返回HTTP状态码 * * @return int * @author Elmer Zhang */ public function httpCode() { return $this->impl_->httpCode(); } /** * 返回网页内容 * 常用于fetch()方法返回false时 * * @return string * @author Elmer Zhang */ public function body() { return $this->impl_->body(); } /** * 返回头里边的cookie信息 * * @param bool $all 是否返回完整Cookies信息。为true时,返回Cookie的name,value,path,max-age,为false时,只返回Cookies的name, value * @return array * @author zhiyong */ public function responseCookies($all = true) { $header = $this->impl_->headerContent(); $matchs = array(); $cookies = array(); $kvs = array(); if (preg_match_all('/Set-Cookie:\s([^\r\n]+)/i', $header, $matchs)) { foreach ($matchs[1] as $match) { $cookie = array(); $items = explode(";", $match); foreach ($items as $_) { $item = explode("=", trim($_)); $cookie[$item[0]]= $item[1]; } array_push($cookies, $cookie); $kvs = array_merge($kvs, $cookie); } } if ($all) { return $cookies; } else { unset($kvs['path']); unset($kvs['max-age']); return $kvs; } } /** * 返回错误码 * * @return int * @author zhiyong */ public function errno() { if ($this->impl_->errno() != 0) { return $this->impl_->errno(); } else { if ($this->impl_->httpCode() != 200) { return $this->impl_->httpCode(); } } return 0; } /** * 返回错误信息 * * @return string * @author zhiyong */ public function errmsg() { if ($this->impl_->errno() != 0) { return $this->impl_->error(); } else { if ($this->impl_->httpCode() != 200) { return $this->impl_->httpDesc(); } } return ""; } /** * 将对象的数据重新初始化,用于多次重用一个SaeFetchurl对象 * * @return void * @author Elmer Zhang */ public function clean() { $this->__construct(); } /** * 开启/关闭调试模式 * * @param bool $on true:开启调试;false:关闭调试 * @return void * @author Elmer Zhang */ public function debug($on) { if ($on) { $this->impl_->setDebugOn(); } else { $this->impl_->setDebugOff(); } } private $impl_; private $opt_; private $headers_; } /** * FetchUrl , the sub class of SaeFetchurl * * * @package sae * @subpackage fetchurl * @author zhiyong * @ignore */ class FetchUrl { const end_ = "http://fetchurl.sae.sina.com.cn/" ; const maxRedirect_ = 5; public static $disabledHeaders = array( 'content-length', 'host', 'vary', 'via', 'x-forwarded-for', 'fetchurl', 'accesskey', 'timestamp', 'signature', 'allowtruncated', 'connecttimeout', 'sendtimeout', 'readtimeout', ); public function __construct($accesskey, $secretkey) { $accesskey = trim($accesskey); $secretkey = trim($secretkey); $this->accesskey_ = $accesskey; $this->secretkey_ = $secretkey; $this->errno_ = 0; $this->error_ = null; $this->debug_ = false; } public function __destruct() { // do nothing } public function setAccesskey($accesskey) { $accesskey = trim($accesskey); $this->accesskey_ = $accesskey; } public function setSecretkey($secretkey) { $secretkey = trim($secretkey); $this->secretkey_ = $secretkey; } public function setDebugOn() { $this->debug_ = true; } public function setDebugOff() { $this->debug_ = false; } public function fetch($url, $opt = null, $headers = null, $callback = null) { $url = trim($url); if (substr($url, 0, 7) != 'http://' && substr($url, 0, 8) != 'https://') { $url = 'http://' . $url; } $this->callback_ = $callback; $maxRedirect = FetchUrl::maxRedirect_; if (is_array($opt) && array_key_exists('redirect',$opt) && !$opt['redirect']) { $maxRedirect = 1; } for ($i = 0; $i < $maxRedirect; ++$i) { $this->dofetch($url, $opt, $headers); if ($this->errno_ == 0) { if ($this->httpCode_ == 301 || $this->httpCode_ == 302) { $matchs = array(); if (preg_match('/Location:\s([^\r\n]+)/i', $this->header_, $matchs)) { $newUrl = $matchs[1]; // if new domain if (strncasecmp($newUrl, "http://", strlen("http://")) == 0) { $url = $newUrl; } else { $url = preg_replace('/^((?:https?:\/\/)?[^\/]+)\/(.*)$/i', '$1', $url) . "/". $newUrl; } if ($this->debug_) { echo "[debug] redirect to $url\n"; } continue; } } } break; } if ($this->errno_ == 0 && $this->httpCode_ == 200) { return $this->body_; } else { return false; } } public function headerContent() { return $this->header_; } public function errno() { return $this->errno_; } public function error() { return $this->error_; } public function httpCode() { return $this->httpCode_; } public function body() { return $this->body_; } public function httpDesc() { return $this->httpDesc_; } private function signature($url, $timestamp) { $content = "FetchUrl" . $url . "TimeStamp" . $timestamp . "AccessKey" . $this->accesskey_; $signature = (base64_encode(hash_hmac('sha256',$content,$this->secretkey_,true))); if ($this->debug_) { echo "[debug] content: $content" . "\n"; echo "[debug] signature: $signature" . "\n"; } return $signature; } // we have to set wirteBody & writeHeader public // for we used them in curl_setopt() public function writeBody($ch, $body) { if ($this->callback_) { call_user_func($this->callback_, $body); } else { $this->body_ .= $body; } if ($this->debug_) { echo "[debug] body => $body"; } return strlen($body); } public function writeHeader($ch, $header) { $this->header_ .= $header; if ($this->debug_) { echo "[debug] header => $header"; } return strlen($header); } private function dofetch($url, $opt, $headers_) { $this->header_ = $this->body_ = null; $headers = array(); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false) ; curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,true) ; curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this, 'writeBody')); curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'writeHeader')); if ($this->debug_) { curl_setopt($ch, CURLOPT_VERBOSE, true); } if (is_array($opt) && !empty($opt)) { foreach( $opt as $k => $v) { switch(strtolower($k)) { case 'username': if (array_key_exists("password",$opt)) { curl_setopt($ch, CURLOPT_USERPWD, $v . ":" . $opt["password"]); } break; case 'password': if (array_key_exists("username",$opt)) { curl_setopt($ch, CURLOPT_USERPWD, $opt["username"] . ":" . $v); } break; case 'useragent': curl_setopt($ch, CURLOPT_USERAGENT, $v); break; case 'post': curl_setopt($ch, CURLOPT_POSTFIELDS, $v); break; case 'cookie': curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_COOKIE, $v); break; case 'multipart': if ($v) array_push($headers, "Content-Type: multipart/form-data"); break; case 'truncated': array_push($headers, "AllowTruncated:" . $v); break; case 'connecttimeout': array_push($headers, "ConnectTimeout:" . intval($v)); break; case 'sendtimeout': array_push($headers, "SendTimeout:" . intval($v)); break; case 'readtimeout': array_push($headers, "ReadTimeout:" . intval($v)); break; default: break; } } } if (isset($opt['method'])) { if (strtolower($opt['method']) == 'get') { curl_setopt($ch, CURLOPT_HTTPGET, true); } } if (is_array($headers_) && !empty($headers_)) { foreach($headers_ as $k => $v) { if (!in_array(strtolower($k), FetchUrl::$disabledHeaders)) { array_push($headers, "{$k}:" . $v); } } } curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_ENCODING, ""); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_exec($ch); $info = curl_getinfo($ch); if ($this->debug_) { echo "[debug] curl_getinfo => " . print_r($info, true) . "\n"; } $this->errno_ = curl_errno($ch); $this->error_ = curl_error($ch); if ($this->errno_ == 0) { $matchs = array(); if (preg_match('/^(?:[^\s]+)\s([^\s]+)\s([^\r\n]+)/', $this->header_, $matchs)) { $this->httpCode_ = $matchs[1]; $this->httpDesc_ = $matchs[2]; if ($this->debug_) { echo "[debug] httpCode = " . $this->httpCode_ . " httpDesc = " . $this->httpDesc_ . "\n"; } } else { $this->errno_ = -1; $this->error_ = "invalid response"; } } curl_close($ch); } private $accesskey_; private $secretkey_; private $errno_; private $error_; private $httpCode_; private $httpDesc_; private $header_; private $body_; private $debug_; }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/SaeFetchurl.class.php
PHP
art
18,374
<?php //SAE系统函数 function sae_set_display_errors($show=true){ //在本地设置不显示错误, 只不显示sae_debug的文字信息, 但是会显示系统错误,方便我们开发。 global $sae_config; $sae_config['display_error']=$show; } function sae_debug($log){ global $sae_config; error_log(date('[c]').$log.PHP_EOL,3,$sae_config['debug_file']); if($sae_config['display_error']!==false){ echo $log.PHP_EOL; } } function memcache_init(){ static $handler; if(is_object($handler)) return $handler; $handler=new Memcache; $handler->connect('127.0.0.1',11211); return $handler; } function sae_xhprof_start() { //pass } function sae_xhprof_end() { return true; } //向下兼容函数 function sae_image_init( $ak='', $sk='', $image_bin = '' ) { if( !isset( $GLOBALS['sae_image_instance'] ) ) { $GLOBALS['sae_image_instance'] = new SaeImage($image_bin); } return $GLOBALS['sae_image_instance']; } function sae_storage_init( $accesskey , $secretkey , $ssl = false ) { if( !isset( $GLOBALS['sae_storage_instance'] ) ) { include_once( 'sae_storage.class.php' ); $GLOBALS['sae_storage_instance'] = new SaeStorage($accesskey,$secretkey); } return $GLOBALS['sae_storage_instance']; } function sae_mysql_init( $host , $port , $accesskey , $secretkey , $appname , $do_replication = true ) { if( !isset( $GLOBALS['sae_mysql_instance'] ) ) { include_once( 'sae_mysql.class.php' ); $GLOBALS['sae_mysql_instance'] = new SaeMysql(); } return $GLOBALS['sae_mysql_instance']; } //TODU 完善 fetch url //------------------------------------------------------------------------------------------------- function _header_info($header) { $hinfo = array(); $header_lines = explode("\r",trim( $header)); $first = array_shift($header_lines); // HTTP/1.1 301 Moved Permanently $reg ="/HTTP\/(.+?)\s([0-9]+)\s(.+)/is"; if(preg_match($reg,trim($first),$out)) { $hinfo['version'] = $out[1]; $hinfo['code'] = $out[2]; $hinfo['code_info'] = $out[3]; } else return false; if(is_array($header_lines)) { foreach($header_lines as $line) { $fs=explode( ":" , trim($line),2); if(strlen(trim($fs[0])) > 0 ) { if(isset( $hinfo[strtolower(trim($fs[0]))] ) ) $hinfo[strtolower(trim($fs[0]))] = array_merge( (array)$hinfo[strtolower(trim($fs[0]))] , (array)trim($fs[1]) ); else $hinfo[strtolower(trim($fs[0]))] = trim($fs[1]); } } } return $hinfo; } //------------------------------------------------------------------------------------------------- function _get_signature($accesskey,$securekey,&$header_array) { $content="FetchUrl"; $content.=$header_array["FetchUrl"]; $content.="TimeStamp"; $content.=$header_array['TimeStamp']; $content.="AccessKey"; $content.=$header_array['AccessKey']; return base64_encode(hash_hmac('sha256',$content,$securekey,true)); } //------------------------------------------------------------------------------------------------- function _read_header($ch,$string) { global $errno,$errmsg,$rheader; $rheader.=$string; $ret=explode(" ",$string); if(count($ret)==3 && $ret[0]=='HTTP/1.1') { if($ret[1]==200) $errno=0; else { $errno=$ret[1]; $errmsg=$ret[2]; } } return strlen($string); } //------------------------------------------------------------------------------------------------- function _read_data($ch,$string) { global $rdata; $rdata.=$string; return strlen($string); } //------------------------------------------------------------------------------------------------- function _fetch_url($url,$accesskey,$securekey,&$header,&$error,$opt=NULL) { global $errno,$errmsg,$rheader,$rdata; $rheader=''; $rdata=''; $errno=0; $errmsg=''; $ch=curl_init(); curl_setopt($ch,CURLOPT_HEADERFUNCTION,'_read_header'); curl_setopt($ch,CURLOPT_WRITEFUNCTION,'_read_data'); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,3); curl_setopt($ch,CURLOPT_TIMEOUT,10); $header_array=array(); if($opt && is_array($opt)) { if(array_key_exists('username',$opt) && array_key_exists('password',$opt)) curl_setopt($ch,CURLOPT_USERPWD,$opt['username'].':'.$opt['password']); if(array_key_exists('useragent',$opt)) curl_setopt($ch,CURLOPT_USERAGENT,$opt['useragent']); if(array_key_exists('post',$opt)) { curl_setopt($ch,CURLOPT_POST,true); curl_setopt($ch,CURLOPT_POSTFIELDS,$opt['post']); } if(array_key_exists('truncated',$opt)) $header_array['AllowTruncated']=$opt['truncated']; // if(array_key_exists('connecttimeout',$opt)) // $header_array['ConnectTimeout']=$opt['connecttimeout']; // if(array_key_exists('sendtimeout',$opt)) // $header_array['SendTimeout']=$opt['sendtimeout']; // if(array_key_exists('readtimeout',$opt)) // $header_array['ReadTimeout']=$opt['readtimeout']; if(array_key_exists('headers',$opt)) { $headers=$opt['headers']; if(is_array($headers)) { foreach($headers as $k => $v) $header_array[$k]=$v; } } }//end if is_array $header_array['FetchUrl']=$url; $header_array['AccessKey']=$accesskey; $header_array['TimeStamp']=date('Y-m-d H:i:s'); $header_array['Signature']=_get_signature($accesskey,$securekey,$header_array); $header_array2=array(); foreach($header_array as $k => $v) array_push($header_array2,$k.': '.$v); curl_setopt($ch,CURLOPT_HTTPHEADER,$header_array2); curl_setopt($ch,CURLOPT_URL,SAE_FETCHURL_SERVICE_ADDRESS); curl_exec($ch); curl_close($ch); $header=$rheader; if($errno==0) return $rdata; $error=$errno.': '.$errmsg; return false; }//end function fetchurl //------------------------------------------------------------------------------------------------- function fetch_url($url,$accesskey,$securekey,&$header,&$error,$opt=NULL) { if($opt && is_array($opt) && array_key_exists('redirect',$opt) && $opt['redirect']==true) { $times=0; while(true) { $rt=_fetch_url($url,$accesskey,$securekey,$header,$error,$opt); if($rt==false) return $rt; $info=_header_info($header); $jump=false; if(isset($info['location']) && ($info['code']==301|| $info['code']==302) && $times<5) $jump=true; if($jump==true) { $times++; $url=$info['location']; continue; } return $rt; }//end while }//end if return _fetch_url($url,$accesskey,$securekey,$header,$error,$opt); } //------------------------------------------------------------------------------------------------- //实现wrapper if ( ! in_array("saemc", stream_get_wrappers()) ) stream_wrapper_register("saemc", "SaeMemcacheWrapper"); class SaeMemcacheWrapper // implements WrapperInterface { public $dir_mode = 16895 ; //040000 + 0222; public $file_mode = 33279 ; //0100000 + 0777; public function __construct() { $this->mc = memcache_init(); } public function mc() { if ( !isset( $this->mc ) ) $this->mc = new Memcache(); return $this->mc; } public function stream_open( $path , $mode , $options , &$opened_path) { $this->position = 0; $this->mckey = trim(substr($path, 8)); $this->mode = $mode; $this->options = $options; if ( in_array( $this->mode, array( 'r', 'r+', 'rb' ) ) ) { if ( $this->mccontent = memcache_get( $this->mc, $this->mckey ) ) { $this->get_file_info( $this->mckey ); $this->stat['mode'] = $this->stat[2] = $this->file_mode; } else { trigger_error("fopen({$path}): failed to read from Memcached: No such key.", E_USER_WARNING); return false; } } elseif ( in_array( $this->mode, array( 'a', 'a+', 'ab' ) ) ) { if ( $this->mccontent = memcache_get( $this->mc , $this->mckey ) ) { $this->get_file_info( $this->mckey ); $this->stat['mode'] = $this->stat[2] = $this->file_mode; $this->position = strlen($this->mccontent); } else { $this->mccontent = ''; $this->stat['ctime'] = $this->stat[10] = time(); } } elseif ( in_array( $this->mode, array( 'x', 'x+', 'xb' ) ) ) { if ( !memcache_get( $this->mc , $this->mckey ) ) { $this->mccontent = ''; $this->statinfo_init(); $this->stat['ctime'] = $this->stat[10] = time(); } else { trigger_error("fopen({$path}): failed to create at Memcached: Key exists.", E_USER_WARNING); return false; } } elseif ( in_array( $this->mode, array( 'w', 'w+', 'wb' ) ) ) { $this->mccontent = ''; $this->statinfo_init(); $this->stat['ctime'] = $this->stat[10] = time(); } else { $this->mccontent = memcache_get( $this->mc , $this->mckey ); } return true; } public function stream_read($count) { if (in_array($this->mode, array('w', 'x', 'a', 'wb', 'xb', 'ab') ) ) { return false; } $ret = substr( $this->mccontent , $this->position, $count); $this->position += strlen($ret); $this->stat['atime'] = $this->stat[8] = time(); $this->stat['uid'] = $this->stat[4] = 0; $this->stat['gid'] = $this->stat[5] = 0; return $ret; } public function stream_write($data) { if ( in_array( $this->mode, array( 'r', 'rb' ) ) ) { return false; } $left = substr($this->mccontent, 0, $this->position); $right = substr($this->mccontent, $this->position + strlen($data)); $this->mccontent = $left . $data . $right; if ( memcache_set( $this->mc , $this->mckey , $this->mccontent ) ) { $this->stat['mtime'] = $this->stat[9] = time(); $this->position += strlen($data); return $this->stat['size'] = $this->stat[7] = strlen( $data ); } else return false; } public function stream_close() { memcache_set( $this->mc , $this->mckey.'.meta' , serialize($this->stat) ); //memcache_close( $this->mc ); } public function stream_eof() { return $this->position >= strlen( $this->mccontent ); } public function stream_tell() { return $this->position; } public function stream_seek($offset , $whence = SEEK_SET) { switch ($whence) { case SEEK_SET: if ($offset < strlen( $this->mccontent ) && $offset >= 0) { $this->position = $offset; return true; } else return false; break; case SEEK_CUR: if ($offset >= 0) { $this->position += $offset; return true; } else return false; break; case SEEK_END: if (strlen( $this->mccontent ) + $offset >= 0) { $this->position = strlen( $this->mccontent ) + $offset; return true; } else return false; break; default: return false; } } public function stream_stat() { return $this->stat; } // ============================================ public function mkdir($path , $mode , $options) { $path = trim(substr($path, 8)); //echo "回调mkdir\n"; $path = rtrim( $path , '/' ); $this->stat = $this->get_file_info( $path ); $this->stat['ctime'] = $this->stat[10] = time(); $this->stat['mode'] = $this->stat[2] = $this->dir_mode; //echo "生成新的stat数据" . print_r( $this->stat , 1 ); memcache_set( $this->mc() , $path.'.meta' , serialize($this->stat) ); //echo "写入MC. key= " . $path.'.meta ' . memcache_get( $this->mc , $path.'.meta' ); memcache_close( $this->mc ); return true; } public function rename($path_from , $path_to) { $path_from = trim(substr($path_from, 8)); $path_to = trim(substr($path_to, 8)); memcache_set( $this->mc() , $path_to , memcache_get( $this->mc() , $path_from ) ); memcache_set( $this->mc() , $path_to . '.meta' , memcache_get( $this->mc() , $path_from . '.meta' ) ); memcache_delete( $this->mc() , $path_from ); memcache_delete( $this->mc() , $path_from.'.meta' ); clearstatcache( true ); return true; } public function rmdir($path , $options) { $path = trim(substr($path, 8)); $path = rtrim( $path , '/' ); memcache_delete( $this->mc() , $path .'.meta' ); clearstatcache( true ); return true; } public function unlink($path) { $path = trim(substr($path, 8)); $path = rtrim( $path , '/' ); memcache_delete( $this->mc() , $path ); memcache_delete( $this->mc() , $path . '.meta' ); clearstatcache( true ); return true; } public function url_stat($path , $flags) { $path = trim(substr($path, 8)); $path = rtrim( $path , '/' ); if ( !$this->is_file_info_exists( $path ) ) { return false; } else { if ( $stat = memcache_get( $this->mc() , $path . '.meta' ) ) { $this->stat = unserialize($stat); if ( is_array($this->stat) ) { if ( $this->stat['mode'] == $this->dir_mode || $c = memcache_get( $this->mc(), $path ) ) { return $this->stat; } else { memcache_delete( $this->mc() , $path . '.meta' ); } } } return false; } } // ============================================ public function is_file_info_exists( $path ) { //echo "获取MC数据 key= " . $path.'.meta' ; $d = memcache_get( $this->mc() , $path . '.meta' ); //echo "\n返回数据为" . $d . "\n"; return $d; } public function get_file_info( $path ) { if ( $stat = memcache_get( $this->mc() , $path . '.meta' ) ) return $this->stat = unserialize($stat); else $this->statinfo_init(); } public function statinfo_init( $is_file = true ) { $this->stat['dev'] = $this->stat[0] = 0x8002; $this->stat['ino'] = $this->stat[1] = mt_rand(10000, PHP_INT_MAX); if( $is_file ) $this->stat['mode'] = $this->stat[2] = $this->file_mode; else $this->stat['mode'] = $this->stat[2] = $this->dir_mode; $this->stat['nlink'] = $this->stat[3] = 0; $this->stat['uid'] = $this->stat[4] = 0; $this->stat['gid'] = $this->stat[5] = 0; $this->stat['rdev'] = $this->stat[6] = 0; $this->stat['size'] = $this->stat[7] = 0; $this->stat['atime'] = $this->stat[8] = 0; $this->stat['mtime'] = $this->stat[9] = 0; $this->stat['ctime'] = $this->stat[10] = 0; $this->stat['blksize'] = $this->stat[11] = 0; $this->stat['blocks'] = $this->stat[12] = 0; } public function dir_closedir() { return false; } public function dir_opendir($path, $options) { return false; } public function dir_readdir() { return false; } public function dir_rewinddir() { return false; } public function stream_cast($cast_as) { return false; } public function stream_flush() { return false; } public function stream_lock($operation) { return false; } public function stream_set_option($option, $arg1, $arg2) { return false; } } /* BEGIN ******************* Storage Wrapper By Elmer Zhang At 16/Mar/2010 14:47 ****************/ class SaeStorageWrapper // implements WrapperInterface { private $writen = true; public function __construct() { $this->stor = new SaeStorage(); } public function stor() { if ( !isset( $this->stor ) ) $this->stor = new SaeStorage(); } public function stream_open( $path , $mode , $options , &$opened_path) { $pathinfo = parse_url($path); $this->domain = $pathinfo['host']; $this->file = ltrim(strstr($path, $pathinfo['path']), '/\\'); $this->position = 0; $this->mode = $mode; $this->options = $options; // print_r("OPEN\tpath:{$path}\tmode:{$mode}\toption:{$option}\topened_path:{$opened_path}\n"); if ( in_array( $this->mode, array( 'r', 'r+', 'rb' ) ) ) { if ( $this->fcontent = $this->stor->read($this->domain, $this->file) ) { } else { trigger_error("fopen({$path}): failed to read from Storage: No such domain or file.", E_USER_WARNING); return false; } } elseif ( in_array( $this->mode, array( 'a', 'a+', 'ab' ) ) ) { trigger_error("fopen({$path}): Sorry, saestor does not support appending", E_USER_WARNING); if ( $this->fcontent = $this->stor->read($this->domain, $this->file) ) { } else { trigger_error("fopen({$path}): failed to read from Storage: No such domain or file.", E_USER_WARNING); return false; } } elseif ( in_array( $this->mode, array( 'x', 'x+', 'xb' ) ) ) { if ( !$this->stor->getAttr($this->domain, $this->file) ) { $this->fcontent = ''; } else { trigger_error("fopen({$path}): failed to create at Storage: File exists.", E_USER_WARNING); return false; } } elseif ( in_array( $this->mode, array( 'w', 'w+', 'wb' ) ) ) { $this->fcontent = ''; } else { $this->fcontent = $this->stor->read($this->domain, $this->file); } return true; } public function stream_read($count) { if (in_array($this->mode, array('w', 'x', 'a', 'wb', 'xb', 'ab') ) ) { return false; } $ret = substr( $this->fcontent , $this->position, $count); $this->position += strlen($ret); return $ret; } public function stream_write($data) { if ( in_array( $this->mode, array( 'r', 'rb' ) ) ) { return false; } // print_r("WRITE\tcontent:".strlen($this->fcontent)."\tposition:".$this->position."\tdata:".strlen($data)."\n"); $left = substr($this->fcontent, 0, $this->position); $right = substr($this->fcontent, $this->position + strlen($data)); $this->fcontent = $left . $data . $right; //if ( $this->stor->write( $this->domain, $this->file, $this->fcontent ) ) { $this->position += strlen($data); if ( strlen( $data ) > 0 ) $this->writen = false; return strlen( $data ); //} //else return false; } public function stream_close() { if (!$this->writen) { $this->stor->write( $this->domain, $this->file, $this->fcontent ); $this->writen = true; } } public function stream_eof() { return $this->position >= strlen( $this->fcontent ); } public function stream_tell() { return $this->position; } public function stream_seek($offset , $whence = SEEK_SET) { switch ($whence) { case SEEK_SET: if ($offset < strlen( $this->fcontent ) && $offset >= 0) { $this->position = $offset; return true; } else return false; break; case SEEK_CUR: if ($offset >= 0) { $this->position += $offset; return true; } else return false; break; case SEEK_END: if (strlen( $this->fcontent ) + $offset >= 0) { $this->position = strlen( $this->fcontent ) + $offset; return true; } else return false; break; default: return false; } } public function unlink($path) { self::stor(); $pathinfo = parse_url($path); $this->domain = $pathinfo['host']; $this->file = ltrim(strstr($path, $pathinfo['path']), '/\\'); clearstatcache( true ); return $this->stor->delete( $this->domain , $this->file ); } public function stream_flush() { if (!$this->writen) { $this->stor->write( $this->domain, $this->file, $this->fcontent ); $this->writen = true; } return $this->writen; } public function stream_stat() { return array(); } public function url_stat($path, $flags) { self::stor(); $pathinfo = parse_url($path); $this->domain = $pathinfo['host']; $this->file = ltrim(strstr($path, $pathinfo['path']), '/\\'); if ( $attr = $this->stor->getAttr( $this->domain , $this->file ) ) { $stat = array(); $stat['dev'] = $stat[0] = 0x8001; $stat['ino'] = $stat[1] = 0;; $stat['mode'] = $stat[2] = 33279; //0100000 + 0777; $stat['nlink'] = $stat[3] = 0; $stat['uid'] = $stat[4] = 0; $stat['gid'] = $stat[5] = 0; $stat['rdev'] = $stat[6] = 0; $stat['size'] = $stat[7] = $attr['length']; $stat['atime'] = $stat[8] = 0; $stat['mtime'] = $stat[9] = $attr['datetime']; $stat['ctime'] = $stat[10] = $attr['datetime']; $stat['blksize'] = $stat[11] = 0; $stat['blocks'] = $stat[12] = 0; return $stat; } else { return false; } } public function dir_closedir() { return false; } public function dir_opendir($path, $options) { return false; } public function dir_readdir() { return false; } public function dir_rewinddir() { return false; } public function mkdir($path, $mode, $options) { return false; } public function rename($path_from, $path_to) { return false; } public function rmdir($path, $options) { return false; } public function stream_cast($cast_as) { return false; } public function stream_lock($operation) { return false; } public function stream_set_option($option, $arg1, $arg2) { return false; } } if ( in_array( "saestor", stream_get_wrappers() ) ) { stream_wrapper_unregister("saestor"); } stream_wrapper_register( "saestor", "SaeStorageWrapper" ) or die( "Failed to register protocol" ); /* END ********************* Storage Wrapper By Elmer Zhang At 16/Mar/2010 14:47 ****************/ /* BEGIN ******************* KVDB Wrapper By Elmer Zhang At 12/Dec/2011 12:37 ****************/ class SaeKVWrapper // implements WrapperInterface { private $dir_mode = 16895 ; //040000 + 0222; private $file_mode = 33279 ; //0100000 + 0777; public function __construct() { } private function kv() { if ( !isset( $this->kv ) ) $this->kv = new SaeKV(); $this->kv->init(); return $this->kv; } private function open( $key ) { $value = $this->kv()->get( $key ); if ( $value !== false && $this->unpack_stat(substr($value, 0, 20)) === true ) { $this->kvcontent = substr($value, 20); return true; } else { return false; } } private function save( $key ) { $this->stat['mtime'] = $this->stat[9] = time(); if ( isset($this->kvcontent) ) { $this->stat['size'] = $this->stat[7] = strlen($this->kvcontent); $value = $this->pack_stat() . $this->kvcontent; } else { $this->stat['size'] = $this->stat[7] = 0; $value = $this->pack_stat(); } return $this->kv()->set($key, $value); } private function unpack_stat( $str ) { $arr = unpack("L5", $str); // check if valid if ( $arr[1] < 10000 ) return false; if ( !in_array($arr[2], array( $this->dir_mode, $this->file_mode ) ) ) return false; if ( $arr[4] > time() ) return false; if ( $arr[5] > time() ) return false; $this->stat['dev'] = $this->stat[0] = 0x8003; $this->stat['ino'] = $this->stat[1] = $arr[1]; $this->stat['mode'] = $this->stat[2] = $arr[2]; $this->stat['nlink'] = $this->stat[3] = 0; $this->stat['uid'] = $this->stat[4] = 0; $this->stat['gid'] = $this->stat[5] = 0; $this->stat['rdev'] = $this->stat[6] = 0; $this->stat['size'] = $this->stat[7] = $arr[3]; $this->stat['atime'] = $this->stat[8] = 0; $this->stat['mtime'] = $this->stat[9] = $arr[4]; $this->stat['ctime'] = $this->stat[10] = $arr[5]; $this->stat['blksize'] = $this->stat[11] = 0; $this->stat['blocks'] = $this->stat[12] = 0; return true; } private function pack_stat( ) { $str = pack("LLLLL", $this->stat['ino'], $this->stat['mode'], $this->stat['size'], $this->stat['ctime'], $this->stat['mtime']); return $str; } public function stream_open( $path , $mode , $options , &$opened_path) { $this->position = 0; $this->kvkey = rtrim(trim(substr(trim($path), 8)), '/'); $this->mode = $mode; $this->options = $options; if ( in_array( $this->mode, array( 'r', 'r+', 'rb' ) ) ) { if ( $this->open( $this->kvkey ) === false ) { trigger_error("fopen({$path}): No such key in KVDB.", E_USER_WARNING); return false; } } elseif ( in_array( $this->mode, array( 'a', 'a+', 'ab' ) ) ) { if ( $this->open( $this->kvkey ) === true ) { $this->position = strlen($this->kvcontent); } else { $this->kvcontent = ''; $this->statinfo_init(); } } elseif ( in_array( $this->mode, array( 'x', 'x+', 'xb' ) ) ) { if ( $this->open( $this->kvkey ) === false ) { $this->kvcontent = ''; $this->statinfo_init(); } else { trigger_error("fopen({$path}): Key exists in KVDB.", E_USER_WARNING); return false; } } elseif ( in_array( $this->mode, array( 'w', 'w+', 'wb' ) ) ) { $this->kvcontent = ''; $this->statinfo_init(); } else { $this->open( $this->kvkey ); } return true; } public function stream_read($count) { if (in_array($this->mode, array('w', 'x', 'a', 'wb', 'xb', 'ab') ) ) { return false; } $ret = substr( $this->kvcontent , $this->position, $count); $this->position += strlen($ret); return $ret; } public function stream_write($data) { if ( in_array( $this->mode, array( 'r', 'rb' ) ) ) { return false; } $left = substr($this->kvcontent, 0, $this->position); $right = substr($this->kvcontent, $this->position + strlen($data)); $this->kvcontent = $left . $data . $right; if ( $this->save( $this->kvkey ) === true ) { $this->position += strlen($data); return strlen( $data ); } else return false; } public function stream_close() { $this->save( $this->kvkey ); } public function stream_eof() { return $this->position >= strlen( $this->kvcontent ); } public function stream_tell() { return $this->position; } public function stream_seek($offset , $whence = SEEK_SET) { switch ($whence) { case SEEK_SET: if ($offset < strlen( $this->kvcontent ) && $offset >= 0) { $this->position = $offset; return true; } else return false; break; case SEEK_CUR: if ($offset >= 0) { $this->position += $offset; return true; } else return false; break; case SEEK_END: if (strlen( $this->kvcontent ) + $offset >= 0) { $this->position = strlen( $this->kvcontent ) + $offset; return true; } else return false; break; default: return false; } } public function stream_stat() { return $this->stat; } // ============================================ public function mkdir($path , $mode , $options) { $path = rtrim(trim(substr(trim($path), 8)), '/'); if ( $this->open( $path ) === false ) { $this->statinfo_init( false ); return $this->save( $path ); } else { trigger_error("mkdir({$path}): Key exists in KVDB.", E_USER_WARNING); return false; } } public function rename($path_from , $path_to) { $path_from = rtrim(trim(substr(trim($path_from), 8)), '/'); $path_to = rtrim(trim(substr(trim($path_to), 8)), '/'); if ( $this->open( $path_from ) === true ) { clearstatcache( true ); return $this->save( $path_to ); } else { trigger_error("rename({$path_from}, {$path_to}): No such key in KVDB.", E_USER_WARNING); return false; } } public function rmdir($path , $options) { $path = rtrim(trim(substr(trim($path), 8)), '/'); clearstatcache( true ); return $this->kv()->delete($path); } public function unlink($path) { $path = rtrim(trim(substr(trim($path), 8)), '/'); clearstatcache( true ); return $this->kv()->delete($path); } public function url_stat($path , $flags) { $path = rtrim(trim(substr(trim($path), 8)), '/'); if ( $this->open( $path ) !== false ) { return $this->stat; } else { return false; } } // ============================================ private function statinfo_init( $is_file = true ) { $this->stat['dev'] = $this->stat[0] = 0x8003; $this->stat['ino'] = $this->stat[1] = crc32(SAE_APPNAME . '/' . $this->kvkey); if( $is_file ) $this->stat['mode'] = $this->stat[2] = $this->file_mode; else $this->stat['mode'] = $this->stat[2] = $this->dir_mode; $this->stat['nlink'] = $this->stat[3] = 0; $this->stat['uid'] = $this->stat[4] = 0; $this->stat['gid'] = $this->stat[5] = 0; $this->stat['rdev'] = $this->stat[6] = 0; $this->stat['size'] = $this->stat[7] = 0; $this->stat['atime'] = $this->stat[8] = 0; $this->stat['mtime'] = $this->stat[9] = time(); $this->stat['ctime'] = $this->stat[10] = 0; $this->stat['blksize'] = $this->stat[11] = 0; $this->stat['blocks'] = $this->stat[12] = 0; } public function dir_closedir() { return false; } public function dir_opendir($path, $options) { return false; } public function dir_readdir() { return false; } public function dir_rewinddir() { return false; } public function stream_cast($cast_as) { return false; } public function stream_flush() { return false; } public function stream_lock($operation) { return false; } public function stream_set_option($option, $arg1, $arg2) { return false; } } if ( ! in_array("saekv", stream_get_wrappers()) ) stream_wrapper_register("saekv", "SaeKVWrapper"); /* END ********************* KVDB Wrapper By Elmer Zhang At 12/Dec/2011 12:37 ****************/ /* START ********************* Supported for AppCookie By Elmer Zhang At 13/Jun/2010 15:49 ****************/ $appSettings = array(); if (isset($_SERVER['HTTP_APPCOOKIE']) && $_SERVER['HTTP_APPCOOKIE']) { $appCookie = trim($_SERVER['HTTP_APPCOOKIE']); $tmpSettings = array_filter(explode(';', $appCookie)); if ($tmpSettings) { foreach($tmpSettings as $setting) { $tmp = explode('=', $setting); $appSettings[$tmp[0]] = $tmp[1]; } } } if (isset($appSettings['xhprof']) && in_array($_SERVER['HTTP_APPVERSION'], explode(',', $appSettings['xhprof']))) { sae_xhprof_start(); register_shutdown_function("sae_xhprof_end"); } if (isset($appSettings['debug']) && in_array($_SERVER['HTTP_APPVERSION'], explode(',', $appSettings['debug']))) { sae_set_display_errors(true); } unset($appSettings); unset($appCookie); unset($tmpSettings); unset($tmp);
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/sae_functions.php
PHP
art
34,744
<?php class SaeMysql extends SaeObject { static $link; static $charset; function __construct() { global $sae_config; self::$charset = $sae_config['db_charset']; $this->connect(); parent::__construct(); } //连接数据库 protected function connect() { global $sae_config; if(empty($sae_config['db_name'])) die(Imit_L('_SAE_PLEASE_CONFIG_DB_')); self::$link = mysql_connect(SAE_MYSQL_HOST_M, SAE_MYSQL_USER, SAE_MYSQL_PASS) or die(Imit_L('_SAE_CONNECT_DB_ERR_')); mysql_select_db(SAE_MYSQL_DB, self::$link); mysql_query("set names " . self::$charset, self::$link); if (!mysql_select_db(SAE_MYSQL_DB, self::$link)) { //如果数据库不存在,自动建立 mysql_query('create database ' . SAE_MYSQL_DB, self::$link); mysql_select_db(SAE_MYSQL_DB, self::$link) or Imit_L('_SAE_DATABASE_NOT_EXIST_'); } } //返回影响条数 public function affectedRows() { return mysql_affected_rows(self::$link); } //关闭数据库 public function closeDb() { mysql_close(self::$link); } //escape public function escape($str) { return mysql_real_escape_string($str, self::$link); } //获得数据,返回数组 public function getData($sql) { $this->last_sql = $sql; $result = mysql_query($sql, self::$link); if(!$result){ return false; } $this->save_error(); $data = array(); while ($arr = mysql_fetch_array($result)) { $data[] = $arr; } mysql_free_result($result); return $data; } //返回第一条数据 public function getLine($sql) { $data = $this->getData($sql); if ($data) { return @reset($data); } else { return false; } } //返回第一条记录的第一个字段值 public function getVar($sql) { $data = $this->getLine($sql); if ($data) { return $data[@reset(@array_keys($data))]; } else { return false; } } //返回最后一个id public function lastId() { return mysql_insert_id(self::$link); } //运行sql语句 public function runSql($sql) { $ret = mysql_query($sql); $this->save_error(); return $ret; } //设置项目名 public function setAppname($appname) { } //设置字符集 public function setCharset($charset) { self::$charset = $charset; mysql_query("set names " . self::$charset, self::$link); } //设置端口 public function setPort($port) { } protected function save_error() { $this->errmsg = mysql_error(self::$link); $this->errno = mysql_errno(self::$link); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/SaeMysql.class.php
PHP
art
3,025
<?php //模拟器需要用的函数 function Imit_L($key){ static $msgs=array(); if(is_array($key)){ $msgs=array_merge($msgs,$key); return ; } return $msgs[$key]; }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/imit_functions.php
PHP
art
213
<?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: luofei614 <www.3g4k.com> // +---------------------------------------------------------------------- // $Id: SaeTaskQueue.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ /** *任务列队 *本地环境暂时需要支持curl才行。 */ class SaeTaskQueue extends SaeObject{ public $queue=array(); //添加列队 public function addTask($tasks,$postdata=null,$prior=false,$options=array()){ if ( is_string($tasks) ) { if ( !filter_var($tasks, FILTER_VALIDATE_URL) ) { $this->errno = SAE_ErrParameter; $this->errmsg = Imit_L("_SAE_ERRPARAMTER_"); return false; } //添加单条任务 $item = array(); $item['url'] = $tasks; if ($postdata != NULL) $item['postdata'] = $postdata; if ($prior) $item['prior'] = true; $tasks=$item; } if ( empty($tasks) ) { $this->errno = SAE_ErrParameter; $this->errmsg = Imit_L("_SAE_ERRPARAMTER_"); return false; } //记录任务,处理优先 foreach($tasks as $k => $v) { if (is_array($v) && isset($v['url'])) { //当是二维数组时 if($v['prior']){ $this->queue=array_merge(array($v),$this->queue); }else{ $this->queue[]=$v; } } elseif ( isset($tasks['url']) ) { //当是一维数组时 if($tasks['prior']){ $this->queue=array_merge(array($tasks),$this->queue); }else{ $this->queue[]=$tasks; } break; } else { $this->errno = SAE_ErrParameter; $this->errmsg = Imit_L("_SAE_ERRPARAMTER_"); return false; } } return true; } public function curLength(){ return true; } public function leftLength(){ return true; } public function push(){ //todu, 当用户环境不支持curl时用socket发送。 if(empty($this->queue)) return false; $s = curl_init(); foreach($this->queue as $k=>$v){ curl_setopt($s,CURLOPT_URL,$v['url']); //curl_setopt($s,CURLOPT_TIMEOUT,5); curl_setopt($s,CURLOPT_RETURNTRANSFER,true); curl_setopt($s,CURLOPT_HEADER, 1); curl_setopt($s,CURLINFO_HEADER_OUT, true); curl_setopt($s,CURLOPT_POST,true); curl_setopt($s,CURLOPT_POSTFIELDS,$v['postdata']); $ret = curl_exec($s); $info = curl_getinfo($s); // print_r($info); if(empty($info['http_code'])) { $this->errno = SAE_ErrInternal; $this->errmsg = Imit_L("_SAE_TASKQUEUE_SERVICE_FAULT_"); return false; } else if($info['http_code'] != 200) { $this->errno = SAE_ErrInternal; $this->errmsg = Imit_L("_SAE_TASKQUEUE_SERVICE_ERROR_"); return false; } else { //todu 这里好像有些问题 if($info['size_download'] == 0) { // get MailError header $this->errno = SAE_ErrUnknown; $this->errmsg = Imit_L("_SAE_UNKNOWN_ERROR_"); return false; } } } //循环结束 $this->queue=array();//清空列队 return true; } } ?>
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/SaeTaskQueue.class.php
PHP
art
3,440
<?php //SAE系统常量,根据自己实际情况进行修改。 define( 'SAE_MYSQL_HOST_M', $sae_config['db_host'] ); define( 'SAE_MYSQL_HOST_S', $sae_config['db_host'] ); define( 'SAE_MYSQL_PORT', 3306 ); define( 'SAE_MYSQL_USER', $sae_config['db_user'] ); define( 'SAE_MYSQL_PASS', $sae_config['db_pass']); define( 'SAE_MYSQL_DB', $sae_config['db_name']); define('IMIT_CREATE_TABLE',true);//是否自动建立模拟器需要的数据表 // settings define('SAE_FETCHURL_SERVICE_ADDRESS','http://fetchurl.sae.sina.com.cn'); // storage define( 'SAE_STOREHOST', 'http://stor.sae.sina.com.cn/storageApi.php' ); define( 'SAE_S3HOST', 'http://s3.sae.sina.com.cn/s3Api.php' ); // saetmp constant define( 'SAE_TMP_PATH' , ''); // define AccessKey and SecretKey define( 'SAE_ACCESSKEY', ''); define( 'SAE_SECRETKEY', ''); //unset( $_SERVER['HTTP_ACCESSKEY'] ); //unset( $_SERVER['HTTP_SECRETKEY'] ); // gravity define define('SAE_NorthWest', 1); define('SAE_North', 2); define('SAE_NorthEast',3); define('SAE_East',6); define('SAE_SouthEast',9); define('SAE_South',8); define('SAE_SouthWest',7); define('SAE_West',4); define('SAE_Static',10); define('SAE_Center',5); // font stretch define('SAE_Undefined',0); define('SAE_Normal',1); define('SAE_UltraCondensed',2); define('SAE_ExtraCondensed',3); define('SAE_Condensed',4); define('SAE_SemiCondensed',5); define('SAE_SemiExpanded',6); define('SAE_Expanded',7); define('SAE_ExtraExpanded',8); define('SAE_UltraExpanded',9); // font style define('SAE_Italic',2); define('SAE_Oblique',3); // font name define('SAE_SimSun',1); define('SAE_SimKai',2); define('SAE_SimHei',3); define('SAE_Arial',4); define('SAE_MicroHei',5); // anchor postion define('SAE_TOP_LEFT','tl'); define('SAE_TOP_CENTER','tc'); define('SAE_TOP_RIGHT','tr'); define('SAE_CENTER_LEFT','cl'); define('SAE_CENTER_CENTER','cc'); define('SAE_CENTER_RIGHT','cr'); define('SAE_BOTTOM_LEFT','bl'); define('SAE_BOTTOM_CENTER','bc'); define('SAE_BOTTOM_RIGHT','br'); // errno define define('SAE_Success', 0); // OK define('SAE_ErrKey', 1); // invalid accesskey or secretkey define('SAE_ErrForbidden', 2); // access fibidden for quota limit define('SAE_ErrParameter', 3); // parameter not exist or invalid define('SAE_ErrInternal', 500); // internal Error define('SAE_ErrUnknown', 999); // unknown error // fonts for gd define('SAE_Font_Sun', '/usr/share/fonts/chinese/TrueType/uming.ttf'); define('SAE_Font_Kai', '/usr/share/fonts/chinese/TrueType/ukai.ttf'); define('SAE_Font_Hei', '/usr/share/fonts/chinese/TrueType/wqy-zenhei.ttc'); define('SAE_Font_MicroHei', '/usr/share/fonts/chinese/TrueType/wqy-microhei.ttc');
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/defines.php
PHP
art
2,720
<?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: luofei614 <www.3g4k.com> // +---------------------------------------------------------------------- // $Id: SaeKVClient.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ /** *KVDB模拟器 *使用到数据库表think_sae_kv */ class SaeKvClient extends SaeObject{ public function delete($key){ $ret=self::$db->runSql("delete from sae_kv where k='$key'"); return $ret?true:false; } public function get($key){ $data=self::$db->getLine("select * from sae_kv where k='$key'"); $value=$this->output(array($data)); $ret=$value[$key]; return $ret?$ret:false; } public function get_info(){ //todu } public function init(){ return true; } public function mget($ary){ if(empty($ary)) return null; array_walk($ary,function(&$r){ $r="'$r'"; }); $where=implode(',', $ary); $data=self::$db->getData("select * from sae_kv where k in($where)"); return $this->output($data); } public function pkrget($prefix_key,$count,$start_key){ //todu } public function set($key,$value){ if(!is_string($value)){ //如果不是字符串序列化 $value=serialize($value); $isobj=1; }else{ $isobj=0; } //判断是否存在键 if(self::$db->getVar("select count(*) from sae_kv where k='$key'")>0){ $ret=self::$db->runSql("update sae_kv set v='$value',isobj='$isobj' where k='$key'"); }else{ $ret=self::$db->runSql("insert into sae_kv(k,v,isobj) values('$key','$value','$isobj')"); } return $ret?true:false; } private function output($arr){ $ret=array(); foreach($arr as $k=>$ary){ $ret[$ary['k']]=$ary['isobj']?unserialize($ary['v']):$ary['v']; } return $ret; } } ?>
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/SaeKVClient.class.php
PHP
art
2,231
<?php // +---------------------------------------------------------------------- // | sae模拟器配置 // +---------------------------------------------------------------------- // | Author: luofei614<www.3g4k.com> // +---------------------------------------------------------------------- // $Id: config.php 2793 2012-03-02 05:34:40Z liu21st $ $appConfig= include APP_PATH.'Conf/config.php'; return array( 'db_host'=>isset($appConfig['DB_HOST'])?$appConfig['DB_HOST']:'localhost', 'db_user'=>isset($appConfig['DB_USER'])?$appConfig['DB_USER']:'root', 'db_pass'=>isset($appConfig['DB_PWD'])?$appConfig['DB_PWD']:'', 'db_name'=>isset($appConfig['DB_NAME'])?$appConfig['DB_NAME']:'sae', 'db_charset'=>isset($appConfig['DB_CHARSET'])?$appConfig['DB_CHARSET']:'utf8', 'storage_url'=>trim(dirname($_SERVER['SCRIPT_NAME']),'/\\').'/', 'storage_dir'=>'./', 'debug_file'=>APP_PATH.'Runtime/Logs/sae_debug.log' );
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/SaeImit/config.php
PHP
art
963
<?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: alias.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ if (!defined('THINK_PATH')) exit(); // 系统别名定义文件 return array( 'Model' => CORE_PATH.'Core/Model.class.php', 'Db' => CORE_PATH.'Core/Db.class.php', 'Log' => SAE_PATH.'Lib/Core/Log.class.php', 'ThinkTemplate' => SAE_PATH.'Lib/Template/ThinkTemplate.class.php', 'TagLib' => CORE_PATH.'Template/TagLib.class.php', 'Cache' => CORE_PATH.'Core/Cache.class.php', 'Widget' => CORE_PATH.'Core/Widget.class.php', 'TagLibCx' => CORE_PATH.'Driver/TagLib/TagLibCx.class.php', );
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Conf/alias.php
PHP
art
1,249
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: tags.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $ // 系统默认的核心行为扩展列表文件 //[sae]定义别名,让在SAE下时,调试模式也加载对应文件。 alias_import(array( 'ParseTemplateBehavior'=>SAE_PATH.'Lib/Behavior/ParseTemplateBehavior.class.php', 'ReadHtmlCacheBehavior'=>SAE_PATH.'Lib/Behavior/ReadHtmlCacheBehavior.class.php', 'WriteHtmlCacheBehavior'=>SAE_PATH.'Lib/Behavior/WriteHtmlCacheBehavior.class.php' )); return array( 'app_init'=>array( ), 'app_begin'=>array( 'ReadHtmlCache'=>SAE_PATH.'Lib/Behavior/ReadHtmlCacheBehavior.class.php', // 读取静态缓存 ), 'route_check'=>array( 'CheckRoute', // 路由检测 ), 'app_end'=>array(), 'path_info'=>array(), 'action_begin'=>array(), 'action_end'=>array(), 'view_begin'=>array(), 'view_template'=>array( 'LocationTemplate', // 自动定位模板文件 ), 'view_parse'=>array( 'ParseTemplate'=>SAE_PATH.'Lib/Behavior/ParseTemplateBehavior.class.php', //[sae] 模板解析 支持PHP、内置模板引擎和第三方模板引擎 ), 'view_filter'=>array( 'ContentReplace', // 模板输出替换 'TokenBuild', // 表单令牌 'WriteHtmlCache'=>SAE_PATH.'Lib/Behavior/WriteHtmlCacheBehavior.class.php', // 写入静态缓存 'ShowRuntime', // 运行时间显示 ), 'view_end'=>array( 'ShowPageTrace', // 页面Trace显示 ), );
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Conf/tags.php
PHP
art
2,135
<?php //sae下的固定配置,以下配置将会覆盖项目配置。 return array( 'DB_TYPE'=> 'mysql', // 数据库类型 'DB_HOST'=> SAE_MYSQL_HOST_M.','.SAE_MYSQL_HOST_S, // 服务器地址 'DB_NAME'=> SAE_MYSQL_DB, // 数据库名 'DB_USER'=> SAE_MYSQL_USER, // 用户名 'DB_PWD'=> SAE_MYSQL_PASS, // 密码 'DB_PORT'=> SAE_MYSQL_PORT, // 端口 'DB_RW_SEPARATE'=>true, 'DB_DEPLOY_TYPE'=> 1, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) 'SAE_SPECIALIZED_FILES'=>array( //SAE系统专属文件。 'UploadFile.class.php'=>SAE_PATH.'Lib/Extend/Library/ORG/Net/UploadFile_sae.class.php', 'Image.class.php'=>SAE_PATH.'Lib/Extend/Library/ORG/Util/Image_sae.class.php' ) );
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae/Conf/convention_sae.php
PHP
art
840
<?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: Sae.php 2793 2012-03-02 05:34:40Z liu21st $ // Sae版ThinkPHP 入口文件 //[sae]定义SAE_PATH defined('ENGINE_PATH') or define('ENGINE_PATH',dirname(__FILE__).'/'); define('SAE_PATH', ENGINE_PATH.'Sae/'); //[sae]判断是否运行在SAE上。 if (!isset($_SERVER['HTTP_APPCOOKIE'])) { define('IS_SAE', FALSE); defined('THINK_PATH') or define('THINK_PATH', dirname(dirname(dirname(__FILE__))) . '/'); defined('APP_PATH') or define('APP_PATH', dirname($_SERVER['SCRIPT_FILENAME']) . '/'); //加载平滑函数 require SAE_PATH.'Common/sae_functions.php'; //加载模拟器 if (!defined('SAE_APPNAME')) require SAE_PATH.'SaeImit.php'; require THINK_PATH . 'ThinkPHP.php'; exit(); } define('IS_SAE', TRUE); require SAE_PATH.'Lib/Core/SaeMC.class.php'; //记录开始运行时间 $GLOBALS['_beginTime'] = microtime(TRUE); // 记录内存初始使用 define('MEMORY_LIMIT_ON', function_exists('memory_get_usage')); if (MEMORY_LIMIT_ON) $GLOBALS['_startUseMems'] = memory_get_usage(); defined('APP_PATH') or define('APP_PATH', dirname($_SERVER['SCRIPT_FILENAME']) . '/'); //[sae] 判断是否手动建立项目目录 if (!is_dir(APP_PATH . '/Lib/')) { header('Content-Type:text/html; charset=utf-8'); exit('<div style=\'font-weight:bold;float:left;width:430px;text-align:center;border:1px solid silver;background:#E8EFFF;padding:8px;color:red;font-size:14px;font-family:Tahoma\'>sae环境下请手动生成项目目录~</div>'); } defined('RUNTIME_PATH') or define('RUNTIME_PATH', APP_PATH . 'Runtime/'); defined('APP_DEBUG') or define('APP_DEBUG', false); // 是否调试模式 $runtime = defined('MODE_NAME') ? '~' . strtolower(MODE_NAME) . '_runtime.php' : '~runtime.php'; defined('RUNTIME_FILE') or define('RUNTIME_FILE', RUNTIME_PATH . $runtime); //[sae] 载入核心编译缓存 if (!APP_DEBUG && SaeMC::file_exists(RUNTIME_FILE)) { // 部署模式直接载入allinone缓存 SaeMC::include_file(RUNTIME_FILE); } else { // ThinkPHP系统目录定义 defined('THINK_PATH') or define('THINK_PATH', dirname(dirname(dirname(__FILE__))) . '/'); //[sae] 加载运行时文件 require SAE_PATH.'Common/runtime.php'; }
zzgcms
ZGCMS/ThinkPHP/Extend/Engine/Sae.php
PHP
art
2,849
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2008 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: alias.php 2504 2011-12-28 07:35:29Z liu21st $ // 导入别名定义 alias_import(array( 'Model' => MODE_PATH.'Amf/Model.class.php', 'Db' => MODE_PATH.'Phprpc/Db.class.php', 'Debug' => CORE_PATH.'Util/Debug.class.php', 'Session' => CORE_PATH.'Util/Session.class.php', ) );
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Phprpc/alias.php
PHP
art
971
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Action.class.php 2504 2011-12-28 07:35:29Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP AMF模式Action控制器基类 +------------------------------------------------------------------------------ */ abstract class Action { /** +---------------------------------------------------------- * 魔术方法 有不存在的操作的时候执行 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名 * @param array $parms 参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$parms) { // 如果定义了_empty操作 则调用 if(method_exists($this,'_empty')) { $this->_empty($method,$parms); } } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Phprpc/Action.class.php
PHP
art
1,643
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Db.class.php 2657 2012-01-23 13:23:09Z liu21st $ define('CLIENT_MULTI_RESULTS', 131072); /** +------------------------------------------------------------------------------ * ThinkPHP AMF模式数据库中间层实现类 只支持Mysql +------------------------------------------------------------------------------ */ class Db { static private $_instance = null; // 是否自动释放查询结果 protected $autoFree = false; // 是否显示调试信息 如果启用会在日志文件记录sql语句 public $debug = false; // 是否使用永久连接 protected $pconnect = false; // 当前SQL指令 protected $queryStr = ''; // 最后插入ID protected $lastInsID = null; // 返回或者影响记录数 protected $numRows = 0; // 返回字段数 protected $numCols = 0; // 事务指令数 protected $transTimes = 0; // 错误信息 protected $error = ''; // 当前连接ID protected $linkID = null; // 当前查询ID protected $queryID = null; // 是否已经连接数据库 protected $connected = false; // 数据库连接参数配置 protected $config = ''; // 数据库表达式 protected $comparison = array('eq'=>'=','neq'=>'!=','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE'); // 查询表达式 protected $selectSql = 'SELECT%DISTINCT% %FIELDS% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT%'; /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $config 数据库配置数组 +---------------------------------------------------------- */ public function __construct($config=''){ if ( !extension_loaded('mysql') ) { throw_exception(L('_NOT_SUPPERT_').':mysql'); } $this->config = $this->parseConfig($config); } /** +---------------------------------------------------------- * 连接数据库方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function connect() { if(!$this->connected) { $config = $this->config; // 处理不带端口号的socket连接情况 $host = $config['hostname'].($config['hostport']?":{$config['hostport']}":''); if($this->pconnect) { $this->linkID = mysql_pconnect( $host, $config['username'], $config['password'],CLIENT_MULTI_RESULTS); }else{ $this->linkID = mysql_connect( $host, $config['username'], $config['password'],true,CLIENT_MULTI_RESULTS); } if ( !$this->linkID || (!empty($config['database']) && !mysql_select_db($config['database'], $this->linkID)) ) { throw_exception(mysql_error()); } $dbVersion = mysql_get_server_info($this->linkID); if ($dbVersion >= "4.1") { //使用UTF8存取数据库 需要mysql 4.1.0以上支持 mysql_query("SET NAMES '".C('DB_CHARSET')."'", $this->linkID); } //设置 sql_model if($dbVersion >'5.0.1'){ mysql_query("SET sql_mode=''",$this->linkID); } // 标记连接成功 $this->connected = true; // 注销数据库连接配置信息 unset($this->config); } } /** +---------------------------------------------------------- * 释放查询结果 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function free() { mysql_free_result($this->queryID); $this->queryID = 0; } /** +---------------------------------------------------------- * 执行查询 主要针对 SELECT, SHOW 等指令 * 返回数据集 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $str sql指令 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function query($str='') { $this->connect(); if ( !$this->linkID ) return false; if ( $str != '' ) $this->queryStr = $str; //释放前次的查询结果 if ( $this->queryID ) { $this->free(); } N('db_query',1); // 记录开始执行时间 G('queryStartTime'); $this->queryID = mysql_query($this->queryStr, $this->linkID); $this->debug(); if ( !$this->queryID ) { if ( $this->debug ) throw_exception($this->error()); else return false; } else { $this->numRows = mysql_num_rows($this->queryID); return $this->getAll(); } } /** +---------------------------------------------------------- * 执行语句 针对 INSERT, UPDATE 以及DELETE +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $str sql指令 +---------------------------------------------------------- * @return integer +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function execute($str='') { $this->connect(); if ( !$this->linkID ) return false; if ( $str != '' ) $this->queryStr = $str; //释放前次的查询结果 if ( $this->queryID ) { $this->free(); } N('db_write',1); // 记录开始执行时间 G('queryStartTime'); $result = mysql_query($this->queryStr, $this->linkID) ; $this->debug(); if ( false === $result) { if ( $this->debug ) throw_exception($this->error()); else return false; } else { $this->numRows = mysql_affected_rows($this->linkID); $this->lastInsID = mysql_insert_id($this->linkID); return $this->numRows; } } /** +---------------------------------------------------------- * 启动事务 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function startTrans() { $this->connect(true); if ( !$this->linkID ) return false; //数据rollback 支持 if ($this->transTimes == 0) { mysql_query('START TRANSACTION', $this->linkID); } $this->transTimes++; return ; } /** +---------------------------------------------------------- * 用于非自动提交状态下面的查询提交 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function commit() { if ($this->transTimes > 0) { $result = mysql_query('COMMIT', $this->linkID); $this->transTimes = 0; if(!$result){ throw_exception($this->error()); return false; } } return true; } /** +---------------------------------------------------------- * 事务回滚 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function rollback() { if ($this->transTimes > 0) { $result = mysql_query('ROLLBACK', $this->linkID); $this->transTimes = 0; if(!$result){ throw_exception($this->error()); return false; } } return true; } /** +---------------------------------------------------------- * 获得所有的查询数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return array +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function getAll() { if ( !$this->queryID ) { throw_exception($this->error()); return false; } //返回数据集 $result = array(); if($this->numRows >0) { while($row = mysql_fetch_assoc($this->queryID)){ $result[] = $row; } mysql_data_seek($this->queryID,0); } return $result; } /** +---------------------------------------------------------- * 取得数据表的字段信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function getFields($tableName) { $result = $this->query('SHOW COLUMNS FROM '.$tableName); $info = array(); foreach ($result as $key => $val) { $info[$val['Field']] = array( 'name' => $val['Field'], 'type' => $val['Type'], 'notnull' => (bool) ($val['Null'] === ''), // not null is empty, null is yes 'default' => $val['Default'], 'primary' => (strtolower($val['Key']) == 'pri'), 'autoinc' => (strtolower($val['Extra']) == 'auto_increment'), ); } return $info; } /** +---------------------------------------------------------- * 取得数据库的表信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function getTables($dbName='') { if(!empty($dbName)) { $sql = 'SHOW TABLES FROM '.$dbName; }else{ $sql = 'SHOW TABLES '; } $result = $this->query($sql); $info = array(); foreach ($result as $key => $val) { $info[$key] = current($val); } return $info; } /** +---------------------------------------------------------- * 关闭数据库 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function close() { if (!empty($this->queryID)) mysql_free_result($this->queryID); if ($this->linkID && !mysql_close($this->linkID)){ throw_exception($this->error()); } $this->linkID = 0; } /** +---------------------------------------------------------- * 数据库错误信息 * 并显示当前的SQL语句 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function error() { $this->error = mysql_error($this->linkID); if($this->queryStr!=''){ $this->error .= "\n [ SQL语句 ] : ".$this->queryStr; } return $this->error; } /** +---------------------------------------------------------- * SQL指令安全过滤 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $str SQL字符串 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function escape_string($str) { return mysql_escape_string($str); } /** +---------------------------------------------------------- * 析构方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __destruct() { // 关闭连接 $this->close(); } /** +---------------------------------------------------------- * 取得数据库类实例 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @return mixed 返回数据库驱动类 +---------------------------------------------------------- */ public static function getInstance($db_config='') { if ( self::$_instance==null ){ self::$_instance = new Db($db_config); } return self::$_instance; } /** +---------------------------------------------------------- * 分析数据库配置信息,支持数组和DSN +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param mixed $db_config 数据库配置信息 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ private function parseConfig($db_config='') { if ( !empty($db_config) && is_string($db_config)) { // 如果DSN字符串则进行解析 $db_config = $this->parseDSN($db_config); }else if(empty($db_config)){ // 如果配置为空,读取配置文件设置 $db_config = array ( 'dbms' => C('DB_TYPE'), 'username' => C('DB_USER'), 'password' => C('DB_PWD'), 'hostname' => C('DB_HOST'), 'hostport' => C('DB_PORT'), 'database' => C('DB_NAME'), 'dsn' => C('DB_DSN'), 'params' => C('DB_PARAMS'), ); } return $db_config; } /** +---------------------------------------------------------- * DSN解析 * 格式: mysql://username:passwd@localhost:3306/DbName +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param string $dsnStr +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function parseDSN($dsnStr) { if( empty($dsnStr) ){return false;} $info = parse_url($dsnStr); if($info['scheme']){ $dsn = array( 'dbms' => $info['scheme'], 'username' => isset($info['user']) ? $info['user'] : '', 'password' => isset($info['pass']) ? $info['pass'] : '', 'hostname' => isset($info['host']) ? $info['host'] : '', 'hostport' => isset($info['port']) ? $info['port'] : '', 'database' => isset($info['path']) ? substr($info['path'],1) : '' ); }else { preg_match('/^(.*?)\:\/\/(.*?)\:(.*?)\@(.*?)\:([0-9]{1, 6})\/(.*?)$/',trim($dsnStr),$matches); $dsn = array ( 'dbms' => $matches[1], 'username' => $matches[2], 'password' => $matches[3], 'hostname' => $matches[4], 'hostport' => $matches[5], 'database' => $matches[6] ); } return $dsn; } /** +---------------------------------------------------------- * 数据库调试 记录当前SQL +---------------------------------------------------------- * @access protected +---------------------------------------------------------- */ protected function debug() { // 记录操作结束时间 if ( $this->debug ) { G('queryEndTime'); Log::record($this->queryStr." [ RunTime:".G('queryStartTime','queryEndTime',6)."s ]",Log::SQL); } } /** +---------------------------------------------------------- * 设置锁机制 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseLock($lock=false) { if(!$lock) return ''; if('ORACLE' == $this->dbType) { return ' FOR UPDATE NOWAIT '; } return ' FOR UPDATE '; } /** +---------------------------------------------------------- * set分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $data +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseSet($data) { foreach ($data as $key=>$val){ $value = $this->parseValue($val); if(is_scalar($value)) // 过滤非标量数据 $set[] = $this->parseKey($key).'='.$value; } return ' SET '.implode(',',$set); } /** +---------------------------------------------------------- * value分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $value +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseValue($value) { if(is_string($value)) { $value = '\''.$this->escape_string($value).'\''; }elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){ $value = $this->escape_string($value[1]); }elseif(is_null($value)){ $value = 'null'; } return $value; } /** +---------------------------------------------------------- * field分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $fields +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseField($fields) { if(is_array($fields)) { // 完善数组方式传字段名的支持 // 支持 'field1'=>'field2' 这样的字段别名定义 $array = array(); foreach ($fields as $key=>$field){ if(!is_numeric($key)) $array[] = $this->parseKey($key).' AS '.$this->parseKey($field); else $array[] = $this->parseKey($field); } $fieldsStr = implode(',', $array); }elseif(is_string($fields) && !empty($fields)) { $fieldsStr = $this->parseKey($fields); }else{ $fieldsStr = '*'; } return $fieldsStr; } /** +---------------------------------------------------------- * table分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $table +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseTable($tables) { if(is_string($tables)) $tables = explode(',',$tables); array_walk($tables, array(&$this, 'parseKey')); return implode(',',$tables); } /** +---------------------------------------------------------- * where分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $where +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseWhere($where) { $whereStr = ''; if(is_string($where)) { // 直接使用字符串条件 $whereStr = $where; }else{ // 使用数组条件表达式 if(isset($where['_logic'])) { // 定义逻辑运算规则 例如 OR XOR AND NOT $operate = ' '.strtoupper($where['_logic']).' '; unset($where['_logic']); }else{ // 默认进行 AND 运算 $operate = ' AND '; } foreach ($where as $key=>$val){ $whereStr .= "( "; if(0===strpos($key,'_')) { // 解析特殊条件表达式 $whereStr .= $this->parseThinkWhere($key,$val); }else{ $key = $this->parseKey($key); if(is_array($val)) { if(is_string($val[0])) { if(preg_match('/^(EQ|NEQ|GT|EGT|LT|ELT|NOTLIKE|LIKE)$/i',$val[0])) { // 比较运算 $whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' '.$this->parseValue($val[1]); }elseif('exp'==strtolower($val[0])){ // 使用表达式 $whereStr .= ' ('.$key.' '.$val[1].') '; }elseif(preg_match('/IN/i',$val[0])){ // IN 运算 $zone = is_array($val[1])? implode(',',$this->parseValue($val[1])):$val[1]; $whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')'; }elseif(preg_match('/BETWEEN/i',$val[0])){ // BETWEEN运算 $data = is_string($val[1])? explode(',',$val[1]):$val[1]; $whereStr .= ' ('.$key.' BETWEEN '.$data[0].' AND '.$data[1].' )'; }else{ throw_exception(L('_EXPRESS_ERROR_').':'.$val[0]); } }else { $count = count($val); if(in_array(strtoupper(trim($val[$count-1])),array('AND','OR','XOR'))) { $rule = strtoupper(trim($val[$count-1])); $count = $count -1; }else{ $rule = 'AND'; } for($i=0;$i<$count;$i++) { $data = is_array($val[$i])?$val[$i][1]:$val[$i]; if('exp'==strtolower($val[$i][0])) { $whereStr .= '('.$key.' '.$data.') '.$rule.' '; }else{ $op = is_array($val[$i])?$this->comparison[strtolower($val[$i][0])]:'='; $whereStr .= '('.$key.' '.$op.' '.$this->parseValue($data).') '.$rule.' '; } } $whereStr = substr($whereStr,0,-4); } }else { //对字符串类型字段采用模糊匹配 if(C('LIKE_MATCH_FIELDS') && preg_match('/('.C('LIKE_MATCH_FIELDS').')/i',$key)) { $val = '%'.$val.'%'; $whereStr .= $key." LIKE ".$this->parseValue($val); }else { $whereStr .= $key." = ".$this->parseValue($val); } } } $whereStr .= ' )'.$operate; } $whereStr = substr($whereStr,0,-strlen($operate)); } return empty($whereStr)?'':' WHERE '.$whereStr; } /** +---------------------------------------------------------- * 特殊条件分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $key * @param mixed $val +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseThinkWhere($key,$val) { $whereStr = ''; switch($key) { case '_string': // 字符串模式查询条件 $whereStr = $val; break; case '_complex': // 复合查询条件 $whereStr = substr($this->parseWhere($val),6); break; case '_query': // 字符串模式查询条件 parse_str($val,$where); if(isset($where['_logic'])) { $op = ' '.strtoupper($where['_logic']).' '; unset($where['_logic']); }else{ $op = ' AND '; } $array = array(); foreach ($where as $field=>$data) $array[] = $this->parseKey($field).' = '.$this->parseValue($data); $whereStr = implode($op,$array); break; } return $whereStr; } /** +---------------------------------------------------------- * limit分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $lmit +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseLimit($limit) { return !empty($limit)? ' LIMIT '.$limit.' ':''; } /** +---------------------------------------------------------- * join分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $join +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseJoin($join) { $joinStr = ''; if(!empty($join)) { if(is_array($join)) { foreach ($join as $key=>$_join){ if(false !== stripos($_join,'JOIN')) $joinStr .= ' '.$_join; else $joinStr .= ' LEFT JOIN ' .$_join; } }else{ $joinStr .= ' LEFT JOIN ' .$join; } } return $joinStr; } /** +---------------------------------------------------------- * order分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $order +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseOrder($order) { return !empty($order)? ' ORDER BY '.$order:''; } /** +---------------------------------------------------------- * group分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $group +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseGroup($group) { return !empty($group)? ' GROUP BY '.$group:''; } /** +---------------------------------------------------------- * having分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $having +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseHaving($having) { return !empty($having)? ' HAVING '.$having:''; } /** +---------------------------------------------------------- * distinct分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $distinct +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseDistinct($distinct) { return !empty($distinct)? ' DISTINCT ' :''; } /** +---------------------------------------------------------- * 插入记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 数据 * @param array $options 参数表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function insert($data,$options=array()) { foreach ($data as $key=>$val){ $value = $this->parseValue($val); if(is_scalar($value)) { // 过滤非标量数据 $values[] = $value; $fields[] = $this->parseKey($key); } } $sql = 'INSERT INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')'; $sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->execute($sql); } /** +---------------------------------------------------------- * 更新记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 数据 * @param array $options 表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function update($data,$options) { $sql = 'UPDATE ' .$this->parseTable($options['table']) .$this->parseSet($data) .$this->parseWhere(isset($options['where'])?$options['where']:'') .$this->parseOrder(isset($options['order'])?$options['order']:'') .$this->parseLimit(isset($options['limit'])?$options['limit']:'') .$this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->execute($sql); } /** +---------------------------------------------------------- * 删除记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $options 表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function delete($options=array()) { $sql = 'DELETE FROM ' .$this->parseTable($options['table']) .$this->parseWhere(isset($options['where'])?$options['where']:'') .$this->parseOrder(isset($options['order'])?$options['order']:'') .$this->parseLimit(isset($options['limit'])?$options['limit']:'') .$this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->execute($sql); } /** +---------------------------------------------------------- * 查找记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $options 表达式 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function select($options=array()) { if(isset($options['page'])) { // 根据页数计算limit list($page,$listRows) = explode(',',$options['page']); $listRows = $listRows?$listRows:($options['limit']?$options['limit']:20); $offset = $listRows*((int)$page-1); $options['limit'] = $offset.','.$listRows; } $sql = str_replace( array('%TABLE%','%DISTINCT%','%FIELDS%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%'), array( $this->parseTable($options['table']), $this->parseDistinct(isset($options['distinct'])?$options['distinct']:false), $this->parseField(isset($options['field'])?$options['field']:'*'), $this->parseJoin(isset($options['join'])?$options['join']:''), $this->parseWhere(isset($options['where'])?$options['where']:''), $this->parseGroup(isset($options['group'])?$options['group']:''), $this->parseHaving(isset($options['having'])?$options['having']:''), $this->parseOrder(isset($options['order'])?$options['order']:''), $this->parseLimit(isset($options['limit'])?$options['limit']:'') ),$this->selectSql); $sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->query($sql); } /** +---------------------------------------------------------- * 字段和表名添加` * 保证指令中使用关键字不出错 针对mysql +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $value +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ protected function parseKey(&$value) { $value = trim($value); if( false !== strpos($value,' ') || false !== strpos($value,',') || false !== strpos($value,'*') || false !== strpos($value,'(') || false !== strpos($value,'.') || false !== strpos($value,'`')) { //如果包含* 或者 使用了sql方法 则不作处理 }else{ $value = '`'.$value.'`'; } return $value; } /** +---------------------------------------------------------- * 获取最近一次查询的sql语句 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastSql() { return $this->queryStr; } /** +---------------------------------------------------------- * 获取最近插入的ID +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastInsID(){ return $this->lastInsID; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Phprpc/Db.class.php
PHP
art
39,438
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Model.class.php 2779 2012-02-24 02:56:57Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP AMF模式Model模型类 * 只支持CURD和连贯操作 以及常用查询 去掉回调接口 +------------------------------------------------------------------------------ */ class Model { // 当前数据库操作对象 protected $db = null; // 主键名称 protected $pk = 'id'; // 数据表前缀 protected $tablePrefix = ''; // 模型名称 protected $name = ''; // 数据库名称 protected $dbName = ''; // 数据表名(不包含表前缀) protected $tableName = ''; // 实际数据表名(包含表前缀) protected $trueTableName =''; // 数据信息 protected $data = array(); // 查询表达式参数 protected $options = array(); // 最近错误信息 protected $error = ''; /** +---------------------------------------------------------- * 架构函数 * 取得DB类的实例对象 +---------------------------------------------------------- * @param string $name 模型名称 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($name='') { // 模型初始化 $this->_initialize(); // 获取模型名称 if(!empty($name)) { $this->name = $name; }elseif(empty($this->name)){ $this->name = $this->getModelName(); } // 数据库初始化操作 $this->db = Db::getInstance(empty($this->connection)?'':$this->connection); // 设置表前缀 $this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX'); // 字段检测 if(!empty($this->name)) $this->_checkTableInfo(); } /** +---------------------------------------------------------- * 自动检测数据表信息 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function _checkTableInfo() { // 如果不是Model类 自动记录数据表信息 // 只在第一次执行记录 if(empty($this->fields)) { // 如果数据表字段没有定义则自动获取 if(C('DB_FIELDS_CACHE')) { $this->fields = F('_fields/'.$this->name); if(!$this->fields) $this->flush(); }else{ // 每次都会读取数据表信息 $this->flush(); } } } /** +---------------------------------------------------------- * 获取字段信息并缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function flush() { // 缓存不存在则查询数据表信息 $fields = $this->db->getFields($this->getTableName()); $this->fields = array_keys($fields); $this->fields['_autoinc'] = false; foreach ($fields as $key=>$val){ // 记录字段类型 $type[$key] = $val['type']; if($val['primary']) { $this->fields['_pk'] = $key; if($val['autoinc']) $this->fields['_autoinc'] = true; } } // 记录字段类型信息 if(C('DB_FIELDTYPE_CHECK')) $this->fields['_type'] = $type; // 2008-3-7 增加缓存开关控制 if(C('DB_FIELDS_CACHE')) // 永久缓存数据表信息 F('_fields/'.$this->name,$this->fields); } // 回调方法 初始化模型 protected function _initialize() {} /** +---------------------------------------------------------- * 利用__call方法实现一些特殊的Model方法 (魔术方法) +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名称 * @param array $args 调用参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$args) { if(in_array(strtolower($method),array('field','table','where','order','limit','page','having','group','lock','distinct'),true)) { // 连贯操作的实现 $this->options[strtolower($method)] = $args[0]; return $this; }elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){ // 统计查询的实现 $field = isset($args[0])?$args[0]:'*'; return $this->getField(strtoupper($method).'('.$field.') AS tp_'.$method); }elseif(strtolower(substr($method,0,5))=='getby') { // 根据某个字段获取记录 $field = parse_name(substr($method,5)); $options['where'] = $field.'=\''.$args[0].'\''; return $this->find($options); }else{ throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); return; } } /** +---------------------------------------------------------- * 设置数据对象的值 (魔术方法) +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 名称 * @param mixed $value 值 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function __set($name,$value) { // 设置数据对象属性 $this->data[$name] = $value; } /** +---------------------------------------------------------- * 获取数据对象的值 (魔术方法) +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 名称 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __get($name) { return isset($this->data[$name])?$this->data[$name]:null; } /** +---------------------------------------------------------- * 新增数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 数据 * @param array $options 表达式 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function add($data='',$options=array()) { if(empty($data)) { // 没有传递数据,获取当前数据对象的值 if(!empty($this->data)) { $data = $this->data; }else{ $this->error = L('_DATA_TYPE_INVALID_'); return false; } } // 分析表达式 $options = $this->_parseOptions($options); // 写入数据到数据库 $result = $this->db->insert($data,$options); $insertId = $this->getLastInsID(); if($insertId) { return $insertId; } //成功后返回插入ID return $result; } /** +---------------------------------------------------------- * 保存数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 数据 * @param array $options 表达式 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function save($data='',$options=array()) { if(empty($data)) { // 没有传递数据,获取当前数据对象的值 if(!empty($this->data)) { $data = $this->data; }else{ $this->error = L('_DATA_TYPE_INVALID_'); return false; } } // 分析表达式 $options = $this->_parseOptions($options); if(!isset($options['where']) ) { // 如果存在主键数据 则自动作为更新条件 if(isset($data[$this->getPk()])) { $pk = $this->getPk(); $options['where'] = $pk.'=\''.$data[$pk].'\''; $pkValue = $data[$pk]; unset($data[$pk]); }else{ // 如果没有任何更新条件则不执行 $this->error = L('_OPERATION_WRONG_'); return false; } } return $this->db->update($data,$options); } /** +---------------------------------------------------------- * 删除数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $options 表达式 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function delete($options=array()) { if(empty($options) && empty($this->options['where'])) { // 如果删除条件为空 则删除当前数据对象所对应的记录 if(!empty($this->data) && isset($this->data[$this->getPk()])) return $this->delete($this->data[$this->getPk()]); else return false; } if(is_numeric($options) || is_string($options)) { // 根据主键删除记录 $pk = $this->getPk(); $where = $pk.'=\''.$options.'\''; $pkValue = $options; $options = array(); $options['where'] = $where; } // 分析表达式 $options = $this->_parseOptions($options); return $this->db->delete($options); } /** +---------------------------------------------------------- * 查询数据集 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $options 表达式参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function select($options=array()) { // 分析表达式 $options = $this->_parseOptions($options); $resultSet = $this->db->select($options); if(empty($resultSet)) { // 查询结果为空 return false; } return $resultSet; } /** +---------------------------------------------------------- * 查询数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $options 表达式参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function find($options=array()) { if(is_numeric($options) || is_string($options)) { $where = $this->getPk().'=\''.$options.'\''; $options = array(); $options['where'] = $where; } // 总是查找一条记录 $options['limit'] = 1; // 分析表达式 $options = $this->_parseOptions($options); $resultSet = $this->db->select($options); if(empty($resultSet)) {// 查询结果为空 return false; } $this->data = $resultSet[0]; return $this->data; } /** +---------------------------------------------------------- * 分析表达式 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param array $options 表达式参数 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ private function _parseOptions($options) { if(is_array($options)) $options = array_merge($this->options,$options); // 查询过后清空sql表达式组装 避免影响下次查询 $this->options = array(); if(!isset($options['table'])) // 自动获取表名 $options['table'] =$this->getTableName(); return $options; } /** +---------------------------------------------------------- * 创建数据对象 但不保存到数据库 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 创建数据 * @param string $type 状态 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function create($data='',$type='') { // 如果没有传值默认取POST数据 if(empty($data)) { $data = $_POST; }elseif(is_object($data)){ $data = get_object_vars($data); }elseif(!is_array($data)){ $this->error = L('_DATA_TYPE_INVALID_'); return false; } // 生成数据对象 $vo = array(); foreach ($this->fields as $key=>$name){ if(substr($key,0,1)=='_') continue; $val = isset($data[$name])?$data[$name]:null; //保证赋值有效 if(!is_null($val)){ $vo[$name] = (MAGIC_QUOTES_GPC && is_string($val))? stripslashes($val) : $val; if(C('DB_FIELDTYPE_CHECK')) { // 字段类型检查 $fieldType = strtolower($this->fields['_type'][$name]); if(false !== strpos($fieldType,'int')) { $vo[$name] = intval($vo[$name]); }elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){ $vo[$name] = floatval($vo[$name]); } } } } // 赋值当前数据对象 $this->data = $vo; // 返回创建的数据以供其他调用 return $vo; } /** +---------------------------------------------------------- * SQL查询 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $sql SQL指令 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function query($sql) { if(!empty($sql)) { if(strpos($sql,'__TABLE__')) $sql = str_replace('__TABLE__',$this->getTableName(),$sql); return $this->db->query($sql); }else{ return false; } } /** +---------------------------------------------------------- * 执行SQL语句 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $sql SQL指令 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function execute($sql='') { if(!empty($sql)) { if(strpos($sql,'__TABLE__')) $sql = str_replace('__TABLE__',$this->getTableName(),$sql); return $this->db->execute($sql); }else { return false; } } /** +---------------------------------------------------------- * 得到当前的数据对象名称 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getModelName() { if(empty($this->name)) { $this->name = substr(get_class($this),0,-5); } return $this->name; } /** +---------------------------------------------------------- * 得到完整的数据表名 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getTableName() { if(empty($this->trueTableName)) { $tableName = !empty($this->tablePrefix) ? $this->tablePrefix : ''; if(!empty($this->tableName)) { $tableName .= $this->tableName; }else{ $tableName .= parse_name($this->name); } if(!empty($this->dbName)) { $tableName = $this->dbName.'.'.$tableName; } $this->trueTableName = strtolower($tableName); } return $this->trueTableName; } /** +---------------------------------------------------------- * 启动事务 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function startTrans() { $this->commit(); $this->db->startTrans(); return ; } /** +---------------------------------------------------------- * 提交事务 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function commit() { return $this->db->commit(); } /** +---------------------------------------------------------- * 事务回滚 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function rollback() { return $this->db->rollback(); } /** +---------------------------------------------------------- * 获取主键名称 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getPk() { return isset($this->fields['_pk'])?$this->fields['_pk']:$this->pk; } /** +---------------------------------------------------------- * 返回最后执行的sql语句 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastSql() { return $this->db->getLastSql(); } /** +---------------------------------------------------------- * 返回最后插入的ID +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastInsID() { return $this->db->getLastInsID(); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Phprpc/Model.class.php
PHP
art
22,044
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: App.class.php 2504 2011-12-28 07:35:29Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP AMF模式应用程序类 +------------------------------------------------------------------------------ */ class App { /** +---------------------------------------------------------- * 应用程序初始化 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function run() { //导入类库 Vendor('phpRPC.phprpc_server'); //实例化phprpc $server = new PHPRPC_Server(); $actions = explode(',',C('APP_PHPRPC_ACTIONS')); foreach ($actions as $action){ //$server -> setClass($action.'Action'); $temp = $action.'Action'; $methods = get_class_methods($temp); $server->add($methods,new $temp); } if(APP_DEBUG) { $server->setDebugMode(true); } $server->setEnableGZIP(true); $server->start(); //C('PHPRPC_COMMENT',$server->comment()); echo $server->comment(); // 保存日志记录 if(C('LOG_RECORD')) Log::save(); return ; } };
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Phprpc/App.class.php
PHP
art
1,985
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: thin.php 2702 2012-02-02 12:35:01Z liu21st $ // 简洁模式核心定义文件列表 return array( 'core' => array( THINK_PATH.'Common/functions.php', // 系统函数库 CORE_PATH.'Core/Log.class.php',// 日志处理 MODE_PATH.'Thin/App.class.php', // 应用程序类 MODE_PATH.'Thin/Action.class.php',// 控制器类 ), // 项目别名定义文件 [支持数组直接定义或者文件名定义] 'alias' => array( 'Model' => MODE_PATH.'Thin/Model.class.php', 'Db' => MODE_PATH.'Thin/Db.class.php', ), // 系统行为定义文件 [必须 支持数组直接定义或者文件名定义 ] 'extends' => array(), // 项目应用行为定义文件 [支持数组直接定义或者文件名定义] 'tags' => array(), );
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/thin.php
PHP
art
1,512
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Action.class.php 2702 2012-02-02 12:35:01Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP 简洁模式Action控制器基类 +------------------------------------------------------------------------------ */ abstract class Action { /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @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_')); } } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Thin/Action.class.php
PHP
art
2,385
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Db.class.php 2702 2012-02-02 12:35:01Z liu21st $ define('CLIENT_MULTI_RESULTS', 131072); /** +------------------------------------------------------------------------------ * ThinkPHP 简洁模式数据库中间层实现类 * 只支持mysql +------------------------------------------------------------------------------ */ class Db { static private $_instance = null; // 是否自动释放查询结果 protected $autoFree = false; // 是否显示调试信息 如果启用会在日志文件记录sql语句 public $debug = false; // 是否使用永久连接 protected $pconnect = false; // 当前SQL指令 protected $queryStr = ''; // 最后插入ID protected $lastInsID = null; // 返回或者影响记录数 protected $numRows = 0; // 返回字段数 protected $numCols = 0; // 事务指令数 protected $transTimes = 0; // 错误信息 protected $error = ''; // 当前连接ID protected $linkID = null; // 当前查询ID protected $queryID = null; // 是否已经连接数据库 protected $connected = false; // 数据库连接参数配置 protected $config = ''; // 数据库表达式 protected $comparison = array('eq'=>'=','neq'=>'!=','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE'); // 查询表达式 protected $selectSql = 'SELECT%DISTINCT% %FIELDS% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT%'; /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $config 数据库配置数组 +---------------------------------------------------------- */ public function __construct($config=''){ if ( !extension_loaded('mysql') ) { throw_exception(L('_NOT_SUPPERT_').':mysql'); } $this->config = $this->parseConfig($config); } /** +---------------------------------------------------------- * 连接数据库方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function connect() { if(!$this->connected) { $config = $this->config; // 处理不带端口号的socket连接情况 $host = $config['hostname'].($config['hostport']?":{$config['hostport']}":''); if($this->pconnect) { $this->linkID = mysql_pconnect( $host, $config['username'], $config['password'],CLIENT_MULTI_RESULTS); }else{ $this->linkID = mysql_connect( $host, $config['username'], $config['password'],true,CLIENT_MULTI_RESULTS); } if ( !$this->linkID || (!empty($config['database']) && !mysql_select_db($config['database'], $this->linkID)) ) { throw_exception(mysql_error()); } $dbVersion = mysql_get_server_info($this->linkID); if ($dbVersion >= "4.1") { //使用UTF8存取数据库 需要mysql 4.1.0以上支持 mysql_query("SET NAMES '".C('DB_CHARSET')."'", $this->linkID); } //设置 sql_model if($dbVersion >'5.0.1'){ mysql_query("SET sql_mode=''",$this->linkID); } // 标记连接成功 $this->connected = true; // 注销数据库连接配置信息 unset($this->config); } } /** +---------------------------------------------------------- * 释放查询结果 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function free() { mysql_free_result($this->queryID); $this->queryID = 0; } /** +---------------------------------------------------------- * 执行查询 主要针对 SELECT, SHOW 等指令 * 返回数据集 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $str sql指令 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function query($str='') { $this->connect(); if ( !$this->linkID ) return false; if ( $str != '' ) $this->queryStr = $str; //释放前次的查询结果 if ( $this->queryID ) { $this->free(); } N('db_query',1); // 记录开始执行时间 G('queryStartTime'); $this->queryID = mysql_query($this->queryStr, $this->linkID); $this->debug(); if ( !$this->queryID ) { if ( $this->debug ) throw_exception($this->error()); else return false; } else { $this->numRows = mysql_num_rows($this->queryID); return $this->getAll(); } } /** +---------------------------------------------------------- * 执行语句 针对 INSERT, UPDATE 以及DELETE +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $str sql指令 +---------------------------------------------------------- * @return integer +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function execute($str='') { $this->connect(); if ( !$this->linkID ) return false; if ( $str != '' ) $this->queryStr = $str; //释放前次的查询结果 if ( $this->queryID ) { $this->free(); } N('db_write',1); // 记录开始执行时间 G('queryStartTime'); $result = mysql_query($this->queryStr, $this->linkID) ; $this->debug(); if ( false === $result) { if ( $this->debug ) throw_exception($this->error()); else return false; } else { $this->numRows = mysql_affected_rows($this->linkID); $this->lastInsID = mysql_insert_id($this->linkID); return $this->numRows; } } /** +---------------------------------------------------------- * 启动事务 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function startTrans() { $this->connect(true); if ( !$this->linkID ) return false; //数据rollback 支持 if ($this->transTimes == 0) { mysql_query('START TRANSACTION', $this->linkID); } $this->transTimes++; return ; } /** +---------------------------------------------------------- * 用于非自动提交状态下面的查询提交 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function commit() { if ($this->transTimes > 0) { $result = mysql_query('COMMIT', $this->linkID); $this->transTimes = 0; if(!$result){ throw_exception($this->error()); return false; } } return true; } /** +---------------------------------------------------------- * 事务回滚 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function rollback() { if ($this->transTimes > 0) { $result = mysql_query('ROLLBACK', $this->linkID); $this->transTimes = 0; if(!$result){ throw_exception($this->error()); return false; } } return true; } /** +---------------------------------------------------------- * 获得所有的查询数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return array +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function getAll() { if ( !$this->queryID ) { throw_exception($this->error()); return false; } //返回数据集 $result = array(); if($this->numRows >0) { while($row = mysql_fetch_assoc($this->queryID)){ $result[] = $row; } mysql_data_seek($this->queryID,0); } return $result; } /** +---------------------------------------------------------- * 关闭数据库 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @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 escapeString($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; } /** +---------------------------------------------------------- * 获取最近插入的ID +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastInsID(){ return $this->lastInsID; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Thin/Db.class.php
PHP
art
18,093
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Model.class.php 2702 2012-02-02 12:35:01Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP 简洁模式Model模型类 * 只支持原生SQL操作 支持多数据库连接和切换 +------------------------------------------------------------------------------ */ class Model { // 当前数据库操作对象 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(); } // 数据库初始化操作 // 获取数据库操作对象 // 当前模型有独立的数据库连接信息 $this->db(0,empty($this->connection)?$connection:$this->connection); // 设置表前缀 $this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX'); } // 回调方法 初始化模型 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); } $this->trueTableName = strtolower($tableName); } return (!empty($this->dbName)?$this->dbName.'.':'').$this->trueTableName; } /** +---------------------------------------------------------- * 启动事务 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function startTrans() { $this->commit(); $this->db->startTrans(); return ; } /** +---------------------------------------------------------- * 提交事务 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function commit() { return $this->db->commit(); } /** +---------------------------------------------------------- * 事务回滚 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function rollback() { return $this->db->rollback(); } /** +---------------------------------------------------------- * 切换当前的数据库连接 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param integer $linkNum 连接序号 * @param mixed $config 数据库连接信息 * @param array $params 模型参数 +---------------------------------------------------------- * @return Model +---------------------------------------------------------- */ public function db($linkNum,$config='',$params=array()){ static $_db = array(); if(!isset($_db[$linkNum])) { // 创建一个新的实例 $_db[$linkNum] = Db::getInstance($config); }elseif(NULL === $config){ $_db[$linkNum]->close(); // 关闭数据库连接 unset($_db[$linkNum]); return ; } if(!empty($params)) { if(is_string($params)) parse_str($params,$params); foreach ($params as $name=>$value){ $this->setProperty($name,$value); } } // 切换数据库连接 $this->db = $_db[$linkNum]; return $this; } }; ?>
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Thin/Model.class.php
PHP
art
8,267
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: App.class.php 2702 2012-02-02 12:35:01Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP 精简模式应用程序类 +------------------------------------------------------------------------------ */ class App { /** +---------------------------------------------------------- * 应用程序初始化 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function run() { // 取得模块和操作名称 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 ; } /** +---------------------------------------------------------- * 获得实际的模块名称 +---------------------------------------------------------- * @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; } };
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Thin/App.class.php
PHP
art
3,397
<?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: amf.php 2504 2011-12-28 07:35:29Z liu21st $ // AMF模式定义文件 return array( 'core' => array( THINK_PATH.'Common/functions.php', // 系统函数库 CORE_PATH.'Core/Log.class.php',// 日志处理 MODE_PATH.'Amf/App.class.php', // 应用程序类 MODE_PATH.'Amf/Action.class.php',// 控制器类 ), // 项目别名定义文件 [支持数组直接定义或者文件名定义] 'alias' => array( 'Model' => MODE_PATH.'Amf/Model.class.php', 'Db' => MODE_PATH.'Amf/Db.class.php', ), // 系统行为定义文件 [必须 支持数组直接定义或者文件名定义 ] 'extends' => array(), // 项目应用行为定义文件 [支持数组直接定义或者文件名定义] 'tags' => array(), );
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/amf.php
PHP
art
1,483
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Action.class.php 2832 2012-03-21 01:05:36Z huangdijia $ /** +------------------------------------------------------------------------------ * ThinkPHP RESTFul 控制器基类 抽象类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id: Action.class.php 2832 2012-03-21 01:05:36Z huangdijia $ +------------------------------------------------------------------------------ */ abstract class Action { // 当前Action名称 private $name = ''; // 视图实例 protected $view = null; protected $_method = ''; // 当前请求类型 protected $_type = ''; // 当前资源类型 // 输出类型 protected $_types = array(); /** +---------------------------------------------------------- * 架构函数 取得模板对象实例 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct() { //实例化视图类 $this->view = Think::instance('View'); defined('__EXT__') or define('__EXT__',''); if(''== __EXT__ || false === stripos(C('REST_CONTENT_TYPE_LIST'),__EXT__)) { // 资源类型没有指定或者非法 则用默认资源类型访问 $this->_type = C('REST_DEFAULT_TYPE'); }else{ $this->_type = __EXT__; } // 请求方式检测 $method = strtolower($_SERVER['REQUEST_METHOD']); if(false === stripos(C('REST_METHOD_LIST'),$method)) { // 请求方式非法 则用默认请求方法 $method = C('REST_DEFAULT_METHOD'); } $this->_method = $method; // 允许输出的资源类型 $this->_types = C('REST_OUTPUT_TYPE'); //控制器初始化 if(method_exists($this,'_initialize')) $this->_initialize(); } /** +---------------------------------------------------------- * 获取当前Action名称 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- */ protected function getActionName() { if(empty($this->name)) { // 获取Action名称 $this->name = substr(get_class($this),0,-6); } return $this->name; } /** +---------------------------------------------------------- * 是否AJAX请求 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @return bool +---------------------------------------------------------- */ protected function isAjax() { if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) ) { if('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])) return true; } if(!empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')])) // 判断Ajax方式提交 return true; return false; } /** +---------------------------------------------------------- * 魔术方法 有不存在的操作的时候执行 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名 * @param array $args 参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$args) { if( 0 === strcasecmp($method,ACTION_NAME)) { if(method_exists($this,$method.'_'.$this->_method.'_'.$this->_type)) { // RESTFul方法支持 $fun = $method.'_'.$this->_method.'_'.$this->_type; $this->$fun(); }elseif($this->_method == C('REST_DEFAULT_METHOD') && method_exists($this,$method.'_'.$this->_type) ){ $fun = $method.'_'.$this->_type; $this->$fun(); }elseif($this->_type == C('REST_DEFAULT_TYPE') && method_exists($this,$method.'_'.$this->_method) ){ $fun = $method.'_'.$this->_method; $this->$fun(); }elseif(method_exists($this,'_empty')) { // 如果定义了_empty操作 则调用 $this->_empty($method,$args); }elseif(file_exists_case(C('TMPL_FILE_NAME'))){ // 检查是否存在默认模版 如果有直接输出模版 $this->display(); }else{ // 抛出异常 throw_exception(L('_ERROR_ACTION_').ACTION_NAME); } }else{ switch(strtolower($method)) { // 获取变量 支持过滤和默认值 调用方式 $this->_post($key,$filter,$default); case '_get': $input =& $_GET;break; case '_post':$input =& $_POST;break; case '_put': case '_delete':parse_str(file_get_contents('php://input'), $input);break; case '_request': $input =& $_REQUEST;break; case '_session': $input =& $_SESSION;break; case '_cookie': $input =& $_COOKIE;break; case '_server': $input =& $_SERVER;break; default: throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); } if(isset($input[$args[0]])) { // 取值操作 $data = $input[$args[0]]; $fun = $args[1]?$args[1]:C('DEFAULT_FILTER'); $data = $fun($data); // 参数过滤 }else{ // 变量默认值 $data = isset($args[2])?$args[2]:NULL; } return $data; } } /** +---------------------------------------------------------- * 模板显示 * 调用内置的模板引擎显示方法, +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $templateFile 指定要调用的模板文件 * 默认为空 由系统自动定位模板文件 * @param string $charset 输出编码 * @param string $contentType 输出类型 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function display($templateFile='',$charset='',$contentType='') { $this->view->display($templateFile,$charset,$contentType); } /** +---------------------------------------------------------- * 模板变量赋值 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $name 要显示的模板变量 * @param mixed $value 变量的值 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function assign($name,$value='') { $this->view->assign($name,$value); } public function __set($name,$value) { $this->view->assign($name,$value); } /** +---------------------------------------------------------- * 设置页面输出的CONTENT_TYPE和编码 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $type content_type 类型对应的扩展名 * @param string $charset 页面输出编码 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function setContentType($type, $charset=''){ if(headers_sent()) return; if(empty($charset)) $charset = C('DEFAULT_CHARSET'); $type = strtolower($type); if(isset($this->_types[$type])) //过滤content_type header('Content-Type: '.$this->_types[$type].'; charset='.$charset); } /** +---------------------------------------------------------- * 输出返回数据 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $data 要返回的数据 * @param String $type 返回类型 JSON XML * @param integer $code HTTP状态 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function response($data,$type='',$code=200) { $this->sendHttpStatus($code); exit($this->encodeData($data,strtolower($type))); } /** +---------------------------------------------------------- * 编码数据 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $data 要返回的数据 * @param String $type 返回类型 JSON XML +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function encodeData($data,$type='') { if(empty($data)) return ''; if(empty($type)) $type = $this->_type; if('json' == $type) { // 返回JSON数据格式到客户端 包含状态信息 $data = json_encode($data); }elseif('xml' == $type){ // 返回xml格式数据 $data = xml_encode($data); }elseif('php'==$type){ $data = serialize($data); }// 默认直接输出 $this->setContentType($type); header('Content-Length: ' . strlen($data)); return $data; } // 发送Http状态信息 protected function sendHttpStatus($code) { static $_status = array( // Informational 1xx 100 => 'Continue', 101 => 'Switching Protocols', // Success 2xx 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', // Redirection 3xx 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Moved Temporarily ', // 1.1 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', // 306 is deprecated but reserved 307 => 'Temporary Redirect', // Client Error 4xx 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', // Server Error 5xx 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 509 => 'Bandwidth Limit Exceeded' ); if(isset($_status[$code])) { header('HTTP/1.1 '.$code.' '.$_status[$code]); // 确保FastCGI模式下正常 header('Status:'.$code.' '.$_status[$code]); } } /** +---------------------------------------------------------- * 析构方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __destruct() { // 保存日志 if(C('LOG_RECORD')) Log::save(); // 执行后续操作 tag('action_end'); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Rest/Action.class.php
PHP
art
13,758
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: CheckRestRouteBehavior.class.php 2732 2012-02-14 04:36:48Z liu21st $ /** +------------------------------------------------------------------------------ * 系统行为扩展 REST路由检测 +------------------------------------------------------------------------------ */ class CheckRestRouteBehavior extends Behavior { // 行为参数定义(默认值) 可在项目配置中覆盖 protected $options = array( 'URL_ROUTER_ON' => false, // 是否开启URL路由 'URL_ROUTE_RULES' => array(), // 默认路由规则,注:分组配置无法替代 ); /** +---------------------------------------------------------- * 路由检测 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function run(&$return) { $regx = trim($_SERVER['PATH_INFO'],'/'); // 是否开启路由使用 if(empty($regx) || !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){ // 定义格式: array('路由规则或者正则','路由地址','路由参数','提交类型','资源类型') if(isset($route[3]) && strtolower($_SERVER['REQUEST_METHOD']) != strtolower($route[3])) { continue; // 如果设置了提交类型则过滤 } if(isset($route[4]) && !in_array(__EXT__,explode(',',$route[4]),true)) { continue; // 如果设置了扩展名则过滤 } if(0===strpos($route[0],'/') && preg_match($route[0],$regx,$matches)) { // 正则路由 return self::parseRegex($matches,$route,$regx); }else{ // 规则路由 $len1= substr_count($regx,'/'); $len2 = substr_count($route[0],'/'); if($len1>=$len2) { if('$' == substr($route[0],-1,1)) {// 完整匹配 if($len1 != $len2) { continue; }else{ $route[0] = substr($route[0],0,-1); } } $match = self::checkUrlMatch($regx,$route[0]); if($match) return $return = self::parseRule($route,$regx); } } } } $return = false; } // 检测URL和规则路由是否匹配 static private function checkUrlMatch($regx,$rule) { $m1 = explode('/',$regx); $m2 = explode('/',$rule); $match = true; // 是否匹配 foreach ($m2 as $key=>$val){ if(':' == substr($val,0,1)) {// 动态变量 if(strpos($val,'\\')) { $type = substr($val,-1); if('d'==$type && !is_numeric($m1[$key])) { $match = false; break; } }elseif(strpos($val,'^')){ $array = explode('|',substr(strstr($val,'^'),1)); if(in_array($m1[$key],$array)) { $match = false; break; } } }elseif(0 !== strcasecmp($val,$m1[$key])){ $match = false; break; } } return $match; } static private function parseUrl($url) { $var = array(); if(false !== strpos($url,'?')) { // [分组/模块/操作?]参数1=值1&参数2=值2... $info = parse_url($url); $path = explode('/',$info['path']); parse_str($info['query'],$var); }elseif(strpos($url,'/')){ // [分组/模块/操作] $path = explode('/',$url); }else{ // 参数1=值1&参数2=值2... parse_str($url,$var); } if(isset($path)) { $var[C('VAR_ACTION')] = array_pop($path); if(!empty($path)) { $var[C('VAR_MODULE')] = array_pop($path); } if(!empty($path)) { $var[C('VAR_GROUP')] = array_pop($path); } } return $var; } // 解析规则路由 // array('路由规则','[分组/模块/操作]','额外参数1=值1&额外参数2=值2...','请求类型','资源类型') // array('路由规则','外部地址','重定向代码','请求类型','资源类型') // 路由规则中 :开头 表示动态变量 // 外部地址中可以用动态变量 采用 :1 :2 的方式 // array('news/:month/:day/:id','News/read?cate=1','status=1','post','html,xml'), // array('new/:id','/new.php?id=:1',301,'get','xml'), 重定向 static private function parseRule($route,$regx) { // 获取路由地址规则 $url = $route[1]; // 获取URL地址中的参数 $paths = explode('/',$regx); // 解析路由规则 $matches = array(); $rule = explode('/',$route[0]); foreach ($rule as $item){ if(0===strpos($item,':')) { // 动态变量获取 if($pos = strpos($item,'^') ) { $var = substr($item,1,$pos-1); }elseif(strpos($item,'\\')){ $var = substr($item,1,-2); }else{ $var = substr($item,1); } $matches[$var] = array_shift($paths); }else{ // 过滤URL中的静态变量 array_shift($paths); } } if(0=== strpos($url,'/') || 0===strpos($url,'http')) { // 路由重定向跳转 if(strpos($url,':')) { // 传递动态参数 $values = array_values($matches); $url = preg_replace('/:(\d)/e','$values[\\1-1]',$url); } header("Location: $url", true,isset($route[2])?$route[2]:301); exit; }else{ // 解析路由地址 $var = self::parseUrl($url); // 解析路由地址里面的动态参数 $values = array_values($matches); foreach ($var as $key=>$val){ if(0===strpos($val,':')) { $var[$key] = $values[substr($val,1)-1]; } } $var = array_merge($matches,$var); // 解析剩余的URL参数 if($paths) { preg_replace('@(\w+)\/([^,\/]+)@e', '$var[strtolower(\'\\1\')]="\\2";', implode('/',$paths)); } // 解析路由自动传人参数 if(isset($route[2])) { parse_str($route[2],$params); $var = array_merge($var,$params); } $_GET = array_merge($var,$_GET); } return true; } // 解析正则路由 // array('路由正则','[分组/模块/操作]?参数1=值1&参数2=值2...','额外参数','请求类型','资源类型') // array('路由正则','外部地址','重定向代码','请求类型','资源类型') // 参数值和外部地址中可以用动态变量 采用 :1 :2 的方式 // array('/new\/(\d+)\/(\d+)/','News/read?id=:1&page=:2&cate=1','status=1','post','html,xml'), // array('/new\/(\d+)/','/new.php?id=:1&page=:2&status=1','301','get','html,xml'), 重定向 static private function parseRegex($matches,$route,$regx) { // 获取路由地址规则 $url = preg_replace('/:(\d)/e','$matches[\\1]',$route[1]); if(0=== strpos($url,'/') || 0===strpos($url,'http')) { // 路由重定向跳转 header("Location: $url", true,isset($route[1])?$route[2]:301); exit; }else{ // 解析路由地址 $var = self::parseUrl($url); // 解析剩余的URL参数 $regx = substr_replace($regx,'',0,strlen($matches[0])); if($regx) { preg_replace('@(\w+)\/([^,\/]+)@e', '$var[strtolower(\'\\1\')]="\\2";', $regx); } // 解析路由自动传人参数 if(isset($route[2])) { parse_str($route[2],$params); $var = array_merge($var,$params); } $_GET = array_merge($var,$_GET); } return true; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Rest/Behavior/CheckRestRouteBehavior.class.php
PHP
art
9,620
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: CheckUrlExtBehavior.class.php 2807 2012-03-08 03:23:57Z liu21st $ /** +------------------------------------------------------------------------------ * 行为扩展 URL资源类型检测 +------------------------------------------------------------------------------ */ class CheckUrlExtBehavior extends Behavior { /** +---------------------------------------------------------- * 检测URL地址中资源扩展 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function run(&$params) { // 获取资源类型 if(!empty($_SERVER['PATH_INFO'])) { $part = pathinfo($_SERVER['PATH_INFO']); if(isset($part['extension'])) { // 判断扩展名 define('__EXT__', strtolower($part['extension'])); $_SERVER['PATH_INFO'] = preg_replace('/.'.__EXT__.'$/i','',$_SERVER['PATH_INFO']); } } } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Rest/Behavior/CheckUrlExtBehavior.class.php
PHP
art
1,750
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: tags.php 2802 2012-03-06 06:19:07Z liu21st $ // Rest 系统行为扩展列表文件 return array( 'app_begin'=>array( 'ReadHtmlCache', // 读取静态缓存 ), 'route_check'=>array( 'CheckRestRoute', // 路由检测 ), 'view_end'=>array( 'ShowPageTrace', // 页面Trace显示 ), 'view_template'=>array( 'LocationTemplate', // 自动定位模板文件 ), 'view_parse'=>array( 'ParseTemplate', // 模板解析 支持PHP、内置模板引擎和第三方模板引擎 ), 'view_filter'=>array( 'ContentReplace', // 模板输出替换 'TokenBuild', // 表单令牌 'WriteHtmlCache', // 写入静态缓存 'ShowRuntime', // 运行时间显示 ), 'path_info'=>array( 'CheckUrlExt' ), );
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Rest/tags.php
PHP
art
1,460
<?php // +---------------------------------------------------------------------- // | TOPThink [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2011 http://topthink.com All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: config.php 2668 2012-01-26 13:07:16Z liu21st $ return array( 'REST_METHOD_LIST' => 'get,post,put,delete', // 允许的请求类型列表 'REST_DEFAULT_METHOD' => 'get', // 默认请求类型 'REST_CONTENT_TYPE_LIST' => 'html,xml,json,rss', // REST允许请求的资源类型列表 'REST_DEFAULT_TYPE' => 'html', // 默认的资源类型 'REST_OUTPUT_TYPE' => array( // REST允许输出的资源类型列表 'xml' => 'application/xml', 'json' => 'application/json', 'html' => 'text/html', ), );
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Rest/config.php
PHP
art
1,212
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Action.class.php 2702 2012-02-02 12:35:01Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP Action控制器基类 精简模式 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id: Action.class.php 2702 2012-02-02 12:35:01Z liu21st $ +------------------------------------------------------------------------------ */ abstract class Action { // 当前Action名称 private $name = ''; protected $tVar = array(); // 模板输出变量 /** +---------------------------------------------------------- * 架构函数 取得模板对象实例 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct() { tag('action_begin'); //控制器初始化 if(method_exists($this,'_initialize')) $this->_initialize(); } /** +---------------------------------------------------------- * 获取当前Action名称 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- */ protected function getActionName() { if(empty($this->name)) { // 获取Action名称 $this->name = substr(get_class($this),0,-6); } return $this->name; } /** +---------------------------------------------------------- * 是否AJAX请求 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @return bool +---------------------------------------------------------- */ protected function isAjax() { if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) ) { if('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])) return true; } if(!empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')])) // 判断Ajax方式提交 return true; return false; } /** +---------------------------------------------------------- * 模板变量赋值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param 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; } } public function __set($name,$value) { $this->assign($name,$value); } /** +---------------------------------------------------------- * 取得模板变量的值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function get($name){ if(isset($this->tVar[$name])) return $this->tVar[$name]; else return false; } /** +---------------------------------------------------------- * 魔术方法 有不存在的操作的时候执行 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名 * @param array $args 参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$args) { if( 0 === strcasecmp($method,ACTION_NAME)) { if(method_exists($this,'_empty')) { // 如果定义了_empty操作 则调用 $this->_empty($method,$args); }elseif(file_exists_case(C('TEMPLATE_NAME'))){ // 检查是否存在默认模版 如果有直接输出模版 $this->display(); }else{ // 抛出异常 throw_exception(L('_ERROR_ACTION_').ACTION_NAME); } }else{ switch(strtolower($method)) { // 判断提交方式 case 'ispost': case 'isget': case 'ishead': case 'isdelete': case 'isput': return strtolower($_SERVER['REQUEST_METHOD']) == strtolower(substr($method,2)); // 获取变量 支持过滤和默认值 调用方式 $this->_post($key,$filter,$default); case '_get': $input =& $_GET;break; case '_post':$input =& $_POST;break; case '_put': parse_str(file_get_contents('php://input'), $input);break; case '_request': $input =& $_REQUEST;break; case '_session': $input =& $_SESSION;break; case '_cookie': $input =& $_COOKIE;break; case '_server': $input =& $_SERVER;break; case '_globals': $input =& $GLOBALS;break; default: throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); } if(isset($input[$args[0]])) { // 取值操作 $data = $input[$args[0]]; $fun = $args[1]?$args[1]:C('DEFAULT_FILTER'); $data = $fun($data); // 参数过滤 }else{ // 变量默认值 $data = isset($args[2])?$args[2]:NULL; } return $data; } } /** +---------------------------------------------------------- * 操作错误跳转的快捷方法 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $message 错误信息 * @param string $jumpUrl 页面跳转地址 * @param Boolean $ajax 是否为Ajax方式 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function error($message,$jumpUrl='',$ajax=false) { $this->dispatchJump($message,0,$jumpUrl,$ajax); } /** +---------------------------------------------------------- * 操作成功跳转的快捷方法 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $message 提示信息 * @param string $jumpUrl 页面跳转地址 * @param Boolean $ajax 是否为Ajax方式 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function success($message,$jumpUrl='',$ajax=false) { $this->dispatchJump($message,1,$jumpUrl,$ajax); } /** +---------------------------------------------------------- * Ajax方式返回数据到客户端 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $data 要返回的数据 * @param String $info 提示信息 * @param boolean $status 返回状态 * @param String $status ajax返回类型 JSON XML +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function ajaxReturn($data,$info='',$status=1,$type='') { $result = array(); $result['status'] = $status; $result['info'] = $info; $result['data'] = $data; //扩展ajax返回数据, 在Action中定义function ajaxAssign(&$result){} 方法 扩展ajax返回数据。 if(method_exists($this,"ajaxAssign")) $this->ajaxAssign($result); if(empty($type)) $type = C('DEFAULT_AJAX_RETURN'); if(strtoupper($type)=='JSON') { // 返回JSON数据格式到客户端 包含状态信息 header("Content-Type:text/html; charset=utf-8"); exit(json_encode($result)); }elseif(strtoupper($type)=='XML'){ // 返回xml格式数据 header("Content-Type:text/xml; charset=utf-8"); exit(xml_encode($result)); } } /** +---------------------------------------------------------- * Action跳转(URL重定向) 支持指定模块和延时跳转 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $url 跳转的URL表达式 * @param array $params 其它URL参数 * @param integer $delay 延时跳转的时间 单位为秒 * @param string $msg 跳转提示信息 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function redirect($url,$params=array(),$delay=0,$msg='') { $url = U($url,$params); redirect($url,$delay,$msg); } /** +---------------------------------------------------------- * 默认跳转操作 支持错误导向和正确跳转 * 调用模板显示 默认为public目录下面的success页面 * 提示页面为可配置 支持模板标签 +---------------------------------------------------------- * @param string $message 提示信息 * @param Boolean $status 状态 * @param string $jumpUrl 页面跳转地址 * @param Boolean $ajax 是否为Ajax方式 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ private function dispatchJump($message,$status=1,$jumpUrl='',$ajax=false) { // 判断是否为AJAX返回 if($ajax || $this->isAjax()) $this->ajaxReturn($ajax,$message,$status); if(!empty($jumpUrl)) $this->assign('jumpUrl',$jumpUrl); // 提示标题 $this->assign('msgTitle',$status? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_')); //如果设置了关闭窗口,则提示完毕后自动关闭窗口 if($this->get('closeWin')) $this->assign('jumpUrl','javascript:window.close();'); $this->assign('status',$status); // 状态 //保证输出不受静态缓存影响 C('HTML_CACHE_ON',false); if($status) { //发送成功信息 $this->assign('message',$message);// 提示信息 // 成功操作后默认停留1秒 if(!$this->get('waitSecond')) $this->assign('waitSecond',"1"); // 默认操作成功自动返回操作前页面 if(!$this->get('jumpUrl')) $this->assign("jumpUrl",$_SERVER["HTTP_REFERER"]); $this->display(C('TMPL_ACTION_SUCCESS')); }else{ $this->assign('error',$message);// 提示信息 //发生错误时候默认停留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')); // 中止执行 避免出错后继续执行 exit ; } } /** +---------------------------------------------------------- * 加载模板和页面输出 可以返回输出内容 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $templateFile 模板文件名 * @param string $charset 模板输出字符集 * @param string $contentType 输出类型 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function display($templateFile='',$charset='',$contentType='') { G('viewStartTime'); // 视图开始标签 tag('view_begin',$templateFile); // 解析并获取模板内容 $content = $this->fetch($templateFile); // 输出模板内容 $this->show($content,$charset,$contentType); // 视图结束标签 tag('view_end'); } /** +---------------------------------------------------------- * 输出内容文本可以包括Html +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $content 输出内容 * @param string $charset 模板输出字符集 * @param string $contentType 输出类型 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function show($content,$charset='',$contentType=''){ if(empty($charset)) $charset = C('DEFAULT_CHARSET'); if(empty($contentType)) $contentType = C('TMPL_CONTENT_TYPE'); // 网页字符编码 header("Content-Type:".$contentType."; charset=".$charset); header("Cache-control: private"); //支持页面回跳 header("X-Powered-By:TOPThink/".THINK_VERSION); // 输出模板文件 echo $content; } /** +---------------------------------------------------------- * 解析和获取模板内容 用于输出 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $templateFile 模板文件名 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function fetch($templateFile='') { // 模板文件解析标签 tag('view_template',$templateFile); // 模板文件不存在直接返回 if(!is_file($templateFile)) return NULL; // 页面缓存 ob_start(); ob_implicit_flush(0); // 视图解析标签 $params = array('var'=>$this->tVar,'file'=>$templateFile); $result = tag('view_parse',$params); if(false === $result) { // 未定义行为 则采用PHP原生模板 // 模板阵列变量分解成为独立变量 extract($this->tVar, EXTR_OVERWRITE); // 直接载入PHP模板 include $templateFile; } // 获取并清空缓存 $content = ob_get_clean(); // 内容过滤标签 tag('view_filter',$content); // 输出模板文件 return $content; } /** +---------------------------------------------------------- * 析构方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __destruct() { // 保存日志 if(C('LOG_RECORD')) Log::save(); // 执行后续操作 tag('action_end'); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Lite/Action.class.php
PHP
art
17,153
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Db.class.php 2702 2012-02-02 12:35:01Z liu21st $ define('CLIENT_MULTI_RESULTS', 131072); /** +------------------------------------------------------------------------------ * ThinkPHP 精简模式数据库中间层实现类 只支持Mysql +------------------------------------------------------------------------------ */ class Db { static private $_instance = null; // 是否自动释放查询结果 protected $autoFree = false; // 是否显示调试信息 如果启用会在日志文件记录sql语句 public $debug = false; // 是否使用永久连接 protected $pconnect = false; // 当前SQL指令 protected $queryStr = ''; // 最后插入ID protected $lastInsID = null; // 返回或者影响记录数 protected $numRows = 0; // 返回字段数 protected $numCols = 0; // 事务指令数 protected $transTimes = 0; // 错误信息 protected $error = ''; // 当前连接ID protected $linkID = null; // 当前查询ID protected $queryID = null; // 是否已经连接数据库 protected $connected = false; // 数据库连接参数配置 protected $config = ''; // 数据库表达式 protected $comparison = array('eq'=>'=','neq'=>'!=','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE'); // 查询表达式 protected $selectSql = 'SELECT%DISTINCT% %FIELDS% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT%'; /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $config 数据库配置数组 +---------------------------------------------------------- */ public function __construct($config=''){ if ( !extension_loaded('mysql') ) { throw_exception(L('_NOT_SUPPERT_').':mysql'); } $this->config = $this->parseConfig($config); if(APP_DEBUG) { $this->debug = true; } } /** +---------------------------------------------------------- * 连接数据库方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function connect() { if(!$this->connected) { $config = $this->config; // 处理不带端口号的socket连接情况 $host = $config['hostname'].($config['hostport']?":{$config['hostport']}":''); $pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect; if($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); $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 escapeString($str) { return mysql_escape_string($str); } /** +---------------------------------------------------------- * 析构方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __destruct() { // 关闭连接 $this->close(); } /** +---------------------------------------------------------- * 取得数据库类实例 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @return mixed 返回数据库驱动类 +---------------------------------------------------------- */ public static function getInstance($db_config='') { if ( self::$_instance==null ){ self::$_instance = new Db($db_config); } return self::$_instance; } /** +---------------------------------------------------------- * 分析数据库配置信息,支持数组和DSN +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param mixed $db_config 数据库配置信息 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ private function parseConfig($db_config='') { if ( !empty($db_config) && is_string($db_config)) { // 如果DSN字符串则进行解析 $db_config = $this->parseDSN($db_config); }else if(empty($db_config)){ // 如果配置为空,读取配置文件设置 $db_config = array ( 'dbms' => C('DB_TYPE'), 'username' => C('DB_USER'), 'password' => C('DB_PWD'), 'hostname' => C('DB_HOST'), 'hostport' => C('DB_PORT'), 'database' => C('DB_NAME'), 'dsn' => C('DB_DSN'), 'params' => C('DB_PARAMS'), ); } return $db_config; } /** +---------------------------------------------------------- * DSN解析 * 格式: mysql://username:passwd@localhost:3306/DbName +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param string $dsnStr +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function parseDSN($dsnStr) { if( empty($dsnStr) ){return false;} $info = parse_url($dsnStr); if($info['scheme']){ $dsn = array( 'dbms' => $info['scheme'], 'username' => isset($info['user']) ? $info['user'] : '', 'password' => isset($info['pass']) ? $info['pass'] : '', 'hostname' => isset($info['host']) ? $info['host'] : '', 'hostport' => isset($info['port']) ? $info['port'] : '', 'database' => isset($info['path']) ? substr($info['path'],1) : '' ); }else { preg_match('/^(.*?)\:\/\/(.*?)\:(.*?)\@(.*?)\:([0-9]{1, 6})\/(.*?)$/',trim($dsnStr),$matches); $dsn = array ( 'dbms' => $matches[1], 'username' => $matches[2], 'password' => $matches[3], 'hostname' => $matches[4], 'hostport' => $matches[5], 'database' => $matches[6] ); } return $dsn; } /** +---------------------------------------------------------- * 数据库调试 记录当前SQL +---------------------------------------------------------- * @access protected +---------------------------------------------------------- */ protected function debug() { // 记录操作结束时间 if ( $this->debug ) { G('queryEndTime'); Log::record($this->queryStr." [ RunTime:".G('queryStartTime','queryEndTime',6)."s ]",Log::SQL); } } /** +---------------------------------------------------------- * 设置锁机制 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseLock($lock=false) { if(!$lock) return ''; if('ORACLE' == $this->dbType) { return ' FOR UPDATE NOWAIT '; } return ' FOR UPDATE '; } /** +---------------------------------------------------------- * set分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $data +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseSet($data) { foreach ($data as $key=>$val){ $value = $this->parseValue($val); if(is_scalar($value)) // 过滤非标量数据 $set[] = $this->parseKey($key).'='.$value; } return ' SET '.implode(',',$set); } /** +---------------------------------------------------------- * value分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $value +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseValue($value) { if(is_string($value)) { $value = '\''.$this->escapeString($value).'\''; }elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){ $value = $this->escapeString($value[1]); }elseif(is_null($value)){ $value = 'null'; } return $value; } /** +---------------------------------------------------------- * field分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $fields +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseField($fields) { if(is_array($fields)) { // 完善数组方式传字段名的支持 // 支持 'field1'=>'field2' 这样的字段别名定义 $array = array(); foreach ($fields as $key=>$field){ if(!is_numeric($key)) $array[] = $this->parseKey($key).' AS '.$this->parseKey($field); else $array[] = $this->parseKey($field); } $fieldsStr = implode(',', $array); }elseif(is_string($fields) && !empty($fields)) { $fieldsStr = $this->parseKey($fields); }else{ $fieldsStr = '*'; } return $fieldsStr; } /** +---------------------------------------------------------- * table分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $table +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseTable($tables) { if(is_string($tables)) $tables = explode(',',$tables); array_walk($tables, array(&$this, 'parseKey')); return implode(',',$tables); } /** +---------------------------------------------------------- * where分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $where +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseWhere($where) { $whereStr = ''; if(is_string($where)) { // 直接使用字符串条件 $whereStr = $where; }else{ // 使用数组条件表达式 if(isset($where['_logic'])) { // 定义逻辑运算规则 例如 OR XOR AND NOT $operate = ' '.strtoupper($where['_logic']).' '; unset($where['_logic']); }else{ // 默认进行 AND 运算 $operate = ' AND '; } foreach ($where as $key=>$val){ $whereStr .= "( "; if(0===strpos($key,'_')) { // 解析特殊条件表达式 $whereStr .= $this->parseThinkWhere($key,$val); }else{ $key = $this->parseKey($key); if(is_array($val)) { if(is_string($val[0])) { if(preg_match('/^(EQ|NEQ|GT|EGT|LT|ELT|NOTLIKE|LIKE)$/i',$val[0])) { // 比较运算 $whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' '.$this->parseValue($val[1]); }elseif('exp'==strtolower($val[0])){ // 使用表达式 $whereStr .= ' ('.$key.' '.$val[1].') '; }elseif(preg_match('/IN/i',$val[0])){ // IN 运算 $zone = is_array($val[1])? implode(',',$this->parseValue($val[1])):$val[1]; $whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')'; }elseif(preg_match('/BETWEEN/i',$val[0])){ // BETWEEN运算 $data = is_string($val[1])? explode(',',$val[1]):$val[1]; $whereStr .= ' ('.$key.' BETWEEN '.$data[0].' AND '.$data[1].' )'; }else{ throw_exception(L('_EXPRESS_ERROR_').':'.$val[0]); } }else { $count = count($val); if(in_array(strtoupper(trim($val[$count-1])),array('AND','OR','XOR'))) { $rule = strtoupper(trim($val[$count-1])); $count = $count -1; }else{ $rule = 'AND'; } for($i=0;$i<$count;$i++) { $data = is_array($val[$i])?$val[$i][1]:$val[$i]; if('exp'==strtolower($val[$i][0])) { $whereStr .= '('.$key.' '.$data.') '.$rule.' '; }else{ $op = is_array($val[$i])?$this->comparison[strtolower($val[$i][0])]:'='; $whereStr .= '('.$key.' '.$op.' '.$this->parseValue($data).') '.$rule.' '; } } $whereStr = substr($whereStr,0,-4); } }else { //对字符串类型字段采用模糊匹配 if(C('LIKE_MATCH_FIELDS') && preg_match('/('.C('LIKE_MATCH_FIELDS').')/i',$key)) { $val = '%'.$val.'%'; $whereStr .= $key." LIKE ".$this->parseValue($val); }else { $whereStr .= $key." = ".$this->parseValue($val); } } } $whereStr .= ' )'.$operate; } $whereStr = substr($whereStr,0,-strlen($operate)); } return empty($whereStr)?'':' WHERE '.$whereStr; } /** +---------------------------------------------------------- * 特殊条件分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $key * @param mixed $val +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseThinkWhere($key,$val) { $whereStr = ''; switch($key) { case '_string': // 字符串模式查询条件 $whereStr = $val; break; case '_complex': // 复合查询条件 $whereStr = substr($this->parseWhere($val),6); break; case '_query': // 字符串模式查询条件 parse_str($val,$where); if(isset($where['_logic'])) { $op = ' '.strtoupper($where['_logic']).' '; unset($where['_logic']); }else{ $op = ' AND '; } $array = array(); foreach ($where as $field=>$data) $array[] = $this->parseKey($field).' = '.$this->parseValue($data); $whereStr = implode($op,$array); break; } return $whereStr; } /** +---------------------------------------------------------- * limit分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $lmit +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseLimit($limit) { return !empty($limit)? ' LIMIT '.$limit.' ':''; } /** +---------------------------------------------------------- * join分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $join +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseJoin($join) { $joinStr = ''; if(!empty($join)) { if(is_array($join)) { foreach ($join as $key=>$_join){ if(false !== stripos($_join,'JOIN')) $joinStr .= ' '.$_join; else $joinStr .= ' LEFT JOIN ' .$_join; } }else{ $joinStr .= ' LEFT JOIN ' .$join; } } return $joinStr; } /** +---------------------------------------------------------- * order分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $order +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseOrder($order) { return !empty($order)? ' ORDER BY '.$order:''; } /** +---------------------------------------------------------- * group分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $group +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseGroup($group) { return !empty($group)? ' GROUP BY '.$group:''; } /** +---------------------------------------------------------- * having分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $having +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseHaving($having) { return !empty($having)? ' HAVING '.$having:''; } /** +---------------------------------------------------------- * distinct分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $distinct +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseDistinct($distinct) { return !empty($distinct)? ' DISTINCT ' :''; } /** +---------------------------------------------------------- * 插入记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 数据 * @param array $options 参数表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function insert($data,$options=array()) { foreach ($data as $key=>$val){ $value = $this->parseValue($val); if(is_scalar($value)) { // 过滤非标量数据 $values[] = $value; $fields[] = $this->parseKey($key); } } $sql = 'INSERT INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')'; $sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->execute($sql); } /** +---------------------------------------------------------- * 更新记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 数据 * @param array $options 表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function update($data,$options) { $sql = 'UPDATE ' .$this->parseTable($options['table']) .$this->parseSet($data) .$this->parseWhere(isset($options['where'])?$options['where']:'') .$this->parseOrder(isset($options['order'])?$options['order']:'') .$this->parseLimit(isset($options['limit'])?$options['limit']:'') .$this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->execute($sql); } /** +---------------------------------------------------------- * 删除记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $options 表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function delete($options=array()) { $sql = 'DELETE FROM ' .$this->parseTable($options['table']) .$this->parseWhere(isset($options['where'])?$options['where']:'') .$this->parseOrder(isset($options['order'])?$options['order']:'') .$this->parseLimit(isset($options['limit'])?$options['limit']:'') .$this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->execute($sql); } /** +---------------------------------------------------------- * 查找记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $options 表达式 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function select($options=array()) { if(isset($options['page'])) { // 根据页数计算limit list($page,$listRows) = explode(',',$options['page']); $listRows = $listRows?$listRows:($options['limit']?$options['limit']:20); $offset = $listRows*((int)$page-1); $options['limit'] = $offset.','.$listRows; } $sql = str_replace( array('%TABLE%','%DISTINCT%','%FIELDS%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%'), array( $this->parseTable($options['table']), $this->parseDistinct(isset($options['distinct'])?$options['distinct']:false), $this->parseField(isset($options['field'])?$options['field']:'*'), $this->parseJoin(isset($options['join'])?$options['join']:''), $this->parseWhere(isset($options['where'])?$options['where']:''), $this->parseGroup(isset($options['group'])?$options['group']:''), $this->parseHaving(isset($options['having'])?$options['having']:''), $this->parseOrder(isset($options['order'])?$options['order']:''), $this->parseLimit(isset($options['limit'])?$options['limit']:'') ),$this->selectSql); $sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->query($sql); } /** +---------------------------------------------------------- * 字段和表名添加` * 保证指令中使用关键字不出错 针对mysql +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $value +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ protected function parseKey(&$value) { $value = trim($value); if( false !== strpos($value,' ') || false !== strpos($value,',') || false !== strpos($value,'*') || false !== strpos($value,'(') || false !== strpos($value,'.') || false !== strpos($value,'`')) { //如果包含* 或者 使用了sql方法 则不作处理 }else{ $value = '`'.$value.'`'; } return $value; } /** +---------------------------------------------------------- * 获取最近一次查询的sql语句 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastSql() { return $this->queryStr; } /** +---------------------------------------------------------- * 获取最近插入的ID +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastInsID(){ return $this->lastInsID; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Lite/Db.class.php
PHP
art
39,553
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Model.class.php 2779 2012-02-24 02:56:57Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP 精简模式Model模型类 * 只支持CURD和连贯操作 以及常用查询 去掉回调接口 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id: Model.class.php 2779 2012-02-24 02:56:57Z liu21st $ +------------------------------------------------------------------------------ */ class Model { // 操作状态 const MODEL_INSERT = 1; // 插入模型数据 const MODEL_UPDATE = 2; // 更新模型数据 const MODEL_BOTH = 3; // 包含上面两种方式 const MUST_VALIDATE = 1;// 必须验证 const EXISTS_VAILIDATE = 0;// 表单存在字段则验证 const VALUE_VAILIDATE = 2;// 表单值不为空则验证 // 当前数据库操作对象 protected $db = null; // 主键名称 protected $pk = 'id'; // 数据表前缀 protected $tablePrefix = ''; // 模型名称 protected $name = ''; // 数据库名称 protected $dbName = ''; // 数据表名(不包含表前缀) protected $tableName = ''; // 实际数据表名(包含表前缀) protected $trueTableName =''; // 最近错误信息 protected $error = ''; // 字段信息 protected $fields = array(); // 数据信息 protected $data = array(); // 查询表达式参数 protected $options = array(); protected $_validate = array(); // 自动验证定义 protected $_auto = array(); // 自动完成定义 // 是否自动检测数据表字段信息 protected $autoCheckFields = true; // 是否批处理验证 protected $patchValidate = false; /** +---------------------------------------------------------- * 架构函数 * 取得DB类的实例对象 字段检查 +---------------------------------------------------------- * @param string $name 模型名称 * @param string $tablePrefix 表前缀 * @param mixed $connection 数据库连接信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($name='',$tablePrefix='',$connection='') { // 模型初始化 $this->_initialize(); // 获取模型名称 if(!empty($name)) { if(strpos($name,'.')) { // 支持 数据库名.模型名的 定义 list($this->dbName,$this->name) = explode('.',$name); }else{ $this->name = $name; } }elseif(empty($this->name)){ $this->name = $this->getModelName(); } if(!empty($tablePrefix)) { $this->tablePrefix = $tablePrefix; } // 设置表前缀 $this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX'); // 数据库初始化操作 // 获取数据库操作对象 // 当前模型有独立的数据库连接信息 $this->db(0,empty($this->connection)?$connection:$this->connection); // 字段检测 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')) { $db = $this->dbName?$this->dbName:C('DB_NAME'); $this->fields = F('_fields/'.$db.'.'.$this->name); if(!$this->fields) $this->flush(); }else{ // 每次都会读取数据表信息 $this->flush(); } } } /** +---------------------------------------------------------- * 获取字段信息并缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function flush() { // 缓存不存在则查询数据表信息 $fields = $this->db->getFields($this->getTableName()); if(!$fields) { // 无法获取字段信息 return false; } $this->fields = array_keys($fields); $this->fields['_autoinc'] = false; foreach ($fields as $key=>$val){ // 记录字段类型 $type[$key] = $val['type']; if($val['primary']) { $this->fields['_pk'] = $key; if($val['autoinc']) $this->fields['_autoinc'] = true; } } // 记录字段类型信息 if(C('DB_FIELDTYPE_CHECK')) $this->fields['_type'] = $type; // 2008-3-7 增加缓存开关控制 if(C('DB_FIELDS_CACHE')){ // 永久缓存数据表信息 $db = $this->dbName?$this->dbName:C('DB_NAME'); F('_fields/'.$db.'.'.$this->name,$this->fields); } } /** +---------------------------------------------------------- * 设置数据对象的值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 名称 * @param mixed $value 值 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function __set($name,$value) { // 设置数据对象属性 $this->data[$name] = $value; } /** +---------------------------------------------------------- * 获取数据对象的值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 名称 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __get($name) { return isset($this->data[$name])?$this->data[$name]:null; } /** +---------------------------------------------------------- * 检测数据对象的值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 名称 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function __isset($name) { return isset($this->data[$name]); } /** +---------------------------------------------------------- * 销毁数据对象的值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 名称 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function __unset($name) { unset($this->data[$name]); } /** +---------------------------------------------------------- * 利用__call方法实现一些特殊的Model方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名称 * @param array $args 调用参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$args) { if(in_array(strtolower($method),array('table','where','order','limit','page','alias','having','group','lock','distinct'),true)) { // 连贯操作的实现 $this->options[strtolower($method)] = $args[0]; return $this; }elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){ // 统计查询的实现 $field = isset($args[0])?$args[0]:'*'; return $this->getField(strtoupper($method).'('.$field.') AS tp_'.$method); }elseif(strtolower(substr($method,0,5))=='getby') { // 根据某个字段获取记录 $field = parse_name(substr($method,5)); $where[$field] = $args[0]; return $this->where($where)->find(); }else{ throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); return; } } // 回调方法 初始化模型 protected function _initialize() {} /** +---------------------------------------------------------- * 对保存到数据库的数据进行处理 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $data 要操作的数据 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ protected function _facade($data) { // 检查非数据字段 if(!empty($this->fields)) { foreach ($data as $key=>$val){ if(!in_array($key,$this->fields,true)){ unset($data[$key]); }elseif(C('DB_FIELDTYPE_CHECK') && is_scalar($val)) { // 字段类型检查 $this->_parseType($data,$key); } } } return $data; } /** +---------------------------------------------------------- * 新增数据 +---------------------------------------------------------- * @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); // 数据处理 $data = $this->_facade($data); // 写入数据到数据库 $result = $this->db->insert($data,$options); if(false !== $result ) { $insertId = $this->getLastInsID(); if($insertId) { // 自增主键返回插入ID return $insertId; } } 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(!isset($options['where']) ) { // 如果存在主键数据 则自动作为更新条件 if(isset($data[$this->getPk()])) { $pk = $this->getPk(); $where[$pk] = $data[$pk]; $options['where'] = $where; unset($data[$pk]); }else{ // 如果没有任何更新条件则不执行 $this->error = L('_OPERATION_WRONG_'); return false; } } $result = $this->db->update($data,$options); return $result; } /** +---------------------------------------------------------- * 删除数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $options 表达式 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function delete($options=array()) { if(empty($options) && empty($this->options['where'])) { // 如果删除条件为空 则删除当前数据对象所对应的记录 if(!empty($this->data) && isset($this->data[$this->getPk()])) return $this->delete($this->data[$this->getPk()]); else return false; } if(is_numeric($options) || is_string($options)) { // 根据主键删除记录 $pk = $this->getPk(); if(strpos($options,',')) { $where[$pk] = array('IN', $options); }else{ $where[$pk] = $options; $pkValue = $options; } $options = array(); $options['where'] = $where; } // 分析表达式 $options = $this->_parseOptions($options); $result= $this->db->delete($options); // 返回删除记录个数 return $result; } /** +---------------------------------------------------------- * 查询数据集 +---------------------------------------------------------- * @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; } return $resultSet; } /** +---------------------------------------------------------- * 分析表达式 +---------------------------------------------------------- * @access proteced +---------------------------------------------------------- * @param array $options 表达式参数 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ protected function _parseOptions($options=array()) { if(is_array($options)) $options = array_merge($this->options,$options); // 查询过后清空sql表达式组装 避免影响下次查询 $this->options = array(); if(!isset($options['table'])) // 自动获取表名 $options['table'] =$this->getTableName(); if(!empty($options['alias'])) { $options['table'] .= ' '.$options['alias']; } // 字段类型验证 if(C('DB_FIELDTYPE_CHECK')) { if(isset($options['where']) && is_array($options['where'])) { // 对数组查询条件进行字段类型检查 foreach ($options['where'] as $key=>$val){ if(in_array($key,$this->fields,true) && is_scalar($val)){ $this->_parseType($options['where'],$key); } } } } return $options; } /** +---------------------------------------------------------- * 数据类型检测 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $data 数据 * @param string $key 字段名 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function _parseType(&$data,$key) { $fieldType = strtolower($this->fields['_type'][$key]); if(false !== strpos($fieldType,'int')) { $data[$key] = intval($data[$key]); }elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){ $data[$key] = floatval($data[$key]); }elseif(false !== strpos($fieldType,'bool')){ $data[$key] = (bool)$data[$key]; } } /** +---------------------------------------------------------- * 查询数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $options 表达式参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function find($options=array()) { if(is_numeric($options) || is_string($options)) { $where[$this->getPk()] =$options; $options = array(); $options['where'] = $where; } // 总是查找一条记录 $options['limit'] = 1; // 分析表达式 $options = $this->_parseOptions($options); $resultSet = $this->db->select($options); if(false === $resultSet) { return false; } if(empty($resultSet)) {// 查询结果为空 return null; } $this->data = $resultSet[0]; return $this->data; } /** +---------------------------------------------------------- * 设置记录的某个字段值 * 支持使用数据库字段和方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string|array $field 字段名 * @param string|array $value 字段值 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setField($field,$value) { if(is_array($field)) { $data = $field; }else{ $data[$field] = $value; } return $this->save($data); } /** +---------------------------------------------------------- * 字段值增长 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param integer $step 增长值 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setInc($field,$step=1) { return $this->setField($field,array('exp',$field.'+'.$step)); } /** +---------------------------------------------------------- * 字段值减少 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param integer $step 减少值 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setDec($field,$step=1) { return $this->setField($field,array('exp',$field.'-'.$step)); } /** +---------------------------------------------------------- * 获取一条记录的某个字段值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param string $spea 字段数据间隔符号 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function getField($field,$sepa=null) { $options['field'] = $field; $options = $this->_parseOptions($options); if(strpos($field,',')) { // 多字段 $resultSet = $this->db->select($options); if(!empty($resultSet)) { $_field = explode(',', $field); $field = array_keys($resultSet[0]); $move = $_field[0]==$_field[1]?false:true; $key = array_shift($field); $key2 = array_shift($field); $cols = array(); $count = count($_field); foreach ($resultSet as $result){ $name = $result[$key]; if($move) { // 删除键值记录 unset($result[$key]); } if(2==$count) { $cols[$name] = $result[$key2]; }else{ $cols[$name] = is_null($sepa)?$result:implode($sepa,$result); } } return $cols; } }else{ // 查找一条记录 $options['limit'] = 1; $result = $this->db->select($options); if(!empty($result)) { return reset($result[0]); } } return null; } /** +---------------------------------------------------------- * 创建数据对象 但不保存到数据库 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 创建数据 * @param string $type 状态 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function create($data='',$type='') { // 如果没有传值默认取POST数据 if(empty($data)) { $data = $_POST; }elseif(is_object($data)){ $data = get_object_vars($data); } // 验证数据 if(empty($data) || !is_array($data)) { $this->error = L('_DATA_TYPE_INVALID_'); return false; } // 状态 $type = $type?$type:(!empty($data[$this->getPk()])?self::MODEL_UPDATE:self::MODEL_INSERT); // 数据自动验证 if(!$this->autoValidation($data,$type)) return false; // 验证完成生成数据对象 if($this->autoCheckFields) { // 开启字段检测 则过滤非法字段数据 $vo = array(); foreach ($this->fields as $key=>$name){ if(substr($key,0,1)=='_') continue; $val = isset($data[$name])?$data[$name]:null; //保证赋值有效 if(!is_null($val)){ $vo[$name] = (MAGIC_QUOTES_GPC && is_string($val))? stripslashes($val) : $val; } } }else{ $vo = $data; } // 创建完成对数据进行自动处理 $this->autoOperation($vo,$type); // 赋值当前数据对象 $this->data = $vo; // 返回创建的数据以供其他调用 return $vo; } /** +---------------------------------------------------------- * 使用正则验证数据 +---------------------------------------------------------- * @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)) { // 如果设置了数据自动验证则进行数据验证 if($this->patchValidate) { // 重置验证错误信息 $this->error = array(); } foreach($this->_validate as $key=>$val) { // 验证因子定义格式 // array(field,rule,message,condition,type,when,params) // 判断是否需要执行验证 if(empty($val[5]) || $val[5]== self::MODEL_BOTH || $val[5]== $type ) { if(0==strpos($val[2],'{%') && strpos($val[2],'}')) // 支持提示信息的多语言 使用 {%语言定义} 方式 $val[2] = L(substr($val[2],2,-1)); $val[3] = isset($val[3])?$val[3]:self::EXISTS_VAILIDATE; $val[4] = isset($val[4])?$val[4]:'regex'; // 判断验证条件 switch($val[3]) { case self::MUST_VALIDATE: // 必须验证 不管表单是否有设置该字段 if(false === $this->_validationField($data,$val)) return false; break; case self::VALUE_VAILIDATE: // 值不为空的时候才验证 if('' != trim($data[$val[0]])) if(false === $this->_validationField($data,$val)) return false; break; default: // 默认表单存在该字段就验证 if(isset($data[$val[0]])) if(false === $this->_validationField($data,$val)) return false; } } } // 批量验证的时候最后返回错误 if(!empty($this->error)) return false; } return true; } /** +---------------------------------------------------------- * 验证表单字段 支持批量验证 * 如果批量验证返回错误的数组信息 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $data 创建数据 * @param array $val 验证因子 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ protected function _validationField($data,$val) { if(false === $this->_validationFieldItem($data,$val)){ if($this->patchValidate) { $this->error[$val[0]] = $val[2]; }else{ $this->error = $val[2]; return false; } } return ; } /** +---------------------------------------------------------- * 根据验证因子验证字段 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $data 创建数据 * @param array $val 验证因子 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ protected function _validationFieldItem($data,$val) { switch($val[4]) { case 'function':// 使用函数进行验证 case 'callback':// 调用方法进行验证 $args = isset($val[6])?$val[6]:array(); array_unshift($args,$data[$val[0]]); if('function'==$val[4]) { return call_user_func_array($val[1], $args); }else{ return call_user_func_array(array(&$this, $val[1]), $args); } case 'confirm': // 验证两个字段是否相同 return $data[$val[0]] == $data[$val[1]]; case 'unique': // 验证某个值是否唯一 if(is_string($val[0]) && strpos($val[0],',')) $val[0] = explode(',',$val[0]); $map = array(); if(is_array($val[0])) { // 支持多个字段验证 foreach ($val[0] as $field) $map[$field] = $data[$field]; }else{ $map[$val[0]] = $data[$val[0]]; } if(!empty($data[$this->getPk()])) { // 完善编辑的时候验证唯一 $map[$this->getPk()] = array('neq',$data[$this->getPk()]); } if($this->where($map)->find()) return false; return true; default: // 检查附加规则 return $this->check($data[$val[0]],$val[1],$val[4]); } } /** +---------------------------------------------------------- * 验证数据 支持 in between equal length regex expire ip_allow ip_deny +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $value 验证数据 * @param mixed $rule 验证表达式 * @param string $type 验证方式 默认为正则验证 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function check($value,$rule,$type='regex'){ switch(strtolower($type)) { case 'in': // 验证是否在某个指定范围之内 逗号分隔字符串或者数组 $range = is_array($rule)?$rule:explode(',',$rule); return in_array($value ,$range); case 'between': // 验证是否在某个范围 list($min,$max) = explode(',',$rule); return $value>=$min && $value<=$max; case 'equal': // 验证是否等于某个值 return $value == $rule; case 'length': // 验证长度 $length = mb_strlen($value,'utf-8'); // 当前数据长度 if(strpos($rule,',')) { // 长度区间 list($min,$max) = explode(',',$rule); return $length >= $min && $length <= $max; }else{// 指定长度 return $length == $rule; } case 'expire': list($start,$end) = explode(',',$rule); if(!is_numeric($start)) $start = strtotime($start); if(!is_numeric($end)) $end = strtotime($end); return $_SERVER['REQUEST_TIME'] >= $start && $_SERVER['REQUEST_TIME'] <= $end; case 'ip_allow': // IP 操作许可验证 return in_array(get_client_ip(),explode(',',$rule)); case 'ip_deny': // IP 操作禁止验证 return !in_array(get_client_ip(),explode(',',$rule)); case 'regex': default: // 默认使用正则验证 可以使用验证类中定义的验证名称 // 检查附加规则 return $this->regex($value,$rule); } } /** +---------------------------------------------------------- * SQL查询 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $sql SQL指令 +---------------------------------------------------------- * @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 +---------------------------------------------------------- * @param integer $linkNum 连接序号 * @param mixed $config 数据库连接信息 * @param array $params 模型参数 +---------------------------------------------------------- * @return Model +---------------------------------------------------------- */ public function db($linkNum,$config='',$params=array()){ static $_db = array(); if(!isset($_db[$linkNum])) { // 创建一个新的实例 if(!empty($config) && false === strpos($config,'/')) { // 支持读取配置参数 $config = C($config); } $_db[$linkNum] = Db::getInstance($config); }elseif(NULL === $config){ $_db[$linkNum]->close(); // 关闭数据库连接 unset($_db[$linkNum]); return ; } if(!empty($params)) { if(is_string($params)) parse_str($params,$params); foreach ($params as $name=>$value){ $this->setProperty($name,$value); } } // 切换数据库连接 $this->db = $_db[$linkNum]; 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); } $this->trueTableName = strtolower($tableName); } return (!empty($this->dbName)?$this->dbName.'.':'').$this->trueTableName; } /** +---------------------------------------------------------- * 启动事务 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function startTrans() { $this->commit(); $this->db->startTrans(); return ; } /** +---------------------------------------------------------- * 提交事务 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function commit() { return $this->db->commit(); } /** +---------------------------------------------------------- * 事务回滚 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function rollback() { return $this->db->rollback(); } /** +---------------------------------------------------------- * 返回模型的错误信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getError() { return $this->error; } /** +---------------------------------------------------------- * 返回数据库的错误信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getDbError() { return $this->db->getError(); } /** +---------------------------------------------------------- * 返回最后插入的ID +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastInsID() { return $this->db->getLastInsID(); } /** +---------------------------------------------------------- * 返回最后执行的sql语句 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastSql() { return $this->db->getLastSql(); } // 鉴于getLastSql比较常用 增加_sql 别名 public function _sql(){ return $this->getLastSql(); } /** +---------------------------------------------------------- * 获取主键名称 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getPk() { return isset($this->fields['_pk'])?$this->fields['_pk']:$this->pk; } /** +---------------------------------------------------------- * 获取数据表字段信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function getDbFields(){ if($this->fields) { $fields = $this->fields; unset($fields['_autoinc'],$fields['_pk'],$fields['_type']); return $fields; } return false; } /** +---------------------------------------------------------- * 指定查询字段 支持字段排除 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $field * @param boolean $except 是否排除 +---------------------------------------------------------- * @return Model +---------------------------------------------------------- */ public function field($field,$except=false){ if($except) {// 字段排除 if(is_string($field)) { $field = explode(',',$field); } $fields = $this->getDbFields(); $field = $fields?array_diff($fields,$field):$field; } $this->options['field'] = $field; return $this; } /** +---------------------------------------------------------- * 设置数据对象值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param 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; } /** +---------------------------------------------------------- * 查询SQL组装 union +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $union +---------------------------------------------------------- * @return Model +---------------------------------------------------------- */ public function union($union) { if(empty($union)) return $this; // 转换union表达式 if($union instanceof Model) { $options = $union->getProperty('options'); if(!isset($options['table'])){ // 自动获取表名 $options['table'] =$union->getTableName(); } if(!isset($options['field'])) { $options['field'] =$this->options['field']; } }elseif(is_object($union)) { $options = get_object_vars($union); }elseif(!is_array($union)){ throw_exception(L('_DATA_TYPE_INVALID_')); } $this->options['union'][] = $options; 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; } /** +---------------------------------------------------------- * 获取模型的属性值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 名称 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function getProperty($name){ if(property_exists($this,$name)) return $this->$name; else return NULL; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Lite/Model.class.php
PHP
art
51,992
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Dispatcher.class.php 2702 2012-02-02 12:35:01Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP内置的Dispatcher类 用于精简模式 * 完成URL解析、路由和调度 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Util * @author liu21st <liu21st@gmail.com> * @version $Id: Dispatcher.class.php 2702 2012-02-02 12:35:01Z liu21st $ +------------------------------------------------------------------------------ */ class Dispatcher { /** +---------------------------------------------------------- * URL映射到控制器 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function dispatch() { $urlMode = C('URL_MODEL'); if($urlMode == URL_COMPAT || !empty($_GET[C('VAR_PATHINFO')])){ // 兼容模式判断 define('PHP_FILE',_PHP_FILE_.'?'.C('VAR_PATHINFO').'='); $_SERVER['PATH_INFO'] = $_GET[C('VAR_PATHINFO')]; unset($_GET[C('VAR_PATHINFO')]); }elseif($urlMode == URL_REWRITE ) { //当前项目地址 $url = dirname(_PHP_FILE_); if($url == '/' || $url == '\\') $url = ''; define('PHP_FILE',$url); }else { //当前项目地址 define('PHP_FILE',_PHP_FILE_); } // 分析PATHINFO信息 tag('path_info'); // 分析PATHINFO信息 $depr = C('URL_PATHINFO_DEPR'); if(!empty($_SERVER['PATH_INFO'])) { if(C('URL_HTML_SUFFIX') && !empty($_SERVER['PATH_INFO'])) { $_SERVER['PATH_INFO'] = preg_replace('/\.'.trim(C('URL_HTML_SUFFIX'),'.').'$/', '', $_SERVER['PATH_INFO']); } 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(!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\']="\\2";', implode($depr,$paths)); $_GET = array_merge($var,$_GET); } } // 获取分组 模块和操作名称 if (C('APP_GROUP_LIST')) { define('GROUP_NAME', self::getGroup(C('VAR_GROUP'))); } define('MODULE_NAME',self::getModule(C('VAR_MODULE'))); define('ACTION_NAME',self::getAction(C('VAR_ACTION'))); // URL常量 define('__SELF__',$_SERVER['REQUEST_URI']); // 当前项目地址 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__', GROUP_NAME == C('DEFAULT_GROUP') ?__APP__ : __APP__.'/'.$group); define('__URL__', __GROUP__.$depr.$module); }else{ define('__URL__',__APP__.'/'.$module); } // 当前操作地址 define('__ACTION__',__URL__.$depr.ACTION_NAME); //保证$_REQUEST正常取值 $_REQUEST = array_merge($_POST,$_GET); } /** +---------------------------------------------------------- * 路由检测 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function routerCheck() { $return = false; // 路由检测标签 tag('route_check',$return); return $return; } /** +---------------------------------------------------------- * 获得实际的模块名称 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static private function getModule($var) { $module = (!empty($_GET[$var])? $_GET[$var]:C('DEFAULT_MODULE')); unset($_GET[$var]); if(C('URL_CASE_INSENSITIVE')) { // URL地址不区分大小写 define('P_MODULE_NAME',strtolower($module)); // 智能识别方式 index.php/user_type/index/ 识别到 UserTypeAction 模块 $module = ucfirst(parse_name(P_MODULE_NAME,1)); } return $module; } /** +---------------------------------------------------------- * 获得实际的操作名称 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ static private function getAction($var) { $action = !empty($_POST[$var]) ? $_POST[$var] : (!empty($_GET[$var])?$_GET[$var]:C('DEFAULT_ACTION')); unset($_POST[$var],$_GET[$var]); define('P_ACTION_NAME',$action); 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)); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Lite/Dispatcher.class.php
PHP
art
7,387
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: tags.php 2702 2012-02-02 12:35:01Z liu21st $ // 核心行为扩展列表文件 return array( 'app_begin'=>array( 'CheckTemplate', // 模板检测 ), 'route_check'=>array('CheckRoute', // 路由检测 ), 'app_end'=>array( 'ShowPageTrace', // 页面Trace显示 ), 'view_template'=>array( 'LocationTemplate', // 自动定位模板文件 ), 'view_parse'=>array( 'ParseTemplate', // 模板解析 支持PHP、内置模板引擎和第三方模板引擎 ), 'view_filter'=>array( 'ContentReplace', // 模板输出替换 'ShowRuntime', // 运行时间显示 ), );
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Lite/tags.php
PHP
art
1,288
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: App.class.php 2702 2012-02-02 12:35:01Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP 应用程序类 精简模式 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id: App.class.php 2702 2012-02-02 12:35:01Z liu21st $ +------------------------------------------------------------------------------ */ class App { /** +---------------------------------------------------------- * 运行应用实例 入口文件使用的快捷方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function run() { // 设置系统时区 date_default_timezone_set(C('DEFAULT_TIMEZONE')); // 加载动态项目公共文件和配置 load_ext_file(); // 项目初始化标签 tag('app_init'); // URL调度 Dispatcher::dispatch(); // 项目开始标签 tag('app_begin'); // Session初始化 支持其他客户端 if(isset($_REQUEST[C("VAR_SESSION_ID")])) session_id($_REQUEST[C("VAR_SESSION_ID")]); if(C('SESSION_AUTO_START')) session_start(); // 记录应用初始化时间 if(C('SHOW_RUN_TIME')) G('initTime'); App::exec(); // 项目结束标签 tag('app_end'); // 保存日志记录 if(C('LOG_RECORD')) Log::save(); return ; } /** +---------------------------------------------------------- * 执行应用程序 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ static public function exec() { // 安全检测 if(!preg_match('/^[A-Za-z_0-9]+$/',MODULE_NAME)){ throw_exception(L('_MODULE_NOT_EXIST_')); } //创建Action控制器实例 $group = defined('GROUP_NAME') ? GROUP_NAME.'/' : ''; $module = A($group.MODULE_NAME); if(!$module) { // 是否定义Empty模块 $module = A("Empty"); if(!$module) // 模块不存在 抛出异常 throw_exception(L('_MODULE_NOT_EXIST_').MODULE_NAME); } //执行当前操作 call_user_func(array(&$module,ACTION_NAME)); return ; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Lite/App.class.php
PHP
art
3,552
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Action.class.php 2504 2011-12-28 07:35:29Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP AMF模式Action控制器基类 +------------------------------------------------------------------------------ */ abstract class Action { /** +---------------------------------------------------------- * 魔术方法 有不存在的操作的时候执行 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名 * @param array $parms 参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$parms) { // 如果定义了_empty操作 则调用 if(method_exists($this,'_empty')) { $this->_empty($method,$parms); } } }//类定义结束 ?>
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Amf/Action.class.php
PHP
art
1,664
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Db.class.php 2779 2012-02-24 02:56:57Z liu21st $ define('CLIENT_MULTI_RESULTS', 131072); /** +------------------------------------------------------------------------------ * ThinkPHP AMF模式数据库中间层实现类 只支持Mysql +------------------------------------------------------------------------------ */ class Db { static private $_instance = null; // 是否自动释放查询结果 protected $autoFree = false; // 是否显示调试信息 如果启用会在日志文件记录sql语句 public $debug = false; // 是否使用永久连接 protected $pconnect = false; // 当前SQL指令 protected $queryStr = ''; // 最后插入ID protected $lastInsID = null; // 返回或者影响记录数 protected $numRows = 0; // 返回字段数 protected $numCols = 0; // 事务指令数 protected $transTimes = 0; // 错误信息 protected $error = ''; // 当前连接ID protected $linkID = null; // 当前查询ID protected $queryID = null; // 是否已经连接数据库 protected $connected = false; // 数据库连接参数配置 protected $config = ''; // 数据库表达式 protected $comparison = array('eq'=>'=','neq'=>'!=','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE'); // 查询表达式 protected $selectSql = 'SELECT%DISTINCT% %FIELDS% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT%'; /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $config 数据库配置数组 +---------------------------------------------------------- */ public function __construct($config=''){ if ( !extension_loaded('mysql') ) { throw_exception(L('_NOT_SUPPERT_').':mysql'); } $this->config = $this->parseConfig($config); } /** +---------------------------------------------------------- * 连接数据库方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function connect() { if(!$this->connected) { $config = $this->config; // 处理不带端口号的socket连接情况 $host = $config['hostname'].($config['hostport']?":{$config['hostport']}":''); if($this->pconnect) { $this->linkID = mysql_pconnect( $host, $config['username'], $config['password'],CLIENT_MULTI_RESULTS); }else{ $this->linkID = mysql_connect( $host, $config['username'], $config['password'],true,CLIENT_MULTI_RESULTS); } if ( !$this->linkID || (!empty($config['database']) && !mysql_select_db($config['database'], $this->linkID)) ) { throw_exception(mysql_error()); } $dbVersion = mysql_get_server_info($this->linkID); if ($dbVersion >= "4.1") { //使用UTF8存取数据库 需要mysql 4.1.0以上支持 mysql_query("SET NAMES '".C('DB_CHARSET')."'", $this->linkID); } //设置 sql_model if($dbVersion >'5.0.1'){ mysql_query("SET sql_mode=''",$this->linkID); } // 标记连接成功 $this->connected = true; // 注销数据库连接配置信息 unset($this->config); } } /** +---------------------------------------------------------- * 释放查询结果 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function free() { mysql_free_result($this->queryID); $this->queryID = 0; } /** +---------------------------------------------------------- * 执行查询 主要针对 SELECT, SHOW 等指令 * 返回数据集 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $str sql指令 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function query($str='') { $this->connect(); if ( !$this->linkID ) return false; if ( $str != '' ) $this->queryStr = $str; //释放前次的查询结果 if ( $this->queryID ) { $this->free(); } N('db_query',1); // 记录开始执行时间 G('queryStartTime'); $this->queryID = mysql_query($this->queryStr, $this->linkID); $this->debug(); if ( !$this->queryID ) { if ( $this->debug ) throw_exception($this->error()); else return false; } else { $this->numRows = mysql_num_rows($this->queryID); return $this->getAll(); } } /** +---------------------------------------------------------- * 执行语句 针对 INSERT, UPDATE 以及DELETE +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $str sql指令 +---------------------------------------------------------- * @return integer +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function execute($str='') { $this->connect(); if ( !$this->linkID ) return false; if ( $str != '' ) $this->queryStr = $str; //释放前次的查询结果 if ( $this->queryID ) { $this->free(); } N('db_write',1); // 记录开始执行时间 G('queryStartTime'); $result = mysql_query($this->queryStr, $this->linkID) ; $this->debug(); if ( false === $result) { if ( $this->debug ) throw_exception($this->error()); else return false; } else { $this->numRows = mysql_affected_rows($this->linkID); $this->lastInsID = mysql_insert_id($this->linkID); return $this->numRows; } } /** +---------------------------------------------------------- * 启动事务 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function startTrans() { $this->connect(true); if ( !$this->linkID ) return false; //数据rollback 支持 if ($this->transTimes == 0) { mysql_query('START TRANSACTION', $this->linkID); } $this->transTimes++; return ; } /** +---------------------------------------------------------- * 用于非自动提交状态下面的查询提交 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function commit() { if ($this->transTimes > 0) { $result = mysql_query('COMMIT', $this->linkID); $this->transTimes = 0; if(!$result){ throw_exception($this->error()); return false; } } return true; } /** +---------------------------------------------------------- * 事务回滚 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function rollback() { if ($this->transTimes > 0) { $result = mysql_query('ROLLBACK', $this->linkID); $this->transTimes = 0; if(!$result){ throw_exception($this->error()); return false; } } return true; } /** +---------------------------------------------------------- * 获得所有的查询数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return array +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function getAll() { if ( !$this->queryID ) { throw_exception($this->error()); return false; } //返回数据集 $result = array(); if($this->numRows >0) { while($row = mysql_fetch_assoc($this->queryID)){ $result[] = $row; } mysql_data_seek($this->queryID,0); } return $result; } /** +---------------------------------------------------------- * 取得数据表的字段信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function getFields($tableName) { $result = $this->query('SHOW COLUMNS FROM '.$tableName); $info = array(); foreach ($result as $key => $val) { $info[$val['Field']] = array( 'name' => $val['Field'], 'type' => $val['Type'], 'notnull' => (bool) ($val['Null'] === ''), // not null is empty, null is yes 'default' => $val['Default'], 'primary' => (strtolower($val['Key']) == 'pri'), 'autoinc' => (strtolower($val['Extra']) == 'auto_increment'), ); } return $info; } /** +---------------------------------------------------------- * 取得数据库的表信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function getTables($dbName='') { if(!empty($dbName)) { $sql = 'SHOW TABLES FROM '.$dbName; }else{ $sql = 'SHOW TABLES '; } $result = $this->query($sql); $info = array(); foreach ($result as $key => $val) { $info[$key] = current($val); } return $info; } /** +---------------------------------------------------------- * 关闭数据库 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function close() { if (!empty($this->queryID)) mysql_free_result($this->queryID); if ($this->linkID && !mysql_close($this->linkID)){ throw_exception($this->error()); } $this->linkID = 0; } /** +---------------------------------------------------------- * 数据库错误信息 * 并显示当前的SQL语句 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function error() { $this->error = mysql_error($this->linkID); if($this->queryStr!=''){ $this->error .= "\n [ SQL语句 ] : ".$this->queryStr; } return $this->error; } /** +---------------------------------------------------------- * SQL指令安全过滤 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $str SQL字符串 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function escape_string($str) { return mysql_escape_string($str); } /** +---------------------------------------------------------- * 析构方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __destruct() { // 关闭连接 $this->close(); } /** +---------------------------------------------------------- * 取得数据库类实例 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @return mixed 返回数据库驱动类 +---------------------------------------------------------- */ public static function getInstance($db_config='') { if ( self::$_instance==null ){ self::$_instance = new Db($db_config); } return self::$_instance; } /** +---------------------------------------------------------- * 分析数据库配置信息,支持数组和DSN +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param mixed $db_config 数据库配置信息 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ private function parseConfig($db_config='') { if ( !empty($db_config) && is_string($db_config)) { // 如果DSN字符串则进行解析 $db_config = $this->parseDSN($db_config); }else if(empty($db_config)){ // 如果配置为空,读取配置文件设置 $db_config = array ( 'dbms' => C('DB_TYPE'), 'username' => C('DB_USER'), 'password' => C('DB_PWD'), 'hostname' => C('DB_HOST'), 'hostport' => C('DB_PORT'), 'database' => C('DB_NAME'), 'dsn' => C('DB_DSN'), 'params' => C('DB_PARAMS'), ); } return $db_config; } /** +---------------------------------------------------------- * DSN解析 * 格式: mysql://username:passwd@localhost:3306/DbName +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param string $dsnStr +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function parseDSN($dsnStr) { if( empty($dsnStr) ){return false;} $info = parse_url($dsnStr); if($info['scheme']){ $dsn = array( 'dbms' => $info['scheme'], 'username' => isset($info['user']) ? $info['user'] : '', 'password' => isset($info['pass']) ? $info['pass'] : '', 'hostname' => isset($info['host']) ? $info['host'] : '', 'hostport' => isset($info['port']) ? $info['port'] : '', 'database' => isset($info['path']) ? substr($info['path'],1) : '' ); }else { preg_match('/^(.*?)\:\/\/(.*?)\:(.*?)\@(.*?)\:([0-9]{1, 6})\/(.*?)$/',trim($dsnStr),$matches); $dsn = array ( 'dbms' => $matches[1], 'username' => $matches[2], 'password' => $matches[3], 'hostname' => $matches[4], 'hostport' => $matches[5], 'database' => $matches[6] ); } return $dsn; } /** +---------------------------------------------------------- * 数据库调试 记录当前SQL +---------------------------------------------------------- * @access protected +---------------------------------------------------------- */ protected function debug() { // 记录操作结束时间 if ( $this->debug ) { G('queryEndTime'); Log::record($this->queryStr." [ RunTime:".G('queryStartTime','queryEndTime',6)."s ]",Log::SQL); } } /** +---------------------------------------------------------- * 设置锁机制 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseLock($lock=false) { if(!$lock) return ''; if('ORACLE' == $this->dbType) { return ' FOR UPDATE NOWAIT '; } return ' FOR UPDATE '; } /** +---------------------------------------------------------- * set分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $data +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseSet($data) { foreach ($data as $key=>$val){ $value = $this->parseValue($val); if(is_scalar($value)) // 过滤非标量数据 $set[] = $this->parseKey($key).'='.$value; } return ' SET '.implode(',',$set); } /** +---------------------------------------------------------- * value分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $value +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseValue($value) { if(is_string($value)) { $value = '\''.$this->escape_string($value).'\''; }elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){ $value = $this->escape_string($value[1]); }elseif(is_null($value)){ $value = 'null'; } return $value; } /** +---------------------------------------------------------- * field分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $fields +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseField($fields) { if(is_array($fields)) { // 完善数组方式传字段名的支持 // 支持 'field1'=>'field2' 这样的字段别名定义 $array = array(); foreach ($fields as $key=>$field){ if(!is_numeric($key)) $array[] = $this->parseKey($key).' AS '.$this->parseKey($field); else $array[] = $this->parseKey($field); } $fieldsStr = implode(',', $array); }elseif(is_string($fields) && !empty($fields)) { $fieldsStr = $this->parseKey($fields); }else{ $fieldsStr = '*'; } return $fieldsStr; } /** +---------------------------------------------------------- * table分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $table +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseTable($tables) { if(is_string($tables)) $tables = explode(',',$tables); array_walk($tables, array(&$this, 'parseKey')); return implode(',',$tables); } /** +---------------------------------------------------------- * where分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $where +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseWhere($where) { $whereStr = ''; if(is_string($where)) { // 直接使用字符串条件 $whereStr = $where; }else{ // 使用数组条件表达式 if(isset($where['_logic'])) { // 定义逻辑运算规则 例如 OR XOR AND NOT $operate = ' '.strtoupper($where['_logic']).' '; unset($where['_logic']); }else{ // 默认进行 AND 运算 $operate = ' AND '; } foreach ($where as $key=>$val){ $whereStr .= "( "; if(0===strpos($key,'_')) { // 解析特殊条件表达式 $whereStr .= $this->parseThinkWhere($key,$val); }else{ $key = $this->parseKey($key); if(is_array($val)) { if(is_string($val[0])) { if(preg_match('/^(EQ|NEQ|GT|EGT|LT|ELT|NOTLIKE|LIKE)$/i',$val[0])) { // 比较运算 $whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' '.$this->parseValue($val[1]); }elseif('exp'==strtolower($val[0])){ // 使用表达式 $whereStr .= ' ('.$key.' '.$val[1].') '; }elseif(preg_match('/IN/i',$val[0])){ // IN 运算 $zone = is_array($val[1])? implode(',',$this->parseValue($val[1])):$val[1]; $whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')'; }elseif(preg_match('/BETWEEN/i',$val[0])){ // BETWEEN运算 $data = is_string($val[1])? explode(',',$val[1]):$val[1]; $whereStr .= ' ('.$key.' BETWEEN '.$data[0].' AND '.$data[1].' )'; }else{ throw_exception(L('_EXPRESS_ERROR_').':'.$val[0]); } }else { $count = count($val); if(in_array(strtoupper(trim($val[$count-1])),array('AND','OR','XOR'))) { $rule = strtoupper(trim($val[$count-1])); $count = $count -1; }else{ $rule = 'AND'; } for($i=0;$i<$count;$i++) { $data = is_array($val[$i])?$val[$i][1]:$val[$i]; if('exp'==strtolower($val[$i][0])) { $whereStr .= '('.$key.' '.$data.') '.$rule.' '; }else{ $op = is_array($val[$i])?$this->comparison[strtolower($val[$i][0])]:'='; $whereStr .= '('.$key.' '.$op.' '.$this->parseValue($data).') '.$rule.' '; } } $whereStr = substr($whereStr,0,-4); } }else { //对字符串类型字段采用模糊匹配 if(C('LIKE_MATCH_FIELDS') && preg_match('/('.C('LIKE_MATCH_FIELDS').')/i',$key)) { $val = '%'.$val.'%'; $whereStr .= $key." LIKE ".$this->parseValue($val); }else { $whereStr .= $key." = ".$this->parseValue($val); } } } $whereStr .= ' )'.$operate; } $whereStr = substr($whereStr,0,-strlen($operate)); } return empty($whereStr)?'':' WHERE '.$whereStr; } /** +---------------------------------------------------------- * 特殊条件分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $key * @param mixed $val +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseThinkWhere($key,$val) { $whereStr = ''; switch($key) { case '_string': // 字符串模式查询条件 $whereStr = $val; break; case '_complex': // 复合查询条件 $whereStr = substr($this->parseWhere($val),6); break; case '_query': // 字符串模式查询条件 parse_str($val,$where); if(isset($where['_logic'])) { $op = ' '.strtoupper($where['_logic']).' '; unset($where['_logic']); }else{ $op = ' AND '; } $array = array(); foreach ($where as $field=>$data) $array[] = $this->parseKey($field).' = '.$this->parseValue($data); $whereStr = implode($op,$array); break; } return $whereStr; } /** +---------------------------------------------------------- * limit分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $lmit +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseLimit($limit) { return !empty($limit)? ' LIMIT '.$limit.' ':''; } /** +---------------------------------------------------------- * join分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $join +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseJoin($join) { $joinStr = ''; if(!empty($join)) { if(is_array($join)) { foreach ($join as $key=>$_join){ if(false !== stripos($_join,'JOIN')) $joinStr .= ' '.$_join; else $joinStr .= ' LEFT JOIN ' .$_join; } }else{ $joinStr .= ' LEFT JOIN ' .$join; } } return $joinStr; } /** +---------------------------------------------------------- * order分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $order +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseOrder($order) { return !empty($order)? ' ORDER BY '.$order:''; } /** +---------------------------------------------------------- * group分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $group +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseGroup($group) { return !empty($group)? ' GROUP BY '.$group:''; } /** +---------------------------------------------------------- * having分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $having +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseHaving($having) { return !empty($having)? ' HAVING '.$having:''; } /** +---------------------------------------------------------- * distinct分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $distinct +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseDistinct($distinct) { return !empty($distinct)? ' DISTINCT ' :''; } /** +---------------------------------------------------------- * 插入记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 数据 * @param array $options 参数表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function insert($data,$options=array()) { foreach ($data as $key=>$val){ $value = $this->parseValue($val); if(is_scalar($value)) { // 过滤非标量数据 $values[] = $value; $fields[] = $this->parseKey($key); } } $sql = 'INSERT INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')'; $sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->execute($sql); } /** +---------------------------------------------------------- * 更新记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 数据 * @param array $options 表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function update($data,$options) { $sql = 'UPDATE ' .$this->parseTable($options['table']) .$this->parseSet($data) .$this->parseWhere(isset($options['where'])?$options['where']:'') .$this->parseOrder(isset($options['order'])?$options['order']:'') .$this->parseLimit(isset($options['limit'])?$options['limit']:'') .$this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->execute($sql); } /** +---------------------------------------------------------- * 删除记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $options 表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function delete($options=array()) { $sql = 'DELETE FROM ' .$this->parseTable($options['table']) .$this->parseWhere(isset($options['where'])?$options['where']:'') .$this->parseOrder(isset($options['order'])?$options['order']:'') .$this->parseLimit(isset($options['limit'])?$options['limit']:'') .$this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->execute($sql); } /** +---------------------------------------------------------- * 查找记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $options 表达式 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function select($options=array()) { if(isset($options['page'])) { // 根据页数计算limit list($page,$listRows) = explode(',',$options['page']); $listRows = $listRows?$listRows:($options['limit']?$options['limit']:20); $offset = $listRows*((int)$page-1); $options['limit'] = $offset.','.$listRows; } $sql = str_replace( array('%TABLE%','%DISTINCT%','%FIELDS%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%'), array( $this->parseTable($options['table']), $this->parseDistinct(isset($options['distinct'])?$options['distinct']:false), $this->parseField(isset($options['field'])?$options['field']:'*'), $this->parseJoin(isset($options['join'])?$options['join']:''), $this->parseWhere(isset($options['where'])?$options['where']:''), $this->parseGroup(isset($options['group'])?$options['group']:''), $this->parseHaving(isset($options['having'])?$options['having']:''), $this->parseOrder(isset($options['order'])?$options['order']:''), $this->parseLimit(isset($options['limit'])?$options['limit']:'') ),$this->selectSql); $sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->query($sql); } /** +---------------------------------------------------------- * 字段和表名添加` * 保证指令中使用关键字不出错 针对mysql +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $value +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ protected function parseKey(&$value) { $value = trim($value); if( false !== strpos($value,' ') || false !== strpos($value,',') || false !== strpos($value,'*') || false !== strpos($value,'(') || false !== strpos($value,'.') || false !== strpos($value,'`')) { //如果包含* 或者 使用了sql方法 则不作处理 }else{ $value = '`'.$value.'`'; } return $value; } /** +---------------------------------------------------------- * 获取最近一次查询的sql语句 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastSql() { return $this->queryStr; } /** +---------------------------------------------------------- * 获取最近插入的ID +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastInsID(){ return $this->lastInsID; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Amf/Db.class.php
PHP
art
39,473
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Model.class.php 2779 2012-02-24 02:56:57Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP AMF模式Model模型类 * 只支持CURD和连贯操作 以及常用查询 去掉回调接口 +------------------------------------------------------------------------------ */ class Model { // 当前数据库操作对象 protected $db = null; // 主键名称 protected $pk = 'id'; // 数据表前缀 protected $tablePrefix = ''; // 模型名称 protected $name = ''; // 数据库名称 protected $dbName = ''; // 数据表名(不包含表前缀) protected $tableName = ''; // 实际数据表名(包含表前缀) protected $trueTableName =''; // 数据信息 protected $data = array(); // 查询表达式参数 protected $options = array(); // 最近错误信息 protected $error = ''; /** +---------------------------------------------------------- * 架构函数 * 取得DB类的实例对象 +---------------------------------------------------------- * @param string $name 模型名称 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($name='') { // 模型初始化 $this->_initialize(); // 获取模型名称 if(!empty($name)) { $this->name = $name; }elseif(empty($this->name)){ $this->name = $this->getModelName(); } // 数据库初始化操作 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['where'])) { // 如果删除条件为空 则删除当前数据对象所对应的记录 if(!empty($this->data) && isset($this->data[$this->getPk()])) return $this->delete($this->data[$this->getPk()]); else return false; } if(is_numeric($options) || is_string($options)) { // 根据主键删除记录 $pk = $this->getPk(); $where = $pk.'=\''.$options.'\''; $pkValue = $options; $options = array(); $options['where'] = $where; } // 分析表达式 $options = $this->_parseOptions($options); return $this->db->delete($options); } /** +---------------------------------------------------------- * 查询数据集 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $options 表达式参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function select($options=array()) { // 分析表达式 $options = $this->_parseOptions($options); $resultSet = $this->db->select($options); if(empty($resultSet)) { // 查询结果为空 return false; } return $resultSet; } /** +---------------------------------------------------------- * 查询数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $options 表达式参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function find($options=array()) { if(is_numeric($options) || is_string($options)) { $where = $this->getPk().'=\''.$options.'\''; $options = array(); $options['where'] = $where; } // 总是查找一条记录 $options['limit'] = 1; // 分析表达式 $options = $this->_parseOptions($options); $resultSet = $this->db->select($options); if(empty($resultSet)) {// 查询结果为空 return false; } $this->data = $resultSet[0]; return $this->data; } /** +---------------------------------------------------------- * 分析表达式 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param array $options 表达式参数 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ private function _parseOptions($options) { if(is_array($options)) $options = array_merge($this->options,$options); // 查询过后清空sql表达式组装 避免影响下次查询 $this->options = array(); if(!isset($options['table'])) // 自动获取表名 $options['table'] =$this->getTableName(); return $options; } /** +---------------------------------------------------------- * 创建数据对象 但不保存到数据库 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 创建数据 * @param string $type 状态 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function create($data='',$type='') { // 如果没有传值默认取POST数据 if(empty($data)) { $data = $_POST; }elseif(is_object($data)){ $data = get_object_vars($data); }elseif(!is_array($data)){ $this->error = L('_DATA_TYPE_INVALID_'); return false; } // 生成数据对象 $vo = array(); foreach ($this->fields as $key=>$name){ if(substr($key,0,1)=='_') continue; $val = isset($data[$name])?$data[$name]:null; //保证赋值有效 if(!is_null($val)){ $vo[$name] = (MAGIC_QUOTES_GPC && is_string($val))? stripslashes($val) : $val; if(C('DB_FIELDTYPE_CHECK')) { // 字段类型检查 $fieldType = strtolower($this->fields['_type'][$name]); if(false !== strpos($fieldType,'int')) { $vo[$name] = intval($vo[$name]); }elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){ $vo[$name] = floatval($vo[$name]); } } } } // 赋值当前数据对象 $this->data = $vo; // 返回创建的数据以供其他调用 return $vo; } /** +---------------------------------------------------------- * SQL查询 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $sql SQL指令 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function query($sql) { if(!empty($sql)) { if(strpos($sql,'__TABLE__')) $sql = str_replace('__TABLE__',$this->getTableName(),$sql); return $this->db->query($sql); }else{ return false; } } /** +---------------------------------------------------------- * 执行SQL语句 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $sql SQL指令 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function execute($sql='') { if(!empty($sql)) { if(strpos($sql,'__TABLE__')) $sql = str_replace('__TABLE__',$this->getTableName(),$sql); return $this->db->execute($sql); }else { return false; } } /** +---------------------------------------------------------- * 得到当前的数据对象名称 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getModelName() { if(empty($this->name)) { $this->name = substr(get_class($this),0,-5); } return $this->name; } /** +---------------------------------------------------------- * 得到完整的数据表名 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getTableName() { if(empty($this->trueTableName)) { $tableName = !empty($this->tablePrefix) ? $this->tablePrefix : ''; if(!empty($this->tableName)) { $tableName .= $this->tableName; }else{ $tableName .= parse_name($this->name); } if(!empty($this->dbName)) { $tableName = $this->dbName.'.'.$tableName; } $this->trueTableName = strtolower($tableName); } return $this->trueTableName; } /** +---------------------------------------------------------- * 启动事务 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function startTrans() { $this->commit(); $this->db->startTrans(); return ; } /** +---------------------------------------------------------- * 提交事务 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function commit() { return $this->db->commit(); } /** +---------------------------------------------------------- * 事务回滚 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function rollback() { return $this->db->rollback(); } /** +---------------------------------------------------------- * 获取主键名称 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getPk() { return isset($this->fields['_pk'])?$this->fields['_pk']:$this->pk; } /** +---------------------------------------------------------- * 返回最后执行的sql语句 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastSql() { return $this->db->getLastSql(); } /** +---------------------------------------------------------- * 返回最后插入的ID +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastInsID() { return $this->db->getLastInsID(); } };
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Amf/Model.class.php
PHP
art
22,108
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2009 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: App.class.php 2504 2011-12-28 07:35:29Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP AMF模式应用程序类 +------------------------------------------------------------------------------ */ class App { /** +---------------------------------------------------------- * 应用程序初始化 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function run() { //导入类库 Vendor('Zend.Amf.Server'); //实例化AMF $server = new Zend_Amf_Server(); $actions = explode(',',C('APP_AMF_ACTIONS')); foreach ($actions as $action) $server -> setClass($action.'Action'); echo $server -> handle(); // 保存日志记录 if(C('LOG_RECORD')) Log::save(); return ; } };
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Amf/App.class.php
PHP
art
1,681
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: rest.php 2702 2012-02-02 12:35:01Z liu21st $ // REST模式定义文件 return array( 'core' => array( THINK_PATH.'Common/functions.php', // 标准模式函数库 CORE_PATH.'Core/Log.class.php', // 日志处理类 CORE_PATH.'Core/Dispatcher.class.php', // URL调度类 CORE_PATH.'Core/App.class.php', // 应用程序类 CORE_PATH.'Core/View.class.php', // 视图类 MODE_PATH.'Rest/Action.class.php',// 控制器类 ), // 系统行为定义文件 [必须 支持数组直接定义或者文件名定义 ] 'extends' => MODE_PATH.'Rest/tags.php', // 模式配置文件 [支持数组直接定义或者文件名定义](如有相同则覆盖项目配置文件中的配置) 'config' => MODE_PATH.'Rest/config.php', );
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/rest.php
PHP
art
1,449
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: lite.php 2702 2012-02-02 12:35:01Z liu21st $ // Lite模式定义文件 return array( 'core' => array( THINK_PATH.'Common/functions.php', // 系统函数库 CORE_PATH.'Core/Log.class.php',// 日志处理 MODE_PATH.'Lite/App.class.php', // 应用程序类 MODE_PATH.'Lite/Action.class.php',// 控制器类 MODE_PATH.'Lite/Dispatcher.class.php', ), // 项目别名定义文件 [支持数组直接定义或者文件名定义] 'alias' => array( 'Model' => MODE_PATH.'Lite/Model.class.php', 'Db' => MODE_PATH.'Lite/Db.class.php', 'ThinkTemplate' => CORE_PATH.'Template/ThinkTemplate.class.php', 'TagLib' => CORE_PATH.'Template/TagLib.class.php', 'Cache' => CORE_PATH.'Core/Cache.class.php', 'Debug' => CORE_PATH.'Util/Debug.class.php', 'Session' => CORE_PATH.'Util/Session.class.php', 'TagLibCx' => CORE_PATH.'Driver/TagLib/TagLibCx.class.php', ), // 系统行为定义文件 [必须 支持数组直接定义或者文件名定义 ] 'extends' => MODE_PATH.'Lite/tags.php', );
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/lite.php
PHP
art
1,840
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Action.class.php 2702 2012-02-02 12:35:01Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP 命令模式Action控制器基类 +------------------------------------------------------------------------------ */ abstract class Action { /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @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 { // 抛出异常 exit(L('_ERROR_ACTION_').ACTION_NAME); } }else{ exit(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); } } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Cli/Action.class.php
PHP
art
2,363
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Db.class.php 2702 2012-02-02 12:35:01Z liu21st $ define('CLIENT_MULTI_RESULTS', 131072); /** +------------------------------------------------------------------------------ * ThinkPHP 精简模式数据库中间层实现类 只支持Mysql +------------------------------------------------------------------------------ */ class Db { static private $_instance = null; // 是否自动释放查询结果 protected $autoFree = false; // 是否显示调试信息 如果启用会在日志文件记录sql语句 public $debug = false; // 是否使用永久连接 protected $pconnect = false; // 当前SQL指令 protected $queryStr = ''; // 最后插入ID protected $lastInsID = null; // 返回或者影响记录数 protected $numRows = 0; // 返回字段数 protected $numCols = 0; // 事务指令数 protected $transTimes = 0; // 错误信息 protected $error = ''; // 当前连接ID protected $linkID = null; // 当前查询ID protected $queryID = null; // 是否已经连接数据库 protected $connected = false; // 数据库连接参数配置 protected $config = ''; // 数据库表达式 protected $comparison = array('eq'=>'=','neq'=>'!=','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE'); // 查询表达式 protected $selectSql = 'SELECT%DISTINCT% %FIELDS% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT%'; /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $config 数据库配置数组 +---------------------------------------------------------- */ public function __construct($config=''){ if ( !extension_loaded('mysql') ) { throw_exception(L('_NOT_SUPPERT_').':mysql'); } $this->config = $this->parseConfig($config); if(APP_DEBUG) { $this->debug = true; } } /** +---------------------------------------------------------- * 连接数据库方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @throws ThinkExecption +---------------------------------------------------------- */ public function connect() { if(!$this->connected) { $config = $this->config; // 处理不带端口号的socket连接情况 $host = $config['hostname'].($config['hostport']?":{$config['hostport']}":''); $pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect; if($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); $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 escapeString($str) { return mysql_escape_string($str); } /** +---------------------------------------------------------- * 析构方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __destruct() { // 关闭连接 $this->close(); } /** +---------------------------------------------------------- * 取得数据库类实例 +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @return mixed 返回数据库驱动类 +---------------------------------------------------------- */ public static function getInstance($db_config='') { if ( self::$_instance==null ){ self::$_instance = new Db($db_config); } return self::$_instance; } /** +---------------------------------------------------------- * 分析数据库配置信息,支持数组和DSN +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param mixed $db_config 数据库配置信息 +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ private function parseConfig($db_config='') { if ( !empty($db_config) && is_string($db_config)) { // 如果DSN字符串则进行解析 $db_config = $this->parseDSN($db_config); }else if(empty($db_config)){ // 如果配置为空,读取配置文件设置 $db_config = array ( 'dbms' => C('DB_TYPE'), 'username' => C('DB_USER'), 'password' => C('DB_PWD'), 'hostname' => C('DB_HOST'), 'hostport' => C('DB_PORT'), 'database' => C('DB_NAME'), 'dsn' => C('DB_DSN'), 'params' => C('DB_PARAMS'), ); } return $db_config; } /** +---------------------------------------------------------- * DSN解析 * 格式: mysql://username:passwd@localhost:3306/DbName +---------------------------------------------------------- * @static * @access public +---------------------------------------------------------- * @param string $dsnStr +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function parseDSN($dsnStr) { if( empty($dsnStr) ){return false;} $info = parse_url($dsnStr); if($info['scheme']){ $dsn = array( 'dbms' => $info['scheme'], 'username' => isset($info['user']) ? $info['user'] : '', 'password' => isset($info['pass']) ? $info['pass'] : '', 'hostname' => isset($info['host']) ? $info['host'] : '', 'hostport' => isset($info['port']) ? $info['port'] : '', 'database' => isset($info['path']) ? substr($info['path'],1) : '' ); }else { preg_match('/^(.*?)\:\/\/(.*?)\:(.*?)\@(.*?)\:([0-9]{1, 6})\/(.*?)$/',trim($dsnStr),$matches); $dsn = array ( 'dbms' => $matches[1], 'username' => $matches[2], 'password' => $matches[3], 'hostname' => $matches[4], 'hostport' => $matches[5], 'database' => $matches[6] ); } return $dsn; } /** +---------------------------------------------------------- * 数据库调试 记录当前SQL +---------------------------------------------------------- * @access protected +---------------------------------------------------------- */ protected function debug() { // 记录操作结束时间 if ( $this->debug ) { G('queryEndTime'); Log::record($this->queryStr." [ RunTime:".G('queryStartTime','queryEndTime',6)."s ]",Log::SQL); } } /** +---------------------------------------------------------- * 设置锁机制 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseLock($lock=false) { if(!$lock) return ''; if('ORACLE' == $this->dbType) { return ' FOR UPDATE NOWAIT '; } return ' FOR UPDATE '; } /** +---------------------------------------------------------- * set分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param array $data +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseSet($data) { foreach ($data as $key=>$val){ $value = $this->parseValue($val); if(is_scalar($value)) // 过滤非标量数据 $set[] = $this->parseKey($key).'='.$value; } return ' SET '.implode(',',$set); } /** +---------------------------------------------------------- * value分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $value +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseValue($value) { if(is_string($value)) { $value = '\''.$this->escapeString($value).'\''; }elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){ $value = $this->escapeString($value[1]); }elseif(is_null($value)){ $value = 'null'; } return $value; } /** +---------------------------------------------------------- * field分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $fields +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseField($fields) { if(is_array($fields)) { // 完善数组方式传字段名的支持 // 支持 'field1'=>'field2' 这样的字段别名定义 $array = array(); foreach ($fields as $key=>$field){ if(!is_numeric($key)) $array[] = $this->parseKey($key).' AS '.$this->parseKey($field); else $array[] = $this->parseKey($field); } $fieldsStr = implode(',', $array); }elseif(is_string($fields) && !empty($fields)) { $fieldsStr = $this->parseKey($fields); }else{ $fieldsStr = '*'; } return $fieldsStr; } /** +---------------------------------------------------------- * table分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $table +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseTable($tables) { if(is_string($tables)) $tables = explode(',',$tables); array_walk($tables, array(&$this, 'parseKey')); return implode(',',$tables); } /** +---------------------------------------------------------- * where分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $where +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseWhere($where) { $whereStr = ''; if(is_string($where)) { // 直接使用字符串条件 $whereStr = $where; }else{ // 使用数组条件表达式 if(isset($where['_logic'])) { // 定义逻辑运算规则 例如 OR XOR AND NOT $operate = ' '.strtoupper($where['_logic']).' '; unset($where['_logic']); }else{ // 默认进行 AND 运算 $operate = ' AND '; } foreach ($where as $key=>$val){ $whereStr .= "( "; if(0===strpos($key,'_')) { // 解析特殊条件表达式 $whereStr .= $this->parseThinkWhere($key,$val); }else{ $key = $this->parseKey($key); if(is_array($val)) { if(is_string($val[0])) { if(preg_match('/^(EQ|NEQ|GT|EGT|LT|ELT|NOTLIKE|LIKE)$/i',$val[0])) { // 比较运算 $whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' '.$this->parseValue($val[1]); }elseif('exp'==strtolower($val[0])){ // 使用表达式 $whereStr .= ' ('.$key.' '.$val[1].') '; }elseif(preg_match('/IN/i',$val[0])){ // IN 运算 $zone = is_array($val[1])? implode(',',$this->parseValue($val[1])):$val[1]; $whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')'; }elseif(preg_match('/BETWEEN/i',$val[0])){ // BETWEEN运算 $data = is_string($val[1])? explode(',',$val[1]):$val[1]; $whereStr .= ' ('.$key.' BETWEEN '.$data[0].' AND '.$data[1].' )'; }else{ throw_exception(L('_EXPRESS_ERROR_').':'.$val[0]); } }else { $count = count($val); if(in_array(strtoupper(trim($val[$count-1])),array('AND','OR','XOR'))) { $rule = strtoupper(trim($val[$count-1])); $count = $count -1; }else{ $rule = 'AND'; } for($i=0;$i<$count;$i++) { $data = is_array($val[$i])?$val[$i][1]:$val[$i]; if('exp'==strtolower($val[$i][0])) { $whereStr .= '('.$key.' '.$data.') '.$rule.' '; }else{ $op = is_array($val[$i])?$this->comparison[strtolower($val[$i][0])]:'='; $whereStr .= '('.$key.' '.$op.' '.$this->parseValue($data).') '.$rule.' '; } } $whereStr = substr($whereStr,0,-4); } }else { //对字符串类型字段采用模糊匹配 if(C('LIKE_MATCH_FIELDS') && preg_match('/('.C('LIKE_MATCH_FIELDS').')/i',$key)) { $val = '%'.$val.'%'; $whereStr .= $key." LIKE ".$this->parseValue($val); }else { $whereStr .= $key." = ".$this->parseValue($val); } } } $whereStr .= ' )'.$operate; } $whereStr = substr($whereStr,0,-strlen($operate)); } return empty($whereStr)?'':' WHERE '.$whereStr; } /** +---------------------------------------------------------- * 特殊条件分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $key * @param mixed $val +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseThinkWhere($key,$val) { $whereStr = ''; switch($key) { case '_string': // 字符串模式查询条件 $whereStr = $val; break; case '_complex': // 复合查询条件 $whereStr = substr($this->parseWhere($val),6); break; case '_query': // 字符串模式查询条件 parse_str($val,$where); if(isset($where['_logic'])) { $op = ' '.strtoupper($where['_logic']).' '; unset($where['_logic']); }else{ $op = ' AND '; } $array = array(); foreach ($where as $field=>$data) $array[] = $this->parseKey($field).' = '.$this->parseValue($data); $whereStr = implode($op,$array); break; } return $whereStr; } /** +---------------------------------------------------------- * limit分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $lmit +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseLimit($limit) { return !empty($limit)? ' LIMIT '.$limit.' ':''; } /** +---------------------------------------------------------- * join分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $join +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseJoin($join) { $joinStr = ''; if(!empty($join)) { if(is_array($join)) { foreach ($join as $key=>$_join){ if(false !== stripos($_join,'JOIN')) $joinStr .= ' '.$_join; else $joinStr .= ' LEFT JOIN ' .$_join; } }else{ $joinStr .= ' LEFT JOIN ' .$join; } } return $joinStr; } /** +---------------------------------------------------------- * order分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $order +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseOrder($order) { return !empty($order)? ' ORDER BY '.$order:''; } /** +---------------------------------------------------------- * group分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $group +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseGroup($group) { return !empty($group)? ' GROUP BY '.$group:''; } /** +---------------------------------------------------------- * having分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param string $having +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseHaving($having) { return !empty($having)? ' HAVING '.$having:''; } /** +---------------------------------------------------------- * distinct分析 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $distinct +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ protected function parseDistinct($distinct) { return !empty($distinct)? ' DISTINCT ' :''; } /** +---------------------------------------------------------- * 插入记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 数据 * @param array $options 参数表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function insert($data,$options=array()) { foreach ($data as $key=>$val){ $value = $this->parseValue($val); if(is_scalar($value)) { // 过滤非标量数据 $values[] = $value; $fields[] = $this->parseKey($key); } } $sql = 'INSERT INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')'; $sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->execute($sql); } /** +---------------------------------------------------------- * 更新记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 数据 * @param array $options 表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function update($data,$options) { $sql = 'UPDATE ' .$this->parseTable($options['table']) .$this->parseSet($data) .$this->parseWhere(isset($options['where'])?$options['where']:'') .$this->parseOrder(isset($options['order'])?$options['order']:'') .$this->parseLimit(isset($options['limit'])?$options['limit']:'') .$this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->execute($sql); } /** +---------------------------------------------------------- * 删除记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $options 表达式 +---------------------------------------------------------- * @return false | integer +---------------------------------------------------------- */ public function delete($options=array()) { $sql = 'DELETE FROM ' .$this->parseTable($options['table']) .$this->parseWhere(isset($options['where'])?$options['where']:'') .$this->parseOrder(isset($options['order'])?$options['order']:'') .$this->parseLimit(isset($options['limit'])?$options['limit']:'') .$this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->execute($sql); } /** +---------------------------------------------------------- * 查找记录 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $options 表达式 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function select($options=array()) { if(isset($options['page'])) { // 根据页数计算limit list($page,$listRows) = explode(',',$options['page']); $listRows = $listRows?$listRows:($options['limit']?$options['limit']:20); $offset = $listRows*((int)$page-1); $options['limit'] = $offset.','.$listRows; } $sql = str_replace( array('%TABLE%','%DISTINCT%','%FIELDS%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%'), array( $this->parseTable($options['table']), $this->parseDistinct(isset($options['distinct'])?$options['distinct']:false), $this->parseField(isset($options['field'])?$options['field']:'*'), $this->parseJoin(isset($options['join'])?$options['join']:''), $this->parseWhere(isset($options['where'])?$options['where']:''), $this->parseGroup(isset($options['group'])?$options['group']:''), $this->parseHaving(isset($options['having'])?$options['having']:''), $this->parseOrder(isset($options['order'])?$options['order']:''), $this->parseLimit(isset($options['limit'])?$options['limit']:'') ),$this->selectSql); $sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false); return $this->query($sql); } /** +---------------------------------------------------------- * 字段和表名添加` * 保证指令中使用关键字不出错 针对mysql +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $value +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ protected function parseKey(&$value) { $value = trim($value); if( false !== strpos($value,' ') || false !== strpos($value,',') || false !== strpos($value,'*') || false !== strpos($value,'(') || false !== strpos($value,'.') || false !== strpos($value,'`')) { //如果包含* 或者 使用了sql方法 则不作处理 }else{ $value = '`'.$value.'`'; } return $value; } /** +---------------------------------------------------------- * 获取最近一次查询的sql语句 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastSql() { return $this->queryStr; } /** +---------------------------------------------------------- * 获取最近插入的ID +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastInsID(){ return $this->lastInsID; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Cli/Db.class.php
PHP
art
39,553
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Model.class.php 2779 2012-02-24 02:56:57Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP CLI模式Model模型类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id: Model.class.php 2779 2012-02-24 02:56:57Z liu21st $ +------------------------------------------------------------------------------ */ class Model { // 当前数据库操作对象 protected $db = null; // 主键名称 protected $pk = 'id'; // 数据表前缀 protected $tablePrefix = ''; // 模型名称 protected $name = ''; // 数据库名称 protected $dbName = ''; // 数据表名(不包含表前缀) protected $tableName = ''; // 实际数据表名(包含表前缀) protected $trueTableName =''; // 最近错误信息 protected $error = ''; // 字段信息 protected $fields = array(); // 数据信息 protected $data = array(); // 查询表达式参数 protected $options = array(); protected $_validate = array(); // 自动验证定义 protected $_auto = array(); // 自动完成定义 // 是否自动检测数据表字段信息 protected $autoCheckFields = true; // 是否批处理验证 protected $patchValidate = false; /** +---------------------------------------------------------- * 架构函数 * 取得DB类的实例对象 字段检查 +---------------------------------------------------------- * @param string $name 模型名称 * @param string $tablePrefix 表前缀 * @param mixed $connection 数据库连接信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($name='',$tablePrefix='',$connection='') { // 模型初始化 $this->_initialize(); // 获取模型名称 if(!empty($name)) { if(strpos($name,'.')) { // 支持 数据库名.模型名的 定义 list($this->dbName,$this->name) = explode('.',$name); }else{ $this->name = $name; } }elseif(empty($this->name)){ $this->name = $this->getModelName(); } if(!empty($tablePrefix)) { $this->tablePrefix = $tablePrefix; } // 设置表前缀 $this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX'); // 数据库初始化操作 // 获取数据库操作对象 // 当前模型有独立的数据库连接信息 $this->db(0,empty($this->connection)?$connection:$this->connection); // 字段检测 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')) { $db = $this->dbName?$this->dbName:C('DB_NAME'); $this->fields = F('_fields/'.$db.'.'.$this->name); if(!$this->fields) $this->flush(); }else{ // 每次都会读取数据表信息 $this->flush(); } } } /** +---------------------------------------------------------- * 获取字段信息并缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function flush() { // 缓存不存在则查询数据表信息 $fields = $this->db->getFields($this->getTableName()); if(!$fields) { // 无法获取字段信息 return false; } $this->fields = array_keys($fields); $this->fields['_autoinc'] = false; foreach ($fields as $key=>$val){ // 记录字段类型 $type[$key] = $val['type']; if($val['primary']) { $this->fields['_pk'] = $key; if($val['autoinc']) $this->fields['_autoinc'] = true; } } // 记录字段类型信息 if(C('DB_FIELDTYPE_CHECK')) $this->fields['_type'] = $type; // 2008-3-7 增加缓存开关控制 if(C('DB_FIELDS_CACHE')){ // 永久缓存数据表信息 $db = $this->dbName?$this->dbName:C('DB_NAME'); F('_fields/'.$db.'.'.$this->name,$this->fields); } } /** +---------------------------------------------------------- * 设置数据对象的值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 名称 * @param mixed $value 值 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function __set($name,$value) { // 设置数据对象属性 $this->data[$name] = $value; } /** +---------------------------------------------------------- * 获取数据对象的值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 名称 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __get($name) { return isset($this->data[$name])?$this->data[$name]:null; } /** +---------------------------------------------------------- * 检测数据对象的值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 名称 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function __isset($name) { return isset($this->data[$name]); } /** +---------------------------------------------------------- * 销毁数据对象的值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 名称 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function __unset($name) { unset($this->data[$name]); } /** +---------------------------------------------------------- * 利用__call方法实现一些特殊的Model方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $method 方法名称 * @param array $args 调用参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function __call($method,$args) { if(in_array(strtolower($method),array('table','where','order','limit','page','alias','having','group','lock','distinct'),true)) { // 连贯操作的实现 $this->options[strtolower($method)] = $args[0]; return $this; }elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){ // 统计查询的实现 $field = isset($args[0])?$args[0]:'*'; return $this->getField(strtoupper($method).'('.$field.') AS tp_'.$method); }elseif(strtolower(substr($method,0,5))=='getby') { // 根据某个字段获取记录 $field = parse_name(substr($method,5)); $where[$field] = $args[0]; return $this->where($where)->find(); }else{ throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); return; } } // 回调方法 初始化模型 protected function _initialize() {} /** +---------------------------------------------------------- * 对保存到数据库的数据进行处理 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $data 要操作的数据 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ protected function _facade($data) { // 检查非数据字段 if(!empty($this->fields)) { foreach ($data as $key=>$val){ if(!in_array($key,$this->fields,true)){ unset($data[$key]); }elseif(C('DB_FIELDTYPE_CHECK') && is_scalar($val)) { // 字段类型检查 $this->_parseType($data,$key); } } } return $data; } /** +---------------------------------------------------------- * 新增数据 +---------------------------------------------------------- * @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); // 数据处理 $data = $this->_facade($data); // 写入数据到数据库 $result = $this->db->insert($data,$options); if(false !== $result ) { $insertId = $this->getLastInsID(); if($insertId) { // 自增主键返回插入ID return $insertId; } } 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(!isset($options['where']) ) { // 如果存在主键数据 则自动作为更新条件 if(isset($data[$this->getPk()])) { $pk = $this->getPk(); $where[$pk] = $data[$pk]; $options['where'] = $where; unset($data[$pk]); }else{ // 如果没有任何更新条件则不执行 $this->error = L('_OPERATION_WRONG_'); return false; } } $result = $this->db->update($data,$options); return $result; } /** +---------------------------------------------------------- * 删除数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $options 表达式 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function delete($options=array()) { if(empty($options) && empty($this->options['where'])) { // 如果删除条件为空 则删除当前数据对象所对应的记录 if(!empty($this->data) && isset($this->data[$this->getPk()])) return $this->delete($this->data[$this->getPk()]); else return false; } if(is_numeric($options) || is_string($options)) { // 根据主键删除记录 $pk = $this->getPk(); if(strpos($options,',')) { $where[$pk] = array('IN', $options); }else{ $where[$pk] = $options; $pkValue = $options; } $options = array(); $options['where'] = $where; } // 分析表达式 $options = $this->_parseOptions($options); $result= $this->db->delete($options); // 返回删除记录个数 return $result; } /** +---------------------------------------------------------- * 查询数据集 +---------------------------------------------------------- * @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; } return $resultSet; } /** +---------------------------------------------------------- * 分析表达式 +---------------------------------------------------------- * @access proteced +---------------------------------------------------------- * @param array $options 表达式参数 +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ protected function _parseOptions($options=array()) { if(is_array($options)) $options = array_merge($this->options,$options); // 查询过后清空sql表达式组装 避免影响下次查询 $this->options = array(); if(!isset($options['table'])) // 自动获取表名 $options['table'] =$this->getTableName(); if(!empty($options['alias'])) { $options['table'] .= ' '.$options['alias']; } // 字段类型验证 if(C('DB_FIELDTYPE_CHECK')) { if(isset($options['where']) && is_array($options['where'])) { // 对数组查询条件进行字段类型检查 foreach ($options['where'] as $key=>$val){ if(in_array($key,$this->fields,true) && is_scalar($val)){ $this->_parseType($options['where'],$key); } } } } return $options; } /** +---------------------------------------------------------- * 数据类型检测 +---------------------------------------------------------- * @access protected +---------------------------------------------------------- * @param mixed $data 数据 * @param string $key 字段名 +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ protected function _parseType(&$data,$key) { $fieldType = strtolower($this->fields['_type'][$key]); if(false !== strpos($fieldType,'int')) { $data[$key] = intval($data[$key]); }elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){ $data[$key] = floatval($data[$key]); }elseif(false !== strpos($fieldType,'bool')){ $data[$key] = (bool)$data[$key]; } } /** +---------------------------------------------------------- * 查询数据 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $options 表达式参数 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function find($options=array()) { if(is_numeric($options) || is_string($options)) { $where[$this->getPk()] =$options; $options = array(); $options['where'] = $where; } // 总是查找一条记录 $options['limit'] = 1; // 分析表达式 $options = $this->_parseOptions($options); $resultSet = $this->db->select($options); if(false === $resultSet) { return false; } if(empty($resultSet)) {// 查询结果为空 return null; } $this->data = $resultSet[0]; return $this->data; } /** +---------------------------------------------------------- * 设置记录的某个字段值 * 支持使用数据库字段和方法 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string|array $field 字段名 * @param string|array $value 字段值 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setField($field,$value) { if(is_array($field)) { $data = $field; }else{ $data[$field] = $value; } return $this->save($data); } /** +---------------------------------------------------------- * 字段值增长 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param integer $step 增长值 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setInc($field,$step=1) { return $this->setField($field,array('exp',$field.'+'.$step)); } /** +---------------------------------------------------------- * 字段值减少 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param integer $step 减少值 +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function setDec($field,$step=1) { return $this->setField($field,array('exp',$field.'-'.$step)); } /** +---------------------------------------------------------- * 获取一条记录的某个字段值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $field 字段名 * @param string $spea 字段数据间隔符号 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function getField($field,$sepa=null) { $options['field'] = $field; $options = $this->_parseOptions($options); if(strpos($field,',')) { // 多字段 $resultSet = $this->db->select($options); if(!empty($resultSet)) { $_field = explode(',', $field); $field = array_keys($resultSet[0]); $move = $_field[0]==$_field[1]?false:true; $key = array_shift($field); $key2 = array_shift($field); $cols = array(); $count = count($_field); foreach ($resultSet as $result){ $name = $result[$key]; if($move) { // 删除键值记录 unset($result[$key]); } if(2==$count) { $cols[$name] = $result[$key2]; }else{ $cols[$name] = is_null($sepa)?$result:implode($sepa,$result); } } return $cols; } }else{ // 查找一条记录 $options['limit'] = 1; $result = $this->db->select($options); if(!empty($result)) { return reset($result[0]); } } return null; } /** +---------------------------------------------------------- * 创建数据对象 但不保存到数据库 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $data 创建数据 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function create($data='') { // 如果没有传值默认取POST数据 if(empty($data)) { $data = $_POST; }elseif(is_object($data)){ $data = get_object_vars($data); } // 验证数据 if(empty($data) || !is_array($data)) { $this->error = L('_DATA_TYPE_INVALID_'); return false; } // 验证完成生成数据对象 if($this->autoCheckFields) { // 开启字段检测 则过滤非法字段数据 $vo = array(); foreach ($this->fields as $key=>$name){ if(substr($key,0,1)=='_') continue; $val = isset($data[$name])?$data[$name]:null; //保证赋值有效 if(!is_null($val)){ $vo[$name] = (MAGIC_QUOTES_GPC && is_string($val))? stripslashes($val) : $val; } } }else{ $vo = $data; } // 赋值当前数据对象 $this->data = $vo; // 返回创建的数据以供其他调用 return $vo; } /** +---------------------------------------------------------- * 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 +---------------------------------------------------------- * @param integer $linkNum 连接序号 * @param mixed $config 数据库连接信息 * @param array $params 模型参数 +---------------------------------------------------------- * @return Model +---------------------------------------------------------- */ public function db($linkNum,$config='',$params=array()){ static $_db = array(); if(!isset($_db[$linkNum])) { // 创建一个新的实例 if(!empty($config) && false === strpos($config,'/')) { // 支持读取配置参数 $config = C($config); } $_db[$linkNum] = Db::getInstance($config); }elseif(NULL === $config){ $_db[$linkNum]->close(); // 关闭数据库连接 unset($_db[$linkNum]); return ; } if(!empty($params)) { if(is_string($params)) parse_str($params,$params); foreach ($params as $name=>$value){ $this->setProperty($name,$value); } } // 切换数据库连接 $this->db = $_db[$linkNum]; 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); } $this->trueTableName = strtolower($tableName); } return (!empty($this->dbName)?$this->dbName.'.':'').$this->trueTableName; } /** +---------------------------------------------------------- * 启动事务 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ public function startTrans() { $this->commit(); $this->db->startTrans(); return ; } /** +---------------------------------------------------------- * 提交事务 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function commit() { return $this->db->commit(); } /** +---------------------------------------------------------- * 事务回滚 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolean +---------------------------------------------------------- */ public function rollback() { return $this->db->rollback(); } /** +---------------------------------------------------------- * 返回模型的错误信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getError(){ return $this->error; } /** +---------------------------------------------------------- * 返回数据库的错误信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getDbError() { return $this->db->getError(); } /** +---------------------------------------------------------- * 返回最后插入的ID +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastInsID() { return $this->db->getLastInsID(); } /** +---------------------------------------------------------- * 返回最后执行的sql语句 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getLastSql() { return $this->db->getLastSql(); } // 鉴于getLastSql比较常用 增加_sql 别名 public function _sql(){ return $this->getLastSql(); } /** +---------------------------------------------------------- * 获取主键名称 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ public function getPk() { return isset($this->fields['_pk'])?$this->fields['_pk']:$this->pk; } /** +---------------------------------------------------------- * 获取数据表字段信息 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return array +---------------------------------------------------------- */ public function getDbFields(){ if($this->fields) { $fields = $this->fields; unset($fields['_autoinc'],$fields['_pk'],$fields['_type']); return $fields; } return false; } /** +---------------------------------------------------------- * 指定查询字段 支持字段排除 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param mixed $field * @param boolean $except 是否排除 +---------------------------------------------------------- * @return Model +---------------------------------------------------------- */ public function field($field,$except=false){ if($except) {// 字段排除 if(is_string($field)) { $field = explode(',',$field); } $fields = $this->getDbFields(); $field = $fields?array_diff($fields,$field):$field; } $this->options['field'] = $field; return $this; } /** +---------------------------------------------------------- * 设置数据对象值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param 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; } /** +---------------------------------------------------------- * 查询SQL组装 union +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param array $union +---------------------------------------------------------- * @return Model +---------------------------------------------------------- */ public function union($union) { if(empty($union)) return $this; // 转换union表达式 if($union instanceof Model) { $options = $union->getProperty('options'); if(!isset($options['table'])){ // 自动获取表名 $options['table'] =$union->getTableName(); } if(!isset($options['field'])) { $options['field'] =$this->options['field']; } }elseif(is_object($union)) { $options = get_object_vars($union); }elseif(!is_array($union)){ throw_exception(L('_DATA_TYPE_INVALID_')); } $this->options['union'][] = $options; 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; } /** +---------------------------------------------------------- * 获取模型的属性值 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 名称 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function getProperty($name){ if(property_exists($this,$name)) return $this->$name; else return NULL; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Cli/Model.class.php
PHP
art
39,481
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: functions.php 2702 2012-02-02 12:35:01Z liu21st $ /** +------------------------------------------------------------------------------ * Think 命令行模式公共函数库 +------------------------------------------------------------------------------ * @category Think * @package Common * @author liu21st <liu21st@gmail.com> * @version $Id: functions.php 2702 2012-02-02 12:35:01Z liu21st $ +------------------------------------------------------------------------------ */ // 错误输出 function halt($error) { exit($error); } // 自定义异常处理 function throw_exception($msg, $type='ThinkException', $code=0) { halt($msg); } // 浏览器友好的变量输出 function dump($var, $echo=true, $label=null, $strict=true) { $label = ($label === null) ? '' : rtrim($label) . ' '; if (!$strict) { if (ini_get('html_errors')) { $output = print_r($var, true); $output = "<pre>" . $label . htmlspecialchars($output, ENT_QUOTES) . "</pre>"; } else { $output = $label . print_r($var, true); } } else { ob_start(); var_dump($var); $output = ob_get_clean(); if (!extension_loaded('xdebug')) { $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output); $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>'; } } if ($echo) { echo($output); return null; }else return $output; } // 区间调试开始 function debug_start($label='') { $GLOBALS[$label]['_beginTime'] = microtime(TRUE); if (MEMORY_LIMIT_ON) $GLOBALS[$label]['_beginMem'] = memory_get_usage(); } // 区间调试结束,显示指定标记到当前位置的调试 function debug_end($label='') { $GLOBALS[$label]['_endTime'] = microtime(TRUE); echo '<div style="text-align:center;width:100%">Process ' . $label . ': Times ' . number_format($GLOBALS[$label]['_endTime'] - $GLOBALS[$label]['_beginTime'], 6) . 's '; if (MEMORY_LIMIT_ON) { $GLOBALS[$label]['_endMem'] = memory_get_usage(); echo ' Memories ' . number_format(($GLOBALS[$label]['_endMem'] - $GLOBALS[$label]['_beginMem']) / 1024) . ' k'; } echo '</div>'; } // 全局缓存设置和读取 function S($name, $value='', $expire='', $type='',$options=null) { static $_cache = array(); alias_import('Cache'); //取得缓存对象实例 $cache = Cache::getInstance($type,$options); if ('' !== $value) { if (is_null($value)) { // 删除缓存 $result = $cache->rm($name); if ($result) unset($_cache[$type . '_' . $name]); return $result; }else { // 缓存数据 $cache->set($name, $value, $expire); $_cache[$type . '_' . $name] = $value; } return; } if (isset($_cache[$type . '_' . $name])) return $_cache[$type . '_' . $name]; // 获取缓存数据 $value = $cache->get($name); $_cache[$type . '_' . $name] = $value; return $value; } // 快速文件数据读取和保存 针对简单类型数据 字符串、数组 function F($name, $value='', $path=DATA_PATH) { static $_cache = array(); $filename = $path . $name . '.php'; if ('' !== $value) { if (is_null($value)) { // 删除缓存 return unlink($filename); } else { // 缓存数据 $dir = dirname($filename); // 目录不存在则创建 if (!is_dir($dir)) mkdir($dir); return file_put_contents($filename, strip_whitespace("<?php\nreturn " . var_export($value, true) . ";\n?>")); } } if (isset($_cache[$name])) return $_cache[$name]; // 获取缓存数据 if (is_file($filename)) { $value = include $filename; $_cache[$name] = $value; } else { $value = false; } return $value; } // 取得对象实例 支持调用类的静态方法 function get_instance_of($name, $method='', $args=array()) { static $_instance = array(); $identify = empty($args) ? $name . $method : $name . $method . to_guid_string($args); if (!isset($_instance[$identify])) { if (class_exists($name)) { $o = new $name(); if (method_exists($o, $method)) { if (!empty($args)) { $_instance[$identify] = call_user_func_array(array(&$o, $method), $args); } else { $_instance[$identify] = $o->$method(); } } else $_instance[$identify] = $o; } else halt(L('_CLASS_NOT_EXIST_') . ':' . $name); } return $_instance[$identify]; } // 根据PHP各种类型变量生成唯一标识号 function to_guid_string($mix) { if (is_object($mix) && function_exists('spl_object_hash')) { return spl_object_hash($mix); } elseif (is_resource($mix)) { $mix = get_resource_type($mix) . strval($mix); } else { $mix = serialize($mix); } return md5($mix); } // 加载扩展配置文件 function load_ext_file() { // 加载自定义外部文件 if(C('LOAD_EXT_FILE')) { $files = explode(',',C('LOAD_EXT_FILE')); foreach ($files as $file){ $file = COMMON_PATH.$file.'.php'; if(is_file($file)) include $file; } } // 加载自定义的动态配置文件 if(C('LOAD_EXT_CONFIG')) { $configs = C('LOAD_EXT_CONFIG'); if(is_string($configs)) $configs = explode(',',$configs); foreach ($configs as $key=>$config){ $file = CONF_PATH.$config.'.php'; if(is_file($file)) { is_numeric($key)?C(include $file):C($key,include $file); } } } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Cli/functions.php
PHP
art
6,709
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: App.class.php 2702 2012-02-02 12:35:01Z liu21st $ /** +------------------------------------------------------------------------------ * ThinkPHP 命令模式应用程序类 +------------------------------------------------------------------------------ */ class App { /** +---------------------------------------------------------- * 执行应用程序 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return void +---------------------------------------------------------- */ static public function run() { if(C('URL_MODEL')==1) {// PATHINFO 模式URL下面 采用 index.php module/action/id/4 $depr = C('URL_PATHINFO_DEPR'); $path = isset($_SERVER['argv'][1])?$_SERVER['argv'][1]:''; if(!empty($path)) { $params = explode($depr,trim($path,$depr)); } // 取得模块和操作名称 define('MODULE_NAME', !empty($params)?array_shift($params):C('DEFAULT_MODULE')); define('ACTION_NAME', !empty($params)?array_shift($params):C('DEFAULT_ACTION')); if(count($params)>1) { // 解析剩余参数 并采用GET方式获取 preg_replace('@(\w+),([^,\/]+)@e', '$_GET[\'\\1\']="\\2";', implode(',',$params)); } }else{// 默认URL模式 采用 index.php module action id 4 // 取得模块和操作名称 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')); if($_SERVER['argc']>3) { // 解析剩余参数 并采用GET方式获取 preg_replace('@(\w+),([^,\/]+)@e', '$_GET[\'\\1\']="\\2";', implode(',',array_slice($_SERVER['argv'],3))); } } // 执行操作 $module = A(MODULE_NAME); if(!$module) { // 是否定义Empty模块 $module = A("Empty"); if(!$module){ // 模块不存在 抛出异常 throw_exception(L('_MODULE_NOT_EXIST_').MODULE_NAME); } } call_user_func(array(&$module,ACTION_NAME)); // 保存日志记录 if(C('LOG_RECORD')) Log::save(); return ; } };
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Cli/App.class.php
PHP
art
3,134
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: Log.class.php 2702 2012-02-02 12:35:01Z liu21st $ /** +------------------------------------------------------------------------------ * 日志处理类 +------------------------------------------------------------------------------ * @category Think * @package Think * @subpackage Core * @author liu21st <liu21st@gmail.com> * @version $Id: Log.class.php 2702 2012-02-02 12:35:01Z liu21st $ +------------------------------------------------------------------------------ */ class Log { // 日志级别 从上到下,由低到高 const EMERG = 'EMERG'; // 严重错误: 导致系统崩溃无法使用 const ALERT = 'ALERT'; // 警戒性错误: 必须被立即修改的错误 const CRIT = 'CRIT'; // 临界值错误: 超过临界值的错误,例如一天24小时,而输入的是25小时这样 const ERR = 'ERR'; // 一般错误: 一般性错误 const WARN = 'WARN'; // 警告性错误: 需要发出警告的错误 const NOTICE = 'NOTIC'; // 通知: 程序可以运行但是还不够完美的错误 const INFO = 'INFO'; // 信息: 程序输出信息 const DEBUG = 'DEBUG'; // 调试: 调试信息 const SQL = 'SQL'; // SQL:SQL语句 注意只在调试模式开启时有效 // 日志记录方式 const SYSTEM = 0; const MAIL = 1; const 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 || strpos(C('LOG_RECORD_LEVEL'),$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(); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/Cli/Log.class.php
PHP
art
5,681
<?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: phprpc.php 2504 2011-12-28 07:35:29Z liu21st $ // PHPRPC模式定义文件 return array( 'core' => array( THINK_PATH.'Common/functions.php', // 系统函数库 CORE_PATH.'Core/Log.class.php',// 日志处理 MODE_PATH.'Phprpc/App.class.php', // 应用程序类 MODE_PATH.'Phprpc/Action.class.php',// 控制器类 CORE_PATH.'Core/Model.class.php', // 模型类 ), // 项目别名定义文件 [支持数组直接定义或者文件名定义] 'alias' => array( 'Model' => MODE_PATH.'Amf/Model.class.php', 'Db' => MODE_PATH.'Phprpc/Db.class.php', ), // 系统行为定义文件 [必须 支持数组直接定义或者文件名定义 ] 'extends' => array(), // 项目应用行为定义文件 [支持数组直接定义或者文件名定义] 'tags' => array(), );
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/phprpc.php
PHP
art
1,558
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: cli.php 2702 2012-02-02 12:35:01Z liu21st $ // 命令行模式定义文件 return array( 'core' => array( MODE_PATH.'Cli/functions.php', // 命令行系统函数库 MODE_PATH.'Cli/Log.class.php', MODE_PATH.'Cli/App.class.php', MODE_PATH.'Cli/Action.class.php', ), // 项目别名定义文件 [支持数组直接定义或者文件名定义] 'alias' => array( 'Model' => MODE_PATH.'Cli/Model.class.php', 'Db' => MODE_PATH.'Cli/Db.class.php', 'Cache' => CORE_PATH.'Core/Cache.class.php', 'Debug' => CORE_PATH.'Util/Debug.class.php', ), // 系统行为定义文件 [必须 支持数组直接定义或者文件名定义 ] 'extends' => array(), // 项目应用行为定义文件 [支持数组直接定义或者文件名定义] 'tags' => array(), );
zzgcms
ZGCMS/ThinkPHP/Extend/Mode/cli.php
PHP
art
1,560
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: CacheShmop.class.php 2728 2012-02-12 04:12:51Z liu21st $ /** +------------------------------------ * Shmop缓存驱动类 +------------------------------------ */ class CacheShmop extends Cache { /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($options='') { if ( !extension_loaded('shmop') ) { throw_exception(L('_NOT_SUPPERT_').':shmop'); } if(!empty($options)){ $options = array( 'size' => C('SHARE_MEM_SIZE'), 'tmp' => TEMP_PATH, 'project' => 's', 'length' =>0, ); } $this->options = $options; $this->handler = $this->_ftok($this->options['project']); } /** +---------------------------------------------------------- * 读取缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function get($name = false) { N('cache_read',1); $id = shmop_open($this->handler, 'c', 0600, 0); if ($id !== false) { $ret = unserialize(shmop_read($id, 0, shmop_size($id))); shmop_close($id); if ($name === false) { return $ret; } if(isset($ret[$name])) { $content = $ret[$name]; if(C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { //启用数据压缩 $content = gzuncompress($content); } return $content; }else { return null; } }else { return false; } } /** +---------------------------------------------------------- * 写入缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 * @param mixed $value 存储数据 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function set($name, $value) { N('cache_write',1); $lh = $this->_lock(); $val = $this->get(); if (!is_array($val)) $val = array(); if( C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { //数据压缩 $value = gzcompress($value,3); } $val[$name] = $value; $val = serialize($val); if($this->_write($val, $lh)) { if($this->options['length']>0) { // 记录缓存队列 $this->queue($name); } return true; } return false; } /** +---------------------------------------------------------- * 删除缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function rm($name) { $lh = $this->_lock(); $val = $this->get(); if (!is_array($val)) $val = array(); unset($val[$name]); $val = serialize($val); return $this->_write($val, $lh); } /** +---------------------------------------------------------- * 生成IPC key +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param string $project 项目标识名 +---------------------------------------------------------- * @return integer +---------------------------------------------------------- */ private function _ftok($project) { if (function_exists('ftok')) return ftok(__FILE__, $project); if(strtoupper(PHP_OS) == 'WINNT'){ $s = stat(__FILE__); return sprintf("%u", (($s['ino'] & 0xffff) | (($s['dev'] & 0xff) << 16) | (($project & 0xff) << 24))); }else { $filename = __FILE__ . (string) $project; for($key = array(); sizeof($key) < strlen($filename); $key[] = ord(substr($filename, sizeof($key), 1))); return dechex(array_sum($key)); } } /** +---------------------------------------------------------- * 写入操作 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return integer|boolen +---------------------------------------------------------- */ private function _write(&$val, &$lh) { $id = shmop_open($this->handler, 'c', 0600, $this->options['size']); if ($id) { $ret = shmop_write($id, $val, 0) == strlen($val); shmop_close($id); $this->_unlock($lh); return $ret; } $this->_unlock($lh); return false; } /** +---------------------------------------------------------- * 共享锁定 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ private function _lock() { if (function_exists('sem_get')) { $fp = sem_get($this->handler, 1, 0600, 1); sem_acquire ($fp); } else { $fp = fopen($this->options['tmp'].$this->prefix.md5($this->handler), 'w'); flock($fp, LOCK_EX); } return $fp; } /** +---------------------------------------------------------- * 解除共享锁定 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ private function _unlock(&$fp) { if (function_exists('sem_release')) { sem_release($fp); } else { fclose($fp); } } }
zzgcms
ZGCMS/ThinkPHP/Extend/Driver/Cache/CacheShmop.class.php
PHP
art
8,043
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: CacheXcache.class.php 2728 2012-02-12 04:12:51Z liu21st $ /** +---------------------------- * Xcache缓存驱动类 +---------------------------- */ class CacheXcache extends Cache { /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($options='') { if ( !function_exists('xcache_info') ) { throw_exception(L('_NOT_SUPPERT_').':Xcache'); } if(!empty($options)) { $this->options = $options; } $this->options['expire'] = isset($options['expire'])?$options['expire']:C('DATA_CACHE_TIME'); $this->options['length'] = isset($options['length'])?$options['length']:0; } /** +---------------------------------------------------------- * 读取缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function get($name) { N('cache_read',1); if (xcache_isset($name)) { return xcache_get($name); } return false; } /** +---------------------------------------------------------- * 写入缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 * @param mixed $value 存储数据 * @param integer $expire 有效时间(秒) +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function set($name, $value,$expire=null) { N('cache_write',1); if(is_null($expire)) { $expire = $this->options['expire'] ; } if(xcache_set($name, $value, $expire)) { if($this->options['length']>0) { // 记录缓存队列 $this->queue($name); } return true; } return false; } /** +---------------------------------------------------------- * 删除缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function rm($name) { return xcache_unset($name); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Driver/Cache/CacheXcache.class.php
PHP
art
3,687
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: CacheEaccelerator.class.php 2728 2012-02-12 04:12:51Z liu21st $ /** +------------------------------------- * Eaccelerator缓存驱动类 +------------------------------------- */ class CacheEaccelerator extends Cache { /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($options='') { if(!empty($options)) { $this->options = $options; } $this->options['expire'] = isset($options['expire'])?$options['expire']:C('DATA_CACHE_TIME'); $this->options['length'] = isset($options['length'])?$options['length']:0; } /** +---------------------------------------------------------- * 读取缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function get($name) { N('cache_read',1); return eaccelerator_get($name); } /** +---------------------------------------------------------- * 写入缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 * @param mixed $value 存储数据 * @param integer $expire 有效时间(秒) +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function set($name, $value, $expire = null) { N('cache_write',1); if(is_null($expire)) { $expire = $this->options['expire']; } eaccelerator_lock($name); if(eaccelerator_put($name, $value, $expire)) { if($this->options['length']>0) { // 记录缓存队列 $this->queue($name); } return true; } return false; } /** +---------------------------------------------------------- * 删除缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function rm($name) { return eaccelerator_rm($name); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Driver/Cache/CacheEaccelerator.class.php
PHP
art
3,595
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: CacheApachenote.class.php 2728 2012-02-12 04:12:51Z liu21st $ /** +----------------------------------------- * Apachenote缓存驱动类 +----------------------------------------- */ class CacheApachenote extends Cache { /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($options='') { if(empty($options)){ $options = array( 'host' => '127.0.0.1', 'port' => 1042, 'timeout' => 10, 'length' =>0 ); } $this->handler = null; $this->open(); $this->options = $options; } /** +---------------------------------------------------------- * 是否连接 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function isConnected() { return $this->connected; } /** +---------------------------------------------------------- * 读取缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function get($name) { $this->open(); $s = 'F' . pack('N', strlen($name)) . $name; fwrite($this->handler, $s); for ($data = ''; !feof($this->handler);) { $data .= fread($this->handler, 4096); } N('cache_read',1); $this->close(); return $data === '' ? '' : unserialize($data); } /** +---------------------------------------------------------- * 写入缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 * @param mixed $value 存储数据 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function set($name, $value) { N('cache_write',1); $this->open(); $value = serialize($value); $s = 'S' . pack('NN', strlen($name), strlen($value)) . $name . $value; fwrite($this->handler, $s); $ret = fgets($this->handler); $this->close(); if($ret === "OK\n") { if($this->options['length']>0) { // 记录缓存队列 $this->queue($name); } return true; } return false; } /** +---------------------------------------------------------- * 删除缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function rm($name) { $this->open(); $s = 'D' . pack('N', strlen($name)) . $name; fwrite($this->handler, $s); $ret = fgets($this->handler); $this->close(); return $ret === "OK\n"; } /** +---------------------------------------------------------- * 关闭缓存 +---------------------------------------------------------- * @access private +---------------------------------------------------------- */ private function close() { fclose($this->handler); $this->handler = false; } /** +---------------------------------------------------------- * 打开缓存 +---------------------------------------------------------- * @access private +---------------------------------------------------------- */ private function open() { if (!is_resource($this->handler)) { $this->handler = fsockopen($this->options['host'], $this->options['port'], $_, $_, $this->options['timeout']); $this->connected = is_resource($this->handler); } } }
zzgcms
ZGCMS/ThinkPHP/Extend/Driver/Cache/CacheApachenote.class.php
PHP
art
5,463
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: CacheApc.class.php 2728 2012-02-12 04:12:51Z liu21st $ /** +------------------------------- * Apc缓存驱动类 +------------------------------- */ class CacheApc extends Cache { /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($options='') { if(!function_exists('apc_cache_info')) { throw_exception(L('_NOT_SUPPERT_').':Apc'); } if(!empty($options)) { $this->options = $options; } $this->options['expire'] = isset($options['expire'])?$options['expire']:C('DATA_CACHE_TIME'); $this->options['length'] = isset($options['length'])?$options['length']:0; } /** +---------------------------------------------------------- * 读取缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function get($name) { N('cache_read',1); return apc_fetch($name); } /** +---------------------------------------------------------- * 写入缓存 * +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 * @param mixed $value 存储数据 * @param integer $expire 有效时间(秒) +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function set($name, $value, $expire = null) { N('cache_write',1); if(is_null($expire)) { $expire = $this->options['expire']; } if($result = apc_store($name, $value, $expire)) { if($this->options['length']>0) { // 记录缓存队列 $this->queue($name); } } return $result; } /** +---------------------------------------------------------- * 删除缓存 * +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function rm($name) { return apc_delete($name); } /** +---------------------------------------------------------- * 清除缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function clear() { return apc_clear_cache(); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Driver/Cache/CacheApc.class.php
PHP
art
4,044
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: CacheMemcache.class.php 2728 2012-02-12 04:12:51Z liu21st $ /** +------------------------------------- * Memcache缓存驱动类 +------------------------------------- */ class CacheMemcache extends Cache { /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ function __construct($options='') { if ( !extension_loaded('memcache') ) { throw_exception(L('_NOT_SUPPERT_').':memcache'); } if(empty($options)) { $options = array ( 'host' => C('MEMCACHE_HOST') ? C('MEMCACHE_HOST') : '127.0.0.1', 'port' => C('MEMCACHE_PORT') ? C('MEMCACHE_PORT') : 11211, 'timeout' => C('DATA_CACHE_TIMEOUT') ? C('DATA_CACHE_TIMEOUT') : false, 'persistent' => false, 'expire' =>C('DATA_CACHE_TIME'), 'length' =>0, ); } $this->options = $options; $func = $options['persistent'] ? 'pconnect' : 'connect'; $this->handler = new Memcache; $this->connected = $options['timeout'] === false ? $this->handler->$func($options['host'], $options['port']) : $this->handler->$func($options['host'], $options['port'], $options['timeout']); } /** +---------------------------------------------------------- * 是否连接 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ private function isConnected() { return $this->connected; } /** +---------------------------------------------------------- * 读取缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function get($name) { N('cache_read',1); return $this->handler->get($name); } /** +---------------------------------------------------------- * 写入缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 * @param mixed $value 存储数据 * @param integer $expire 有效时间(秒) +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function set($name, $value, $expire = null) { N('cache_write',1); if(is_null($expire)) { $expire = $this->options['expire']; } if($this->handler->set($name, $value, 0, $expire)) { if($this->options['length']>0) { // 记录缓存队列 $this->queue($name); } return true; } return false; } /** +---------------------------------------------------------- * 删除缓存 * +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function rm($name, $ttl = false) { return $ttl === false ? $this->handler->delete($name) : $this->handler->delete($name, $ttl); } /** +---------------------------------------------------------- * 清除缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function clear() { return $this->handler->flush(); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Driver/Cache/CacheMemcache.class.php
PHP
art
5,191
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: CacheWincache.class.php 2728 2012-02-12 04:12:51Z liu21st $ /** +---------------------------- * WinCache 缓存驱动类 +---------------------------- */ class CacheWincache extends Cache { /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($options='') { if ( !function_exists('wincache_ucache_info') ) { throw_exception(L('_NOT_SUPPERT_').':WinCache'); } if(!empty($options)) { $this->options = $options; } $this->options['expire'] = isset($options['expire'])?$options['expire']:C('DATA_CACHE_TIME'); $this->options['length'] = isset($options['length'])?$options['length']:0; } /** +---------------------------------------------------------- * 读取缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function get($name) { N('cache_read',1); return wincache_ucache_exists($name)? wincache_ucache_get($name) : false; } /** +---------------------------------------------------------- * 写入缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 * @param mixed $value 存储数据 * @param integer $expire 有效时间(秒) +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function set($name, $value,$expire=null) { N('cache_write',1); if(is_null($expire)) { $expire = $this->options['expire']; } if(wincache_ucache_set($name, $value, $expire)) { if($this->options['length']>0) { // 记录缓存队列 $this->queue($name); } return true; } return false; } /** +---------------------------------------------------------- * 删除缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function rm($name) { return wincache_ucache_delete($name); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Driver/Cache/CacheWincache.class.php
PHP
art
3,699
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: 尘缘 <130775@qq.com> // +---------------------------------------------------------------------- // $Id: CacheRedis.class.php 2787 2012-02-28 08:50:32Z shuhai.sir@gmail.com $ /** +------------------------------------- * CacheRedis缓存驱动类 * 要求安装phpredis扩展:https://github.com/owlient/phpredis +------------------------------------- */ class CacheRedis extends Cache { /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($options='') { if ( !extension_loaded('redis') ) { throw_exception(L('_NOT_SUPPERT_').':redis'); } if(empty($options)) { $options = array ( 'host' => C('REDIS_HOST') ? C('REDIS_HOST') : '127.0.0.1', 'port' => C('REDIS_PORT') ? C('REDIS_PORT') : 6379, 'timeout' => C('DATA_CACHE_TIMEOUT') ? C('DATA_CACHE_TIMEOUT') : false, 'persistent' => false, 'expire' => C('DATA_CACHE_TIME'), 'length' => 0, ); } $this->options = $options; $func = $options['persistent'] ? 'pconnect' : 'connect'; $this->handler = new Redis; $this->connected = $options['timeout'] === false ? $this->handler->$func($options['host'], $options['port']) : $this->handler->$func($options['host'], $options['port'], $options['timeout']); } /** +---------------------------------------------------------- * 是否连接 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ private function isConnected() { return $this->connected; } /** +---------------------------------------------------------- * 读取缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function get($name) { N('cache_read',1); return $this->handler->get($name); } /** +---------------------------------------------------------- * 写入缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 * @param mixed $value 存储数据 * @param integer $expire 有效时间(秒) +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function set($name, $value, $expire = null) { N('cache_write',1); if(is_null($expire)) { $expire = $this->options['expire']; } if(is_int($expire)) { $result = $this->handler->setex($name, $expire, $value); }else{ $result = $this->handler->set($name, $value); } if($result && $this->options['length']>0) { // 记录缓存队列 $this->queue($name); } return $result; } /** +---------------------------------------------------------- * 删除缓存 * +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function rm($name) { return $this->handler->delete($name); } /** +---------------------------------------------------------- * 清除缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function clear() { return $this->handler->flushDB(); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Driver/Cache/CacheRedis.class.php
PHP
art
5,243
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: CacheSqlite.class.php 2734 2012-02-14 06:55:15Z liu21st $ /** +-------------------------------- * Sqlite缓存类 +-------------------------------- */ class CacheSqlite extends Cache { /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($options='') { if ( !extension_loaded('sqlite') ) { throw_exception(L('_NOT_SUPPERT_').':sqlite'); } if(empty($options)){ $options= array ( 'db' => ':memory:', 'table' => 'sharedmemory', 'expire' => C('DATA_CACHE_TIME'), 'persistent'=> false, 'length' =>0, ); } $this->options = $options; $func = $this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open'; $this->handler = $func($this->options['db']); $this->connected = is_resource($this->handler); } /** +---------------------------------------------------------- * 是否连接 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ private function isConnected() { return $this->connected; } /** +---------------------------------------------------------- * 读取缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function get($name) { N('cache_read',1); $name = sqlite_escape_string($name); $sql = 'SELECT value FROM '.$this->options['table'].' WHERE var=\''.$name.'\' AND (expire=0 OR expire >'.time().') LIMIT 1'; $result = sqlite_query($this->handler, $sql); if (sqlite_num_rows($result)) { $content = sqlite_fetch_single($result); if(C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { //启用数据压缩 $content = gzuncompress($content); } return unserialize($content); } return false; } /** +---------------------------------------------------------- * 写入缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 * @param mixed $value 存储数据 * @param integer $expire 有效时间(秒) +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function set($name, $value,$expire=null) { N('cache_write',1); $expire = !empty($expireTime)? $expireTime : C('DATA_CACHE_TIME'); $name = sqlite_escape_string($name); $value = sqlite_escape_string(serialize($value)); if(is_null($expire)) { $expire = $this->options['expire']; } $expire = ($expire==0)?0: (time()+$expire) ;//缓存有效期为0表示永久缓存 if( C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { //数据压缩 $value = gzcompress($value,3); } $sql = 'REPLACE INTO '.$this->options['table'].' (var, value,expire) VALUES (\''.$name.'\', \''.$value.'\', \''.$expire.'\')'; if(sqlite_query($this->handler, $sql)){ if($this->options['length']>0) { // 记录缓存队列 $this->queue($name); } return true; } return false; } /** +---------------------------------------------------------- * 删除缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function rm($name) { $name = sqlite_escape_string($name); $sql = 'DELETE FROM '.$this->options['table'].' WHERE var=\''.$name.'\''; sqlite_query($this->handler, $sql); return true; } /** +---------------------------------------------------------- * 清除缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function clear() { $sql = 'DELETE FROM '.$this->options['table']; sqlite_query($this->handler, $sql); return ; } }
zzgcms
ZGCMS/ThinkPHP/Extend/Driver/Cache/CacheSqlite.class.php
PHP
art
6,102
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- // $Id: CacheDb.class.php 2734 2012-02-14 06:55:15Z liu21st $ /** +----------------------------------------------- * 数据库类型缓存驱动类 CREATE TABLE think_cache ( cachekey varchar(255) NOT NULL, expire int(11) NOT NULL, data blob, datacrc int(32), UNIQUE KEY `cachekey` (`cachekey`) ); +----------------------------------------------- */ class CacheDb extends Cache { /** +---------------------------------------------------------- * 缓存数据库对象 采用数据库方式有效 +---------------------------------------------------------- * @var string * @access protected +---------------------------------------------------------- */ private $db ; /** +---------------------------------------------------------- * 架构函数 +---------------------------------------------------------- * @access public +---------------------------------------------------------- */ public function __construct($options='') { if(empty($options)){ $options= array ( 'db' => C('DB_NAME'), 'table' => C('DATA_CACHE_TABLE'), 'expire' => C('DATA_CACHE_TIME'), 'length' => 0, ); } $this->options = $options; import('Db'); $this->db = DB::getInstance(); $this->connected = is_resource($this->db); } /** +---------------------------------------------------------- * 是否连接 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ private function isConnected() { return $this->connected; } /** +---------------------------------------------------------- * 读取缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return mixed +---------------------------------------------------------- */ public function get($name) { $name = addslashes($name); N('cache_read',1); $result = $this->db->query('SELECT `data`,`datacrc` FROM `'.$this->options['table'].'` WHERE `cachekey`=\''.$name.'\' AND (`expire` =0 OR `expire`>'.time().') LIMIT 0,1'); if(false !== $result ) { $result = $result[0]; if(C('DATA_CACHE_CHECK')) {//开启数据校验 if($result['datacrc'] != md5($result['data'])) {//校验错误 return false; } } $content = $result['data']; if(C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { //启用数据压缩 $content = gzuncompress($content); } $content = unserialize($content); return $content; } else { return false; } } /** +---------------------------------------------------------- * 写入缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 * @param mixed $value 存储数据 * @param integer $expire 有效时间(秒) +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function set($name, $value,$expire=null) { $data = serialize($value); $name = addslashes($name); N('cache_write',1); if( C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { //数据压缩 $data = gzcompress($data,3); } if(C('DATA_CACHE_CHECK')) {//开启数据校验 $crc = md5($data); }else { $crc = ''; } if(is_null($expire)) { $expire = $this->options['expire']; } $expire = ($expire==0)?0: (time()+$expire) ;//缓存有效期为0表示永久缓存 $result = $this->db->query('select `cachekey` from `'.$this->options['table'].'` where `cachekey`=\''.$name.'\' limit 0,1'); if(!empty($result) ) { //更新记录 $result = $this->db->execute('UPDATE '.$this->options['table'].' SET data=\''.$data.'\' ,datacrc=\''.$crc.'\',expire='.$expire.' WHERE `cachekey`=\''.$name.'\''); }else { //新增记录 $result = $this->db->execute('INSERT INTO '.$this->options['table'].' (`cachekey`,`data`,`datacrc`,`expire`) VALUES (\''.$name.'\',\''.$data.'\',\''.$crc.'\','.$expire.')'); } if($result) { if($this->options['length']>0) { // 记录缓存队列 $this->queue($name); } return true; }else { return false; } } /** +---------------------------------------------------------- * 删除缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @param string $name 缓存变量名 +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function rm($name) { $name = addslashes($name); return $this->db->execute('DELETE FROM `'.$this->options['table'].'` WHERE `cachekey`=\''.$name.'\''); } /** +---------------------------------------------------------- * 清除缓存 +---------------------------------------------------------- * @access public +---------------------------------------------------------- * @return boolen +---------------------------------------------------------- */ public function clear() { return $this->db->execute('TRUNCATE TABLE `'.$this->options['table'].'`'); } }
zzgcms
ZGCMS/ThinkPHP/Extend/Driver/Cache/CacheDb.class.php
PHP
art
7,184