Commit 14f95149 by 施宇

init

parent 549c60ab
Showing with 4854 additions and 0 deletions

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [L,E=PATH_INFO:$1]
</IfModule>
\ No newline at end of file
<?php
return array(
'LOAD_EXT_CONFIG' => 'config_db,config_url,config_pwd,config_param,config_supplier,chain_config,footstone_config,config_pcb',
'VAR_PAGE' => 'p',
'APP_SUB_DOMAIN_DEPLOY' => true,
'APP_SUB_DOMAIN_RULES' => array(
'm' => 'M',
'szm' => 'M',
'tm' => 'M',
'ichuntm' => 'M',
'sc' => 'Sc',
'bom' => 'Bom',
'szbom' => 'Bom',
'tbom' => 'Bom',
'szsc' => 'Sc',
'supply'=>'Supply'
),
//内部调用免验证秘钥
'SUPER_AUTH_KEY' => 'fh6y5t4rr351d2c3bryi',
// 极验
'GEE_ID' => 'afac726bf717235a47424e3f6059f524',
'GEE_KEY' => '52d86db9a61ae00a3e1d68fee908a248',
//是否显示自营搜索数据
'ZIYING_BUTTON'=>1,
//爬虫token验证时间
'SEARCH_TOKEN_EXPIRE_TIME' => 30,
//搜索词过滤2个英文特殊词
'BRAND_SEARCH_WORD'=>'FH,BL,TE,FM,CJ,ST,SK,ST,ON,TM,TP,TI,MD,EG,HF,DY,MK,M2,M4,M7,M1,A7,F7',
// 首页自营模块获取限时限量商品
'HOME_SELF_ACTIVITY_GOODS' => 'http://cube.liexin.net/WebApi/HDLimitGoodsID?Token=',
//首页内容缓存
'HOME_TEMPLATE_REDIS' => 'home_template_datas',
'H5_HOME_TEMPLATE_REDIS' => 'h5_home_template_datas',
);
\ No newline at end of file
<?php
return array(
'URL_CASE_INSENSITIVE' => true, // 默true 表示URL不区分大小写 false则表示区分大小写
'URL_MODEL' => 2, // URL访问模式,可选参数0、1、2、3,代表以下四种模式: 0 (普通模式); 1 (PATHINFO 模式); 2 (REWRITE 模式); 3 (兼容模式) 默认为PATHINFO 模式
'URL_ROUTER_ON' => true, // 是否开启URL路由
'URL_ROUTE_RULES' => array(//动态路由
),
'TMPL_PARSE_STRING' =>array(
'__PUBLIC__' => STATIC_DOMAIN,
),
'URL_MAP_RULES' => array(//静态路由
'login' => 'Home/Index/login',
'home' => 'Home/Index/home'
),
);
\ No newline at end of file
\ No newline at end of file
\ No newline at end of file
\ No newline at end of file
\ No newline at end of file
<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller
{
public function login()
{
$this->display('Login/index');
}
public function home()
{
$this->display('Home/index');
}
}
<?php
namespace Home\Controller;
use Think\Controller;
class LoginController extends Controller
{
public function index()
{
$this->display('Login/index');
}
}
\ No newline at end of file
\ No newline at end of file
<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
<include file="public/header" />
</head>
<body>
<div class="wrapper">
<include file="public/navleft" />
<div class="wrapper_right">
<include file="public/top" />
<div class="right_content">
<div class="content">
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
</div>
</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=div, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="__PUBLIC__/css/test.css">
</head>
<body>
<div>login</div>
</body>
</html>
\ No newline at end of file
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="keywords" content=""/>
<meta name="description" content=""/>
<meta name="viewport" content="width=device-width; initial-scale=1; maximum-scale=1; user-scalable=0;"/>
<title>IC业务助手</title>
<link rel="stylesheet" type="text/css" href="__PUBLIC__/common/css/base.css">
<link rel="stylesheet" type="text/css" href="__PUBLIC__/common/css/fonts.css">
<link rel="stylesheet" type="text/css" href="__PUBLIC__/common/css/navleft.css">
<link rel="stylesheet" type="text/css" href="__PUBLIC__/common/css/top.css">
\ No newline at end of file
<div class="nav_left">
<div class="nav_content boxsiz">
<div class="nav_left_header">
<div class="nav_logo">
<img src="__PUBLIC__/images/navlogo.png" alt="IClogo">
</div>
<div class="nav_title">IC业务助手</div>
<div class="nav_desc">让询报价更轻松、便捷</div>
</div>
<div class="nav_left_content">
<ul class="content_ul">
<li class="content_ul_li active">
<span class="li_icon icon iconfont iconjuxing4"></span>
<span class="li_title">首页</span>
</li>
<li class="content_ul_li">
<span class="li_icon icon iconfont iconjuxing5"></span>
<span class="li_title">询报价</span>
<span class="li_right icon iconfont iconjuxing12">
</li>
<li class="content_ul_li">
<span class="li_icon icon iconfont iconjuxing6"></span>
<span class="li_title">抢单专区</span>
</li>
<li class="content_ul_li">
<span class="li_icon icon iconfont iconjuxing7"></span>
<span class="li_title">在线沟通</span>
</li>
<li class="content_ul_li">
<span class="li_icon icon iconfont iconjuxing8"></span>
<span class="li_title">商品管理</span>
</li>
<li class="content_ul_li">
<span class="li_icon icon iconfont iconjuxing9"></span>
<span class="li_title">积分管理</span>
</li>
<li class="content_ul_li">
<span class="li_icon icon iconfont iconjuxing10"></span>
<span class="li_title">认证管理</span>
</li>
<li class="content_ul_li">
<span class="li_icon icon iconfont iconjuxing11"></span>
<span class="li_title">账户设置</span>
</li>
</ul>
</div>
<div class="nav_end">
<span class="li_icon icon iconfont iconjuxing3"></span>
<span class="li_title">安全退出</span>
</div>
</div>
</div>
\ No newline at end of file
<div class="right_header">
<div class="user_logo fr">
<img src="__PUBLIC__/images/navlogo.png" alt="IClogo">
</div>
<div class="message_icon fr">
<span class="icon iconfont iconjuxing1"></span>
<span class="num">23</span>
</div>
<div class="input_div fr">
<input type="text" placeholder="请输入要搜索的内容">
<span class="icon iconfont iconjuxing"></span>
</div>
</div>
\ No newline at end of file
\ No newline at end of file
<?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=div, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="STATIC_DOMAIN/dist/css/test.css">
</head>
<body>
<div>login</div>
</body>
</html>
\ No newline at end of file
<?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="keywords" content=""/>
<meta name="description" content=""/>
<meta name="viewport" content="width=device-width; initial-scale=1; maximum-scale=1; user-scalable=0;"/>
<title>IC业务助手</title>
<link rel="stylesheet" type="text/css" href="http://resic.liexin.com/common/css/base.css">
<link rel="stylesheet" type="text/css" href="http://resic.liexin.com/common/css/fonts.css">
<link rel="stylesheet" type="text/css" href="http://resic.liexin.com/common/css/navleft.css">
<link rel="stylesheet" type="text/css" href="http://resic.liexin.com/common/css/top.css">
</head>
<body>
<div class="wrapper">
<div class="nav_left">
<div class="nav_content boxsiz">
<div class="nav_left_header">
<div class="nav_logo">
<img src="http://resic.liexin.com/images/navlogo.png" alt="IClogo">
</div>
<div class="nav_title">IC业务助手</div>
<div class="nav_desc">让询报价更轻松、便捷</div>
</div>
<div class="nav_left_content">
<ul class="content_ul">
<li class="content_ul_li active">
<span class="li_icon icon iconfont iconjuxing4"></span>
<span class="li_title">首页</span>
</li>
<li class="content_ul_li">
<span class="li_icon icon iconfont iconjuxing5"></span>
<span class="li_title">询报价</span>
<span class="li_right icon iconfont iconjuxing12">
</li>
<li class="content_ul_li">
<span class="li_icon icon iconfont iconjuxing6"></span>
<span class="li_title">抢单专区</span>
</li>
<li class="content_ul_li">
<span class="li_icon icon iconfont iconjuxing7"></span>
<span class="li_title">在线沟通</span>
</li>
<li class="content_ul_li">
<span class="li_icon icon iconfont iconjuxing8"></span>
<span class="li_title">商品管理</span>
</li>
<li class="content_ul_li">
<span class="li_icon icon iconfont iconjuxing9"></span>
<span class="li_title">积分管理</span>
</li>
<li class="content_ul_li">
<span class="li_icon icon iconfont iconjuxing10"></span>
<span class="li_title">认证管理</span>
</li>
<li class="content_ul_li">
<span class="li_icon icon iconfont iconjuxing11"></span>
<span class="li_title">账户设置</span>
</li>
</ul>
</div>
<div class="nav_end">
<span class="li_icon icon iconfont iconjuxing3"></span>
<span class="li_title">安全退出</span>
</div>
</div>
</div>
<div class="wrapper_right">
<div class="right_header">
<div class="user_logo fr">
<img src="http://resic.liexin.com/images/navlogo.png" alt="IClogo">
</div>
<div class="message_icon fr">
<span class="icon iconfont iconjuxing1"></span>
<span class="num">23</span>
</div>
<div class="input_div fr">
<input type="text" placeholder="请输入要搜索的内容">
<span class="icon iconfont iconjuxing"></span>
</div>
</div>
<div class="right_content">
<div class="content">
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
<p>11111111</p>
</div>
</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
{"msg":"require(): Failed opening required '.\/vendor\/autoload.php' (include_path='.;C:\\php\\pear')","msgCode":"000000","ts":1559704037,"dateStr":"2019-06-05 03:07:17","app":"api","serverIp":"127.0.0.1","fileName":"E:\\ic\\index.php","lineNo":41,"method":""}
{"msg":"require(): Failed opening required '.\/vendor\/autoload.php' (include_path='.;C:\\php\\pear')","msgCode":"000000","ts":1559704037,"dateStr":"2019-06-05 03:07:17","app":"api","serverIp":"127.0.0.1","fileName":"E:\\ic\\index.php","lineNo":41,"method":""}
This diff could not be displayed because it is too large.
<?php
//000000000000a:2:{i:0;a:2:{s:5:"login";a:2:{i:0;s:16:"Home/Index/login";i:1;a:0:{}}s:4:"home";a:2:{i:0;s:15:"Home/Index/home";i:1;a:0:{}}}i:1;a:0:{}}
?>
\ No newline at end of file
<?php
//000000000000a:2:{i:0;a:2:{s:5:"login";a:2:{i:0;s:16:"Home/Index/login";i:1;a:0:{}}s:4:"home";a:2:{i:0;s:15:"Home/Index/home";i:1;a:0:{}}}i:1;a:0:{}}
?>
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* ThinkPHP 默认的调试模式配置文件
*/
// 调试模式下面默认设置 可以在应用配置目录下重新定义 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_DEBUG' => true, // 开启调试模式 记录SQL日志
'TMPL_CACHE_ON' => false, // 是否开启模板编译缓存,设为false则每次都会重新编译
'TMPL_STRIP_SPACE' => false, // 是否去除模板文件里面的html空格与换行
'SHOW_ERROR_MSG' => true, // 显示错误信息
'URL_CASE_INSENSITIVE' => false, // URL区分大小写
);
ThinkPHP遵循Apache2开源协议发布,并提供免费使用。
版权所有Copyright © 2006-2014 by ThinkPHP (http://thinkphp.cn)
All rights reserved。
ThinkPHP® 商标和著作权所有者为上海顶想信息科技有限公司。
Apache Licence是著名的非盈利开源组织Apache采用的协议。
该协议和BSD类似,鼓励代码共享和尊重原作者的著作权,
允许代码修改,再作为开源或商业软件发布。需要满足
的条件:
1. 需要给代码的用户一份Apache Licence ;
2. 如果你修改了代码,需要在被修改的文件中说明;
3. 在延伸的代码中(修改和有源代码衍生的代码中)需要
带有原来代码中的协议,商标,专利声明和其他原来作者规
定需要包含的说明;
4. 如果再发布的产品中包含一个Notice文件,则在Notice文
件中需要带有本协议内容。你可以在Notice中增加自己的
许可,但不可以表现为对Apache Licence构成更改。
具体的协议参考:http://www.apache.org/licenses/LICENSE-2.0
5. are you ok?
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* ThinkPHP English language package
*/
return array(
/* core language package */
'_MODULE_NOT_EXIST_' => "Module can't be loaded",
'_CONTROLLER_NOT_EXIST_' => "Controller can't be loaded",
'_ERROR_ACTION_' => 'Illegal Action',
'_LANGUAGE_NOT_LOAD_' => "Can't load language package",
'_TEMPLATE_NOT_EXIST_' => "Template doesn't exist",
'_MODULE_' => 'Module',
'_ACTION_' => 'Action',
'_MODEL_NOT_EXIST_' => "Model can't be loaded",
'_VALID_ACCESS_' => 'No access',
'_XML_TAG_ERROR_' => 'XML tag syntax errors',
'_DATA_TYPE_INVALID_' => 'Illegal data objects!',
'_OPERATION_WRONG_' => 'Operation error occurs',
'_NOT_LOAD_DB_' => 'Unable to load the database',
'_NO_DB_DRIVER_' => 'Unable to load database driver',
'_NOT_SUPPORT_DB_' => 'The system is temporarily not support database',
'_NO_DB_CONFIG_' => 'Not define the database configuration',
'_NOT_SUPPORT_' => 'The system does not support',
'_CACHE_TYPE_INVALID_' => 'Unable to load the cache type',
'_FILE_NOT_WRITABLE_' => 'Directory (file) is not writable',
'_METHOD_NOT_EXIST_' => 'The method you requested does not exist!',
'_CLASS_NOT_EXIST_' => 'Instantiating a class does not exist!',
'_CLASS_CONFLICT_' => 'Class name conflicts',
'_TEMPLATE_ERROR_' => 'Template Engine errors',
'_CACHE_WRITE_ERROR_' => 'Cache file write failed!',
'_TAGLIB_NOT_EXIST_' => 'Tag library is not defined',
'_OPERATION_FAIL_' => 'Operation failed!',
'_OPERATION_SUCCESS_' => 'Operation succeed!',
'_SELECT_NOT_EXIST_' => 'Record does not exist!',
'_EXPRESS_ERROR_' => 'Expression errors',
'_TOKEN_ERROR_' => "Form's token errors",
'_RECORD_HAS_UPDATE_' => 'Record has been updated',
'_NOT_ALLOW_PHP_' => 'PHP codes are not allowed in the template',
'_PARAM_ERROR_' => 'Parameter error or undefined',
'_ERROR_QUERY_EXPRESS_' => 'Query express error',
);
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Daiane Azevedo <daianeaze16@gmail.com>
// +----------------------------------------------------------------------
/**
* ThinkPHP Portuguese language package
*/
return array(
/* core language package */
'_MODULE_NOT_EXIST_' => "Módulo não pode ser carregado",
'_CONTROLLER_NOT_EXIST_' => "Controller não pode ser carregado",
'_ERROR_ACTION_' => 'Ação ilegal',
'_LANGUAGE_NOT_LOAD_' => "Não é possível carregar pacote da linguagem",
'_TEMPLATE_NOT_EXIST_' => "Template não existe",
'_MODULE_' => 'Módulo',
'_ACTION_' => 'Ação',
'_MODEL_NOT_EXIST_' => "Modelo não pode ser carregado",
'_VALID_ACCESS_' => 'Sem acesso',
'_XML_TAG_ERROR_' => 'Erro de sintaxe - XML tag',
'_DATA_TYPE_INVALID_' => 'Tipos de dados ilegais!',
'_OPERATION_WRONG_' => 'Erro na operação',
'_NOT_LOAD_DB_' => 'Impossível carregar banco de dados',
'_NO_DB_DRIVER_' => 'Impossível carregar driver do bando de dados',
'_NOT_SUPPORT_DB_' => 'Temporariamente sem suporte ao banco',
'_NO_DB_CONFIG_' => 'Não define a configuração do banco',
'_NOT_SUPPORT_' => 'O sistema não suporta',
'_CACHE_TYPE_INVALID_' => 'Impossível carregar o tipo de cache',
'_FILE_NOT_WRITABLE_' => 'Diretório (arquivo) não pode ser escrito',
'_METHOD_NOT_EXIST_' => 'O método solicitado não existe!',
'_CLASS_NOT_EXIST_' => 'Não existe instância da classe',
'_CLASS_CONFLICT_' => 'Conflitos com nome da classe',
'_TEMPLATE_ERROR_' => 'Erros na contrução do template',
'_CACHE_WRITE_ERROR_' => 'Escrita do arquivo de cache falhou!',
'_TAGLIB_NOT_EXIST_' => 'Biblioteca da tag não foi definida',
'_OPERATION_FAIL_' => 'Operação falhou!',
'_OPERATION_SUCCESS_' => 'Operação bem sucessida!',
'_SELECT_NOT_EXIST_' => 'Gravação não existe!',
'_EXPRESS_ERROR_' => 'Erros de expressão',
'_TOKEN_ERROR_' => 'Erro no token do formulário',
'_RECORD_HAS_UPDATE_' => 'Gravação não foi atualizada',
'_NOT_ALLOW_PHP_' => 'Código PHP não é permitido no template',
'_PARAM_ERROR_' => 'Parâmetro errado ou indefinido',
'_ERROR_QUERY_EXPRESS_' => 'Erros na expressão da query',
);
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* ThinkPHP 简体中文语言包
*/
return array(
/* 核心语言变量 */
'_MODULE_NOT_EXIST_' => '无法加载模块',
'_CONTROLLER_NOT_EXIST_' => '无法加载控制器',
'_ERROR_ACTION_' => '非法操作',
'_LANGUAGE_NOT_LOAD_' => '无法加载语言包',
'_TEMPLATE_NOT_EXIST_' => '模板不存在',
'_MODULE_' => '模块',
'_ACTION_' => '操作',
'_MODEL_NOT_EXIST_' => '模型不存在或者没有定义',
'_VALID_ACCESS_' => '没有权限',
'_XML_TAG_ERROR_' => 'XML标签语法错误',
'_DATA_TYPE_INVALID_' => '非法数据对象!',
'_OPERATION_WRONG_' => '操作出现错误',
'_NOT_LOAD_DB_' => '无法加载数据库',
'_NO_DB_DRIVER_' => '无法加载数据库驱动',
'_NOT_SUPPORT_DB_' => '系统暂时不支持数据库',
'_NO_DB_CONFIG_' => '没有定义数据库配置',
'_NOT_SUPPORT_' => '系统不支持',
'_CACHE_TYPE_INVALID_' => '无法加载缓存类型',
'_FILE_NOT_WRITABLE_' => '目录(文件)不可写',
'_METHOD_NOT_EXIST_' => '方法不存在!',
'_CLASS_NOT_EXIST_' => '实例化一个不存在的类!',
'_CLASS_CONFLICT_' => '类名冲突',
'_TEMPLATE_ERROR_' => '模板引擎错误',
'_CACHE_WRITE_ERROR_' => '缓存文件写入失败!',
'_TAGLIB_NOT_EXIST_' => '标签库未定义',
'_OPERATION_FAIL_' => '操作失败!',
'_OPERATION_SUCCESS_' => '操作成功!',
'_SELECT_NOT_EXIST_' => '记录不存在!',
'_EXPRESS_ERROR_' => '表达式错误',
'_TOKEN_ERROR_' => '表单令牌错误',
'_RECORD_HAS_UPDATE_' => '记录已经更新',
'_NOT_ALLOW_PHP_' => '模板禁用PHP代码',
'_PARAM_ERROR_' => '参数错误或者未定义',
'_ERROR_QUERY_EXPRESS_' => '错误的查询条件',
);
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* ThinkPHP 繁体中文語言包
*/
return array(
/* 核心語言變數 */
'_MODULE_NOT_EXIST_' => '無法載入模組',
'_CONTROLLER_NOT_EXIST_' => '無法載入控制器',
'_ERROR_ACTION_' => '非法操作',
'_LANGUAGE_NOT_LOAD_' => '無法載入語言包',
'_TEMPLATE_NOT_EXIST_' => '模板不存在',
'_MODULE_' => '模組',
'_ACTION_' => '操作',
'_MODEL_NOT_EXIST_' => '模型不存在或者沒有定義',
'_VALID_ACCESS_' => '沒有權限',
'_XML_TAG_ERROR_' => 'XML標籤語法錯誤',
'_DATA_TYPE_INVALID_' => '非法資料物件!',
'_OPERATION_WRONG_' => '操作出現錯誤',
'_NOT_LOAD_DB_' => '無法載入資料庫',
'_NO_DB_DRIVER_' => '無法載入資料庫驅動',
'_NOT_SUPPORT_DB_' => '系統暫時不支援資料庫',
'_NO_DB_CONFIG_' => '沒有定義資料庫設定',
'_NOT_SUPPORT_' => '系統不支援',
'_CACHE_TYPE_INVALID_' => '無法載入快取類型',
'_FILE_NOT_WRITABLE_' => '目錄(檔案)不可寫',
'_METHOD_NOT_EXIST_' => '方法不存在!',
'_CLASS_NOT_EXIST_' => '實例化一個不存在的類別!',
'_CLASS_CONFLICT_' => '類別名稱衝突',
'_TEMPLATE_ERROR_' => '模板引擎錯誤',
'_CACHE_WRITE_ERROR_' => '快取檔案寫入失敗!',
'_TAGLIB_NOT_EXIST_' => '標籤庫未定義',
'_OPERATION_FAIL_' => '操作失敗!',
'_OPERATION_SUCCESS_' => '操作成功!',
'_SELECT_NOT_EXIST_' => '記錄不存在!',
'_EXPRESS_ERROR_' => '運算式錯誤',
'_TOKEN_ERROR_' => '表單權限錯誤',
'_RECORD_HAS_UPDATE_' => '記錄已經更新',
'_NOT_ALLOW_PHP_' => '模板禁用PHP代碼',
'_PARAM_ERROR_' => '參數錯誤或者未定義',
'_ERROR_QUERY_EXPRESS_' => '錯誤的查詢條件',
);
<?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>
// +----------------------------------------------------------------------
namespace Behavior;
/**
* 行为扩展:代理检测
*/
class AgentCheckBehavior
{
public function run(&$params)
{
// 代理访问检测
$limitProxyVisit = C('LIMIT_PROXY_VISIT', null, true);
if ($limitProxyVisit && ($_SERVER['HTTP_X_FORWARDED_FOR'] || $_SERVER['HTTP_VIA'] || $_SERVER['HTTP_PROXY_CONNECTION'] || $_SERVER['HTTP_USER_AGENT_VIA'])) {
// 禁止代理访问
exit('Access Denied');
}
}
}
<?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>
// +----------------------------------------------------------------------
namespace Behavior;
use Think\Think;
/**
* Boris行为扩展
*/
class BorisBehavior
{
public function run(&$params)
{
if (IS_CLI) {
if (!function_exists('pcntl_signal')) {
E("pcntl_signal not working.\nRepl mode based on Linux OS or PHP for OS X(http://php-osx.liip.ch/)\n");
}
Think::addMap(array(
'Boris\Boris' => VENDOR_PATH . 'Boris/Boris.php',
'Boris\Config' => VENDOR_PATH . 'Boris/Config.php',
'Boris\CLIOptionsHandler' => VENDOR_PATH . 'Boris/CLIOptionsHandler.php',
'Boris\ColoredInspector' => VENDOR_PATH . 'Boris/ColoredInspector.php',
'Boris\DumpInspector' => VENDOR_PATH . 'Boris/DumpInspector.php',
'Boris\EvalWorker' => VENDOR_PATH . 'Boris/EvalWorker.php',
'Boris\ExportInspector' => VENDOR_PATH . 'Boris/ExportInspector.php',
'Boris\Inspector' => VENDOR_PATH . 'Boris/Inspector.php',
'Boris\ReadlineClient' => VENDOR_PATH . 'Boris/ReadlineClient.php',
'Boris\ShallowParser' => VENDOR_PATH . 'Boris/ShallowParser.php',
));
$boris = new \Boris\Boris(">>> ");
$config = new \Boris\Config();
$config->apply($boris, true);
$options = new \Boris\CLIOptionsHandler();
$options->handle($boris);
$boris->onStart(sprintf("echo 'REPL MODE FOR THINKPHP \nTHINKPHP_VERSION: %s, PHP_VERSION: %s, BORIS_VERSION: %s\n';", THINK_VERSION, PHP_VERSION, $boris::VERSION));
$boris->start();
}
}
}
<?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>
// +----------------------------------------------------------------------
namespace Behavior;
/**
* 浏览器防刷新检测
*/
class BrowserCheckBehavior
{
public function run(&$params)
{
if ('GET' == $_SERVER['REQUEST_METHOD']) {
// 启用页面防刷新机制
$guid = md5($_SERVER['PHP_SELF']);
// 浏览器防刷新的时间间隔(秒) 默认为10
$refleshTime = C('LIMIT_REFLESH_TIMES', null, 10);
// 检查页面刷新间隔
if (cookie('_last_visit_time_' . $guid) && cookie('_last_visit_time_' . $guid) > time() - $refleshTime) {
// 页面刷新读取浏览器缓存
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');
}
}
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Behavior;
// 创建Lite运行文件
// 可以替换框架入口文件运行
// 建议绑定位置app_init
use Think\Hook as Hook;
class BuildLiteBehavior
{
public function run(&$params)
{
if (!defined('BUILD_LITE_FILE') || BUILD_LITE_FILE == false) {
return;
}
$litefile = C('RUNTIME_LITE_FILE', null, RUNTIME_PATH . 'lite.php');
if (is_file($litefile)) {
return;
}
$defs = get_defined_constants(true);
$content = 'namespace {$GLOBALS[\'_beginTime\'] = microtime(TRUE);';
if (MEMORY_LIMIT_ON) {
$content .= '$GLOBALS[\'_startUseMems\'] = memory_get_usage();';
}
// 生成数组定义
unset($defs['user']['BUILD_LITE_FILE']);
$content .= $this->buildArrayDefine($defs['user']) . '}';
// 读取编译列表文件
$filelist = is_file(CONF_PATH . 'lite.php') ?
include CONF_PATH . 'lite.php' :
array(
THINK_PATH . 'Common/functions.php',
COMMON_PATH . 'Common/function.php',
CORE_PATH . 'Think' . EXT,
CORE_PATH . 'Hook' . EXT,
CORE_PATH . 'App' . EXT,
CORE_PATH . 'Dispatcher' . EXT,
CORE_PATH . 'Log' . EXT,
CORE_PATH . 'Log/Driver/File' . EXT,
CORE_PATH . 'Route' . EXT,
CORE_PATH . 'Controller' . EXT,
CORE_PATH . 'View' . EXT,
CORE_PATH . 'Storage' . EXT,
CORE_PATH . 'Storage/Driver/File' . EXT,
CORE_PATH . 'Exception' . EXT,
BEHAVIOR_PATH . 'ParseTemplateBehavior' . EXT,
BEHAVIOR_PATH . 'ContentReplaceBehavior' . EXT,
);
// 编译文件
foreach ($filelist as $file) {
if (is_file($file)) {
$content .= compile($file);
}
}
// 处理Think类的start方法
$content = preg_replace('/\$runtimefile = RUNTIME_PATH(.+?)(if\(APP_STATUS)/', '\2', $content, 1);
$content .= "\nnamespace { Think\Think::addMap(" . var_export(\Think\Think::getMap(), true) . ");";
$content .= "\nL(" . var_export(L(), true) . ");\nC(" . var_export(C(), true) . ');Think\Hook::import(' . var_export(\Think\Hook::get(), true) . ');Think\Think::start();}';
// 生成运行Lite文件
file_put_contents($litefile, strip_whitespace('<?php ' . $content));
}
// 根据数组生成常量定义
private function buildArrayDefine($array)
{
$content = "\n";
foreach ($array as $key => $val) {
$key = strtoupper($key);
$content .= 'defined(\'' . $key . '\') or ';
if (is_int($val) || is_float($val)) {
$content .= "define('" . $key . "'," . $val . ');';
} elseif (is_bool($val)) {
$val = ($val) ? 'true' : 'false';
$content .= "define('" . $key . "'," . $val . ');';
} elseif (is_string($val)) {
$content .= "define('" . $key . "','" . addslashes($val) . "');";
}
$content .= "\n";
}
return $content;
}
}
<?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>
// +----------------------------------------------------------------------
namespace Behavior;
/**
* 系统行为扩展:操作路由检测
*/
class CheckActionRouteBehavior
{
// 行为扩展的执行入口必须是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;
}
}
<?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>
// +----------------------------------------------------------------------
namespace Behavior;
/**
* 语言检测 并自动加载语言包
*/
class CheckLangBehavior
{
// 行为扩展的执行入口必须是run
public function run(&$params)
{
// 检测语言
$this->checkLanguage();
}
/**
* 语言检查
* 检查浏览器支持语言,并自动加载语言包
* @access private
* @return void
*/
private function checkLanguage()
{
// 不开启语言包功能,仅仅加载框架语言文件直接返回
if (!C('LANG_SWITCH_ON', null, false)) {
return;
}
$langSet = C('DEFAULT_LANG');
$varLang = C('VAR_LANGUAGE', null, 'l');
$langList = C('LANG_LIST', null, 'zh-cn');
// 启用了语言包功能
// 根据是否启用自动侦测设置获取语言选择
if (C('LANG_AUTO_DETECT', null, true)) {
if (isset($_GET[$varLang])) {
$langSet = $_GET[$varLang]; // 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($langList, $langSet)) {
// 非法语言参数
$langSet = C('DEFAULT_LANG');
}
}
// 定义当前语言
define('LANG_SET', strtolower($langSet));
// 读取框架语言包
$file = THINK_PATH . 'Lang/' . LANG_SET . '.php';
if (LANG_SET != C('DEFAULT_LANG') && is_file($file)) {
L(include $file);
}
// 读取应用公共语言包
$file = LANG_PATH . LANG_SET . '.php';
if (is_file($file)) {
L(include $file);
}
// 读取模块语言包
$file = MODULE_PATH . 'Lang/' . LANG_SET . '.php';
if (is_file($file)) {
L(include $file);
}
// 读取当前控制器语言包
$file = MODULE_PATH . 'Lang/' . LANG_SET . '/' . strtolower(CONTROLLER_NAME) . '.php';
if (is_file($file)) {
L(include $file);
}
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Behavior;
/**
* 系统行为扩展:模板内容输出替换
*/
class ContentReplaceBehavior
{
// 行为扩展的执行入口必须是run
public function run(&$content)
{
$content = $this->templateContentReplace($content);
}
/**
* 模板内容替换
* @access protected
* @param string $content 模板内容
* @return string
*/
protected function templateContentReplace($content)
{
// 系统默认的特殊变量替换
$replace = array(
'__ROOT__' => __ROOT__, // 当前网站地址
'__APP__' => __APP__, // 当前应用地址
'__MODULE__' => __MODULE__,
'__ACTION__' => __ACTION__, // 当前操作地址
'__SELF__' => htmlentities(__SELF__), // 当前页面地址
'__CONTROLLER__' => __CONTROLLER__,
'__URL__' => __CONTROLLER__,
'__PUBLIC__' => __ROOT__ . '/Public', // 站点公共目录
);
// 允许用户自定义模板的字符串替换
if (is_array(C('TMPL_PARSE_STRING'))) {
$replace = array_merge($replace, C('TMPL_PARSE_STRING'));
}
$content = str_replace(array_keys($replace), array_values($replace), $content);
return $content;
}
}
<?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>
// +----------------------------------------------------------------------
namespace Behavior;
/**
* 自动执行任务
*/
use Think\Log as Log;
class CronRunBehavior
{
public function run(&$params)
{
// 锁定自动执行
$lockfile = RUNTIME_PATH . 'cron.lock';
if (is_writable($lockfile) && filemtime($lockfile) > $_SERVER['REQUEST_TIME'] - C('CRON_MAX_TIME', null, 60)) {
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(COMMON_PATH . 'Conf/crons.php')) {
$crons = include COMMON_PATH . 'Conf/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 COMMON_PATH . 'Cron/' . $cron[0] . '.php';
G('cronEnd');
$_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执行日志
\Think\Log::write(implode('', $log));
// 更新cron文件
$content = "<?php\nreturn " . var_export($crons, true) . ";\n?>";
file_put_contents(RUNTIME_PATH . '~crons.php', $content);
}
}
// 解除锁定
unlink($lockfile);
return;
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Behavior;
use Think\Storage;
use Think\Think;
/**
* 系统行为扩展:模板解析
*/
class ParseTemplateBehavior
{
// 行为扩展的执行入口必须是run
public function run(&$_data)
{
$engine = strtolower(C('TMPL_ENGINE_TYPE'));
$_content = empty($_data['content']) ? $_data['file'] : $_data['content'];
$_data['prefix'] = !empty($_data['prefix']) ? $_data['prefix'] : C('TMPL_CACHE_PREFIX');
if ('think' == $engine) {
// 采用Think模板引擎
if ((!empty($_data['content']) && $this->checkContentCache($_data['content'], $_data['prefix']))
|| $this->checkCache($_data['file'], $_data['prefix'])) {
// 缓存有效
//载入模版缓存文件
Storage::load(C('CACHE_PATH') . $_data['prefix'] . md5($_content) . C('TMPL_CACHFILE_SUFFIX'), $_data['var']);
} else {
$tpl = Think::instance('Think\\Template');
// 编译并加载模板文件
$tpl->fetch($_content, $_data['var'], $_data['prefix']);
}
} else {
// 调用第三方模板引擎解析和输出
if (strpos($engine, '\\')) {
$class = $engine;
} else {
$class = 'Think\\Template\\Driver\\' . ucwords($engine);
}
if (class_exists($class)) {
$tpl = new $class;
$tpl->fetch($_content, $_data['var']);
} else {
// 类没有定义
E(L('_NOT_SUPPORT_') . ': ' . $class);
}
}
}
/**
* 检查缓存文件是否有效
* 如果无效则需要重新编译
* @access public
* @param string $tmplTemplateFile 模板文件名
* @return boolean
*/
protected function checkCache($tmplTemplateFile, $prefix = '')
{
if (!C('TMPL_CACHE_ON')) // 优先对配置设定检测
{
return false;
}
$tmplCacheFile = C('CACHE_PATH') . $prefix . md5($tmplTemplateFile) . C('TMPL_CACHFILE_SUFFIX');
if (!Storage::has($tmplCacheFile)) {
return false;
} elseif (filemtime($tmplTemplateFile) > Storage::get($tmplCacheFile, 'mtime')) {
// 模板文件如果有更新则缓存需要更新
return false;
} elseif (C('TMPL_CACHE_TIME') != 0 && time() > Storage::get($tmplCacheFile, 'mtime') + C('TMPL_CACHE_TIME')) {
// 缓存是否在有效期
return false;
}
// 开启布局模板
if (C('LAYOUT_ON')) {
$layoutFile = THEME_PATH . C('LAYOUT_NAME') . C('TMPL_TEMPLATE_SUFFIX');
if (filemtime($layoutFile) > Storage::get($tmplCacheFile, 'mtime')) {
return false;
}
}
// 缓存有效
return true;
}
/**
* 检查缓存内容是否有效
* 如果无效则需要重新编译
* @access public
* @param string $tmplContent 模板内容
* @return boolean
*/
protected function checkContentCache($tmplContent, $prefix = '')
{
if (Storage::has(C('CACHE_PATH') . $prefix . md5($tmplContent) . C('TMPL_CACHFILE_SUFFIX'))) {
return true;
} else {
return false;
}
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Behavior;
use Think\Storage;
/**
* 系统行为扩展:静态缓存读取
*/
class ReadHtmlCacheBehavior
{
// 行为扩展的执行入口必须是run
public function run(&$params)
{
// 开启静态缓存
if (IS_GET && C('HTML_CACHE_ON')) {
$cacheTime = $this->requireHtmlCache();
if (false !== $cacheTime && $this->checkHTMLCache(HTML_FILE_NAME, $cacheTime)) {
//静态页面有效
// 读取静态页面输出
echo Storage::read(HTML_FILE_NAME, 'html');
exit();
}
}
}
// 判断是否需要静态缓存
private static function requireHtmlCache()
{
// 分析当前的静态规则
$htmls = C('HTML_CACHE_RULES'); // 读取静态规则
if (!empty($htmls)) {
$htmls = array_change_key_case($htmls);
// 静态规则文件定义格式 actionName=>array('静态规则','缓存时间','附加规则')
// 'read'=>array('{id},{name}',60,'md5') 必须保证静态规则的唯一性 和 可判断性
// 检测静态规则
$controllerName = strtolower(CONTROLLER_NAME);
$actionName = strtolower(ACTION_NAME);
if (isset($htmls[$controllerName . ':' . $actionName])) {
$html = $htmls[$controllerName . ':' . $actionName]; // 某个控制器的操作的静态规则
} elseif (isset($htmls[$controllerName . ':'])) {
// 某个控制器的静态规则
$html = $htmls[$controllerName . ':'];
} elseif (isset($htmls[$actionName])) {
$html = $htmls[$actionName]; // 所有操作的静态规则
} elseif (isset($htmls['*'])) {
$html = $htmls['*']; // 全局静态规则
}
if (!empty($html)) {
// 解读静态规则
$rule = is_array($html) ? $html[0] : $html;
// 以$_开头的系统变量
$callback = function ($match) {
switch ($match[1]) {
case '_GET':$var = $_GET[$match[2]];
break;
case '_POST':$var = $_POST[$match[2]];
break;
case '_REQUEST':$var = $_REQUEST[$match[2]];
break;
case '_SERVER':$var = $_SERVER[$match[2]];
break;
case '_SESSION':$var = $_SESSION[$match[2]];
break;
case '_COOKIE':$var = $_COOKIE[$match[2]];
break;
}
return (count($match) == 4) ? $match[3]($var) : $var;
};
$rule = preg_replace_callback('/{\$(_\w+)\.(\w+)(?:\|(\w+))?}/', $callback, $rule);
// {ID|FUN} GET变量的简写
$rule = preg_replace_callback('/{(\w+)\|(\w+)}/', function ($match) {return $match[2]($_GET[$match[1]]);}, $rule);
$rule = preg_replace_callback('/{(\w+)}/', function ($match) {return $_GET[$match[1]];}, $rule);
// 特殊系统变量
$rule = str_ireplace(
array('{:controller}', '{:action}', '{:module}'),
array(CONTROLLER_NAME, ACTION_NAME, MODULE_NAME),
$rule);
// {|FUN} 单独使用函数
$rule = preg_replace_callback('/{|(\w+)}/', function ($match) {return $match[1]();}, $rule);
$cacheTime = C('HTML_CACHE_TIME', null, 60);
if (is_array($html)) {
if (!empty($html[2])) {
$rule = $html[2]($rule);
}
// 应用附加函数
$cacheTime = isset($html[1]) ? $html[1] : $cacheTime; // 缓存有效期
} else {
$cacheTime = $cacheTime;
}
// 当前缓存文件
define('HTML_FILE_NAME', HTML_PATH . $rule . C('HTML_FILE_SUFFIX', null, '.html'));
return $cacheTime;
}
}
// 无需缓存
return false;
}
/**
* 检查静态HTML文件是否有效
* 如果无效需要重新更新
* @access public
* @param string $cacheFile 静态文件名
* @param integer $cacheTime 缓存有效期
* @return boolean
*/
public static function checkHTMLCache($cacheFile = '', $cacheTime = '')
{
if (!is_file($cacheFile) && 'sae' != APP_MODE) {
return false;
} elseif (filemtime(\Think\Think::instance('Think\View')->parseTemplate()) > Storage::get($cacheFile, 'mtime', 'html')) {
// 模板文件如果更新静态文件需要更新
return false;
} elseif (!is_numeric($cacheTime) && function_exists($cacheTime)) {
return $cacheTime($cacheFile);
} elseif (0 != $cacheTime && NOW_TIME > Storage::get($cacheFile, 'mtime', 'html') + $cacheTime) {
// 文件是否在有效期
return false;
}
//静态文件有效
return true;
}
}
<?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>
// +----------------------------------------------------------------------
namespace Behavior;
/**
* 机器人检测
* @author liu21st <liu21st@gmail.com>
*/
class RobotCheckBehavior
{
public function run(&$params)
{
// 机器人访问检测
if (C('LIMIT_ROBOT_VISIT', null, true) && self::isRobot()) {
// 禁止机器人访问
exit('Access Denied');
}
}
private static 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;
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Behavior;
/**
* 系统行为扩展:页面Trace显示输出
*/
class ShowPageTraceBehavior
{
protected $tracePageTabs = array('BASE' => '基本', 'FILE' => '文件', 'INFO' => '流程', 'ERR|NOTIC' => '错误', 'SQL' => 'SQL', 'DEBUG' => '调试');
// 行为扩展的执行入口必须是run
public function run(&$params)
{
if (!IS_AJAX && !IS_CLI && C('SHOW_PAGE_TRACE')) {
echo $this->showTrace();
}
}
/**
* 显示页面Trace信息
* @access private
*/
private function showTrace()
{
// 系统默认显示信息
$files = get_included_files();
$info = array();
foreach ($files as $key => $file) {
$info[] = $file . ' ( ' . number_format(filesize($file) / 1024, 2) . ' KB )';
}
$trace = array();
$base = array(
'请求信息' => date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']) . ' ' . $_SERVER['SERVER_PROTOCOL'] . ' ' . $_SERVER['REQUEST_METHOD'] . ' : ' . __SELF__,
'运行时间' => $this->showTime(),
'吞吐率' => number_format(1 / G('beginTime', 'viewEndTime'), 2) . 'req/s',
'内存开销' => MEMORY_LIMIT_ON ? number_format((memory_get_usage() - $GLOBALS['_startUseMems']) / 1024, 2) . ' kb' : '不支持',
'查询信息' => N('db_query') . ' queries ' . N('db_write') . ' writes ',
'文件加载' => count(get_included_files()),
'缓存信息' => N('cache_read') . ' gets ' . N('cache_write') . ' writes ',
'配置加载' => count(C()),
'会话信息' => 'SESSION_ID=' . session_id(),
);
// 读取应用定义的Trace文件
$traceFile = COMMON_PATH . 'Conf/trace.php';
if (is_file($traceFile)) {
$base = array_merge($base, include $traceFile);
}
$debug = trace();
$tabs = C('TRACE_PAGE_TABS', null, $this->tracePageTabs);
foreach ($tabs as $name => $title) {
switch (strtoupper($name)) {
case 'BASE': // 基本信息
$trace[$title] = $base;
break;
case 'FILE': // 文件信息
$trace[$title] = $info;
break;
default: // 调试信息
$name = strtoupper($name);
if (strpos($name, '|')) {
// 多组信息
$names = explode('|', $name);
$result = array();
foreach ($names as $name) {
$result += isset($debug[$name]) ? $debug[$name] : array();
}
$trace[$title] = $result;
} else {
$trace[$title] = isset($debug[$name]) ? $debug[$name] : '';
}
}
}
if ($save = C('PAGE_TRACE_SAVE')) {
// 保存页面Trace日志
if (is_array($save)) { // 选择选项卡保存
$tabs = C('TRACE_PAGE_TABS', null, $this->tracePageTabs);
$array = array();
foreach ($save as $tab) {
$array[] = $tabs[$tab];
}
}
$content = date('[ c ]') . ' ' . get_client_ip() . ' ' . $_SERVER['REQUEST_URI'] . "\r\n";
foreach ($trace as $key => $val) {
if (!isset($array) || in_array_case($key, $array)) {
$content .= '[ ' . $key . " ]\r\n";
if (is_array($val)) {
foreach ($val as $k => $v) {
$content .= (!is_numeric($k) ? $k . ':' : '') . print_r($v, true) . "\r\n";
}
} else {
$content .= print_r($val, true) . "\r\n";
}
$content .= "\r\n";
}
}
error_log(str_replace('<br/>', "\r\n", $content), 3, C('LOG_PATH') . date('y_m_d') . '_trace.log');
}
unset($files, $info, $base);
// 调用Trace页面模板
ob_start();
include C('TMPL_TRACE_FILE') ? C('TMPL_TRACE_FILE') : THINK_PATH . 'Tpl/page_trace.tpl';
return ob_get_clean();
}
/**
* 获取运行时间
*/
private function showTime()
{
// 显示运行时间
G('beginTime', $GLOBALS['_beginTime']);
G('viewEndTime');
// 显示详细运行时间
return G('beginTime', 'viewEndTime') . 's ( Load:' . G('beginTime', 'loadTime') . 's Init:' . G('loadTime', 'initTime') . 's Exec:' . G('initTime', 'viewStartTime') . 's Template:' . G('viewStartTime', 'viewEndTime') . 's )';
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Behavior;
/**
* 系统行为扩展:运行时间信息显示
*/
class ShowRuntimeBehavior
{
// 行为扩展的执行入口必须是run
public function run(&$content)
{
if (C('SHOW_RUN_TIME')) {
if (false !== strpos($content, '{__NORUNTIME__}')) {
$content = str_replace('{__NORUNTIME__}', '', $content);
} else {
$runtime = $this->showTime();
if (strpos($content, '{__RUNTIME__}')) {
$content = str_replace('{__RUNTIME__}', $runtime, $content);
} else {
$content .= $runtime;
}
}
} else {
$content = str_replace(array('{__NORUNTIME__}', '{__RUNTIME__}'), '', $content);
}
}
/**
* 显示运行时间、数据库操作、缓存次数、内存使用信息
* @access private
* @return string
*/
private function showTime()
{
// 显示运行时间
G('beginTime', $GLOBALS['_beginTime']);
G('viewEndTime');
$showTime = 'Process: ' . G('beginTime', 'viewEndTime') . 's ';
if (C('SHOW_ADV_TIME')) {
// 显示详细运行时间
$showTime .= '( Load:' . G('beginTime', 'loadTime') . 's Init:' . G('loadTime', 'initTime') . 's Exec:' . G('initTime', 'viewStartTime') . 's Template:' . G('viewStartTime', 'viewEndTime') . 's )';
}
if (C('SHOW_DB_TIMES')) {
// 显示数据库操作次数
$showTime .= ' | DB :' . N('db_query') . ' queries ' . N('db_write') . ' writes ';
}
if (C('SHOW_CACHE_TIMES')) {
// 显示缓存读写次数
$showTime .= ' | Cache :' . N('cache_read') . ' gets ' . N('cache_write') . ' writes ';
}
if (MEMORY_LIMIT_ON && C('SHOW_USE_MEM')) {
// 显示内存开销
$showTime .= ' | UseMem:' . number_format((memory_get_usage() - $GLOBALS['_startUseMems']) / 1024) . ' kb';
}
if (C('SHOW_LOAD_FILE')) {
$showTime .= ' | LoadFile:' . count(get_included_files());
}
if (C('SHOW_FUN_TIMES')) {
$fun = get_defined_functions();
$showTime .= ' | CallFun:' . count($fun['user']) . ',' . count($fun['internal']);
}
return $showTime;
}
}
<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Behavior;
/**
* 系统行为扩展:表单令牌生成
*/
class TokenBuildBehavior
{
public function run(&$content)
{
if (C('TOKEN_ON')) {
list($tokenName, $tokenKey, $tokenValue) = $this->getToken();
$input_token = '<input type="hidden" name="' . $tokenName . '" value="' . $tokenKey . '_' . $tokenValue . '" />';
$meta_token = '<meta name="' . $tokenName . '" content="' . $tokenKey . '_' . $tokenValue . '" />';
if (strpos($content, '{__TOKEN__}')) {
// 指定表单令牌隐藏域位置
$content = str_replace('{__TOKEN__}', $input_token, $content);
} elseif (preg_match('/<\/form(\s*)>/is', $content, $match)) {
// 智能生成表单令牌隐藏域
$content = str_replace($match[0], $input_token . $match[0], $content);
}
$content = str_ireplace('</head>', $meta_token . '</head>', $content);
} else {
$content = str_replace('{__TOKEN__}', '', $content);
}
}
//获得token
private function getToken()
{
$tokenName = C('TOKEN_NAME', null, '__hash__');
$tokenType = C('TOKEN_TYPE', null, 'md5');
if (!isset($_SESSION[$tokenName])) {
$_SESSION[$tokenName] = array();
}
// 标识当前页面唯一性
$tokenKey = md5($_SERVER['REQUEST_URI']);
if (isset($_SESSION[$tokenName][$tokenKey])) {
// 相同页面不重复生成session
$tokenValue = $_SESSION[$tokenName][$tokenKey];
} else {
$tokenValue = is_callable($tokenType) ? $tokenType(microtime(true)) : md5(microtime(true));
$_SESSION[$tokenName][$tokenKey] = $tokenValue;
if (IS_AJAX && C('TOKEN_RESET', null, true)) {
header($tokenName . ': ' . $tokenKey . '_' . $tokenValue);
}
//ajax需要获得这个header并替换页面中meta中的token值
}
return array($tokenName, $tokenKey, $tokenValue);
}
}
<?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>
// +----------------------------------------------------------------------
namespace Behavior;
/**
* 升级短信通知, 如果有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
{
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', null, '');
$skey = C('UPGRADE_NOTICE_SKEY', null, '');
$this->accesskey_ = $akey ? $akey : (defined('SAE_ACCESSKEY') ? SAE_ACCESSKEY : '');
$this->secretkey_ = $skey ? $skey : (defined('SAE_SECRETKEY') ? SAE_SECRETKEY : '');
$current_version = C('UPGRADE_CURRENT_VERSION', null, 0);
//读取接口
$info = $this->send('http://sinaclouds.sinaapp.com/thinkapi/upgrade.php?v=' . $current_version);
if ($info['version'] != $current_version) {
if ($this->sendSms($info['msg'])) {
trace($info['msg'], '升级通知成功', 'NOTIC', true);
}
//发送升级短信
}
S('think_upgrade_interval', true, C('UPGRADE_NOTICE_CHECK_INTERVAL', null, 604800));
}
}
private function sendSms($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', null, ''),
'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-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Behavior;
use Think\Storage;
/**
* 系统行为扩展:静态缓存写入
*/
class WriteHtmlCacheBehavior
{
// 行为扩展的执行入口必须是run
public function run(&$content)
{
//2014-11-28 修改 如果有HTTP 4xx 3xx 5xx 头部,禁止存储
//2014-12-1 修改 对注入的网址 防止生成,例如 /game/lst/SortType/hot/-e8-90-8c-e5-85-94-e7-88-b1-e6-b6-88-e9-99-a4/-e8-bf-9b-e5-87-bb-e7-9a-84-e9-83-a8-e8-90-bd/-e9-a3-8e-e4-ba-91-e5-a4-a9-e4-b8-8b/index.shtml
if (C('HTML_CACHE_ON') && defined('HTML_FILE_NAME')
&& !preg_match('/Status.*[345]{1}\d{2}/i', implode(' ', headers_list()))
&& !preg_match('/(-[a-z0-9]{2}){3,}/i', HTML_FILE_NAME)) {
//静态文件写入
Storage::put(HTML_FILE_NAME, $content, 'html');
}
}
}
<?php
/**
* 基本redis的消息队列
* 用法:
* use Com\Queue;
* $queue = Queue::getInstance('msg');
* 加入队列
* $queue->push('aaaaaa');
* $queue->push('bbbbb');
* 获取队列长度
* $queue->len();
* 读取队列
* $value = $queue->pop()
* 删除队列
* $queue->flushQueue();
*/
namespace Com;
class Queue extends \Think\Cache\Driver\Redisrw
{
static public $timeout = 1;
static public $queueName = 'queue';
/**
* 操作句柄
* @var string
* @access protected
*/
protected $handler;
/**
* 缓存连接参数
* @var integer
* @access protected
*/
protected $options = array();
/**
* 取得缓存类实例
* @static
* @access public
* @return mixed
*/
public static function getInstance($queueName, $options = [])
{
if (C('DATA_CACHE_TYPE') != 'Redisrw') exit('DATA_CACHE_TYPE DO NOT Support Redis');
//当前队列名称
self::$queueName = $queueName;
static $_instance = array();
if (!isset($_instance[$queueName])) {
$_instance[$queueName] = new Queue();
}
return $_instance[$queueName];
}
//设置队列名称
public static function setQueueName($name)
{
self::$queueName = $name;
}
/**
* 添加队列(lpush)
* @param string $value
* @return int 队列长度
*/
public function push($value)
{
return $this->lPush(self::$queueName, $value);
}
//brpop
/**
* 读取队列
* @return string|nil
*/
public function pop()
{
$result = $this->brPop(self::$queueName, self::$timeout);
return empty($result) ? $result : $result[1];
}
/**
* 删除一个消息队列
*/
public function flushQueue()
{
$this->delete(self::$queueName);
}
/**
* 返回队列长茺
* @return int
*/
public function len()
{
return $this->LLEN(self::$queueName);
}
}
?>
\ No newline at end of file
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2015 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi.cn@gmail.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Com;
class WechatCrypt{
/**
* 加密KEY
* @var string
*/
private $cyptKey = '';
/**
* 公众平台APPID
* @var string
*/
private $appId = '';
/**
* 构造方法,初始化加密KEY
* @param string $key 加密KEY
* @param string $appid 微信APP_KEY
*/
public function __construct($key, $appid){
if($key && $appid){
$this->appId = $appid;
$this->cyptKey = base64_decode($key . '=');
} else {
throw new \Exception('缺少参数 APP_ID 和加密KEY!');
}
}
/**
* 对明文进行加密
* @param string $text 需要加密的字符串
* @return string 密文字符串
*/
public function encrypt($text){
//填充到明文之前的随机字符
$random = self::getRandomStr(16);
//网络字节序
$size = pack("N", strlen($text));
//生成被加密字符串
$text = $random . $size . $text . $this->appId;
//打开加密算法模块
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
//使用PKCS7对明文进行补位
$text = self::PKCS7Encode($text, mcrypt_enc_get_key_size($td));
//初始化加密算法模块
mcrypt_generic_init($td, $this->cyptKey, substr($this->cyptKey, 0, 16));
//执行加密
$encrypt = mcrypt_generic($td, $text);
//关闭加密算法模块
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
//输出密文
return base64_encode($encrypt);
}
/**
* 对密文进行解密
* @param string $encrypt 密文
* @return string 明文
*/
public function decrypt($encrypt){
//BASE64解码
$encrypt = base64_decode($encrypt);
//打开加密算法模块
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
//初始化加密算法模块
mcrypt_generic_init($td, $this->cyptKey, substr($this->cyptKey, 0, 16));
//执行解密
$decrypt = mdecrypt_generic($td, $encrypt);
//去除PKCS7补位
$decrypt = self::PKCS7Decode($decrypt, mcrypt_enc_get_key_size($td));
//关闭加密算法模块
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
if(strlen($decrypt) < 16){
throw new \Exception("非法密文字符串!");
}
//去除随机字符串
$decrypt = substr($decrypt, 16);
//获取网络字节序
$size = unpack("N", substr($decrypt, 0, 4));
$size = $size[1];
//APP_ID
$appid = substr($decrypt, $size + 4);
//验证APP_ID
if($appid !== $this->appId){
throw new \Exception("非法APP_ID!");
}
//明文内容
$text = substr($decrypt, 4, $size);
return $text;
}
/**
* PKCS7填充字符
* @param string $text 被填充字符
* @param integer $size Block长度
*/
private static function PKCS7Encode($text, $size){
//字符串长度
$str_size = strlen($text);
//填充长度
$pad_size = $size - ($str_size % $size);
$pad_size = $pad_size ? : $size;
//填充的字符
$pad_chr = chr($pad_size);
//执行填充
$text = str_pad($text, $str_size + $pad_size, $pad_chr, STR_PAD_RIGHT);
return $text;
}
/**
* 删除PKCS7填充的字符
* @param string $text 已填充的字符
* @param integer $size Block长度
*/
private static function PKCS7Decode($text, $size){
//获取补位字符
$pad_str = ord(substr($text, -1));
if ($pad_str < 1 || $pad_str > $size) {
return '';
} else {
return substr($text, 0, strlen($text) - $pad_str);
}
}
/**
* 生成指定长度的字符串
* @param integer $len 字符串长度
* @return string 生成的字符串
*/
private static function getRandomStr($len){
static $pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
$str = '';
$max = strlen($pol) - 1;
for ($i = 0; $i < $len; $i++) {
$str .= $pol[mt_rand(0, $max)];
}
return $str;
}
}
<?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>
// +----------------------------------------------------------------------
namespace Org\Net;
/**
* IP 地理位置查询类 修改自 CoolCode.CN
* 由于使用UTF8编码 如果使用纯真IP地址库的话 需要对返回结果进行编码转换
* @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(!is_file($filename)) {
$filename = dirname(__FILE__) . '/' . $filename;
}
if (($this->fp = fopen($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;
}
}
<?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>
// +----------------------------------------------------------------------
namespace Org\Util;
/**
* 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 boolean
*/
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 boolean
*/
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 boolean
*/
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 ($this->get($i) == $element) {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);
}
}
<?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>
// +----------------------------------------------------------------------
namespace Org\Util;
class CodeSwitch
{
// 错误信息
private static $error = array();
// 提示信息
private static $info = array();
// 记录错误
private static function error($msg)
{
self::$error[] = $msg;
}
// 记录信息
private static function info($info)
{
self::$info[] = $info;
}
/**
* 编码转换函数,对整个文件进行编码转换
* 支持以下转换
* GB2312、UTF-8 WITH BOM转换为UTF-8
* UTF-8、UTF-8 WITH BOM转换为GB2312
* @access public
* @param string $filename 文件名
* @param string $out_charset 转换后的文件编码,与iconv使用的参数一致
* @return void
*/
public static function DetectAndSwitch($filename, $out_charset)
{
$fpr = fopen($filename, "r");
$char1 = fread($fpr, 1);
$char2 = fread($fpr, 1);
$char3 = fread($fpr, 1);
$originEncoding = "";
if (chr(239) == $char1 && chr(187) == $char2 && chr(191) == $char3) //UTF-8 WITH BOM
{
$originEncoding = "UTF-8 WITH BOM";
} elseif (chr(255) == $char1 && chr(254) == $char2) //UNICODE LE
{
self::error("不支持从UNICODE LE转换到UTF-8或GB编码");
fclose($fpr);
return;
} elseif (chr(254) == $char1 && chr(255) == $char2) {
//UNICODE BE
self::error("不支持从UNICODE BE转换到UTF-8或GB编码");
fclose($fpr);
return;
} else {
//没有文件头,可能是GB或UTF-8
if (rewind($fpr) === false) { //回到文件开始部分,准备逐字节读取判断编码
self::error($filename . "文件指针后移失败");
fclose($fpr);
return;
}
while (!feof($fpr)) {
$char = fread($fpr, 1);
//对于英文,GB和UTF-8都是单字节的ASCII码小于128的值
if (ord($char) < 128) {
continue;
}
//对于汉字GB编码第一个字节是110*****第二个字节是10******(有特例,比如联字)
//UTF-8编码第一个字节是1110****第二个字节是10******第三个字节是10******
//按位与出来结果要跟上面非星号相同,所以应该先判断UTF-8
//因为使用GB的掩码按位与,UTF-8的111得出来的也是110,所以要先判断UTF-8
if ((ord($char) & 224) == 224) {
//第一个字节判断通过
$char = fread($fpr, 1);
if ((ord($char) & 128) == 128) {
//第二个字节判断通过
$char = fread($fpr, 1);
if ((ord($char) & 128) == 128) {
$originEncoding = "UTF-8";
break;
}
}
}
if ((ord($char) & 192) == 192) {
//第一个字节判断通过
$char = fread($fpr, 1);
if ((ord($char) & 128) == 128) {
//第二个字节判断通过
$originEncoding = "GB2312";
break;
}
}
}
}
if (strtoupper($out_charset) == $originEncoding) {
self::info("文件" . $filename . "转码检查完成,原始文件编码" . $originEncoding);
fclose($fpr);
} else {
//文件需要转码
$originContent = "";
if ("UTF-8 WITH BOM" == $originEncoding) {
//跳过三个字节,把后面的内容复制一遍得到utf-8的内容
fseek($fpr, 3);
$originContent = fread($fpr, filesize($filename) - 3);
fclose($fpr);
} elseif (rewind($fpr) != false) {
//不管是UTF-8还是GB2312,回到文件开始部分,读取内容
$originContent = fread($fpr, filesize($filename));
fclose($fpr);
} else {
self::error("文件编码不正确或指针后移失败");
fclose($fpr);
return;
}
//转码并保存文件
$content = iconv(str_replace(" WITH BOM", "", $originEncoding), strtoupper($out_charset), $originContent);
$fpw = fopen($filename, "w");
fwrite($fpw, $content);
fclose($fpw);
if ("" != $originEncoding) {
self::info("对文件" . $filename . "转码完成,原始文件编码" . $originEncoding . ",转换后文件编码" . strtoupper($out_charset));
} elseif ("" == $originEncoding) {
self::info("文件" . $filename . "中没有出现中文,但是可以断定不是带BOM的UTF-8编码,没有进行编码转换,不影响使用");
}
}
}
/**
* 目录遍历函数
* @access public
* @param string $path 要遍历的目录名
* @param string $mode 遍历模式,一般取FILES,这样只返回带路径的文件名
* @param array $file_types 文件后缀过滤数组
* @param int $maxdepth 遍历深度,-1表示遍历到最底层
* @return void
*/
public static function searchdir($path, $mode = "FULL", $file_types = array(".html", ".php"), $maxdepth = -1, $d = 0)
{
if (substr($path, strlen($path) - 1) != '/') {
$path .= '/';
}
$dirlist = array();
if ("FILES" != $mode) {
$dirlist[] = $path;
}
if ($handle = @opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ('.' != $file && '..' != $file) {
$file = $path . $file;
if (!is_dir($file)) {
if ("DIRS" != $mode) {
$extension = "";
$extpos = strrpos($file, '.');
if (false !== $extpos) {
$extension = substr($file, $extpos, strlen($file) - $extpos);
}
$extension = strtolower($extension);
if (in_array($extension, $file_types)) {
$dirlist[] = $file;
}
}
} elseif ($d >= 0 && ($d < $maxdepth || $maxdepth < 0)) {
$result = self::searchdir($file . '/', $mode, $file_types, $maxdepth, $d + 1);
$dirlist = array_merge($dirlist, $result);
}
}
}
closedir($handle);
}
if (0 == $d) {
natcasesort($dirlist);
}
return ($dirlist);
}
/**
* 对整个项目目录中的PHP和HTML文件行进编码转换
* @access public
* @param string $app 要遍历的项目路径
* @param string $mode 遍历模式,一般取FILES,这样只返回带路径的文件名
* @param array $file_types 文件后缀过滤数组
* @return void
*/
public static function CodingSwitch($app = "./", $charset = 'UTF-8', $mode = "FILES", $file_types = array(".html", ".php"))
{
self::info("注意: 程序使用的文件编码检测算法可能对某些特殊字符不适用");
$filearr = self::searchdir($app, $mode, $file_types);
foreach ($filearr as $file) {
self::DetectAndSwitch($file, $charset);
}
}
public static function getError()
{
return self::$error;
}
public static function getInfo()
{
return self::$info;
}
}
<?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>
// +----------------------------------------------------------------------
namespace Org\Util;
/**
* Stack实现类
* @category ORG
* @package ORG
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
*/
class Stack extends ArrayList
{
/**
* 架构函数
* @access public
* @param array $values 初始化数组元素
*/
public function __construct($values = array())
{
parent::__construct($values);
}
/**
* 将堆栈的内部指针指向第一个单元
* @access public
* @return mixed
*/
public function peek()
{
return reset($this->toArray());
}
/**
* 元素进栈
* @access public
* @param mixed $value
* @return mixed
*/
public function push($value)
{
$this->add($value);
return $value;
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think;
/**
* ThinkPHP Behavior基础类
*/
abstract class Behavior
{
/**
* 执行行为 run方法是Behavior唯一的接口
* @access public
* @param mixed $params 行为参数
* @return void
*/
abstract public function run(&$params);
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think;
/**
* 用于ThinkPHP的自动生成
*/
class Build
{
protected static $controller = '<?php
namespace [MODULE]\Controller;
use Think\Controller;
class [CONTROLLER]Controller extends Controller
{
public function index()
{
[CONTENT]
}
}';
protected static $model = '<?php
namespace [MODULE]\Model;
use Think\Model;
class [MODEL]Model extends Model
{
}';
// 检测应用目录是否需要自动创建
public static function checkDir($module)
{
if (!is_dir(APP_PATH . $module)) {
// 创建模块的目录结构
self::buildAppDir($module);
} elseif (!is_dir(LOG_PATH)) {
// 检查缓存目录
self::buildRuntime();
}
}
// 创建应用和模块的目录结构
public static function buildAppDir($module)
{
// 没有创建的话自动创建
if (!is_dir(APP_PATH)) {
mkdir(APP_PATH, 0755, true);
}
if (is_writeable(APP_PATH)) {
$dirs = array(
COMMON_PATH,
COMMON_PATH . 'Common/',
CONF_PATH,
APP_PATH . $module . '/',
APP_PATH . $module . '/Common/',
APP_PATH . $module . '/Controller/',
APP_PATH . $module . '/Model/',
APP_PATH . $module . '/Conf/',
APP_PATH . $module . '/View/',
RUNTIME_PATH,
CACHE_PATH,
CACHE_PATH . $module . '/',
LOG_PATH,
LOG_PATH . $module . '/',
TEMP_PATH,
DATA_PATH,
);
foreach ($dirs as $dir) {
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
}
// 写入目录安全文件
self::buildDirSecure($dirs);
// 写入应用配置文件
if (!is_file(CONF_PATH . 'config' . CONF_EXT)) {
file_put_contents(CONF_PATH . 'config' . CONF_EXT, '.php' == CONF_EXT ? "<?php\nreturn array(\n\t//'配置项'=>'配置值'\n);" : '');
}
// 写入模块配置文件
if (!is_file(APP_PATH . $module . '/Conf/config' . CONF_EXT)) {
file_put_contents(APP_PATH . $module . '/Conf/config' . CONF_EXT, '.php' == CONF_EXT ? "<?php\nreturn array(\n\t//'配置项'=>'配置值'\n);" : '');
}
// 自动生成控制器类
self::buildController($module, defined('BUILD_CONTROLLER_LIST') ? BUILD_CONTROLLER_LIST : C('DEFAULT_CONTROLLER'));
// 自动生成模型类
if (defined('BUILD_MODEL_LIST')) {
self::buildModel($module, BUILD_MODEL_LIST);
}
} else {
header('Content-Type:text/html; charset=utf-8');
exit('应用目录[' . APP_PATH . ']不可写,目录无法自动生成!<BR>请手动生成项目目录~');
}
}
// 检查缓存目录(Runtime) 如果不存在则自动创建
public static function buildRuntime()
{
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;
}
// 创建控制器类
public static function buildController($module, $controllers)
{
$list = is_array($controllers) ? $controllers : explode(',', $controllers);
$hello = '$this->show(\'<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} body{ background: #fff; font-family: "微软雅黑"; color: #333;font-size:24px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.8em; font-size: 36px } a,a:hover{color:blue;}</style><div style="padding: 24px 48px;"> <h1>:)</h1><p>欢迎使用 <b>ThinkPHP</b>!</p><br/>版本 V{$Think.version}</div><script type="text/javascript" src="http://ad.topthink.com/Public/static/client.js"></script><thinkad id="ad_55e75dfae343f5a1"></thinkad><script type="text/javascript" src="http://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script>\',\'utf-8\');';
foreach ($list as $controller) {
$hello = C('DEFAULT_CONTROLLER') == $controller ? $hello : '';
$file = APP_PATH . $module . '/Controller/' . $controller . 'Controller' . EXT;
if (!is_file($file)) {
$content = str_replace(array('[MODULE]', '[CONTROLLER]', '[CONTENT]'), array($module, $controller, $hello), self::$controller);
if (!C('APP_USE_NAMESPACE')) {
$content = preg_replace('/namespace\s(.*?);/', '', $content, 1);
}
$dir = dirname($file);
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
file_put_contents($file, $content);
}
}
}
// 创建模型类
public static function buildModel($module, $models)
{
$list = is_array($models) ? $models : explode(',', $models);
foreach ($list as $model) {
$file = APP_PATH . $module . '/Model/' . $model . 'Model' . EXT;
if (!is_file($file)) {
$content = str_replace(array('[MODULE]', '[MODEL]'), array($module, $model), self::$model);
if (!C('APP_USE_NAMESPACE')) {
$content = preg_replace('/namespace\s(.*?);/', '', $content, 1);
}
$dir = dirname($file);
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
file_put_contents($file, $content);
}
}
}
// 生成目录安全文件
public static function buildDirSecure($dirs = array())
{
// 目录安全写入(默认开启)
defined('BUILD_DIR_SECURE') or define('BUILD_DIR_SECURE', true);
if (BUILD_DIR_SECURE) {
defined('DIR_SECURE_FILENAME') or define('DIR_SECURE_FILENAME', 'index.html');
defined('DIR_SECURE_CONTENT') or define('DIR_SECURE_CONTENT', ' ');
// 自动写入目录安全文件
$content = DIR_SECURE_CONTENT;
$files = explode(',', DIR_SECURE_FILENAME);
foreach ($files as $filename) {
foreach ($dirs as $dir) {
file_put_contents($dir . $filename, $content);
}
}
}
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think;
/**
* 缓存管理类
*/
class Cache
{
/**
* 操作句柄
* @var string
* @access protected
*/
protected $handler;
/**
* 缓存连接参数
* @var integer
* @access protected
*/
protected $options = array();
/**
* 连接缓存
* @access public
* @param string $type 缓存类型
* @param array $options 配置数组
* @return object
*/
public function connect($type = '', $options = array())
{
if (empty($type)) {
$type = C('DATA_CACHE_TYPE');
}
$class = strpos($type, '\\') ? $type : 'Think\\Cache\\Driver\\' . ucwords(strtolower($type));
if (class_exists($class)) {
$cache = new $class($options);
} else {
E(L('_CACHE_TYPE_INVALID_') . ':' . $type);
}
return $cache;
}
/**
* 取得缓存类实例
* @static
* @access public
* @return mixed
*/
public static function getInstance($type = '', $options = array())
{
static $_instance = array();
$guid = $type . to_guid_string($options);
if (!isset($_instance[$guid])) {
$obj = new Cache();
$_instance[$guid] = $obj->connect($type, $options);
}
return $_instance[$guid];
}
public function __get($name)
{
return $this->get($name);
}
public function __set($name, $value)
{
return $this->set($name, $value);
}
public function __unset($name)
{
$this->rm($name);
}
public function setOptions($name, $value)
{
$this->options[$name] = $value;
}
public function getOptions($name)
{
return $this->options[$name];
}
/**
* 队列缓存
* @access protected
* @param string $key 队列名
* @return mixed
*/
//
protected function queue($key)
{
static $_handler = array(
'file' => array('F', 'F'),
'xcache' => array('xcache_get', 'xcache_set'),
'apc' => array('apc_fetch', 'apc_store'),
);
$queue = isset($this->options['queue']) ? $this->options['queue'] : 'file';
$fun = isset($_handler[$queue]) ? $_handler[$queue] : $_handler['file'];
$queue_name = isset($this->options['queue_name']) ? $this->options['queue_name'] : 'think_queue';
$value = $fun[0]($queue_name);
if (!$value) {
$value = array();
}
// 进列
if (false === array_search($key, $value)) {
array_push($value, $key);
}
if (count($value) > $this->options['length']) {
// 出列
$key = array_shift($value);
// 删除缓存
$this->rm($key);
if (APP_DEBUG) {
//调试模式下,记录出列次数
N($queue_name . '_out_times', 1);
}
}
return $fun[1]($queue_name, $value);
}
public function __call($method, $args)
{
//调用缓存类型自己的方法
if (method_exists($this->handler, $method)) {
return call_user_func_array(array($this->handler, $method), $args);
} else {
E(__CLASS__ . ':' . $method . L('_METHOD_NOT_EXIST_'));
return;
}
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think\Cache\Driver;
use Think\Cache;
/**
* Apachenote缓存驱动
*/
class Apachenote 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 boolean
*/
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 ("OK\n" === $ret) {
if ($this->options['length'] > 0) {
// 记录缓存队列
$this->queue($name);
}
return true;
}
return false;
}
/**
* 删除缓存
* @access public
* @param string $name 缓存变量名
* @return boolean
*/
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 "OK\n" === $ret;
}
/**
* 关闭缓存
* @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']);
}
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think\Cache\Driver;
use Think\Cache;
/**
* Apc缓存驱动
*/
class Apc extends Cache
{
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options = array())
{
if (!function_exists('apc_cache_info')) {
E(L('_NOT_SUPPORT_') . ':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 boolean
*/
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 boolean
*/
public function rm($name)
{
return apc_delete($this->options['prefix'] . $name);
}
/**
* 清除缓存
* @access public
* @return boolean
*/
public function clear()
{
return apc_clear_cache();
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think\Cache\Driver;
use Think\Cache;
/**
* 数据库方式缓存驱动
* CREATE TABLE think_cache (
* cachekey varchar(255) NOT NULL,
* expire int(11) NOT NULL,
* data blob,
* datacrc int(32),
* UNIQUE KEY `cachekey` (`cachekey`)
* );
*/
class Db 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');
$this->handler = \Think\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 (md5($result['data']) != $result['datacrc']) { //校验错误
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 boolean
*/
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 = (0 == $expire) ? 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 boolean
*/
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 boolean
*/
public function clear()
{
return $this->handler->execute('TRUNCATE TABLE `' . $this->options['table'] . '`');
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think\Cache\Driver;
use Think\Cache;
/**
* Eaccelerator缓存驱动
*/
class Eaccelerator 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 boolean
*/
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 boolean
*/
public function rm($name)
{
return eaccelerator_rm($this->options['prefix'] . $name);
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think\Cache\Driver;
use Think\Cache;
/**
* 文件类型缓存类
*/
class File extends Cache
{
/**
* 架构函数
* @access public
*/
public function __construct($options = array())
{
if (!empty($options)) {
$this->options = $options;
}
$this->options['temp'] = !empty($options['temp']) ? $options['temp'] : C('DATA_CACHE_PATH');
$this->options['prefix'] = isset($options['prefix']) ? $options['prefix'] : C('DATA_CACHE_PREFIX');
$this->options['expire'] = isset($options['expire']) ? $options['expire'] : C('DATA_CACHE_TIME');
$this->options['length'] = isset($options['length']) ? $options['length'] : 0;
if (substr($this->options['temp'], -1) != '/') {
$this->options['temp'] .= '/';
}
$this->init();
}
/**
* 初始化检查
* @access private
* @return boolean
*/
private function init()
{
// 创建应用缓存目录
if (!is_dir($this->options['temp'])) {
mkdir($this->options['temp']);
}
}
/**
* 取得变量的存储文件名
* @access private
* @param string $name 缓存变量名
* @return string
*/
private function filename($name)
{
$name = md5(C('DATA_CACHE_KEY') . $name);
if (C('DATA_CACHE_SUBDIR')) {
// 使用子目录
$dir = '';
for ($i = 0; $i < C('DATA_PATH_LEVEL'); $i++) {
$dir .= $name{$i} . '/';
}
if (!is_dir($this->options['temp'] . $dir)) {
mkdir($this->options['temp'] . $dir, 0755, true);
}
$filename = $dir . $this->options['prefix'] . $name . '.php';
} else {
$filename = $this->options['prefix'] . $name . '.php';
}
return $this->options['temp'] . $filename;
}
/**
* 读取缓存
* @access public
* @param string $name 缓存变量名
* @return mixed
*/
public function get($name)
{
$filename = $this->filename($name);
if (!is_file($filename)) {
return false;
}
N('cache_read', 1);
$content = file_get_contents($filename);
if (false !== $content) {
$expire = (int) substr($content, 8, 12);
if (0 != $expire && time() > filemtime($filename) + $expire) {
//缓存过期删除缓存文件
unlink($filename);
return false;
}
if (C('DATA_CACHE_CHECK')) {
//开启数据校验
$check = substr($content, 20, 32);
$content = substr($content, 52, -3);
if (md5($content) != $check) {
//校验错误
return false;
}
} else {
$content = substr($content, 20, -3);
}
if (C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) {
//启用数据压缩
$content = gzuncompress($content);
}
$content = unserialize($content);
return $content;
} else {
return false;
}
}
/**
* 写入缓存
* @access public
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param int $expire 有效时间 0为永久
* @return boolean
*/
public function set($name, $value, $expire = null)
{
N('cache_write', 1);
if (is_null($expire)) {
$expire = $this->options['expire'];
}
$filename = $this->filename($name);
$data = serialize($value);
if (C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) {
//数据压缩
$data = gzcompress($data, 3);
}
if (C('DATA_CACHE_CHECK')) {
//开启数据校验
$check = md5($data);
} else {
$check = '';
}
$data = "<?php\n//" . sprintf('%012d', $expire) . $check . $data . "\n?>";
$result = file_put_contents($filename, $data);
if ($result) {
if ($this->options['length'] > 0) {
// 记录缓存队列
$this->queue($name);
}
clearstatcache();
return true;
} else {
return false;
}
}
/**
* 删除缓存
* @access public
* @param string $name 缓存变量名
* @return boolean
*/
public function rm($name)
{
return unlink($this->filename($name));
}
/**
* 清除缓存
* @access public
* @param string $name 缓存变量名
* @return boolean
*/
public function clear()
{
$path = $this->options['temp'];
$files = scandir($path);
if ($files) {
foreach ($files as $file) {
if ('.' != $file && '..' != $file && is_dir($path . $file)) {
array_map('unlink', glob($path . $file . '/*.*'));
} elseif (is_file($path . $file)) {
unlink($path . $file);
}
}
return true;
}
return false;
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think\Cache\Driver;
use Think\Cache;
/**
* Memcache缓存驱动
*/
class Memcache extends Cache
{
/**
* 架构函数
* @param array $options 缓存参数
* @access public
*/
public function __construct($options = array())
{
if (!extension_loaded('memcache')) {
E(L('_NOT_SUPPORT_') . ':memcache');
}
$options = array_merge(array(
'host' => C('MEMCACHE_HOST') ?: '127.0.0.1',
'port' => C('MEMCACHE_PORT') ?: 11211,
'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; false === $options['timeout'] ?
$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 boolean
*/
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 boolean
*/
public function rm($name, $ttl = false)
{
$name = $this->options['prefix'] . $name;
return false === $ttl ?
$this->handler->delete($name) :
$this->handler->delete($name, $ttl);
}
/**
* 清除缓存
* @access public
* @return boolean
*/
public function clear()
{
return $this->handler->flush();
}
}
<?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: 何辉 <runphp@qq.com>
// +----------------------------------------------------------------------
namespace Think\Cache\Driver;
use Memcached as MemcachedResource;
use Think\Cache;
/**
* Memcached缓存驱动
*/
class Memcached extends Cache
{
/**
*
* @param array $options
*/
public function __construct($options = array())
{
if (!extension_loaded('memcached')) {
E(L('_NOT_SUPPORT_') . ':memcached');
}
$options = array_merge(array(
'servers' => C('MEMCACHED_SERVER') ?: null,
'lib_options' => C('MEMCACHED_LIB') ?: null,
), $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;
$this->handler = new MemcachedResource;
$options['servers'] && $this->handler->addServers($options['servers']);
$options['lib_options'] && $this->handler->setOptions($options['lib_options']);
}
/**
* 读取缓存
* @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 boolean
*/
public function set($name, $value, $expire = null)
{
N('cache_write', 1);
if (is_null($expire)) {
$expire = $this->options['expire'];
}
$name = $this->options['prefix'] . $name;
$expire = $expire == 0 ? 0 : time() + $expire;
if ($this->handler->set($name, $value, $expire)) {
if ($this->options['length'] > 0) {
// 记录缓存队列
$this->queue($name);
}
return true;
}
return false;
}
/**
* 删除缓存
* @access public
* @param string $name 缓存变量名
* @return boolean
*/
public function rm($name, $ttl = false)
{
$name = $this->options['prefix'] . $name;
return false === $ttl ?
$this->handler->delete($name) :
$this->handler->delete($name, $ttl);
}
/**
* 清除缓存
* @access public
* @return boolean
*/
public function clear()
{
return $this->handler->flush();
}
}
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
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.
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.
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.
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.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment