Commit 592fc9d1 by 石迎春

删除了target

1 parent f1f51c02
Showing 860 changed files with 0 additions and 4917 deletions
<?php
$htmlData = '';
if (!empty($_POST['content1'])) {
if (get_magic_quotes_gpc()) {
$htmlData = stripslashes($_POST['content1']);
} else {
$htmlData = $_POST['content1'];
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>KindEditor PHP</title>
<link rel="stylesheet" href="../themes/default/default.css" />
<link rel="stylesheet" href="../plugins/code/prettify.css" />
<script charset="utf-8" src="../kindeditor.js"></script>
<script charset="utf-8" src="../lang/zh_CN.js"></script>
<script charset="utf-8" src="../plugins/code/prettify.js"></script>
<script>
KindEditor.ready(function(K) {
var editor1 = K.create('textarea[name="content1"]', {
cssPath : '../plugins/code/prettify.css',
uploadJson : '../php/upload_json.php',
fileManagerJson : '../php/file_manager_json.php',
allowFileManager : true,
afterCreate : function() {
var self = this;
K.ctrl(document, 13, function() {
self.sync();
K('form[name=example]')[0].submit();
});
K.ctrl(self.edit.doc, 13, function() {
self.sync();
K('form[name=example]')[0].submit();
});
}
});
prettyPrint();
});
</script>
</head>
<body>
<?php echo $htmlData; ?>
<form name="example" method="post" action="demo.php">
<textarea name="content1" style="width:700px;height:200px;visibility:hidden;"><?php echo htmlspecialchars($htmlData); ?></textarea>
<br />
<input type="submit" name="button" value="提交内容" /> (提交快捷键: Ctrl + Enter)
</form>
</body>
</html>
<?php
/**
* KindEditor PHP
*
* 本PHP程序是演示程序,建议不要直接在实际项目中使用。
* 如果您确定直接使用本程序,使用之前请仔细确认相关安全设置。
*
*/
require_once 'JSON.php';
$php_path = dirname(__FILE__) . '/';
$php_url = dirname($_SERVER['PHP_SELF']) . '/';
//根目录路径,可以指定绝对路径,比如 /var/www/attached/
$root_path = $php_path . '../Uploads/';
//根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
$root_url = $php_url . '../Uploads/';
//图片扩展名
$ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
//目录名
$dir_name = empty($_GET['dir']) ? '' : trim($_GET['dir']);
if (!in_array($dir_name, array('', 'image', 'flash', 'media', 'file'))) {
echo "Invalid Directory name.";
exit;
}
if ($dir_name !== '') {
$root_path .= $dir_name . "/";
$root_url .= $dir_name . "/";
if (!file_exists($root_path)) {
mkdir($root_path);
}
}
//根据path参数,设置各路径和URL
if (empty($_GET['path'])) {
$current_path = realpath($root_path) . '/';
$current_url = $root_url;
$current_dir_path = '';
$moveup_dir_path = '';
} else {
$current_path = realpath($root_path) . '/' . $_GET['path'];
$current_url = $root_url . $_GET['path'];
$current_dir_path = $_GET['path'];
$moveup_dir_path = preg_replace('/(.*?)[^\/]+\/$/', '$1', $current_dir_path);
}
echo realpath($root_path);
//排序形式,name or size or type
$order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);
//不允许使用..移动到上一级目录
if (preg_match('/\.\./', $current_path)) {
echo 'Access is not allowed.';
exit;
}
//最后一个字符不是/
if (!preg_match('/\/$/', $current_path)) {
echo 'Parameter is not valid.';
exit;
}
//目录不存在或不是目录
if (!file_exists($current_path) || !is_dir($current_path)) {
echo 'Directory does not exist.';
exit;
}
//遍历目录取得文件信息
$file_list = array();
if ($handle = opendir($current_path)) {
$i = 0;
while (false !== ($filename = readdir($handle))) {
if ($filename{0} == '.') continue;
$file = $current_path . $filename;
if (is_dir($file)) {
$file_list[$i]['is_dir'] = true; //是否文件夹
$file_list[$i]['has_file'] = (count(scandir($file)) > 2); //文件夹是否包含文件
$file_list[$i]['filesize'] = 0; //文件大小
$file_list[$i]['is_photo'] = false; //是否图片
$file_list[$i]['filetype'] = ''; //文件类别,用扩展名判断
} else {
$file_list[$i]['is_dir'] = false;
$file_list[$i]['has_file'] = false;
$file_list[$i]['filesize'] = filesize($file);
$file_list[$i]['dir_path'] = '';
$file_ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
$file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);
$file_list[$i]['filetype'] = $file_ext;
}
$file_list[$i]['filename'] = $filename; //文件名,包含扩展名
$file_list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime($file)); //文件最后修改时间
$i++;
}
closedir($handle);
}
//排序
function cmp_func($a, $b) {
global $order;
if ($a['is_dir'] && !$b['is_dir']) {
return -1;
} else if (!$a['is_dir'] && $b['is_dir']) {
return 1;
} else {
if ($order == 'size') {
if ($a['filesize'] > $b['filesize']) {
return 1;
} else if ($a['filesize'] < $b['filesize']) {
return -1;
} else {
return 0;
}
} else if ($order == 'type') {
return strcmp($a['filetype'], $b['filetype']);
} else {
return strcmp($a['filename'], $b['filename']);
}
}
}
usort($file_list, 'cmp_func');
$result = array();
//相对于根目录的上一级目录
$result['moveup_dir_path'] = $moveup_dir_path;
//相对于根目录的当前目录
$result['current_dir_path'] = $current_dir_path;
//当前目录的URL
$result['current_url'] = $current_url;
//文件数
$result['total_count'] = count($file_list);
//文件列表数组
$result['file_list'] = $file_list;
//输出JSON字符串
header('Content-type: application/json; charset=UTF-8');
$json = new Services_JSON();
echo $json->encode($result);
<?php
/**
* KindEditor PHP
*
* 本PHP程序是演示程序,建议不要直接在实际项目中使用。
* 如果您确定直接使用本程序,使用之前请仔细确认相关安全设置。
*
*/
require_once 'JSON.php';
$php_path = dirname(__FILE__) . '/';
$php_url = dirname($_SERVER['PHP_SELF']) . '/';
//文件保存目录路径
$save_path = $php_path . '../Uploads/';
//文件保存目录URL
$save_url = $php_url . '../Uploads/';
//定义允许上传的文件扩展名
$ext_arr = array(
'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
'flash' => array('swf', 'flv'),
'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
);
//最大文件大小
$max_size = 1000000;
$save_path = realpath($save_path) . '/';
//PHP上传失败
if (!empty($_FILES['imgFile']['error'])) {
switch($_FILES['imgFile']['error']){
case '1':
$error = '超过php.ini允许的大小。';
break;
case '2':
$error = '超过表单允许的大小。';
break;
case '3':
$error = '图片只有部分被上传。';
break;
case '4':
$error = '请选择图片。';
break;
case '6':
$error = '找不到临时目录。';
break;
case '7':
$error = '写文件到硬盘出错。';
break;
case '8':
$error = 'File upload stopped by extension。';
break;
case '999':
default:
$error = '未知错误。';
}
alert($error);
}
//有上传文件时
if (empty($_FILES) === false) {
//原文件名
$file_name = $_FILES['imgFile']['name'];
//服务器上临时文件名
$tmp_name = $_FILES['imgFile']['tmp_name'];
//文件大小
$file_size = $_FILES['imgFile']['size'];
//检查文件名
if (!$file_name) {
alert("请选择文件。");
}
//检查目录
if (@is_dir($save_path) === false) {
alert("上传目录不存在。");
}
//检查目录写权限
if (@is_writable($save_path) === false) {
alert("上传目录没有写权限。");
}
//检查是否已上传
if (@is_uploaded_file($tmp_name) === false) {
alert("上传失败。");
}
//检查文件大小
if ($file_size > $max_size) {
alert("上传文件大小超过限制。");
}
//检查目录名
$dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
if (empty($ext_arr[$dir_name])) {
alert("目录名不正确。");
}
//获得文件扩展名
$temp_arr = explode(".", $file_name);
$file_ext = array_pop($temp_arr);
$file_ext = trim($file_ext);
$file_ext = strtolower($file_ext);
//检查扩展名
if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
alert("上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。");
}
//创建文件夹
if ($dir_name !== '') {
$save_path .= $dir_name . "/";
$save_url .= $dir_name . "/";
if (!file_exists($save_path)) {
mkdir($save_path);
}
}
$ymd = date("Ymd");
$save_path .= $ymd . "/";
$save_url .= $ymd . "/";
if (!file_exists($save_path)) {
mkdir($save_path);
}
//新文件名
$new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
//移动文件
$file_path = $save_path . $new_file_name;
if (move_uploaded_file($tmp_name, $file_path) === false) {
alert("上传文件失败。");
}
@chmod($file_path, 0644);
$file_url = $save_url . $new_file_name;
header('Content-type: text/html; charset=UTF-8');
$json = new Services_JSON();
echo $json->encode(array('error' => 0, 'url' => $file_url));
exit;
}
function alert($msg) {
header('Content-type: text/html; charset=UTF-8');
$json = new Services_JSON();
echo $json->encode(array('error' => 1, 'message' => $msg));
exit;
}
<?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>
// +----------------------------------------------------------------------
/**
* ThinkPHP 运行时文件 编译后不再加载
* @category Think
* @package Common
* @author liu21st <liu21st@gmail.com>
*/
defined('THINK_PATH') or exit();
if(version_compare(PHP_VERSION,'5.2.0','<')) die('require PHP > 5.2.0 !');
// 版本信息
define('THINK_VERSION', '3.1.3');
// 系统信息
if(version_compare(PHP_VERSION,'5.4.0','<')) {
ini_set('magic_quotes_runtime',0);
define('MAGIC_QUOTES_GPC',get_magic_quotes_gpc()?True:False);
}else{
define('MAGIC_QUOTES_GPC',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);
}
// 系统行为扩展文件统一编译
$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 '.str_replace("defined('THINK_PATH') or exit();",' ',$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)) mkdir(APP_PATH,0755,true);
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)) mkdir($dir,0755,true);
}
// 写入目录安全文件
build_dir_secure($dirs);
// 写入初始配置文件
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);
}
// 生成目录安全文件
function build_dir_secure($dirs=array()) {
// 目录安全写入
if(defined('BUILD_DIR_SECURE') && 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;
$files = explode(',', DIR_SECURE_FILENAME);
foreach ($files as $filename){
foreach ($dirs as $dir)
file_put_contents($dir.$filename,$content);
}
}
}
// 加载运行时所需文件
load_runtime_file();
// 记录加载文件时间
G('loadTime');
// 执行入口
Think::Start();
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
// 系统别名定义文件
return array(
'Model' => CORE_PATH.'Core/Model.class.php',
'Db' => CORE_PATH.'Core/Db.class.php',
'Log' => CORE_PATH.'Core/Log.class.php',
'ThinkTemplate' => CORE_PATH.'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',
);
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
/**
* ThinkPHP惯例配置文件
* 该文件请不要修改,如果要覆盖惯例配置的值,可在项目配置文件中设定和惯例不符的配置项
* 配置名称大小写任意,系统会统一转换成小写
* 所有配置参数都可以在生效前动态改变
* @category Think
* @package Common
* @author liu21st <liu21st@gmail.com>
* @version $Id: convention.php 3088 2012-07-29 09:12:19Z luofei614@gmail.com $
*/
defined('THINK_PATH') or exit();
return array(
/* 项目设定 */
'APP_STATUS' => 'debug', // 应用调试模式状态 调试模式开启后有效 默认为debug 可扩展 并自动加载对应的配置文件
'APP_FILE_CASE' => false, // 是否检查文件的大小写 对Windows平台有效
'APP_AUTOLOAD_PATH' => '',// 自动加载机制的自动搜索路径,注意搜索顺序
'APP_TAGS_ON' => true, // 系统标签扩展开关
'APP_SUB_DOMAIN_DEPLOY' => false, // 是否开启子域名部署
'APP_SUB_DOMAIN_RULES' => array(), // 子域名部署规则
'APP_SUB_DOMAIN_DENY' => array(), // 子域名禁用列表
'APP_GROUP_LIST' => '', // 项目分组设定,多个组之间用逗号分隔,例如'Home,Admin'
'APP_GROUP_MODE' => 0, // 分组模式 0 普通分组 1 独立分组
'APP_GROUP_PATH' => 'Modules', // 分组目录 独立分组模式下面有效
'ACTION_SUFFIX' => '', // 操作方法后缀
/* Cookie设置 */
'COOKIE_EXPIRE' => 0, // Coodie有效期
'COOKIE_DOMAIN' => '', // Cookie有效域名
'COOKIE_PATH' => '/', // Cookie路径
'COOKIE_PREFIX' => '', // Cookie前缀 避免冲突
/* 默认设定 */
'DEFAULT_M_LAYER' => 'Model', // 默认的模型层名称
'DEFAULT_C_LAYER' => 'Action', // 默认的控制器层名称
'DEFAULT_V_LAYER' => 'Tpl', // 默认的视图层名称
'DEFAULT_APP' => '@', // 默认项目名称,@表示当前项目
'DEFAULT_LANG' => 'zh-cn', // 默认语言
'DEFAULT_THEME' => '', // 默认模板主题名称
'DEFAULT_GROUP' => 'Home', // 默认分组
'DEFAULT_MODULE' => 'Index', // 默认模块名称
'DEFAULT_ACTION' => 'index', // 默认操作名称
'DEFAULT_CHARSET' => 'utf-8', // 默认输出编码
'DEFAULT_TIMEZONE' => 'PRC', // 默认时区
'DEFAULT_AJAX_RETURN' => 'JSON', // 默认AJAX 数据返回格式,可选JSON XML ...
'DEFAULT_JSONP_HANDLER' => 'jsonpReturn', // 默认JSONP格式返回的处理方法
'DEFAULT_FILTER' => 'htmlspecialchars', // 默认参数过滤方法 用于 $this->_get('变量名');$this->_post('变量名')...
/* 数据库设置 */
'DB_TYPE' => 'mysql', // 数据库类型
'DB_HOST' => 'localhost', // 服务器地址
'DB_NAME' => '', // 数据库名
'DB_USER' => 'root', // 用户名
'DB_PWD' => '', // 密码
'DB_PORT' => '', // 端口
'DB_PREFIX' => 'think_', // 数据库表前缀
'DB_FIELDTYPE_CHECK' => false, // 是否进行字段类型检查
'DB_FIELDS_CACHE' => true, // 启用字段缓存
'DB_CHARSET' => 'utf8', // 数据库编码默认采用utf8
'DB_DEPLOY_TYPE' => 0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'DB_RW_SEPARATE' => false, // 数据库读写是否分离 主从式有效
'DB_MASTER_NUM' => 1, // 读写分离后 主服务器数量
'DB_SLAVE_NO' => '', // 指定从服务器序号
'DB_SQL_BUILD_CACHE' => false, // 数据库查询的SQL创建缓存
'DB_SQL_BUILD_QUEUE' => 'file', // SQL缓存队列的缓存方式 支持 file xcache和apc
'DB_SQL_BUILD_LENGTH' => 20, // SQL缓存的队列长度
'DB_SQL_LOG' => false, // SQL执行日志记录
/* 数据缓存设置 */
'DATA_CACHE_TIME' => 0, // 数据缓存有效期 0表示永久缓存
'DATA_CACHE_COMPRESS' => false, // 数据缓存是否压缩缓存
'DATA_CACHE_CHECK' => false, // 数据缓存是否校验缓存
'DATA_CACHE_PREFIX' => '', // 缓存前缀
'DATA_CACHE_TYPE' => 'File', // 数据缓存类型,支持:File|Db|Apc|Memcache|Shmop|Sqlite|Xcache|Apachenote|Eaccelerator
'DATA_CACHE_PATH' => TEMP_PATH,// 缓存路径设置 (仅对File方式缓存有效)
'DATA_CACHE_SUBDIR' => false, // 使用子目录缓存 (自动根据缓存标识的哈希创建子目录)
'DATA_PATH_LEVEL' => 1, // 子目录缓存级别
/* 错误设置 */
'ERROR_MESSAGE' => '页面错误!请稍后再试~',//错误显示信息,非调试模式有效
'ERROR_PAGE' => '', // 错误定向页面
'SHOW_ERROR_MSG' => false, // 显示错误信息
'TRACE_EXCEPTION' => false, // TRACE错误信息是否抛异常 针对trace方法
/* 日志设置 */
'LOG_RECORD' => false, // 默认不记录日志
'LOG_TYPE' => 3, // 日志记录类型 0 系统 1 邮件 3 文件 4 SAPI 默认为文件方式
'LOG_DEST' => '', // 日志记录目标
'LOG_EXTRA' => '', // 日志记录额外信息
'LOG_LEVEL' => 'EMERG,ALERT,CRIT,ERR',// 允许记录的日志级别
'LOG_FILE_SIZE' => 2097152, // 日志文件大小限制
'LOG_EXCEPTION_RECORD' => false, // 是否记录异常信息日志
/* SESSION设置 */
'SESSION_AUTO_START' => true, // 是否自动开启Session
'SESSION_OPTIONS' => array(), // session 配置数组 支持type name id path expire domain 等参数
'SESSION_TYPE' => '', // session hander类型 默认无需设置 除非扩展了session hander驱动
'SESSION_PREFIX' => '', // session 前缀
//'VAR_SESSION_ID' => 'session_id', //sessionID的提交变量
/* 模板引擎设置 */
'TMPL_CONTENT_TYPE' => 'text/html', // 默认模板输出类型
'TMPL_ACTION_ERROR' => THINK_PATH.'Tpl/dispatch_jump.tpl', // 默认错误跳转对应的模板文件
'TMPL_ACTION_SUCCESS' => THINK_PATH.'Tpl/dispatch_jump.tpl', // 默认成功跳转对应的模板文件
'TMPL_EXCEPTION_FILE' => THINK_PATH.'Tpl/think_exception.tpl',// 异常页面的模板文件
'TMPL_DETECT_THEME' => false, // 自动侦测模板主题
'TMPL_TEMPLATE_SUFFIX' => '.html', // 默认模板文件后缀
'TMPL_FILE_DEPR' => '/', //模板文件MODULE_NAME与ACTION_NAME之间的分割符
/* URL设置 */
'URL_CASE_INSENSITIVE' => false, // 默认false 表示URL区分大小写 true则表示不区分大小写
'URL_MODEL' => 1, // URL访问模式,可选参数0、1、2、3,代表以下四种模式:
// 0 (普通模式); 1 (PATHINFO 模式); 2 (REWRITE 模式); 3 (兼容模式) 默认为PATHINFO 模式,提供最好的用户体验和SEO支持
'URL_PATHINFO_DEPR' => '/', // PATHINFO模式下,各参数之间的分割符号
'URL_PATHINFO_FETCH' => 'ORIG_PATH_INFO,REDIRECT_PATH_INFO,REDIRECT_URL', // 用于兼容判断PATH_INFO 参数的SERVER替代变量列表
'URL_HTML_SUFFIX' => 'html', // URL伪静态后缀设置
'URL_DENY_SUFFIX' => 'ico|png|gif|jpg', // URL禁止访问的后缀设置
'URL_PARAMS_BIND' => true, // URL变量绑定到Action方法参数
'URL_404_REDIRECT' => '', // 404 跳转页面 部署模式有效
/* 系统变量名称设置 */
'VAR_GROUP' => 'g', // 默认分组获取变量
'VAR_MODULE' => 'm', // 默认模块获取变量
'VAR_ACTION' => 'a', // 默认操作获取变量
'VAR_AJAX_SUBMIT' => 'ajax', // 默认的AJAX提交变量
'VAR_JSONP_HANDLER' => 'callback',
'VAR_PATHINFO' => 's', // PATHINFO 兼容模式获取变量例如 ?s=/module/action/id/1 后面的参数取决于URL_PATHINFO_DEPR
'VAR_URL_PARAMS' => '_URL_', // PATHINFO URL参数变量
'VAR_TEMPLATE' => 't', // 默认模板切换变量
'VAR_FILTERS' => 'filter_exp', // 全局系统变量的默认过滤方法 多个用逗号分割
'OUTPUT_ENCODE' => false, // 页面压缩输出
'HTTP_CACHE_CONTROL' => 'private', // 网页缓存控制
);
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
/**
* ThinkPHP 默认的调试模式配置文件
* 如果项目有定义自己的调试模式配置文件,本文件无效
* @category Think
* @package Common
* @author liu21st <liu21st@gmail.com>
* @version $Id: debug.php 3071 2012-07-15 07:59:23Z liu21st@gmail.com $
*/
defined('THINK_PATH') or exit();
// 调试模式下面默认设置 可以在项目配置目录下重新定义 debug.php 覆盖
return array(
'LOG_RECORD' => true, // 进行日志记录
'LOG_EXCEPTION_RECORD' => true, // 是否记录异常信息日志
'LOG_LEVEL' => 'EMERG,ALERT,CRIT,ERR,WARN,NOTIC,INFO,DEBUG,SQL', // 允许记录的日志级别
'DB_FIELDS_CACHE' => false, // 字段缓存信息
'DB_SQL_LOG' => true, // 记录SQL信息
'APP_FILE_CASE' => true, // 是否检查文件的大小写 对Windows平台有效
'TMPL_CACHE_ON' => false, // 是否开启模板编译缓存,设为false则每次都会重新编译
'TMPL_STRIP_SPACE' => false, // 是否去除模板文件里面的html空格与换行
'SHOW_ERROR_MSG' => true, // 显示错误信息
);
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
// 系统默认的核心行为扩展列表文件
return array(
'app_init' => array(
),
'app_begin' => array(
'ReadHtmlCache', // 读取静态缓存
),
'route_check' => array(
'CheckRoute', // 路由检测
),
'app_end' => array(),
'path_info' => array(),
'action_begin' => array(),
'action_end' => array(),
'view_begin' => array(),
'view_parse' => array(
'ParseTemplate', // 模板解析 支持PHP、内置模板引擎和第三方模板引擎
),
'view_filter' => array(
'ContentReplace', // 模板输出替换
'TokenBuild', // 表单令牌
'WriteHtmlCache', // 写入静态缓存
'ShowRuntime', // 运行时间显示
),
'view_end' => array(
'ShowPageTrace', // 页面Trace显示
),
);
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* 行为扩展:代理检测
* @category Extend
* @package Extend
* @subpackage Behavior
* @author liu21st <liu21st@gmail.com>
*/
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');
}
}
}
?>
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* 浏览器防刷新检测
* @category Extend
* @package Extend
* @subpackage Behavior
* @author liu21st <liu21st@gmail.com>
*/
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('_last_visit_time_'.$guid) && cookie('_last_visit_time_'.$guid)>time()-C('LIMIT_REFLESH_TIMES')) {
// 页面刷新读取浏览器缓存
header('HTTP/1.1 304 Not Modified');
exit;
}else{
// 缓存当前地址访问时间
cookie('_last_visit_time_'.$guid, $_SERVER['REQUEST_TIME']);
//header('Last-Modified:'.(date('D,d M Y H:i:s',$_SERVER['REQUEST_TIME']-C('LIMIT_REFLESH_TIMES'))).' GMT');
}
}
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* 系统行为扩展:操作路由检测
* @category Think
* @package Think
* @subpackage Behavior
* @author liu21st <liu21st@gmail.com>
*/
class CheckActionRouteBehavior extends Behavior {
// 行为扩展的执行入口必须是run
public function run(&$config){
// 优先检测是否存在PATH_INFO
$regx = trim($_SERVER['PATH_INFO'],'/');
if(empty($regx)) return ;
// 路由定义文件优先于config中的配置定义
// 路由处理
$routes = $config['routes'];
if(!empty($routes)) {
$depr = C('URL_PATHINFO_DEPR');
// 分隔符替换 确保路由定义使用统一的分隔符
$regx = str_replace($depr,'/',$regx);
$regx = substr_replace($regx,'',0,strlen(__URL__));
foreach ($routes as $rule=>$route){
if(0===strpos($rule,'/') && preg_match($rule,$regx,$matches)) { // 正则路由
return C('ACTION_NAME',$this->parseRegex($matches,$route,$regx));
}else{ // 规则路由
$len1 = substr_count($regx,'/');
$len2 = substr_count($rule,'/');
if($len1>=$len2) {
if('$' == substr($rule,-1,1)) {// 完整匹配
if($len1 != $len2) {
continue;
}else{
$rule = substr($rule,0,-1);
}
}
$match = $this->checkUrlMatch($regx,$rule);
if($match) return C('ACTION_NAME',$this->parseRule($rule,$route,$regx));
}
}
}
}
}
// 检测URL和规则路由是否匹配
private function checkUrlMatch($regx,$rule) {
$m1 = explode('/',$regx);
$m2 = explode('/',$rule);
$match = true; // 是否匹配
foreach ($m2 as $key=>$val){
if(':' == substr($val,0,1)) {// 动态变量
if(strpos($val,'\\')) {
$type = substr($val,-1);
if('d'==$type && !is_numeric($m1[$key])) {
$match = false;
break;
}
}elseif(strpos($val,'^')){
$array = explode('|',substr(strstr($val,'^'),1));
if(in_array($m1[$key],$array)) {
$match = false;
break;
}
}
}elseif(0 !== strcasecmp($val,$m1[$key])){
$match = false;
break;
}
}
return $match;
}
// 解析规范的路由地址
// 地址格式 操作?参数1=值1&参数2=值2...
private function parseUrl($url) {
$var = array();
if(false !== strpos($url,'?')) { // 操作?参数1=值1&参数2=值2...
$info = parse_url($url);
$path = $info['path'];
parse_str($info['query'],$var);
}else{ // 操作
$path = $url;
}
$var[C('VAR_ACTION')] = $path;
return $var;
}
// 解析规则路由
// '路由规则'=>'操作?额外参数1=值1&额外参数2=值2...'
// '路由规则'=>array('操作','额外参数1=值1&额外参数2=值2...')
// '路由规则'=>'外部地址'
// '路由规则'=>array('外部地址','重定向代码')
// 路由规则中 :开头 表示动态变量
// 外部地址中可以用动态变量 采用 :1 :2 的方式
// 'news/:month/:day/:id'=>array('News/read?cate=1','status=1'),
// 'new/:id'=>array('/new.php?id=:1',301), 重定向
private function parseRule($rule,$route,$regx) {
// 获取路由地址规则
$url = is_array($route)?$route[0]:$route;
// 获取URL地址中的参数
$paths = explode('/',$regx);
// 解析路由规则
$matches = array();
$rule = explode('/',$rule);
foreach ($rule as $item){
if(0===strpos($item,':')) { // 动态变量获取
if($pos = strpos($item,'^') ) {
$var = substr($item,1,$pos-1);
}elseif(strpos($item,'\\')){
$var = substr($item,1,-2);
}else{
$var = substr($item,1);
}
$matches[$var] = array_shift($paths);
}else{ // 过滤URL中的静态变量
array_shift($paths);
}
}
if(0=== strpos($url,'/') || 0===strpos($url,'http')) { // 路由重定向跳转
if(strpos($url,':')) { // 传递动态参数
$values = array_values($matches);
$url = preg_replace('/:(\d+)/e','$values[\\1-1]',$url);
}
header("Location: $url", true,(is_array($route) && isset($route[1]))?$route[1]:301);
exit;
}else{
// 解析路由地址
$var = $this->parseUrl($url);
// 解析路由地址里面的动态参数
$values = array_values($matches);
foreach ($var as $key=>$val){
if(0===strpos($val,':')) {
$var[$key] = $values[substr($val,1)-1];
}
}
$var = array_merge($matches,$var);
// 解析剩余的URL参数
if($paths) {
preg_replace('@(\w+)\/([^\/]+)@e', '$var[strtolower(\'\\1\')]=strip_tags(\'\\2\');', implode('/',$paths));
}
// 解析路由自动传人参数
if(is_array($route) && isset($route[1])) {
parse_str($route[1],$params);
$var = array_merge($var,$params);
}
$action = $var[C('VAR_ACTION')];
unset($var[C('VAR_ACTION')]);
$_GET = array_merge($var,$_GET);
return $action;
}
}
// 解析正则路由
// '路由正则'=>'[分组/模块/操作]?参数1=值1&参数2=值2...'
// '路由正则'=>array('[分组/模块/操作]?参数1=值1&参数2=值2...','额外参数1=值1&额外参数2=值2...')
// '路由正则'=>'外部地址'
// '路由正则'=>array('外部地址','重定向代码')
// 参数值和外部地址中可以用动态变量 采用 :1 :2 的方式
// '/new\/(\d+)\/(\d+)/'=>array('News/read?id=:1&page=:2&cate=1','status=1'),
// '/new\/(\d+)/'=>array('/new.php?id=:1&page=:2&status=1','301'), 重定向
private function parseRegex($matches,$route,$regx) {
// 获取路由地址规则
$url = is_array($route)?$route[0]:$route;
$url = preg_replace('/:(\d+)/e','$matches[\\1]',$url);
if(0=== strpos($url,'/') || 0===strpos($url,'http')) { // 路由重定向跳转
header("Location: $url", true,(is_array($route) && isset($route[1]))?$route[1]:301);
exit;
}else{
// 解析路由地址
$var = $this->parseUrl($url);
// 解析剩余的URL参数
$regx = substr_replace($regx,'',0,strlen($matches[0]));
if($regx) {
preg_replace('@(\w+)\/([^,\/]+)@e', '$var[strtolower(\'\\1\')]=strip_tags(\'\\2\');', $regx);
}
// 解析路由自动传人参数
if(is_array($route) && isset($route[1])) {
parse_str($route[1],$params);
$var = array_merge($var,$params);
}
$action = $var[C('VAR_ACTION')];
unset($var[C('VAR_ACTION')]);
$_GET = array_merge($var,$_GET);
}
return $action;
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* 语言检测 并自动加载语言包
* @category Extend
* @package Extend
* @subpackage Behavior
* @author liu21st <liu21st@gmail.com>
*/
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\d\-]+)/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));
$group = '';
$path = (defined('GROUP_NAME') && C('APP_GROUP_MODE')==1) ? BASE_LIB_PATH.'Lang/'.LANG_SET.'/' : LANG_PATH.LANG_SET.'/';
// 读取项目公共语言包
if(is_file(LANG_PATH.LANG_SET.'/common.php'))
L(include LANG_PATH.LANG_SET.'/common.php');
// 读取分组公共语言包
if(defined('GROUP_NAME')){
if(C('APP_GROUP_MODE')==1){ // 独立分组
$file = $path.'common.php';
}else{ // 普通分组
$file = $path.GROUP_NAME.'.php';
$group = GROUP_NAME.C('TMPL_FILE_DEPR');
}
if(is_file($file))
L(include $file);
}
// 读取当前模块语言包
if (is_file($path.$group.strtolower(MODULE_NAME).'.php'))
L(include $path.$group.strtolower(MODULE_NAME).'.php');
}
}
<?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>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* 自动执行任务
* @category Extend
* @package Extend
* @subpackage Behavior
* @author liu21st <liu21st@gmail.com>
*/
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 ;
}
}
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* 机器人检测
* @category Extend
* @package Extend
* @subpackage Behavior
* @author liu21st <liu21st@gmail.com>
*/
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;
}
}
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* 升级短信通知, 如果有ThinkPHP新版升级,或者重要的更新,会发送短信通知你。
* 需要使用SAE的短信服务。请先找一个SAE的应用开通短信服务。
* 使用步骤如下:
* 1,在项目的Conf目录下建立tags.php配置文件,内容如下:
* <code>
* <?php
* return array(
* 'app_init' => array('UpgradeNotice')
* );
* </code>
*
* 2,将此文件放在项目的Lib/Behavior文件夹下。
*注:在SAE上面使用时,以上两步可以省略
* 3,在config.php中配置:
* 'UPGRADE_NOTICE_ON'=>true,//开启短信升级提醒功能
* 'UPGRADE_NOTICE_AKEY'=>'your akey',//SAE应用的AKEY,如果在SAE上使用可以不填
* 'UPGRADE_NOTICE_SKEY'=>'your skey',//SAE应用的SKEY,如果在SAE上使用可以不填
*'UPGRADE_NOTICE_MOBILE'=>'136456789',//接受短信的手机号
*'UPGRADE_NOTICE_CHECK_INTERVAL' => 604800,//检测频率,单位秒,默认是一周
*'UPGRADE_CURRENT_VERSION'=>'0',//升级后的版本号,会在短信中告诉你填写什么
*UPGRADE_NOTICE_DEBUG=>true, //调试默认,如果为true,UPGRADE_NOTICE_CHECK_INTERVAL配置不起作用,每次都会进行版本检查,此时用于调试,调试完毕后请设置次配置为false
*
*/
class UpgradeNoticeBehavior extends Behavior {
// 行为参数定义(默认值) 可在项目配置中覆盖
protected $options = array(
'UPGRADE_NOTICE_ON' => false, // 是否开启升级提醒
'UPGRADE_NOTICE_DEBUG'=>false,
'UPGRADE_NOTICE_QUEUE'=>'',//队列名称, 在SAE平台上设置
'UPGRADE_NOTICE_AKEY' => '', //SAE应用的AKEY
'UPGRADE_NOTICE_SKEY' => '', //SAE应用的SKEY
'UPGRADE_NOTICE_MOBILE' => '', //接受短信的手机号
'UPGRADE_CURRENT_VERSION'=>'0',
'UPGRADE_NOTICE_CHECK_INTERVAL' => 604800, //检测频率,单位秒,默认是一周
);
protected $header_ = '';
protected $httpCode_;
protected $httpDesc_;
protected $accesskey_;
protected $secretkey_;
public function run(&$params) {
if (C('UPGRADE_NOTICE_ON') && (!S('think_upgrade_interval') || C('UPGRADE_NOTICE_DEBUG'))) {
if(IS_SAE && C('UPGRADE_NOTICE_QUEUE') && !isset($_POST['think_upgrade_queque'])){
$queue=new SaeTaskQueue(C('UPGRADE_NOTICE_QUEUE'));
$queue->addTask('http://'.$_SERVER['HTTP_HOST'].__APP__,'think_upgrade_queque=1');
if(!$queue->push()){
trace('升级提醒队列执行失败,错误原因:'.$queue->errmsg(), '升级通知出错', 'NOTIC', true);
}
return ;
}
$akey = C('UPGRADE_NOTICE_AKEY');
$skey = C('UPGRADE_NOTICE_SKEY');
$this->accesskey_ = $akey ? $akey : (defined('SAE_ACCESSKEY') ? SAE_ACCESSKEY : '');
$this->secretkey_ = $skey ? $skey : (defined('SAE_SECRETKEY') ? SAE_SECRETKEY : '');
$current_version = C('UPGRADE_CURRENT_VERSION');
//读取接口
$info = $this->send('http://sinaclouds.sinaapp.com/thinkapi/upgrade.php?v=' . $current_version);
if ($info['version'] != $current_version) {
if($this->send_sms($info['msg'])) trace($info['msg'], '升级通知成功', 'NOTIC', true); //发送升级短信
}
S('think_upgrade_interval', true, C('UPGRADE_NOTICE_CHECK_INTERVAL'));
}
}
private function send_sms($msg) {
$timestamp=time();
$url = 'http://inno.smsinter.sina.com.cn/sae_sms_service/sendsms.php'; //发送短信的接口地址
$content = "FetchUrl" . $url . "TimeStamp" . $timestamp . "AccessKey" . $this->accesskey_;
$signature = (base64_encode(hash_hmac('sha256', $content, $this->secretkey_, true)));
$headers = array(
"FetchUrl: $url",
"AccessKey: ".$this->accesskey_,
"TimeStamp: " . $timestamp,
"Signature: $signature"
);
$data = array(
'mobile' => C('UPGRADE_NOTICE_MOBILE') ,
'msg' => $msg,
'encoding' => 'UTF-8'
);
if(!$ret = $this->send('http://g.apibus.io', $data, $headers)){
return false;
}
if (isset($ret['ApiBusError'])) {
trace('errno:' . $ret['ApiBusError']['errcode'] . ',errmsg:' . $ret['ApiBusError']['errdesc'], '升级通知出错', 'NOTIC', true);
return false;
}
return true;
}
private function send($url, $params = array() , $headers = array()) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if (!empty($params)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
if (!empty($headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$txt = curl_exec($ch);
if (curl_errno($ch)) {
trace(curl_error($ch) , '升级通知出错', 'NOTIC', true);
return false;
}
curl_close($ch);
$ret = json_decode($txt, true);
if (!$ret) {
trace('接口[' . $url . ']返回格式不正确', '升级通知出错', 'NOTIC', true);
return false;
}
return $ret;
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* Apachenote缓存驱动
* @category Extend
* @package Extend
* @subpackage Driver
* @author liu21st <liu21st@gmail.com>
*/
class CacheApachenote extends Cache {
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options=array()) {
if(!empty($options)) {
$this->options = $options;
}
if(empty($options)) {
$options = array (
'host' => '127.0.0.1',
'port' => 1042,
'timeout' => 10,
);
}
$this->options = $options;
$this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX');
$this->options['length'] = isset($options['length'])? $options['length'] : 0;
$this->handler = null;
$this->open();
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name) {
$this->open();
$name = $this->options['prefix'].$name;
$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);
$name = $this->options['prefix'].$name;
$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();
$name = $this->options['prefix'].$name;
$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']);
}
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* Apc缓存驱动
* @category Extend
* @package Extend
* @subpackage Driver.Cache
* @author liu21st <liu21st@gmail.com>
*/
class CacheApc extends Cache {
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options=array()) {
if(!function_exists('apc_cache_info')) {
throw_exception(L('_NOT_SUPPERT_').':Apc');
}
$this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX');
$this->options['length'] = isset($options['length'])? $options['length'] : 0;
$this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME');
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name) {
N('cache_read',1);
return apc_fetch($this->options['prefix'].$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'];
}
$name = $this->options['prefix'].$name;
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($this->options['prefix'].$name);
}
/**
* 清除缓存
* @access public
* @return boolen
*/
public function clear() {
return apc_clear_cache();
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* 数据库方式缓存驱动
* CREATE TABLE think_cache (
* cachekey varchar(255) NOT NULL,
* expire int(11) NOT NULL,
* data blob,
* datacrc int(32),
* UNIQUE KEY `cachekey` (`cachekey`)
* );
* @category Extend
* @package Extend
* @subpackage Driver.Cache
* @author liu21st <liu21st@gmail.com>
*/
class CacheDb extends Cache {
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options=array()) {
if(empty($options)) {
$options = array (
'table' => C('DATA_CACHE_TABLE'),
);
}
$this->options = $options;
$this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX');
$this->options['length'] = isset($options['length'])? $options['length'] : 0;
$this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME');
import('Db');
$this->handler = DB::getInstance();
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name) {
$name = $this->options['prefix'].addslashes($name);
N('cache_read',1);
$result = $this->handler->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 = $this->options['prefix'].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->handler->query('select `cachekey` from `'.$this->options['table'].'` where `cachekey`=\''.$name.'\' limit 0,1');
if(!empty($result) ) {
//更新记录
$result = $this->handler->execute('UPDATE '.$this->options['table'].' SET data=\''.$data.'\' ,datacrc=\''.$crc.'\',expire='.$expire.' WHERE `cachekey`=\''.$name.'\'');
}else {
//新增记录
$result = $this->handler->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 = $this->options['prefix'].addslashes($name);
return $this->handler->execute('DELETE FROM `'.$this->options['table'].'` WHERE `cachekey`=\''.$name.'\'');
}
/**
* 清除缓存
* @access public
* @return boolen
*/
public function clear() {
return $this->handler->execute('TRUNCATE TABLE `'.$this->options['table'].'`');
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* Eaccelerator缓存驱动
* @category Extend
* @package Extend
* @subpackage Driver.Cache
* @author liu21st <liu21st@gmail.com>
*/
class CacheEaccelerator extends Cache {
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options=array()) {
$this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME');
$this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX');
$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($this->options['prefix'].$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'];
}
$name = $this->options['prefix'].$name;
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($this->options['prefix'].$name);
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* Memcache缓存驱动
* @category Extend
* @package Extend
* @subpackage Driver.Cache
* @author liu21st <liu21st@gmail.com>
*/
class CacheMemcache extends Cache {
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
function __construct($options=array()) {
if ( !extension_loaded('memcache') ) {
throw_exception(L('_NOT_SUPPERT_').':memcache');
}
$options = array_merge(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,
),$options);
$this->options = $options;
$this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME');
$this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX');
$this->options['length'] = isset($options['length'])? $options['length'] : 0;
$func = $options['persistent'] ? 'pconnect' : 'connect';
$this->handler = new Memcache;
$options['timeout'] === false ?
$this->handler->$func($options['host'], $options['port']) :
$this->handler->$func($options['host'], $options['port'], $options['timeout']);
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name) {
N('cache_read',1);
return $this->handler->get($this->options['prefix'].$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'];
}
$name = $this->options['prefix'].$name;
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) {
$name = $this->options['prefix'].$name;
return $ttl === false ?
$this->handler->delete($name) :
$this->handler->delete($name, $ttl);
}
/**
* 清除缓存
* @access public
* @return boolen
*/
public function clear() {
return $this->handler->flush();
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* Redis缓存驱动
* 要求安装phpredis扩展:https://github.com/nicolasff/phpredis
* @category Extend
* @package Extend
* @subpackage Driver.Cache
* @author 尘缘 <130775@qq.com>
*/
class CacheRedis extends Cache {
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options=array()) {
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,
);
}
$this->options = $options;
$this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME');
$this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX');
$this->options['length'] = isset($options['length'])? $options['length'] : 0;
$func = $options['persistent'] ? 'pconnect' : 'connect';
$this->handler = new Redis;
$options['timeout'] === false ?
$this->handler->$func($options['host'], $options['port']) :
$this->handler->$func($options['host'], $options['port'], $options['timeout']);
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name) {
N('cache_read',1);
$value = $this->handler->get($this->options['prefix'].$name);
$jsonData = json_decode( $value, true );
return ($jsonData === NULL) ? $value : $jsonData; //检测是否为JSON数据 true 返回JSON解析数组, 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'];
}
$name = $this->options['prefix'].$name;
//对数组/对象数据进行缓存处理,保证数据完整性
$value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;
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($this->options['prefix'].$name);
}
/**
* 清除缓存
* @access public
* @return boolen
*/
public function clear() {
return $this->handler->flushDB();
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* Shmop缓存驱动
* @category Extend
* @package Extend
* @subpackage Driver.Cache
* @author liu21st <liu21st@gmail.com>
*/
class CacheShmop extends Cache {
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options=array()) {
if ( !extension_loaded('shmop') ) {
throw_exception(L('_NOT_SUPPERT_').':shmop');
}
if(!empty($options)){
$options = array(
'size' => C('SHARE_MEM_SIZE'),
'temp' => TEMP_PATH,
'project' => 's',
'length' => 0,
);
}
$this->options = $options;
$this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX');
$this->options['length'] = isset($options['length'])? $options['length'] : 0;
$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;
}
$name = $this->options['prefix'].$name;
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);
}
$name = $this->options['prefix'].$name;
$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();
$name = $this->options['prefix'].$name;
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['temp'].$this->options['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);
}
}
}
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* Sqlite缓存驱动
* @category Extend
* @package Extend
* @subpackage Driver.Cache
* @author liu21st <liu21st@gmail.com>
*/
class CacheSqlite extends Cache {
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options=array()) {
if ( !extension_loaded('sqlite') ) {
throw_exception(L('_NOT_SUPPERT_').':sqlite');
}
if(empty($options)) {
$options = array (
'db' => ':memory:',
'table' => 'sharedmemory',
);
}
$this->options = $options;
$this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX');
$this->options['length'] = isset($options['length'])? $options['length'] : 0;
$this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME');
$func = $this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open';
$this->handler = $func($this->options['db']);
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name) {
N('cache_read',1);
$name = $this->options['prefix'].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);
$name = $this->options['prefix'].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 = $this->options['prefix'].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 ;
}
}
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* Wincache缓存驱动
* @category Extend
* @package Extend
* @subpackage Driver.Cache
* @author liu21st <liu21st@gmail.com>
*/
class CacheWincache extends Cache {
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options=array()) {
if ( !function_exists('wincache_ucache_info') ) {
throw_exception(L('_NOT_SUPPERT_').':WinCache');
}
$this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME');
$this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX');
$this->options['length'] = isset($options['length'])? $options['length'] : 0;
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name) {
N('cache_read',1);
$name = $this->options['prefix'].$name;
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'];
}
$name = $this->options['prefix'].$name;
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($this->options['prefix'].$name);
}
}
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* Xcache缓存驱动
* @category Extend
* @package Extend
* @subpackage Driver.Cache
* @author liu21st <liu21st@gmail.com>
*/
class CacheXcache extends Cache {
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options=array()) {
if ( !function_exists('xcache_info') ) {
throw_exception(L('_NOT_SUPPERT_').':Xcache');
}
$this->options['expire'] = isset($options['expire'])?$options['expire']:C('DATA_CACHE_TIME');
$this->options['prefix'] = isset($options['prefix'])?$options['prefix']:C('DATA_CACHE_PREFIX');
$this->options['length'] = isset($options['length'])?$options['length']:0;
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name) {
N('cache_read',1);
$name = $this->options['prefix'].$name;
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'] ;
}
$name = $this->options['prefix'].$name;
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($this->options['prefix'].$name);
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* Pgsql数据库驱动
* @category Extend
* @package Extend
* @subpackage Driver.Db
* @author liu21st <liu21st@gmail.com>
*/
class DbPgsql extends Db{
/**
* 架构函数 读取数据库配置信息
* @access public
* @param array $config 数据库配置数组
*/
public function __construct($config='') {
if ( !extension_loaded('pgsql') ) {
throw_exception(L('_NOT_SUPPERT_').':pgsql');
}
if(!empty($config)) {
$this->config = $config;
if(empty($this->config['params'])) {
$this->config['params'] = array();
}
}
}
/**
* 连接数据库方法
* @access public
*/
public function connect($config='',$linkNum=0) {
if ( !isset($this->linkID[$linkNum]) ) {
if(empty($config)) $config = $this->config;
$pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;
$conn = $pconnect ? 'pg_pconnect':'pg_connect';
$this->linkID[$linkNum] = $conn('host='.$config['hostname'].' port='.$config['hostport'].' dbname='.$config['database'].' user='.$config['username'].' password='.$config['password']);
if (0 !== pg_connection_status($this->linkID[$linkNum])){
throw_exception($this->error(false));
}
//设置编码
pg_set_client_encoding($this->linkID[$linkNum], C('DB_CHARSET'));
//$pgInfo = pg_version($this->linkID[$linkNum]);
//$dbVersion = $pgInfo['server'];
// 标记连接成功
$this->connected = true;
//注销数据库安全信息
if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
}
return $this->linkID[$linkNum];
}
/**
* 释放查询结果
* @access public
*/
public function free() {
pg_free_result($this->queryID);
$this->queryID = null;
}
/**
* 执行查询 返回数据集
* @access public
* @param string $str sql指令
* @return mixed
*/
public function query($str) {
$this->initConnect(false);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID = pg_query($this->_linkID,$str);
$this->debug();
if ( false === $this->queryID ) {
$this->error();
return false;
} else {
$this->numRows = pg_num_rows($this->queryID);
return $this->getAll();
}
}
/**
* 执行语句
* @access public
* @param string $str sql指令
* @return integer
*/
public function execute($str) {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_write',1);
// 记录开始执行时间
G('queryStartTime');
$result = pg_query($this->_linkID,$str);
$this->debug();
if ( false === $result ) {
$this->error();
return false;
} else {
$this->numRows = pg_affected_rows($result);
$this->lastInsID = $this->last_insert_id();
return $this->numRows;
}
}
/**
* 用于获取最后插入的ID
* @access public
* @return integer
*/
public function last_insert_id() {
$query = "SELECT LASTVAL() AS insert_id";
$result = pg_query($this->_linkID,$query);
list($last_insert_id) = pg_fetch_array($result,null,PGSQL_ASSOC);
pg_free_result($result);
return $last_insert_id;
}
/**
* 启动事务
* @access public
* @return void
*/
public function startTrans() {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
//数据rollback 支持
if ($this->transTimes == 0) {
pg_exec($this->_linkID,'begin;');
}
$this->transTimes++;
return ;
}
/**
* 用于非自动提交状态下面的查询提交
* @access public
* @return boolen
*/
public function commit() {
if ($this->transTimes > 0) {
$result = pg_exec($this->_linkID,'end;');
if(!$result){
$this->error();
return false;
}
$this->transTimes = 0;
}
return true;
}
/**
* 事务回滚
* @access public
* @return boolen
*/
public function rollback() {
if ($this->transTimes > 0) {
$result = pg_exec($this->_linkID,'abort;');
if(!$result){
$this->error();
return false;
}
$this->transTimes = 0;
}
return true;
}
/**
* 获得所有的查询数据
* @access private
* @return array
*/
private function getAll() {
//返回数据集
$result = pg_fetch_all($this->queryID);
pg_result_seek($this->queryID,0);
return $result;
}
/**
* 取得数据表的字段信息
* @access public
*/
public function getFields($tableName) {
$result = $this->query("select a.attname as \"Field\",
t.typname as \"Type\",
a.attnotnull as \"Null\",
i.indisprimary as \"Key\",
d.adsrc as \"Default\"
from pg_class c
inner join pg_attribute a on a.attrelid = c.oid
inner join pg_type t on a.atttypid = t.oid
left join pg_attrdef d on a.attrelid=d.adrelid and d.adnum=a.attnum
left join pg_index i on a.attnum=ANY(i.indkey) and c.oid = i.indrelid
where (c.relname='{$tableName}' or c.relname = lower('{$tableName}')) AND a.attnum > 0
order by a.attnum asc;");
$info = array();
if($result) {
foreach ($result as $key => $val) {
$info[$val['Field']] = array(
'name' => $val['Field'],
'type' => $val['Type'],
'notnull' => (bool) ($val['Null'] == 't'?1:0), // 't' is 'not null'
'default' => $val['Default'],
'primary' => (strtolower($val['Key']) == 't'),
'autoinc' => (strtolower($val['Default']) == "nextval('{$tableName}_id_seq'::regclass)"),
);
}
}
return $info;
}
/**
* 取得数据库的表信息
* @access public
*/
public function getTables($dbName='') {
$result = $this->query("select tablename as Tables_in_test from pg_tables where schemaname ='public'");
$info = array();
foreach ($result as $key => $val) {
$info[$key] = current($val);
}
return $info;
}
/**
* 关闭数据库
* @access public
*/
public function close() {
if($this->_linkID){
pg_close($this->_linkID);
}
$this->_linkID = null;
}
/**
* 数据库错误信息
* 并显示当前的SQL语句
* @access public
* @return string
*/
public function error($result = true) {
$this->error = $result?pg_result_error($this->queryID): pg_last_error($this->_linkID);
if('' != $this->queryStr){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
trace($this->error,'','ERR');
return $this->error;
}
/**
* SQL指令安全过滤
* @access public
* @param string $str SQL指令
* @return string
*/
public function escapeString($str) {
return pg_escape_string($str);
}
/**
* limit
* @access public
* @return string
*/
public function parseLimit($limit) {
$limitStr = '';
if(!empty($limit)) {
$limit = explode(',',$limit);
if(count($limit)>1) {
$limitStr .= ' LIMIT '.$limit[1].' OFFSET '.$limit[0].' ';
}else{
$limitStr .= ' LIMIT '.$limit[0].' ';
}
}
return $limitStr;
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* Sqlite数据库驱动
* @category Extend
* @package Extend
* @subpackage Driver.Db
* @author liu21st <liu21st@gmail.com>
*/
class DbSqlite extends Db {
/**
* 架构函数 读取数据库配置信息
* @access public
* @param array $config 数据库配置数组
*/
public function __construct($config='') {
if ( !extension_loaded('sqlite') ) {
throw_exception(L('_NOT_SUPPERT_').':sqlite');
}
if(!empty($config)) {
if(!isset($config['mode'])) {
$config['mode'] = 0666;
}
$this->config = $config;
if(empty($this->config['params'])) {
$this->config['params'] = array();
}
}
}
/**
* 连接数据库方法
* @access public
*/
public function connect($config='',$linkNum=0) {
if ( !isset($this->linkID[$linkNum]) ) {
if(empty($config)) $config = $this->config;
$pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;
$conn = $pconnect ? 'sqlite_popen':'sqlite_open';
$this->linkID[$linkNum] = $conn($config['database'],$config['mode']);
if ( !$this->linkID[$linkNum]) {
throw_exception(sqlite_error_string());
}
// 标记连接成功
$this->connected = true;
//注销数据库安全信息
if(1 != C('DB_DEPLOY_TYPE')) unset($this->config);
}
return $this->linkID[$linkNum];
}
/**
* 释放查询结果
* @access public
*/
public function free() {
$this->queryID = null;
}
/**
* 执行查询 返回数据集
* @access public
* @param string $str sql指令
* @return mixed
*/
public function query($str) {
$this->initConnect(false);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID = sqlite_query($this->_linkID,$str);
$this->debug();
if ( false === $this->queryID ) {
$this->error();
return false;
} else {
$this->numRows = sqlite_num_rows($this->queryID);
return $this->getAll();
}
}
/**
* 执行语句
* @access public
* @param string $str sql指令
* @return integer
*/
public function execute($str) {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) $this->free();
N('db_write',1);
// 记录开始执行时间
G('queryStartTime');
$result = sqlite_exec($this->_linkID,$str);
$this->debug();
if ( false === $result ) {
$this->error();
return false;
} else {
$this->numRows = sqlite_changes($this->_linkID);
$this->lastInsID = sqlite_last_insert_rowid($this->_linkID);
return $this->numRows;
}
}
/**
* 启动事务
* @access public
* @return void
*/
public function startTrans() {
$this->initConnect(true);
if ( !$this->_linkID ) return false;
//数据rollback 支持
if ($this->transTimes == 0) {
sqlite_query($this->_linkID,'BEGIN TRANSACTION');
}
$this->transTimes++;
return ;
}
/**
* 用于非自动提交状态下面的查询提交
* @access public
* @return boolen
*/
public function commit() {
if ($this->transTimes > 0) {
$result = sqlite_query($this->_linkID,'COMMIT TRANSACTION');
if(!$result){
$this->error();
return false;
}
$this->transTimes = 0;
}
return true;
}
/**
* 事务回滚
* @access public
* @return boolen
*/
public function rollback() {
if ($this->transTimes > 0) {
$result = sqlite_query($this->_linkID,'ROLLBACK TRANSACTION');
if(!$result){
$this->error();
return false;
}
$this->transTimes = 0;
}
return true;
}
/**
* 获得所有的查询数据
* @access private
* @return array
*/
private function getAll() {
//返回数据集
$result = array();
if($this->numRows >0) {
for($i=0;$i<$this->numRows ;$i++ ){
// 返回数组集
$result[$i] = sqlite_fetch_array($this->queryID,SQLITE_ASSOC);
}
sqlite_seek($this->queryID,0);
}
return $result;
}
/**
* 取得数据表的字段信息
* @access public
* @return array
*/
public function getFields($tableName) {
$result = $this->query('PRAGMA table_info( '.$tableName.' )');
$info = array();
if($result){
foreach ($result as $key => $val) {
$info[$val['Field']] = array(
'name' => $val['Field'],
'type' => $val['Type'],
'notnull' => (bool) ($val['Null'] === ''), // not null is empty, null is yes
'default' => $val['Default'],
'primary' => (strtolower($val['Key']) == 'pri'),
'autoinc' => (strtolower($val['Extra']) == 'auto_increment'),
);
}
}
return $info;
}
/**
* 取得数据库的表信息
* @access public
* @return array
*/
public function getTables($dbName='') {
$result = $this->query("SELECT name FROM sqlite_master WHERE type='table' "
. "UNION ALL SELECT name FROM sqlite_temp_master "
. "WHERE type='table' ORDER BY name");
$info = array();
foreach ($result as $key => $val) {
$info[$key] = current($val);
}
return $info;
}
/**
* 关闭数据库
* @access public
*/
public function close() {
if ($this->_linkID){
sqlite_close($this->_linkID);
}
$this->_linkID = null;
}
/**
* 数据库错误信息
* 并显示当前的SQL语句
* @access public
* @return string
*/
public function error() {
$code = sqlite_last_error($this->_linkID);
$this->error = $code.':'.sqlite_error_string($code);
if('' != $this->queryStr){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
trace($this->error,'','ERR');
return $this->error;
}
/**
* SQL指令安全过滤
* @access public
* @param string $str SQL指令
* @return string
*/
public function escapeString($str) {
return sqlite_escape_string($str);
}
/**
* limit
* @access public
* @return string
*/
public function parseLimit($limit) {
$limitStr = '';
if(!empty($limit)) {
$limit = explode(',',$limit);
if(count($limit)>1) {
$limitStr .= ' LIMIT '.$limit[1].' OFFSET '.$limit[0].' ';
}else{
$limitStr .= ' LIMIT '.$limit[0].' ';
}
}
return $limitStr;
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* 数据库方式Session驱动
* CREATE TABLE think_session (
* session_id varchar(255) NOT NULL,
* session_expire int(11) NOT NULL,
* session_data blob,
* UNIQUE KEY `session_id` (`session_id`)
* );
* @category Extend
* @package Extend
* @subpackage Driver.Session
* @author liu21st <liu21st@gmail.com>
*/
class SessionDb {
/**
* Session有效时间
*/
protected $lifeTime = '';
/**
* session保存的数据库名
*/
protected $sessionTable = '';
/**
* 数据库句柄
*/
protected $hander = array();
/**
* 打开Session
* @access public
* @param string $savePath
* @param mixed $sessName
*/
public function open($savePath, $sessName) {
$this->lifeTime = C('SESSION_EXPIRE')?C('SESSION_EXPIRE'):ini_get('session.gc_maxlifetime');
$this->sessionTable = C('SESSION_TABLE')?C('SESSION_TABLE'):C("DB_PREFIX")."session";
//分布式数据库
$host = explode(',',C('DB_HOST'));
$port = explode(',',C('DB_PORT'));
$name = explode(',',C('DB_NAME'));
$user = explode(',',C('DB_USER'));
$pwd = explode(',',C('DB_PWD'));
if(1 == C('DB_DEPLOY_TYPE')){
//读写分离
if(C('DB_RW_SEPARATE')){
$w = floor(mt_rand(0,C('DB_MASTER_NUM')-1));
if(is_numeric(C('DB_SLAVE_NO'))){//指定服务器读
$r = C('DB_SLAVE_NO');
}else{
$r = floor(mt_rand(C('DB_MASTER_NUM'),count($host)-1));
}
//主数据库链接
$hander = mysql_connect(
$host[$w].(isset($port[$w])?':'.$port[$w]:':'.$port[0]),
isset($user[$w])?$user[$w]:$user[0],
isset($pwd[$w])?$pwd[$w]:$pwd[0]
);
$dbSel = mysql_select_db(
isset($name[$w])?$name[$w]:$name[0]
,$hander);
if(!$hander || !$dbSel)
return false;
$this->hander[0] = $hander;
//从数据库链接
$hander = mysql_connect(
$host[$r].(isset($port[$r])?':'.$port[$r]:':'.$port[0]),
isset($user[$r])?$user[$r]:$user[0],
isset($pwd[$r])?$pwd[$r]:$pwd[0]
);
$dbSel = mysql_select_db(
isset($name[$r])?$name[$r]:$name[0]
,$hander);
if(!$hander || !$dbSel)
return false;
$this->hander[1] = $hander;
return true;
}
}
//从数据库链接
$r = floor(mt_rand(0,count($host)-1));
$hander = mysql_connect(
$host[$r].(isset($port[$r])?':'.$port[$r]:':'.$port[0]),
isset($user[$r])?$user[$r]:$user[0],
isset($pwd[$r])?$pwd[$r]:$pwd[0]
);
$dbSel = mysql_select_db(
isset($name[$r])?$name[$r]:$name[0]
,$hander);
if(!$hander || !$dbSel)
return false;
$this->hander = $hander;
return true;
}
/**
* 关闭Session
* @access public
*/
public function close() {
if(is_array($this->hander)){
$this->gc($this->lifeTime);
return (mysql_close($this->hander[0]) && mysql_close($this->hander[1]));
}
$this->gc($this->lifeTime);
return mysql_close($this->hander);
}
/**
* 读取Session
* @access public
* @param string $sessID
*/
public function read($sessID) {
$hander = is_array($this->hander)?$this->hander[1]:$this->hander;
$res = mysql_query("SELECT session_data AS data FROM ".$this->sessionTable." WHERE session_id = '$sessID' AND session_expire >".time(),$hander);
if($res) {
$row = mysql_fetch_assoc($res);
return $row['data'];
}
return "";
}
/**
* 写入Session
* @access public
* @param string $sessID
* @param String $sessData
*/
public function write($sessID,$sessData) {
$hander = is_array($this->hander)?$this->hander[0]:$this->hander;
$expire = time() + $this->lifeTime;
mysql_query("REPLACE INTO ".$this->sessionTable." ( session_id, session_expire, session_data) VALUES( '$sessID', '$expire', '$sessData')",$hander);
if(mysql_affected_rows($hander))
return true;
return false;
}
/**
* 删除Session
* @access public
* @param string $sessID
*/
public function destroy($sessID) {
$hander = is_array($this->hander)?$this->hander[0]:$this->hander;
mysql_query("DELETE FROM ".$this->sessionTable." WHERE session_id = '$sessID'",$hander);
if(mysql_affected_rows($hander))
return true;
return false;
}
/**
* Session 垃圾回收
* @access public
* @param string $sessMaxLifeTime
*/
public function gc($sessMaxLifeTime) {
$hander = is_array($this->hander)?$this->hander[0]:$this->hander;
mysql_query("DELETE FROM ".$this->sessionTable." WHERE session_expire < ".time(),$hander);
return mysql_affected_rows($hander);
}
/**
* 打开Session
* @access public
*/
public function execute() {
session_set_save_handler(array(&$this,"open"),
array(&$this,"close"),
array(&$this,"read"),
array(&$this,"write"),
array(&$this,"destroy"),
array(&$this,"gc"));
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* EaseTemplate模板引擎驱动
* @category Extend
* @package Extend
* @subpackage Driver.Template
* @author liu21st <liu21st@gmail.com>
*/
class TemplateEase {
/**
* 渲染模板输出
* @access public
* @param string $templateFile 模板文件名
* @param array $var 模板变量
* @return void
*/
public function fetch($templateFile,$var) {
$templateFile = substr($templateFile,strlen(THEME_PATH),-5);
$CacheDir = substr(CACHE_PATH,0,-1);
$TemplateDir = substr(THEME_PATH,0,-1);
vendor('EaseTemplate.template#ease');
$config = array(
'CacheDir' => $CacheDir,
'TemplateDir' => $TemplateDir,
'TplType' => 'html'
);
if(C('TMPL_ENGINE_CONFIG')) {
$config = array_merge($config,C('TMPL_ENGINE_CONFIG'));
}
$tpl = new EaseTemplate($config);
$tpl->set_var($var);
$tpl->set_file($templateFile);
$tpl->p();
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* TemplateLite模板引擎驱动
* @category Extend
* @package Extend
* @subpackage Driver.Template
* @author liu21st <liu21st@gmail.com>
*/
class TemplateLite {
/**
* 渲染模板输出
* @access public
* @param string $templateFile 模板文件名
* @param array $var 模板变量
* @return void
*/
public function fetch($templateFile,$var) {
vendor("TemplateLite.class#template");
$templateFile = substr($templateFile,strlen(THEME_PATH));
$tpl = new Template_Lite();
$tpl->template_dir = THEME_PATH;
$tpl->compile_dir = CACHE_PATH ;
$tpl->cache_dir = TEMP_PATH ;
if(C('TMPL_ENGINE_CONFIG')) {
$config = C('TMPL_ENGINE_CONFIG');
foreach ($config as $key=>$val){
$tpl->{$key} = $val;
}
}
$tpl->assign($var);
$tpl->display($templateFile);
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2013 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614<weibo.com/luofei614>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* MobileTemplate模板引擎驱动
* @category Extend
* @package Extend
* @subpackage Driver.Template
* @author luofei614 <weibo.com/luofei614>
*/
class TemplateMobile {
/**
* 渲染模板输出
* @access public
* @param string $templateFile 模板文件名
* @param array $var 模板变量
* @return void
*/
public function fetch($templateFile,$var) {
$templateFile=substr($templateFile,strlen(THEME_PATH));
$var['_think_template_path']=$templateFile;
exit(json_encode($var));
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* Smart模板引擎驱动
* @category Extend
* @package Extend
* @subpackage Driver.Template
* @author liu21st <liu21st@gmail.com>
*/
class TemplateSmart {
/**
* 渲染模板输出
* @access public
* @param string $templateFile 模板文件名
* @param array $var 模板变量
* @return void
*/
public function fetch($templateFile,$var) {
$templateFile = substr($templateFile,strlen(THEME_PATH));
vendor('SmartTemplate.class#smarttemplate');
$tpl = new SmartTemplate($templateFile);
$tpl->caching = C('TMPL_CACHE_ON');
$tpl->template_dir = THEME_PATH;
$tpl->compile_dir = CACHE_PATH ;
$tpl->cache_dir = TEMP_PATH ;
if(C('TMPL_ENGINE_CONFIG')) {
$config = C('TMPL_ENGINE_CONFIG');
foreach ($config as $key=>$val){
$tpl->{$key} = $val;
}
}
$tpl->assign($var);
$tpl->output();
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
defined('THINK_PATH') or exit();
/**
* Smarty模板引擎驱动
* @category Extend
* @package Extend
* @subpackage Driver.Template
* @author liu21st <liu21st@gmail.com>
*/
class TemplateSmarty {
/**
* 渲染模板输出
* @access public
* @param string $templateFile 模板文件名
* @param array $var 模板变量
* @return void
*/
public function fetch($templateFile,$var) {
$templateFile = substr($templateFile,strlen(THEME_PATH));
vendor('Smarty.Smarty#class');
$tpl = new Smarty();
$tpl->caching = C('TMPL_CACHE_ON');
$tpl->template_dir = THEME_PATH;
$tpl->compile_dir = CACHE_PATH ;
$tpl->cache_dir = TEMP_PATH ;
if(C('TMPL_ENGINE_CONFIG')) {
$config = C('TMPL_ENGINE_CONFIG');
foreach ($config as $key=>$val){
$tpl->{$key} = $val;
}
}
$tpl->assign($var);
$tpl->display($templateFile);
}
}
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
/**
* Base64 加密实现类
* @category ORG
* @package ORG
* @subpackage Crypt
* @author liu21st <liu21st@gmail.com>
*/
class Base64 {
/**
* 加密字符串
* @access static
* @param string $str 字符串
* @param string $key 加密key
* @return string
*/
public static function encrypt($data,$key) {
$key = md5($key);
$data = base64_encode($data);
$x=0;
$len = strlen($data);
$l = strlen($key);
for ($i=0;$i< $len;$i++) {
if ($x== $l) $x=0;
$char .=substr($key,$x,1);
$x++;
}
for ($i=0;$i< $len;$i++) {
$str .=chr(ord(substr($data,$i,1))+(ord(substr($char,$i,1)))%256);
}
return $str;
}
/**
* 解密字符串
* @access static
* @param string $str 字符串
* @param string $key 加密key
* @return string
*/
public static function decrypt($data,$key) {
$key = md5($key);
$x=0;
$len = strlen($data);
$l = strlen($key);
for ($i=0;$i< $len;$i++) {
if ($x== $l) $x=0;
$char .=substr($key,$x,1);
$x++;
}
for ($i=0;$i< $len;$i++) {
if (ord(substr($data,$i,1))<ord(substr($char,$i,1))) {
$str .=chr((ord(substr($data,$i,1))+256)-ord(substr($char,$i,1)));
}else{
$str .=chr(ord(substr($data,$i,1))-ord(substr($char,$i,1)));
}
}
return base64_decode($str);
}
}
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
/**
* Crypt 加密实现类
* @category ORG
* @package ORG
* @subpackage Crypt
* @author liu21st <liu21st@gmail.com>
*/
class Crypt {
/**
* 加密字符串
* @access static
* @param string $str 字符串
* @param string $key 加密key
* @return string
*/
function encrypt($str,$key,$toBase64=false){
$r = md5($key);
$c=0;
$v = "";
$len = strlen($str);
$l = strlen($r);
for ($i=0;$i<$len;$i++){
if ($c== $l) $c=0;
$v.= substr($r,$c,1) .
(substr($str,$i,1) ^ substr($r,$c,1));
$c++;
}
if($toBase64) {
return base64_encode(self::ed($v,$key));
}else {
return self::ed($v,$key);
}
}
/**
* 解密字符串
* @access static
* @param string $str 字符串
* @param string $key 加密key
* @return string
*/
function decrypt($str,$key,$toBase64=false) {
if($toBase64) {
$str = self::ed(base64_decode($str),$key);
}else {
$str = self::ed($str,$key);
}
$v = "";
$len = strlen($str);
for ($i=0;$i<$len;$i++){
$md5 = substr($str,$i,1);
$i++;
$v.= (substr($str,$i,1) ^ $md5);
}
return $v;
}
function ed($str,$key) {
$r = md5($key);
$c=0;
$v = "";
$len = strlen($str);
$l = strlen($r);
for ($i=0;$i<$len;$i++) {
if ($c==$l) $c=0;
$v.= substr($str,$i,1) ^ substr($r,$c,1);
$c++;
}
return $v;
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: cevin <cevin1991@gmail.com>
// +----------------------------------------------------------------------
/**
* HMAC 加密实现类
* @category ORG
* @package ORG
* @subpackage Crypt
* @author cevin <cevin1991@gmail.com>
*/
class Hmac {
/**
* SHA1加密
* @access static
* @param string $key 加密key
* @param string $str 字符串
* @return string
*/
public static function sha1($key,$str) {
$blocksize=64;
$hashfunc='sha1';
if (strlen($key)>$blocksize)
$key=pack('H*', $hashfunc($key));
$key=str_pad($key,$blocksize,chr(0x00));
$ipad=str_repeat(chr(0x36),$blocksize);
$opad=str_repeat(chr(0x5c),$blocksize);
$hmac = pack(
'H*',$hashfunc(
($key^$opad).pack(
'H*',$hashfunc(
($key^$ipad).$str
)
)
)
);
return $hmac;
}
/**
* MD5加密
* @access static
* @param string $key 加密key
* @param string $str 字符串
* @return string
*/
public static function md5($key, $str) {
$b = 64;
if (strlen($key) > $b) {
$key = pack("H*",md5($key));
}
$key = str_pad($key, $b, chr(0x00));
$ipad = str_pad('', $b, chr(0x36));
$opad = str_pad('', $b, chr(0x5c));
$k_ipad = $key ^ $ipad ;
$k_opad = $key ^ $opad;
return md5($k_opad . pack("H*",md5($k_ipad . $str)));
}
}
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
define("BCCOMP_LARGER", 1);
/**
* Rsa 加密实现类
* @category ORG
* @package ORG
* @subpackage Crypt
* @author liu21st <liu21st@gmail.com>
*/
class Rsa {
/**
* 加密字符串
* @access static
* @param string $str 字符串
* @param string $key 加密key
* @return string
*/
public static function encrypt($message, $public_key, $modulus, $keylength) {
$padded = self::add_PKCS1_padding($message, true, $keylength / 8);
$number = self::binary_to_number($padded);
$encrypted = self::pow_mod($number, $public_key, $modulus);
$result = self::number_to_binary($encrypted, $keylength / 8);
return $result;
}
/**
* 解密字符串
* @access static
* @param string $str 字符串
* @param string $key 加密key
* @return string
*/
public static function decrypt($message, $private_key, $modulus, $keylength) {
$number = self::binary_to_number($message);
$decrypted = self::pow_mod($number, $private_key, $modulus);
$result = self::number_to_binary($decrypted, $keylength / 8);
return self::remove_PKCS1_padding($result, $keylength / 8);
}
function sign($message, $private_key, $modulus, $keylength) {
$padded = self::add_PKCS1_padding($message, false, $keylength / 8);
$number = self::binary_to_number($padded);
$signed = self::pow_mod($number, $private_key, $modulus);
$result = self::number_to_binary($signed, $keylength / 8);
return $result;
}
function verify($message, $public_key, $modulus, $keylength) {
return decrypt($message, $public_key, $modulus, $keylength);
}
function pow_mod($p, $q, $r) {
// Extract powers of 2 from $q
$factors = array();
$div = $q;
$power_of_two = 0;
while(bccomp($div, "0") == BCCOMP_LARGER)
{
$rem = bcmod($div, 2);
$div = bcdiv($div, 2);
if($rem) array_push($factors, $power_of_two);
$power_of_two++;
}
// Calculate partial results for each factor, using each partial result as a
// starting point for the next. This depends of the factors of two being
// generated in increasing order.
$partial_results = array();
$part_res = $p;
$idx = 0;
foreach($factors as $factor)
{
while($idx < $factor)
{
$part_res = bcpow($part_res, "2");
$part_res = bcmod($part_res, $r);
$idx++;
}
array_push($partial_results, $part_res);
}
// Calculate final result
$result = "1";
foreach($partial_results as $part_res)
{
$result = bcmul($result, $part_res);
$result = bcmod($result, $r);
}
return $result;
}
//--
// Function to add padding to a decrypted string
// We need to know if this is a private or a public key operation [4]
//--
function add_PKCS1_padding($data, $isPublicKey, $blocksize) {
$pad_length = $blocksize - 3 - strlen($data);
if($isPublicKey)
{
$block_type = "\x02";
$padding = "";
for($i = 0; $i < $pad_length; $i++)
{
$rnd = mt_rand(1, 255);
$padding .= chr($rnd);
}
}
else
{
$block_type = "\x01";
$padding = str_repeat("\xFF", $pad_length);
}
return "\x00" . $block_type . $padding . "\x00" . $data;
}
//--
// Remove padding from a decrypted string
// See [4] for more details.
//--
function remove_PKCS1_padding($data, $blocksize) {
assert(strlen($data) == $blocksize);
$data = substr($data, 1);
// We cannot deal with block type 0
if($data{0} == '\0')
die("Block type 0 not implemented.");
// Then the block type must be 1 or 2
assert(($data{0} == "\x01") || ($data{0} == "\x02"));
// Remove the padding
$offset = strpos($data, "\0", 1);
return substr($data, $offset + 1);
}
//--
// Convert binary data to a decimal number
//--
function binary_to_number($data) {
$base = "256";
$radix = "1";
$result = "0";
for($i = strlen($data) - 1; $i >= 0; $i--)
{
$digit = ord($data{$i});
$part_res = bcmul($digit, $radix);
$result = bcadd($result, $part_res);
$radix = bcmul($radix, $base);
}
return $result;
}
//--
// Convert a number back into binary form
//--
function number_to_binary($number, $blocksize) {
$base = "256";
$result = "";
$div = $number;
while($div > 0)
{
$mod = bcmod($div, $base);
$div = bcdiv($div, $base);
$result = chr($mod) . $result;
}
return str_pad($result, $blocksize, "\x00", STR_PAD_LEFT);
}
}
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
/**
* Xxtea 加密实现类
* @category ORG
* @package ORG
* @subpackage Crypt
* @author liu21st <liu21st@gmail.com>
*/
class Xxtea {
/**
* 加密字符串
* @access static
* @param string $str 字符串
* @param string $key 加密key
* @return string
*/
public static function encrypt($str, $key) {
if ($str == "") {
return "";
}
$v = self::str2long($str, true);
$k = self::str2long($key, false);
$n = count($v) - 1;
$z = $v[$n];
$y = $v[0];
$delta = 0x9E3779B9;
$q = floor(6 + 52 / ($n + 1));
$sum = 0;
while (0 < $q--) {
$sum = self::int32($sum + $delta);
$e = $sum >> 2 & 3;
for ($p = 0; $p < $n; $p++) {
$y = $v[$p + 1];
$mx = self::int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ self::int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$z = $v[$p] = self::int32($v[$p] + $mx);
}
$y = $v[0];
$mx = self::int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ self::int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$z = $v[$n] = self::int32($v[$n] + $mx);
}
return self::long2str($v, false);
}
/**
* 解密字符串
* @access static
* @param string $str 字符串
* @param string $key 加密key
* @return string
*/
public static function decrypt($str, $key) {
if ($str == "") {
return "";
}
$v = self::str2long($str, false);
$k = self::str2long($key, false);
$n = count($v) - 1;
$z = $v[$n];
$y = $v[0];
$delta = 0x9E3779B9;
$q = floor(6 + 52 / ($n + 1));
$sum = self::int32($q * $delta);
while ($sum != 0) {
$e = $sum >> 2 & 3;
for ($p = $n; $p > 0; $p--) {
$z = $v[$p - 1];
$mx = self::int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ self::int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$y = $v[$p] = self::int32($v[$p] - $mx);
}
$z = $v[$n];
$mx = self::int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ self::int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$y = $v[0] = self::int32($v[0] - $mx);
$sum = self::int32($sum - $delta);
}
return self::long2str($v, true);
}
private static function long2str($v, $w) {
$len = count($v);
$s = array();
for ($i = 0; $i < $len; $i++) {
$s[$i] = pack("V", $v[$i]);
}
if ($w) {
return substr(join('', $s), 0, $v[$len - 1]);
}else{
return join('', $s);
}
}
private static function str2long($s, $w) {
$v = unpack("V*", $s. str_repeat("\0", (4 - strlen($s) % 4) & 3));
$v = array_values($v);
if ($w) {
$v[count($v)] = strlen($s);
}
return $v;
}
private static function int32($n) {
while ($n >= 2147483648) $n -= 4294967296;
while ($n <= -2147483649) $n += 4294967296;
return (int)$n;
}
}
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
/**
* IP 地理位置查询类 修改自 CoolCode.CN
* 由于使用UTF8编码 如果使用纯真IP地址库的话 需要对返回结果进行编码转换
* @category ORG
* @package ORG
* @subpackage Net
* @author liu21st <liu21st@gmail.com>
*/
class IpLocation {
/**
* QQWry.Dat文件指针
*
* @var resource
*/
private $fp;
/**
* 第一条IP记录的偏移地址
*
* @var int
*/
private $firstip;
/**
* 最后一条IP记录的偏移地址
*
* @var int
*/
private $lastip;
/**
* IP记录的总条数(不包含版本信息记录)
*
* @var int
*/
private $totalip;
/**
* 构造函数,打开 QQWry.Dat 文件并初始化类中的信息
*
* @param string $filename
* @return IpLocation
*/
public function __construct($filename = "UTFWry.dat") {
$this->fp = 0;
if (($this->fp = fopen(dirname(__FILE__).'/'.$filename, 'rb')) !== false) {
$this->firstip = $this->getlong();
$this->lastip = $this->getlong();
$this->totalip = ($this->lastip - $this->firstip) / 7;
}
}
/**
* 返回读取的长整型数
*
* @access private
* @return int
*/
private function getlong() {
//将读取的little-endian编码的4个字节转化为长整型数
$result = unpack('Vlong', fread($this->fp, 4));
return $result['long'];
}
/**
* 返回读取的3个字节的长整型数
*
* @access private
* @return int
*/
private function getlong3() {
//将读取的little-endian编码的3个字节转化为长整型数
$result = unpack('Vlong', fread($this->fp, 3).chr(0));
return $result['long'];
}
/**
* 返回压缩后可进行比较的IP地址
*
* @access private
* @param string $ip
* @return string
*/
private function packip($ip) {
// 将IP地址转化为长整型数,如果在PHP5中,IP地址错误,则返回False,
// 这时intval将Flase转化为整数-1,之后压缩成big-endian编码的字符串
return pack('N', intval(ip2long($ip)));
}
/**
* 返回读取的字符串
*
* @access private
* @param string $data
* @return string
*/
private function getstring($data = "") {
$char = fread($this->fp, 1);
while (ord($char) > 0) { // 字符串按照C格式保存,以\0结束
$data .= $char; // 将读取的字符连接到给定字符串之后
$char = fread($this->fp, 1);
}
return $data;
}
/**
* 返回地区信息
*
* @access private
* @return string
*/
private function getarea() {
$byte = fread($this->fp, 1); // 标志字节
switch (ord($byte)) {
case 0: // 没有区域信息
$area = "";
break;
case 1:
case 2: // 标志字节为1或2,表示区域信息被重定向
fseek($this->fp, $this->getlong3());
$area = $this->getstring();
break;
default: // 否则,表示区域信息没有被重定向
$area = $this->getstring($byte);
break;
}
return $area;
}
/**
* 根据所给 IP 地址或域名返回所在地区信息
*
* @access public
* @param string $ip
* @return array
*/
public function getlocation($ip='') {
if (!$this->fp) return null; // 如果数据文件没有被正确打开,则直接返回空
if(empty($ip)) $ip = get_client_ip();
$location['ip'] = gethostbyname($ip); // 将输入的域名转化为IP地址
$ip = $this->packip($location['ip']); // 将输入的IP地址转化为可比较的IP地址
// 不合法的IP地址会被转化为255.255.255.255
// 对分搜索
$l = 0; // 搜索的下边界
$u = $this->totalip; // 搜索的上边界
$findip = $this->lastip; // 如果没有找到就返回最后一条IP记录(QQWry.Dat的版本信息)
while ($l <= $u) { // 当上边界小于下边界时,查找失败
$i = floor(($l + $u) / 2); // 计算近似中间记录
fseek($this->fp, $this->firstip + $i * 7);
$beginip = strrev(fread($this->fp, 4)); // 获取中间记录的开始IP地址
// strrev函数在这里的作用是将little-endian的压缩IP地址转化为big-endian的格式
// 以便用于比较,后面相同。
if ($ip < $beginip) { // 用户的IP小于中间记录的开始IP地址时
$u = $i - 1; // 将搜索的上边界修改为中间记录减一
}
else {
fseek($this->fp, $this->getlong3());
$endip = strrev(fread($this->fp, 4)); // 获取中间记录的结束IP地址
if ($ip > $endip) { // 用户的IP大于中间记录的结束IP地址时
$l = $i + 1; // 将搜索的下边界修改为中间记录加一
}
else { // 用户的IP在中间记录的IP范围内时
$findip = $this->firstip + $i * 7;
break; // 则表示找到结果,退出循环
}
}
}
//获取查找到的IP地理位置信息
fseek($this->fp, $findip);
$location['beginip'] = long2ip($this->getlong()); // 用户IP所在范围的开始地址
$offset = $this->getlong3();
fseek($this->fp, $offset);
$location['endip'] = long2ip($this->getlong()); // 用户IP所在范围的结束地址
$byte = fread($this->fp, 1); // 标志字节
switch (ord($byte)) {
case 1: // 标志字节为1,表示国家和区域信息都被同时重定向
$countryOffset = $this->getlong3(); // 重定向地址
fseek($this->fp, $countryOffset);
$byte = fread($this->fp, 1); // 标志字节
switch (ord($byte)) {
case 2: // 标志字节为2,表示国家信息又被重定向
fseek($this->fp, $this->getlong3());
$location['country'] = $this->getstring();
fseek($this->fp, $countryOffset + 4);
$location['area'] = $this->getarea();
break;
default: // 否则,表示国家信息没有被重定向
$location['country'] = $this->getstring($byte);
$location['area'] = $this->getarea();
break;
}
break;
case 2: // 标志字节为2,表示国家信息被重定向
fseek($this->fp, $this->getlong3());
$location['country'] = $this->getstring();
fseek($this->fp, $offset + 8);
$location['area'] = $this->getarea();
break;
default: // 否则,表示国家信息没有被重定向
$location['country'] = $this->getstring($byte);
$location['area'] = $this->getarea();
break;
}
if (trim($location['country']) == 'CZ88.NET') { // CZ88.NET表示没有有效信息
$location['country'] = '未知';
}
if (trim($location['area']) == 'CZ88.NET') {
$location['area'] = '';
}
return $location;
}
/**
* 析构函数,用于在页面执行结束后自动关闭打开的文件。
*
*/
public function __destruct() {
if ($this->fp) {
fclose($this->fp);
}
$this->fp = 0;
}
}
\ No newline at end of file
<?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>
// +----------------------------------------------------------------------
/**
* ArrayList实现类
* @category Think
* @package Think
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
*/
class ArrayList implements IteratorAggregate {
/**
* 集合元素
* @var array
* @access protected
*/
protected $_elements = array();
/**
* 架构函数
* @access public
* @param string $elements 初始化数组元素
*/
public function __construct($elements = array()) {
if (!empty($elements)) {
$this->_elements = $elements;
}
}
/**
* 若要获得迭代因子,通过getIterator方法实现
* @access public
* @return ArrayObject
*/
public function getIterator() {
return new ArrayObject($this->_elements);
}
/**
* 增加元素
* @access public
* @param mixed $element 要添加的元素
* @return boolen
*/
public function add($element) {
return (array_push($this->_elements, $element)) ? true : false;
}
//
public function unshift($element) {
return (array_unshift($this->_elements,$element))?true : false;
}
//
public function pop() {
return array_pop($this->_elements);
}
/**
* 增加元素列表
* @access public
* @param ArrayList $list 元素列表
* @return boolen
*/
public function addAll($list) {
$before = $this->size();
foreach( $list as $element) {
$this->add($element);
}
$after = $this->size();
return ($before < $after);
}
/**
* 清除所有元素
* @access public
*/
public function clear() {
$this->_elements = array();
}
/**
* 是否包含某个元素
* @access public
* @param mixed $element 查找元素
* @return string
*/
public function contains($element) {
return (array_search($element, $this->_elements) !== false );
}
/**
* 根据索引取得元素
* @access public
* @param integer $index 索引
* @return mixed
*/
public function get($index) {
return $this->_elements[$index];
}
/**
* 查找匹配元素,并返回第一个元素所在位置
* 注意 可能存在0的索引位置 因此要用===False来判断查找失败
* @access public
* @param mixed $element 查找元素
* @return integer
*/
public function indexOf($element) {
return array_search($element, $this->_elements);
}
/**
* 判断元素是否为空
* @access public
* @return boolen
*/
public function isEmpty() {
return empty($this->_elements);
}
/**
* 最后一个匹配的元素位置
* @access public
* @param mixed $element 查找元素
* @return integer
*/
public function lastIndexOf($element) {
for ($i = (count($this->_elements) - 1); $i > 0; $i--) {
if ($element == $this->get($i)) { return $i; }
}
}
public function toJson() {
return json_encode($this->_elements);
}
/**
* 根据索引移除元素
* 返回被移除的元素
* @access public
* @param integer $index 索引
* @return mixed
*/
public function remove($index) {
$element = $this->get($index);
if (!is_null($element)) { array_splice($this->_elements, $index, 1); }
return $element;
}
/**
* 移出一定范围的数组列表
* @access public
* @param integer $offset 开始移除位置
* @param integer $length 移除长度
*/
public function removeRange($offset , $length) {
array_splice($this->_elements, $offset , $length);
}
/**
* 移出重复的值
* @access public
*/
public function unique() {
$this->_elements = array_unique($this->_elements);
}
/**
* 取出一定范围的数组列表
* @access public
* @param integer $offset 开始位置
* @param integer $length 长度
*/
public function range($offset,$length=null) {
return array_slice($this->_elements,$offset,$length);
}
/**
* 设置列表元素
* 返回修改之前的值
* @access public
* @param integer $index 索引
* @param mixed $element 元素
* @return mixed
*/
public function set($index, $element) {
$previous = $this->get($index);
$this->_elements[$index] = $element;
return $previous;
}
/**
* 获取列表长度
* @access public
* @return integer
*/
public function size() {
return count($this->_elements);
}
/**
* 转换成数组
* @access public
* @return array
*/
public function toArray() {
return $this->_elements;
}
// 列表排序
public function ksort() {
ksort($this->_elements);
}
// 列表排序
public function asort() {
asort($this->_elements);
}
// 逆向排序
public function rsort() {
rsort($this->_elements);
}
// 自然排序
public function natsort() {
natsort($this->_elements);
}
}
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <weibo.com/luofei614> 
// +----------------------------------------------------------------------
/**
* 权限认证类
* 功能特性:
* 1,是对规则进行认证,不是对节点进行认证。用户可以把节点当作规则名称实现对节点进行认证。
* $auth=new Auth(); $auth->check('规则名称','用户id')
* 2,可以同时对多条规则进行认证,并设置多条规则的关系(or或者and)
* $auth=new Auth(); $auth->check('规则1,规则2','用户id','and')
* 第三个参数为and时表示,用户需要同时具有规则1和规则2的权限。 当第三个参数为or时,表示用户值需要具备其中一个条件即可。默认为or
* 3,一个用户可以属于多个用户组(think_auth_group_access表 定义了用户所属用户组)。我们需要设置每个用户组拥有哪些规则(think_auth_group 定义了用户组权限)
*
* 4,支持规则表达式。
* 在think_auth_rule 表中定义一条规则时,如果type为1, condition字段就可以定义规则表达式。 如定义{score}>5 and {score}<100 表示用户的分数在5-100之间时这条规则才会通过。
* @category ORG
* @package ORG
* @subpackage Util
* @author luofei614<weibo.com/luofei614>
*/
//数据库
/*
-- ----------------------------
-- think_auth_rule,规则表,
-- id:主键,name:规则唯一标识, title:规则中文名称 status 状态:为1正常,为0禁用,condition:规则表达式,为空表示存在就验证,不为空表示按照条件验证
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_rule`;
CREATE TABLE `think_auth_rule` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`name` char(80) NOT NULL DEFAULT '',
`title` char(20) NOT NULL DEFAULT '',
`status` tinyint(1) NOT NULL DEFAULT '1',
`condition` char(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- think_auth_group 用户组表,
-- id:主键, title:用户组中文名称, rules:用户组拥有的规则id, 多个规则","隔开,status 状态:为1正常,为0禁用
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_group`;
CREATE TABLE `think_auth_group` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`title` char(100) NOT NULL DEFAULT '',
`status` tinyint(1) NOT NULL DEFAULT '1',
`rules` char(80) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- think_auth_group_access 用户组明细表
-- uid:用户id,group_id:用户组id
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_group_access`;
CREATE TABLE `think_auth_group_access` (
`uid` mediumint(8) unsigned NOT NULL,
`group_id` mediumint(8) unsigned NOT NULL,
UNIQUE KEY `uid_group_id` (`uid`,`group_id`),
KEY `uid` (`uid`),
KEY `group_id` (`group_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
*/
class Auth{
//默认配置
protected $_config = array(
// 'AUTH_ON' => true, //认证开关
// 'AUTH_TYPE' => 1, // 认证方式,1为时时认证;2为登录认证。
// 'AUTH_GROUP' => 'wy_auth_group', //用户组数据表名
// 'AUTH_GROUP_ACCESS' => 'wy_auth_group_access', //用户组明细表
// 'AUTH_RULE' => 'wy_auth_rule', //权限规则表
// 'AUTH_USER' => 'wy_members'//用户信息表
);
public function __construct() {
if (C('AUTH_CONFIG')) {
//可设置配置项 AUTH_CONFIG, 此配置项为数组。
$this->_config = array_merge($this->_config, C('AUTH_CONFIG'));
}
}
//获得权限$name 可以是字符串或数组或逗号分割, uid为 认证的用户id, $or 是否为or关系,为true是, name为数组,只要数组中有一个条件通过则通过,如果为false需要全部条件通过。
public function check($name, $uid, $relation='or') {
if (!$this->_config['AUTH_ON'])
return true;
$authList = $this->getAuthList($uid);
if (is_string($name)) {
if (strpos($name, ',') !== false) {
$name = explode(',', $name);
} else {
$name = array($name);
}
}
$list = array(); //有权限的name
foreach ($authList as $val) {
if (in_array(strtolower($val), $name))
$list[] = $val;
}
if ($relation=='or' and !empty($list)) {
return true;
}
$diff = array_diff($name, $list);
if ($relation=='and' and empty($diff)) {
return true;
}
return false;
}
//获得用户组,外部也可以调用
public function getGroups($uid) {
static $groups = array();
if (isset($groups[$uid]))
return $groups[$uid];
$user_groups = M()->table($this->_config['AUTH_GROUP_ACCESS'] . ' a')->where("a.uid='$uid' and g.status='1'")->join($this->_config['AUTH_GROUP']." g on a.group_id=g.id")->select();
//echo M()->getLastSql();
$groups[$uid]=$user_groups?$user_groups:array();
return $groups[$uid];
}
//获得权限列表
protected function getAuthList($uid) {
static $_authList = array();
if (isset($_authList[$uid])) {
return $_authList[$uid];
}
if(isset($_SESSION['_AUTH_LIST_'.$uid])){
return $_SESSION['_AUTH_LIST_'.$uid];
}
//读取用户所属用户组
$groups = $this->getGroups($uid);
$ids = array();
foreach ($groups as $g) {
$ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
}
$ids = array_unique($ids);
if (empty($ids)) {
$_authList[$uid] = array();
return array();
}
//读取用户组所有权限规则
$map=array(
'id'=>array('in',$ids),
'status'=>1
);
$rules = M()->table($this->_config['AUTH_RULE'])->where($map)->select();
//循环规则,判断结果。
$authList = array();
foreach ($rules as $r) {
if (!empty($r['condition'])) {
//条件验证
$user = $this->getUserInfo($uid);
$command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $r['condition']);
//dump($command);//debug
@(eval('$condition=(' . $command . ');'));
if ($condition) {
$authList[] = strtolower($r['name']);
}
} else {
//存在就通过
$authList[] = strtolower($r['name']);
}
}
$_authList[$uid] = $authList;
if($this->_config['AUTH_TYPE']==2){
//session结果
$_SESSION['_AUTH_LIST_'.$uid]=$authList;
}
return $authList;
}
//获得用户资料,根据自己的情况读取数据库
protected function getUserInfo($uid) {
static $userinfo=array();
if(!isset($userinfo[$uid])){
$userinfo[$uid]=M()->table($this->_config['AUTH_USER'])->find($uid);
}
return $userinfo[$uid];
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <weibo.com/luofei614> 
// +----------------------------------------------------------------------
/**
* 权限认证类
* 功能特性:
* 1,是对规则进行认证,不是对节点进行认证。用户可以把节点当作规则名称实现对节点进行认证。
* $auth=new Auth(); $auth->check('规则名称','用户id')
* 2,可以同时对多条规则进行认证,并设置多条规则的关系(or或者and)
* $auth=new Auth(); $auth->check('规则1,规则2','用户id','and')
* 第三个参数为and时表示,用户需要同时具有规则1和规则2的权限。 当第三个参数为or时,表示用户值需要具备其中一个条件即可。默认为or
* 3,一个用户可以属于多个用户组(think_auth_group_access表 定义了用户所属用户组)。我们需要设置每个用户组拥有哪些规则(think_auth_group 定义了用户组权限)
*
* 4,支持规则表达式。
* 在think_auth_rule 表中定义一条规则时,如果type为1, condition字段就可以定义规则表达式。 如定义{score}>5 and {score}<100 表示用户的分数在5-100之间时这条规则才会通过。
* @category ORG
* @package ORG
* @subpackage Util
* @author luofei614<weibo.com/luofei614>
*/
//数据库
/*
-- ----------------------------
-- think_auth_rule,规则表,
-- id:主键,name:规则唯一标识, title:规则中文名称 status 状态:为1正常,为0禁用,condition:规则表达式,为空表示存在就验证,不为空表示按照条件验证
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_rule`;
CREATE TABLE `think_auth_rule` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`name` char(80) NOT NULL DEFAULT '',
`title` char(20) NOT NULL DEFAULT '',
`status` tinyint(1) NOT NULL DEFAULT '1',
`condition` char(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- think_auth_group 用户组表,
-- id:主键, title:用户组中文名称, rules:用户组拥有的规则id, 多个规则","隔开,status 状态:为1正常,为0禁用
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_group`;
CREATE TABLE `think_auth_group` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`title` char(100) NOT NULL DEFAULT '',
`status` tinyint(1) NOT NULL DEFAULT '1',
`rules` char(80) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- think_auth_group_access 用户组明细表
-- uid:用户id,group_id:用户组id
-- ----------------------------
DROP TABLE IF EXISTS `think_auth_group_access`;
CREATE TABLE `think_auth_group_access` (
`uid` mediumint(8) unsigned NOT NULL,
`group_id` mediumint(8) unsigned NOT NULL,
UNIQUE KEY `uid_group_id` (`uid`,`group_id`),
KEY `uid` (`uid`),
KEY `group_id` (`group_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
*/
class Auth{
//默认配置
protected $_config = array(
// 'AUTH_ON' => true, //认证开关
// 'AUTH_TYPE' => 1, // 认证方式,1为时时认证;2为登录认证。
// 'AUTH_GROUP' => 'wy_auth_group', //用户组数据表名
// 'AUTH_GROUP_ACCESS' => 'wy_auth_group_access', //用户组明细表
// 'AUTH_RULE' => 'wy_auth_rule', //权限规则表
// 'AUTH_USER' => 'wy_members'//用户信息表
);
public function __construct() {
if (C('AUTH_CONFIG')) {
//可设置配置项 AUTH_CONFIG, 此配置项为数组。
$this->_config = array_merge($this->_config, C('AUTH_CONFIG'));
}
}
//获得权限$name 可以是字符串或数组或逗号分割, uid为 认证的用户id, $or 是否为or关系,为true是, name为数组,只要数组中有一个条件通过则通过,如果为false需要全部条件通过。
public function check($name, $uid, $relation='or') {
if (!$this->_config['AUTH_ON'])
return true;
$authList = $this->getAuthList($uid);
if (is_string($name)) {
if (strpos($name, ',') !== false) {
$name = explode(',', $name);
} else {
$name = array($name);
}
}
$list = array(); //有权限的name
foreach ($authList as $val) {
if (in_array(strtolower($val), $name))
$list[] = $val;
}
if ($relation=='or' and !empty($list)) {
return true;
}
$diff = array_diff($name, $list);
if ($relation=='and' and empty($diff)) {
return true;
}
return false;
}
//获得用户组,外部也可以调用
public function getGroups($uid) {
static $groups = array();
if (isset($groups[$uid]))
return $groups[$uid];
$user_groups = M()->table($this->_config['AUTH_GROUP_ACCESS'] . ' a')->where("a.uid='$uid' and g.status='1'")->join($this->_config['AUTH_GROUP']." g on a.group_id=g.id")->select();
//echo M()->getLastSql();
$groups[$uid]=$user_groups?$user_groups:array();
return $groups[$uid];
}
//获得权限列表
public function getAuthList($uid) {
static $_authList = array();
if (isset($_authList[$uid])) {
return $_authList[$uid];
}
if(isset($_SESSION['_AUTH_LIST_'.$uid])){
return $_SESSION['_AUTH_LIST_'.$uid];
}
//读取用户所属用户组
$groups = $this->getGroups($uid);
$ids = array();
foreach ($groups as $g) {
$ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
}
$ids = array_unique($ids);
if (empty($ids)) {
$_authList[$uid] = array();
return array();
}
//读取用户组所有权限规则
$map=array(
'id'=>array('in',$ids),
'status'=>1
);
$rules = M()->table($this->_config['AUTH_RULE'])->where($map)->select();
//循环规则,判断结果。
$authList = array();
foreach ($rules as $r) {
if (!empty($r['condition'])) {
//条件验证
$user = $this->getUserInfo($uid);
$command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $r['condition']);
//dump($command);//debug
@(eval('$condition=(' . $command . ');'));
if ($condition) {
$authList[] = strtolower($r['name']);
}
} else {
//存在就通过
$authList[] = strtolower($r['name']);
}
}
$_authList[$uid] = $authList;
if($this->_config['AUTH_TYPE']==2){
//session结果
$_SESSION['_AUTH_LIST_'.$uid]=$authList;
}
return $authList;
}
//获得用户资料,根据自己的情况读取数据库
protected function getUserInfo($uid) {
static $userinfo=array();
if(!isset($userinfo[$uid])){
$userinfo[$uid]=M()->table($this->_config['AUTH_USER'])->find($uid);
}
return $userinfo[$uid];
}
}
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!