更新核心类库

This commit is contained in:
thinkphp
2015-01-19 11:04:05 +08:00
parent 5f1623aa7d
commit b34b209af4
85 changed files with 1266 additions and 6142 deletions

View File

@@ -10,6 +10,7 @@
// +----------------------------------------------------------------------
namespace Think;
use Think\Exception;
/**
* App 应用管理
@@ -22,52 +23,76 @@ class App {
* @access public
* @return void
*/
static public function run() {
static public function run($config) {
// 监听app_init
Tag::listen('app_init');
if(Config::get('common_module')){
define('COMMON_PATH', APP_PATH . Config::get('common_module').'/');
// 加载全局初始化文件
if(is_file( COMMON_PATH . 'init' . EXT )) {
include COMMON_PATH . 'init' . EXT;
}else{
// 检测全局配置文件
if(is_file(COMMON_PATH . 'config' . EXT)) {
Config::set(include COMMON_PATH . 'config' . EXT);
}
// 加载全局别名文件
if(is_file(COMMON_PATH . 'alias' . EXT)) {
Loader::addMap(include COMMON_PATH . 'alias' . EXT);
}
// 加载全局公共文件
if(is_file( COMMON_PATH . 'common' . EXT)) {
include COMMON_PATH . 'common' . EXT;
}
if(is_file(COMMON_PATH . 'tags' . EXT)) {
// 全局行为扩展文件
Tag::import(include COMMON_PATH . 'tags' . EXT);
}
}
}
Hook::listen('app_init');
define('COMMON_PATH', APP_PATH . $config['common_module'].'/');
// 加载全局初始化文件
if(is_file( COMMON_PATH . 'init' . EXT )) {
include COMMON_PATH . 'init' . EXT;
}else{
// 检测全局配置文件
if(is_file(COMMON_PATH . 'config' . EXT)) {
$config = Config::set(include COMMON_PATH . 'config' . EXT);
}
// 加载全局别名文件
if(is_file(COMMON_PATH . 'alias' . EXT)) {
Loader::addMap(include COMMON_PATH . 'alias' . EXT);
}
// 加载全局公共文件
if(is_file( COMMON_PATH . 'common' . EXT)) {
include COMMON_PATH . 'common' . EXT;
}
if(is_file(COMMON_PATH . 'tags' . EXT)) {
// 全局行为扩展文件
Hook::import(include COMMON_PATH . 'tags' . EXT);
}
}
// 应用URL调度
self::dispatch($config);
// 监听app_run
Tag::listen('app_run');
Hook::listen('app_run');
// 执行操作
$instance = Loader::controller(CONTROLLER_NAME);
if(!preg_match('/^[A-Za-z](\/|\w)*$/',CONTROLLER_NAME)){ // 安全检测
$instance = false;
}elseif($config['action_bind_class']){
// 操作绑定到类:模块\Controller\控制器\操作
$layer = $config['controller_layer'];
if(is_dir(MODULE_PATH.$layer.'/'.CONTROLLER_NAME)){
$namespace = MODULE_NAME.'\\'.$layer.'\\'.CONTROLLER_NAME.'\\';
}else{
// 空控制器
$namespace = MODULE_NAME.'\\'.$layer.'\\_empty\\';
}
$actionName = strtolower(ACTION_NAME);
if(class_exists($namespace.$actionName)){
$class = $namespace.$actionName;
}elseif(class_exists($namespace.'_empty')){
// 空操作
$class = $namespace.'_empty';
}else{
throw new Exception('_ERROR_ACTION_:'.ACTION_NAME);
}
$instance = new $class;
// 操作绑定到类后 固定执行run入口
$action = 'run';
}else{
$instance = Loader::controller(CONTROLLER_NAME);
// 获取当前操作名
$action = ACTION_NAME . $config['action_suffix'];
}
if(!$instance) {
E('[ ' . MODULE_NAME . '\\Controller\\' . parse_name(CONTROLLER_NAME, 1) . 'Controller ] not exists');
throw new Exception('[ ' . MODULE_NAME . '\\Controller\\' . parse_name(CONTROLLER_NAME, 1) . 'Controller ] not exists');
}
// 获取当前操作名
$action = ACTION_NAME . $config['action_suffix'];
try{
// 操作方法开始监听
$call = [$instance, $action];
Tag::listen('action_begin', $call);
Hook::listen('action_begin', $call);
if(!preg_match('/^[A-Za-z](\w)*$/', $action)){
// 非法操作
throw new \ReflectionException();
@@ -88,9 +113,12 @@ class App {
$vars = $_GET;
}
$params = $method->getParameters();
$paramsBindType = $config['url_parmas_bind_type'];
foreach ($params as $param){
$name = $param->getName();
if(isset($vars[$name])) {
if( 1 == $paramsBindType && !empty($vars) ){
$args[] = array_shift($vars);
}if(0 == $paramsBindType && isset($vars[$name])) {
$args[] = $vars[$name];
}elseif($param->isDefaultValueAvailable()){
$args[] = $param->getDefaultValue();
@@ -98,12 +126,13 @@ class App {
E('_PARAM_ERROR_:' . $name);
}
}
array_walk_recursive($args,'Input::filterExp');
$method->invokeArgs($instance, $args);
}else{
$method->invoke($instance);
}
// 操作方法执行完成监听
Tag::listen('action_end', $call);
Hook::listen('action_end', $call);
}else{
// 操作方法不是Public 抛出异常
throw new \ReflectionException();
@@ -114,11 +143,11 @@ class App {
$method = new \ReflectionMethod($instance, '_empty');
$method->invokeArgs($instance, [$action, '']);
}else{
E('[ ' . (new \ReflectionClass($instance))->getName() . ':' . $action . ' ] not exists ', 404);
throw new Exception('[ ' . (new \ReflectionClass($instance))->getName() . ':' . $action . ' ] not exists ', 404);
}
}
// 监听app_end
Tag::listen('app_end');
Hook::listen('app_end');
return ;
}
@@ -128,25 +157,20 @@ class App {
* @return void
*/
static public function dispatch($config) {
$var_m = $config['var_module'];
$var_g = $config['var_group'];
$var_c = $config['var_controller'];
$var_a = $config['var_action'];
$var_p = $config['var_pathinfo'];
if(isset($_GET[$var_p])) { // 判断URL里面是否有兼容模式参数
$_SERVER['PATH_INFO'] = $_GET[$var_p];
unset($_GET[$var_p]);
if(isset($_GET[$config['var_pathinfo']])) { // 判断URL里面是否有兼容模式参数
$_SERVER['PATH_INFO'] = $_GET[$config['var_pathinfo']];
unset($_GET[$config['var_pathinfo']]);
}elseif(IS_CLI){ // CLI模式下 index.php module/controller/action/params/...
$_SERVER['PATH_INFO'] = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : '';
}
// 检测域名部署
if(!IS_CLI) {
Route::checkDomain();
if(!IS_CLI && $config['sub_domain_deploy']) {
Route::checkDomain($config);
}
// 监听path_info
Tag::listen('path_info');
Hook::listen('path_info');
// 分析PATHINFO信息
if(!isset($_SERVER['PATH_INFO']) && $_SERVER['SCRIPT_NAME'] != $_SERVER['PHP_SELF']) {
$types = explode(',', $config['pathinfo_fetch']);
@@ -162,43 +186,34 @@ class App {
}
}
// 定位模块
if(empty($_SERVER['PATH_INFO'])) {
$_SERVER['PATH_INFO'] = '';
}
// URL后缀
define('__EXT__', strtolower(pathinfo($_SERVER['PATH_INFO'],PATHINFO_EXTENSION)));
$_SERVER['PATH_INFO'] = trim(preg_replace('/\.(' . trim($config['url_html_suffix'], '.') . ')$/i', '', $_SERVER['PATH_INFO']), '/');
if($_SERVER['PATH_INFO']) {
if($config['url_deny_suffix'] && preg_match('/\.('.$config['url_deny_suffix'].')$/i', $_SERVER['PATH_INFO'])){
exit;
}
$paths = explode($config['pathinfo_depr'], $_SERVER['PATH_INFO']);
// 获取URL中的模块名
if($config['require_module'] && !isset($_GET[$var_m])) {
$_GET[$var_m] = array_shift($paths);
$_SERVER['PATH_INFO'] = implode('/', $paths);
}
define('__INFO__','');
define('__EXT__','');
}else{
define('__INFO__',trim($_SERVER['PATH_INFO'],'/'));
// URL后缀
define('__EXT__', strtolower(pathinfo($_SERVER['PATH_INFO'],PATHINFO_EXTENSION)));
$_SERVER['PATH_INFO'] = __INFO__;
if(!defined('BIND_MODULE')){
if($config['url_deny_suffix'] && preg_match('/\.('.$config['url_deny_suffix'].')$/i', $_SERVER['PATH_INFO'])){
exit;
}
$paths = explode($config['pathinfo_depr'], $_SERVER['PATH_INFO']);
// 获取URL中的模块名
if($config['require_module'] && !isset($_GET[$config['var_module']])) {
$_GET[$config['var_module']] = array_shift($paths);
$_SERVER['PATH_INFO'] = implode('/', $paths);
}
}
}
// 获取模块名称
$module = strtolower(isset($_GET[$var_m]) ? $_GET[$var_m] : $config['default_module']);
if($maps = Config::get('url_module_map')) {
if(isset($maps[$module])) {
// 记录当前别名
define('MODULE_ALIAS',$module);
// 获取实际的项目名
$module = $maps[MODULE_ALIAS];
}elseif(array_search($module,$maps)){
// 禁止访问原始项目
$module = '';
}
}
define('MODULE_NAME', ucwords($module));
define('MODULE_NAME', defined('BIND_MODULE')? BIND_MODULE : self::getModule($config));
// 模块初始化
if(MODULE_NAME && Config::get('common_module') != MODULE_NAME && is_dir( APP_PATH . MODULE_NAME )) {
Tag::listen('app_begin');
if(MODULE_NAME && $config['common_module'] != MODULE_NAME && is_dir( APP_PATH . MODULE_NAME )) {
Hook::listen('app_begin');
define('MODULE_PATH', APP_PATH . MODULE_NAME . '/');
// 加载模块初始化文件
if(is_file( MODULE_PATH . 'init' . EXT )) {
@@ -223,33 +238,39 @@ class App {
}
if(is_file(MODULE_PATH . 'tags' . EXT)) {
// 行为扩展文件
Tag::import(include MODULE_PATH . 'tags' . EXT);
Hook::import(include MODULE_PATH . 'tags' . EXT);
}
}
$var_g = $config['var_group'];
$var_c = $config['var_controller'];
$var_a = $config['var_action'];
}else{
E('module not exists :' . MODULE_NAME);
throw new Exception('module not exists :' . MODULE_NAME);
}
// 路由检测和控制器、操作解析
Route::check($_SERVER['PATH_INFO']);
// 获取分组名
if(Config::get('require_group')){
define('GROUP_NAME', strtolower(isset($_GET[$var_g]) ? $_GET[$var_g] : $config['default_group']));
}else{
define('GROUP_NAME', '');
}
Route::check($_SERVER['PATH_INFO'],$config);
// 获取控制器名
define('CONTROLLER_NAME', strtolower(isset($_GET[$var_c]) ? $_GET[$var_c] : $config['default_controller']));
define('CONTROLLER_NAME', strip_tags(strtolower(isset($_GET[$config['var_controller']]) ? $_GET[$config['var_controller']] : $config['default_controller'])));
// 获取操作名
define('ACTION_NAME', strtolower(isset($_GET[$var_a]) ? $_GET[$var_a] : $config['default_action']));
define('ACTION_NAME', strip_tags(strtolower(isset($_GET[$config['var_action']]) ? $_GET[$config['var_action']] : $config['default_action'])));
unset($_GET[$var_a], $_GET[$var_c], $_GET[$var_m]);
unset($_GET[$config['var_action']], $_GET[$config['var_controller']], $_GET[$config['var_module']]);
//保证$_REQUEST正常取值
$_REQUEST = array_merge($_POST, $_GET);
}
static private function getModule($config){
$module = strtolower(isset($_GET[$config['var_module']]) ? $_GET[$config['var_module']] : $config['default_module']);
if($maps = $config['url_module_map']) {
if(isset($maps[$module])) {
// 记录当前别名
define('MODULE_ALIAS',$module);
// 获取实际的项目名
$module = $maps[MODULE_ALIAS];
}elseif(array_search($module,$maps)){
// 禁止访问原始项目
$module = '';
}
}
return strip_tags(ucwords($module));
}
}

View File

@@ -52,7 +52,7 @@ class TokenBuildBehavior extends Behavior {
if(isset($_SESSION[$tokenName][$tokenKey])) {// 相同页面不重复生成session
$tokenValue = $_SESSION[$tokenName][$tokenKey];
}else{
$tokenValue = $tokenType(microtime(TRUE));
$tokenValue = $tokenType(microtime(true));
$_SESSION[$tokenName][$tokenKey] = $tokenValue;
}
$token = '<input type="hidden" name="'.$tokenName.'" value="'.$tokenKey.'_'.$tokenValue.'" />';

View File

@@ -27,12 +27,12 @@ class Cache {
*/
static public function connect($options=[]) {
$type = !empty($options['type'])?$options['type']:'File';
$class = 'Think\\Cache\\Driver\\'.ucwords($type);
$class = 'Think\\Cache\\Driver\\'.ucwords($type);
self::$handler = new $class($options);
return self::$handler;
}
static public function __callStatic($method, $params){
return call_user_func_array(array(self::$handler, $method), $params);
}
static public function __callStatic($method, $params){
return call_user_func_array(array(self::$handler, $method), $params);
}
}

View File

@@ -36,15 +36,16 @@ class Config {
// 检测配置是否存在
static public function has($name,$range=''){
$range = $range?$range:self::$_range;
$name = strtolower($name);
// 优先执行设置获取或赋值
$range = $range ? $range : self::$_range;
$name = strtolower($name);
if (!strpos($name, '.')) {
return isset(self::$_config[$range][$name]);
}else{
// 二维数组设置和获取支持
$name = explode('.', $name);
return isset(self::$_config[$range][$name[0]][$name[1]]);
}
// 二维数组设置和获取支持
$name = explode('.', $name);
return isset(self::$_config[$range][$name[0]][$name[1]]);
}
// 获取配置参数 为空则获取所有配置
@@ -55,13 +56,13 @@ class Config {
return self::$_config[$range];
}
$name = strtolower($name);
// 优先执行设置获取或赋值
if (!strpos($name, '.')) {
return isset(self::$_config[$range][$name]) ? self::$_config[$range][$name] : null;
}else{
// 二维数组设置和获取支持
$name = explode('.', $name);
return isset(self::$_config[$range][$name[0]][$name[1]]) ? self::$_config[$range][$name[0]][$name[1]] : null;
}
// 二维数组设置和获取支持
$name = explode('.', $name);
return isset(self::$_config[$range][$name[0]][$name[1]]) ? self::$_config[$range][$name[0]][$name[1]] : null;
}
// 设置配置参数 name为数组则为批量设置
@@ -74,18 +75,18 @@ class Config {
$name = strtolower($name);
if (!strpos($name, '.')) {
self::$_config[$range][$name] = $value;
return;
}else{
// 二维数组设置和获取支持
$name = explode('.', $name);
self::$_config[$range][$name[0]][$name[1]] = $value;
}
// 二维数组设置和获取支持
$name = explode('.', $name);
self::$_config[$range][$name[0]][$name[1]] = $value;
return;
}
// 批量设置
if (is_array($name)){
}elseif (is_array($name)){
// 批量设置
self::$_config[$range] = array_merge(self::$_config[$range], array_change_key_case($name));
return self::$_config[$range];
}else{
return null; // 避免非法参数
}
return null; // 避免非法参数
}
}

View File

@@ -11,6 +11,7 @@
namespace Think;
use Think\View;
use Think\Transform;
class Controller {
// 视图类实例
@@ -27,7 +28,7 @@ class Controller {
'cache_path' => RUNTIME_PATH . 'Cache/',
];
$this->view = new View();
$this->view->engine('think', $config);
$this->view->engine(Config::get('template_engine'), $config);
//控制器初始化
if(method_exists($this, '_initialize'))
@@ -80,39 +81,41 @@ class Controller {
* @return void
*/
protected function ajaxReturn($data, $type='') {
if(empty($type)) $type = C('default_ajax_return');
if(empty($type)) $type = Config::get('default_ajax_return');
switch (strtoupper($type)){
case 'JSON':
// 返回JSON数据格式到客户端 包含状态信息
header('Content-Type:application/json; charset=utf-8');
exit(Think\Transform::jsonEncode($data));
$data = Transform::jsonEncode($data);
break;
case 'XML':
// 返回xml格式数据
header('Content-Type:text/xml; charset=utf-8');
exit(Think\Transform::xmlEncode($data));
$data = Transform::xmlEncode($data);
break;
case 'JSONP':
// 返回JSON数据格式到客户端 包含状态信息
header('Content-Type:application/javascript; charset=utf-8');
$handler = isset($_GET[C('var_jsonp_handler')]) ? $_GET[C('var_jsonp_handler')] : C('default_jsonp_handler');
exit($handler . '(' . Think\Transform::jsonEncode($data) . ');');
$data = $handler . '(' . Transform::jsonEncode($data) . ');';
break;
case 'SCRIPT':
// 返回可执行的js脚本
header('Content-Type:application/javascript; charset=utf-8');
exit($data);
break;
case 'HTML':
// 返回html片段
header('Content-Type:text/html; charset=utf-8');
echo $data;
exit;
break;
case 'TEXT':
// 返回一段纯文本
header('Content-Type:text/plain; charset=utf-8');
echo $data;
exit;
break;
default:
// 用于扩展其他返回格式数据
Tag::listen('ajax_return', $data);
$data = Hook::listen('ajax_return', $data);
}
exit($data);
}
/**
@@ -158,27 +161,35 @@ class Controller {
$data['url'] = $jumpUrl;
$this->ajaxReturn($data);
}
if(is_int($ajax)) $this->view->assign('waitSecond', $ajax);
if(!empty($jumpUrl)) $this->view->assign('jumpUrl', $jumpUrl);
// 模板变量
$data = [];
if(is_int($ajax))
$data['waitSecond'] = $ajax;
if(!empty($jumpUrl))
$data['jumpUrl'] = $jumpUrl;
// 提示标题
$this->view->assign('msgTitle', $status ? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_'));
$this->view->assign('status', $status); // 状态
$data['msgTitle'] = $status ? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_');
$data['status'] = $status; // 状态
//保证输出不受静态缓存影响
C('HTML_CACHE_ON',false);
Config::set('html_cache_on',false);
if($status) { //发送成功信息
$this->view->assign('message', $message);// 提示信息
$data['message'] = $message;// 提示信息
// 成功操作后默认停留1秒
$this->view->assign('waitSecond', '1');
$data['waitSecond'] = '1';
// 默认操作成功自动返回操作前页面
if(!$jumpUrl) $this->view->assign("jumpUrl", $_SERVER["HTTP_REFERER"]);
$this->display(C('success_tmpl'));
if(!$jumpUrl)
$data["jumpUrl"] = $_SERVER["HTTP_REFERER"];
$this->display(Config::get('success_tmpl'),$data);
}else{
$this->view->assign('error', $message);// 提示信息
$data['error'] = $message;// 提示信息
//发生错误时候默认停留3秒
$this->view->assign('waitSecond', '3');
$data['waitSecond'] = '3';
// 默认发生错误的话自动返回上页
if(!$jumpUrl) $this->view->assign('jumpUrl', 'javascript:history.back(-1);');
$this->display(C('error_tmpl'));
if(!$jumpUrl)
$data['jumpUrl'] = 'javascript:history.back(-1);';
$this->display(Config::get('error_tmpl'),$data);
// 中止执行 避免出错后继续执行
exit ;
}

View File

@@ -18,6 +18,8 @@ class Cookie {
'expire' => 0, // cookie 保存时间
'path' => '/', // cookie 保存路径
'domain' => '', // cookie 有效域名
'secure' => false, // cookie 启用安全传输
'httponly' => '', // httponly设置
];
/**
@@ -27,6 +29,9 @@ class Cookie {
*/
static public function init($config=[]){
self::$config = array_merge(self::$config, array_change_key_case($config));
if(!empty(self::$config['httponly'])){
ini_set('session.cookie_httponly', 1);
}
}
/**
@@ -66,7 +71,7 @@ class Cookie {
$value = 'think:'.json_encode(array_map('urlencode',$value));
}
$expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0;
setcookie($name, $value, $expire, $config['path'], $config['domain']);
setcookie($name, $value, $expire, $config['path'], $config['domain'],$config['secure'],$config['httponly']);
$_COOKIE[$name] = $value;
}
@@ -77,11 +82,11 @@ class Cookie {
* @return mixed
*/
static public function get($name, $prefix='') {
$prefix = $prefix?$prefix:self::$config['prefix'];
$prefix = $prefix ? $prefix : self::$config['prefix'];
$name = $prefix . $name;
if(isset($_COOKIE[$name])){
$value = $_COOKIE[$name];
if(0===strpos($value,'think:')){
if(0 === strpos($value,'think:')){
$value = substr($value,6);
return array_map('urldecode',json_decode($value,true));
}else{
@@ -99,9 +104,10 @@ class Cookie {
* @return mixed
*/
static public function delete($name, $prefix='') {
$prefix = $prefix?$prefix:self::$config['prefix'];
$name = $prefix . $name;
setcookie($name, '', time() - 3600, self::$config['path'], self::$config['domain']);
$config = self::$config;
$prefix = $prefix ? $prefix : $config['prefix'];
$name = $prefix . $name;
setcookie($name, '', time() - 3600, $config['path'], $config['domain'],$config['secure'],$config['httponly']);
unset($_COOKIE[$name]); // 删除指定cookie
}
@@ -115,11 +121,12 @@ class Cookie {
if (empty($_COOKIE))
return;
// 要删除的cookie前缀不指定则删除config设置的指定前缀
$prefix = $prefix ? $prefix: self::$config['prefix'];
$config = self::$config;
$prefix = $prefix ? $prefix: $config['prefix'];
if ($prefix) {// 如果前缀为空字符串将不作处理直接返回
foreach ($_COOKIE as $key => $val) {
if (0 === strpos($key, $prefix)) {
setcookie($key, '', time() - 3600, self::$config['path'], self::$config['domain']);
setcookie($key, '', time() - 3600, $config['path'], $config['domain'],$config['secure'],$config['httponly']);
unset($_COOKIE[$key]);
}
}

View File

@@ -1,74 +0,0 @@
<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think;
class Crypt {
/**
* 加密字符串
* @access public
* @param string $str 字符串
* @param string $key 加密key
* @return string
*/
static public function encrypt($data,$key,$expire=0){
$key = md5($key);
$data = base64_encode($data);
$x = 0;
$len = strlen($data);
$l = strlen($key);
$char = '';
for ($i = 0; $i< $len; $i++) {
if ($x == $l) $x = 0;
$char .=substr($key, $x, 1);
$x++;
}
$str = sprintf('%010d', $expire ? $expire + time() : 0);
for ($i=0; $i< $len; $i++) {
$str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
}
return str_replace('=', '', base64_encode($str));
}
/**
* 解密字符串
* @access public
* @param string $str 字符串
* @param string $key 加密key
* @return string
*/
static public function decrypt($data,$key){
$key = md5($key);
$x = 0;
$data = base64_decode($data);
$expire = substr($data,0,10);
$data = substr($data,10);
if($expire > 0 && $expire<time()) {
return '';
}
$len = strlen($data);
$l = strlen($key);
$char = $str = '';
for ($i=0; $i< $len; $i++) {
if ($x == $l) $x = 0;
$char .= substr($key, $x, 1);
$x++;
}
for ($i = 0; $i < $len; $i++) {
if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
$str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
}else{
$str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
}
}
return base64_decode($str);
}
}

View File

@@ -91,7 +91,7 @@ class Db {
}
// 调用驱动类的方法
static public function __callStatic($method, $params){
return call_user_func_array(array(self::$_instance, $method), $params);
}
static public function __callStatic($method, $params){
return call_user_func_array(array(self::$_instance, $method), $params);
}
}

View File

@@ -24,10 +24,10 @@ class Debug {
*/
static public function remark($name,$value='') {
// 记录时间和内存使用
self::$_info[$name] = is_float($value)?$value:microtime(TRUE);
if('time' != $value && function_exists('memory_get_usage')) {
self::$_mem['mem'][$name] = is_float($value)?$value:memory_get_usage();
self::$_mem['peak'][$name] = function_exists('memory_get_peak_usage')?memory_get_peak_usage(): self::$_mem['mem'][$name];
self::$_info[$name] = is_float($value) ? $value : microtime(true);
if('time' != $value ) {
self::$_mem['mem'][$name] = is_float($value) ? $value : memory_get_usage();
self::$_mem['peak'][$name] = function_exists('memory_get_peak_usage') ? memory_get_peak_usage() : self::$_mem['mem'][$name];
}
}
@@ -35,11 +35,12 @@ class Debug {
* 统计某个区间的时间(微秒)使用情况
* @param string $start 开始标签
* @param string $end 结束标签
* @param integer|string $dec 小数位或者m
* @param integer|string $dec 小数位
* @return mixed
*/
static public function getUseTime($start,$end,$dec=6) {
if(!isset(self::$_info[$end])) self::$_info[$end] = microtime(TRUE);
if(!isset(self::$_info[$end]))
self::$_info[$end] = microtime(true);
return number_format((self::$_info[$end]-self::$_info[$start]),$dec);
}
@@ -47,7 +48,7 @@ class Debug {
* 记录内存使用情况
* @param string $start 开始标签
* @param string $end 结束标签
* @param integer|string $dec 小数位或者m
* @param integer|string $dec 小数位
* @return mixed
*/
static public function getUseMem($start,$end,$dec=2) {
@@ -67,11 +68,12 @@ class Debug {
* 统计内存峰值情况
* @param string $start 开始标签
* @param string $end 结束标签
* @param integer|string $dec 小数位或者m
* @param integer|string $dec 小数位
* @return mixed
*/
static public function getMemPeak($start,$end,$dec=2) {
if(!isset(self::$_mem['peak'][$end])) self::$_mem['peak'][$end] = function_exists('memory_get_peak_usage')?memory_get_peak_usage():memory_get_usage();
if(!isset(self::$_mem['peak'][$end]))
self::$_mem['peak'][$end] = function_exists('memory_get_peak_usage') ? memory_get_peak_usage() : memory_get_usage();
$size = self::$_mem['peak'][$end]-self::$_mem['peak'][$start];
$a = ['B', 'KB', 'MB', 'GB', 'TB'];
$pos = 0;
@@ -85,7 +87,7 @@ class Debug {
/**
* 浏览器友好的变量输出
* @param mixed $var 变量
* @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
* @param boolean $echo 是否输出 默认为true 如果为false 则返回输出字符串
* @param string $label 标签 默认为空
* @return void|string
*/

View File

@@ -12,5 +12,5 @@
namespace Think;
class Exception extends \Exception {
}

View File

@@ -1,222 +0,0 @@
<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think;
class Filter {
//html标签设置
static public $htmlTags = [
'allow' => 'table|td|th|tr|i|b|u|strong|img|p|br|div|strong|em|ul|ol|li|dl|dd|dt|a',
'ban' => 'html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|script|style|xml',
];
static public function filter($data,$filter,$option=''){
return filter_var($data,is_int($filter)?$filter:filter_id($filter),$option);
}
static private function filter_input($type,$name,$filter,$options=''){
return filter_input($type,$name,is_int($filter)?$filter:filter_id($filter),$option);
}
static public function get($name,$filter,$option=''){
return self::filter_input(INPUT_GET,$name,$filter,$option);
}
static public function post($name,$filter,$option=''){
return self::filter_input(INPUT_POST,$name,$filter,$option);
}
static public function cookie($name,$filter,$option=''){
return self::filter_input(INPUT_COOKIE,$name,$filter,$option);
}
static public function server($name,$filter,$option=''){
return self::filter_input(INPUT_SERVER,$name,$filter,$option);
}
/**
* 处理字符串,以便可以正常进行搜索
* @access public
* @param string $string 要处理的字符串
* @return string
*/
static public function forSearch($string) {
return str_replace( ['%','_'], ['\%','\_'], $string );
}
/**
* @access public
* @param string $string 要处理的字符串
* @return string
*/
static public function forShow($string) {
return self::nl2Br( self::hsc($string) );
}
/**
* 处理纯文本数据以便在textarea标签中显示
* @access public
* @param string $string 要处理的字符串
* @return string
*/
static public function forTarea($string) {
return str_ireplace(['<textarea>','</textarea>'], ['&lt;textarea>','&lt;/textarea>'], $string);
}
/**
* 将数据中的单引号和双引号进行转义
* @access public
* @param string $text 要处理的字符串
* @return string
*/
static public function forTag($string) {
return str_replace(['"',"'"], ['&quot;','&#039;'], $string);
}
/**
* 把换行转换为<br />标签
* @access public
* @param string $string 要处理的字符串
* @return string
*/
static public function nl2Br($string) {
return nl2Br($string);
}
/**
* 如果 magic_quotes_gpc 为关闭状态,这个函数可以转义字符串
* @access public
* @param string $string 要处理的字符串
* @return string
*/
static public function addSlashes($string) {
return addslashes($string);
}
/**
* 用于在textbox表单中显示html代码
* @access public
* @param string $string 要处理的字符串
* @return string
*/
static function hsc($string) {
return preg_replace(["/&amp;/i", "/&nbsp;/i"], ['&', '&amp;nbsp;'], htmlspecialchars($string, ENT_QUOTES));
}
/**
* 是hsc()方法的逆操作
* @access public
* @param string $text 要处理的字符串
* @return string
*/
static function undoHsc($text) {
return preg_replace(["/&gt;/i", "/&lt;/i", "/&quot;/i", "/&#039;/i", '/&amp;nbsp;/i'], [">", "<", "\"", "'", "&nbsp;"], $text);
}
/**
* 输出安全的html用于过滤危险代码
* @access public
* @param string $text 要处理的字符串
* @param mixed $allowTags 允许的标签列表,如 table|td|th|td
* @return string
*/
static public function safeHtml($text, $allowTags = null) {
$text = trim($text);
//完全过滤注释
$text = preg_replace('/<!--?.*-->/','',$text);
//完全过滤动态代码
$text = preg_replace('/<\?|\?'.'>/','',$text);
//完全过滤js
$text = preg_replace('/<script?.*\/script>/','',$text);
$text = str_replace('[','&#091;',$text);
$text = str_replace(']','&#093;',$text);
$text = str_replace('|','&#124;',$text);
//过滤换行符
$text = preg_replace('/\r?\n/','',$text);
//br
$text = preg_replace('/<br(\s\/)?'.'>/i','[br]',$text);
$text = preg_replace('/(\[br\]\s*){10,}/i','[br]',$text);
//过滤危险的属性过滤on事件lang js
while(preg_match('/(<[^><]+)(lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1],$text);
}
while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1].$mat[3],$text);
}
if( empty($allowTags) ) { $allowTags = self::$htmlTags['allow']; }
//允许的HTML标签
$text = preg_replace('/<('.$allowTags.')( [^><\[\]]*)>/i','[\1\2]',$text);
//过滤多余html
if ( empty($banTag) ) { $banTag = self::$htmlTags['ban']; }
$text = preg_replace('/<\/?('.$banTag.')[^><]*>/i','',$text);
//过滤合法的html标签
while(preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i',$text,$mat)){
$text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
}
//转换引号
while(preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2=\[\]]+)\2([^\[\]]*\])/i',$text,$mat)){
$text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
}
//空属性转换
$text = str_replace('\'\'','||',$text);
$text = str_replace('""','||',$text);
//过滤错误的单个引号
while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i',$text,$mat)){
$text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
}
//转换其它所有不合法的 < >
$text = str_replace('<','&lt;',$text);
$text = str_replace('>','&gt;',$text);
$text = str_replace('"','&quot;',$text);
//反转换
$text = str_replace('[','<',$text);
$text = str_replace(']','>',$text);
$text = str_replace('|','"',$text);
//过滤多余空格
$text = str_replace(' ',' ',$text);
return $text;
}
/**
* 删除html标签得到纯文本。可以处理嵌套的标签
* @access public
* @param string $string 要处理的html
* @return string
*/
static public function deleteHtmlTags($string) {
while(strstr($string, '>')) {
$currentBeg = strpos($string, '<');
$currentEnd = strpos($string, '>');
$tmpStringBeg = @substr($string, 0, $currentBeg);
$tmpStringEnd = @substr($string, $currentEnd + 1, strlen($string));
$string = $tmpStringBeg.$tmpStringEnd;
}
return $string;
}
/**
* 处理文本中的换行
* @access public
* @param string $string 要处理的字符串
* @param mixed $br 对换行的处理,
* false去除换行true保留原样string替换成string
* @return string
*/
static public function nl2($string, $br = '<br />') {
if ($br == false) {
$string = preg_replace("/(\015\012)|(\015)|(\012)/", '', $string);
} elseif ($br != true){
$string = preg_replace("/(\015\012)|(\015)|(\012)/", $br, $string);
}
return $string;
}
}

86
Library/Think/Hook.php Normal file
View File

@@ -0,0 +1,86 @@
<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think;
class Hook {
static private $tags = [];
/**
* 动态添加行为扩展到某个标签
* @param string $tag 标签名称
* @param mixed $behavior 行为名称
* @return void
*/
static public function add($tag,$behavior) {
if(is_array($behavior)) {
self::$tags[$tag] = array_merge(self::$tags[$tag],$behavior);
}else{
self::$tags[$tag][] = $behavior;
}
}
/**
* 批量导入行为
* @param array $tags 标签行为
* @return void
*/
static public function import($tags) {
self::$tags = array_merge(self::$tags,$tags);
}
/**
* 监听标签的行为
* @param string $tag 标签名称
* @param mixed $params 传入参数
* @return void
*/
static public function listen($tag, &$params=null) {
if(isset(self::$tags[$tag])) {
foreach (self::$tags[$tag] as $name) {
Config::get('app_debug') && Debug::remark('behavior_start','time');
$result = self::exec($name, $tag,$params);
if(Config::get('app_debug')){
Debug::remark('behavior_end','time');
Log::record('Run '.$name.' [ RunTime:'.Debug::getUseTime('behavior_start','behavior_end').'s ]','INFO');
}
if(false === $result) {
// 如果返回false 则中断行为执行
return ;
}
}
}
return;
}
/**
* 执行某个行为
* @param string $name 行为名称
* @param string $tag 方法名(标签名)
* @param Mixed $params 传人的参数
* @return void
*/
static public function exec($name, $tag,&$params=null) {
if($name instanceof \Closure) {
return $name($params);
}
if('Behavior' == substr($name,-8) ){
// 行为扩展必须用run入口方法
$tag = 'run';
}
$addon = new $name();
return $addon->$tag($params);
}
}

View File

@@ -1,61 +0,0 @@
<?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: 麦当苗儿 <zuojiazi.cn@gmail.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Think;
/* 缩略图相关常量定义 */
define('THINKIMAGE_THUMB_SCALING', 1); //常量,标识缩略图等比例缩放类型
define('THINKIMAGE_THUMB_FILLED', 2); //常量,标识缩略图缩放后填充类型
define('THINKIMAGE_THUMB_CENTER', 3); //常量,标识缩略图居中裁剪类型
define('THINKIMAGE_THUMB_NORTHWEST', 4); //常量,标识缩略图左上角裁剪类型
define('THINKIMAGE_THUMB_SOUTHEAST', 5); //常量,标识缩略图右下角裁剪类型
define('THINKIMAGE_THUMB_FIXED', 6); //常量,标识缩略图固定尺寸缩放类型
/* 水印相关常量定义 */
define('THINKIMAGE_WATER_NORTHWEST', 1); //常量,标识左上角水印
define('THINKIMAGE_WATER_NORTH', 2); //常量,标识上居中水印
define('THINKIMAGE_WATER_NORTHEAST', 3); //常量,标识右上角水印
define('THINKIMAGE_WATER_WEST', 4); //常量,标识左居中水印
define('THINKIMAGE_WATER_CENTER', 5); //常量,标识居中水印
define('THINKIMAGE_WATER_EAST', 6); //常量,标识右居中水印
define('THINKIMAGE_WATER_SOUTHWEST', 7); //常量,标识左下角水印
define('THINKIMAGE_WATER_SOUTH', 8); //常量,标识下居中水印
define('THINKIMAGE_WATER_SOUTHEAST', 9); //常量,标识右下角水印
/**
* 图片处理驱动类,可配置图片处理库
* 目前支持GD库和imagick
* @author 麦当苗儿 <zuojiazi.cn@gmail.com>
*/
class Image {
/**
* 图片资源
* @var resource
*/
private static $im;
/**
* 初始化方法,用于实例化一个图片处理对象
* @param string $type 要使用的类库默认使用GD库
*/
static public function init($type = 'Gd', $imgname = null){
/* 引入处理库,实例化图片处理对象 */
$class = '\\Think\\Image\\Driver\\'.ucwords($type);
self::$im = new $class($imgname);
return self::$im;
}
// 调用驱动类的方法
static public function __callStatic($method, $params){
self::$im || self::init();
return call_user_func_array([self::$im, $method], $params);
}
}

View File

@@ -1,549 +0,0 @@
<?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: 麦当苗儿 <zuojiazi.cn@gmail.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Think\Image\Driver;
class Gd{
/**
* 图像资源对象
* @var resource
*/
private $im;
private $gif;
/**
* 图像信息包括width,height,type,mime,size
* @var array
*/
private $info;
/**
* 构造方法,可用于打开一张图像
* @param string $imgname 图像路径
*/
public function __construct($imgname = null) {
$imgname && $this->open($imgname);
}
/**
* 打开一张图像
* @param string $imgname 图像路径
*/
public function open($imgname){
//检测图像文件
if(!is_file($imgname)) throw new \Exception('不存在的图像文件');
//获取图像信息
$info = getimagesize($imgname);
//检测图像合法性
if(false === $info || (IMAGETYPE_GIF === $info[2] && empty($info['bits']))){
throw new \Exception('非法图像文件');
}
//设置图像信息
$this->info = [
'width' => $info[0],
'height' => $info[1],
'type' => image_type_to_extension($info[2], false),
'mime' => $info['mime'],
];
//销毁已存在的图像
empty($this->im) || imagedestroy($this->im);
//打开图像
if('gif' == $this->info['type']){
$class = '\\Think\\Image\\Driver\\Gif';
$this->gif = new $class($imgname);
$this->im = imagecreatefromstring($this->gif->image());
} else {
$fun = "imagecreatefrom{$this->info['type']}";
$this->im = $fun($imgname);
}
return $this;
}
/**
* 保存图像
* @param string $imgname 图像保存名称
* @param string $type 图像类型
* @param boolean $interlace 是否对JPEG类型图像设置隔行扫描
*/
public function save($imgname, $type = null, $interlace = true){
if(empty($this->im)) throw new \Exception('没有可以被保存的图像资源');
//自动获取图像类型
if(is_null($type)){
$type = $this->info['type'];
} else {
$type = strtolower($type);
}
//JPEG图像设置隔行扫描
if('jpeg' == $type || 'jpg' == $type){
$type = 'jpeg';
imageinterlace($this->im, $interlace);
}
//保存图像
if('gif' == $type && !empty($this->gif)){
$this->gif->save($imgname);
} else {
$fun = "image{$type}";
$fun($this->im, $imgname);
}
return $this;
}
/**
* 返回图像宽度
* @return integer 图像宽度
*/
public function width(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
return $this->info['width'];
}
/**
* 返回图像高度
* @return integer 图像高度
*/
public function height(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
return $this->info['height'];
}
/**
* 返回图像类型
* @return string 图像类型
*/
public function type(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
return $this->info['type'];
}
/**
* 返回图像MIME类型
* @return string 图像MIME类型
*/
public function mime(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
return $this->info['mime'];
}
/**
* 返回图像尺寸数组 0 - 图像宽度1 - 图像高度
* @return array 图像尺寸
*/
public function size(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
return [$this->info['width'], $this->info['height']];
}
/**
* 裁剪图像
* @param integer $w 裁剪区域宽度
* @param integer $h 裁剪区域高度
* @param integer $x 裁剪区域x坐标
* @param integer $y 裁剪区域y坐标
* @param integer $width 图像保存宽度
* @param integer $height 图像保存高度
*/
public function crop($w, $h, $x = 0, $y = 0, $width = null, $height = null){
if(empty($this->im)) throw new \Exception('没有可以被裁剪的图像资源');
//设置保存尺寸
empty($width) && $width = $w;
empty($height) && $height = $h;
do {
//创建新图像
$img = imagecreatetruecolor($width, $height);
// 调整默认颜色
$color = imagecolorallocate($img, 255, 255, 255);
imagefill($img, 0, 0, $color);
//裁剪
imagecopyresampled($img, $this->im, 0, 0, $x, $y, $width, $height, $w, $h);
imagedestroy($this->im); //销毁原图
//设置新图像
$this->im = $img;
} while(!empty($this->gif) && $this->gifNext());
$this->info['width'] = $width;
$this->info['height'] = $height;
return $this;
}
/**
* 生成缩略图
* @param integer $width 缩略图最大宽度
* @param integer $height 缩略图最大高度
* @param integer $type 缩略图裁剪类型
*/
public function thumb($width, $height, $type = THINKIMAGE_THUMB_SCALE){
if(empty($this->im)) throw new \Exception('没有可以被缩略的图像资源');
//原图宽度和高度
$w = $this->info['width'];
$h = $this->info['height'];
/* 计算缩略图生成的必要参数 */
switch ($type) {
/* 等比例缩放 */
case THINKIMAGE_THUMB_SCALING:
//原图尺寸小于缩略图尺寸则不进行缩略
if($w < $width && $h < $height) return;
//计算缩放比例
$scale = min($width/$w, $height/$h);
//设置缩略图的坐标及宽度和高度
$x = $y = 0;
$width = $w * $scale;
$height = $h * $scale;
break;
/* 居中裁剪 */
case THINKIMAGE_THUMB_CENTER:
//计算缩放比例
$scale = max($width/$w, $height/$h);
//设置缩略图的坐标及宽度和高度
$w = $width/$scale;
$h = $height/$scale;
$x = ($this->info['width'] - $w)/2;
$y = ($this->info['height'] - $h)/2;
break;
/* 左上角裁剪 */
case THINKIMAGE_THUMB_NORTHWEST:
//计算缩放比例
$scale = max($width/$w, $height/$h);
//设置缩略图的坐标及宽度和高度
$x = $y = 0;
$w = $width/$scale;
$h = $height/$scale;
break;
/* 右下角裁剪 */
case THINKIMAGE_THUMB_SOUTHEAST:
//计算缩放比例
$scale = max($width/$w, $height/$h);
//设置缩略图的坐标及宽度和高度
$w = $width/$scale;
$h = $height/$scale;
$x = $this->info['width'] - $w;
$y = $this->info['height'] - $h;
break;
/* 填充 */
case THINKIMAGE_THUMB_FILLED:
//计算缩放比例
if($w < $width && $h < $height){
$scale = 1;
} else {
$scale = min($width/$w, $height/$h);
}
//设置缩略图的坐标及宽度和高度
$neww = $w * $scale;
$newh = $h * $scale;
$posx = ($width - $w * $scale)/2;
$posy = ($height - $h * $scale)/2;
do{
//创建新图像
$img = imagecreatetruecolor($width, $height);
// 调整默认颜色
$color = imagecolorallocate($img, 255, 255, 255);
imagefill($img, 0, 0, $color);
//裁剪
imagecopyresampled($img, $this->im, $posx, $posy, $x, $y, $neww, $newh, $w, $h);
imagedestroy($this->im); //销毁原图
$this->im = $img;
} while(!empty($this->gif) && $this->gifNext());
$this->info['width'] = $width;
$this->info['height'] = $height;
return $this;
/* 固定 */
case THINKIMAGE_THUMB_FIXED:
$x = $y = 0;
break;
default:
throw new \Exception('不支持的缩略图裁剪类型');
}
/* 裁剪图像 */
$this->crop($w, $h, $x, $y, $width, $height);
return $this;
}
/**
* 添加水印
* @param string $source 水印图片路径
* @param integer $locate 水印位置
* @param integer $alpha 水印透明度
*/
public function water($source, $locate = THINKIMAGE_WATER_SOUTHEAST){
//资源检测
if(empty($this->im)) throw new \Exception('没有可以被添加水印的图像资源');
if(!is_file($source)) throw new \Exception('水印图像不存在');
//获取水印图像信息
$info = getimagesize($source);
if(false === $info || (IMAGETYPE_GIF === $info[2] && empty($info['bits']))){
throw new \Exception('非法水印文件');
}
//创建水印图像资源
$fun = 'imagecreatefrom' . image_type_to_extension($info[2], false);
$water = $fun($source);
//设定水印图像的混色模式
imagealphablending($water, true);
/* 设定水印位置 */
switch ($locate) {
/* 右下角水印 */
case THINKIMAGE_WATER_SOUTHEAST:
$x = $this->info['width'] - $info[0];
$y = $this->info['height'] - $info[1];
break;
/* 左下角水印 */
case THINKIMAGE_WATER_SOUTHWEST:
$x = 0;
$y = $this->info['height'] - $info[1];
break;
/* 左上角水印 */
case THINKIMAGE_WATER_NORTHWEST:
$x = $y = 0;
break;
/* 右上角水印 */
case THINKIMAGE_WATER_NORTHEAST:
$x = $this->info['width'] - $info[0];
$y = 0;
break;
/* 居中水印 */
case THINKIMAGE_WATER_CENTER:
$x = ($this->info['width'] - $info[0])/2;
$y = ($this->info['height'] - $info[1])/2;
break;
/* 下居中水印 */
case THINKIMAGE_WATER_SOUTH:
$x = ($this->info['width'] - $info[0])/2;
$y = $this->info['height'] - $info[1];
break;
/* 右居中水印 */
case THINKIMAGE_WATER_EAST:
$x = $this->info['width'] - $info[0];
$y = ($this->info['height'] - $info[1])/2;
break;
/* 上居中水印 */
case THINKIMAGE_WATER_NORTH:
$x = ($this->info['width'] - $info[0])/2;
$y = 0;
break;
/* 左居中水印 */
case THINKIMAGE_WATER_WEST:
$x = 0;
$y = ($this->info['height'] - $info[1])/2;
break;
default:
/* 自定义水印坐标 */
if(is_array($locate)){
list($x, $y) = $locate;
} else {
throw new \Exception('不支持的水印位置类型');
}
}
do{
//添加水印
$src = imagecreatetruecolor($info[0], $info[1]);
// 调整默认颜色
$color = imagecolorallocate($src, 255, 255, 255);
imagefill($src, 0, 0, $color);
imagecopy($src, $this->im, 0, 0, $x, $y, $info[0], $info[1]);
imagecopy($src, $water, 0, 0, 0, 0, $info[0], $info[1]);
imagecopymerge($this->im, $src, $x, $y, 0, 0, $info[0], $info[1], 100);
//销毁零时图片资源
imagedestroy($src);
} while(!empty($this->gif) && $this->gifNext());
//销毁水印资源
imagedestroy($water);
return $this;
}
/**
* 图像添加文字
* @param string $text 添加的文字
* @param string $font 字体路径
* @param integer $size 字号
* @param string $color 文字颜色
* @param integer $locate 文字写入位置
* @param integer $offset 文字相对当前位置的偏移量
* @param integer $angle 文字倾斜角度
*/
public function text($text, $font, $size, $color = '#00000000',
$locate = THINKIMAGE_WATER_SOUTHEAST, $offset = 0, $angle = 0){
//资源检测
if(empty($this->im)) throw new \Exception('没有可以被写入文字的图像资源');
if(!is_file($font)) throw new \Exception("不存在的字体文件:{$font}");
//获取文字信息
$info = imagettfbbox($size, $angle, $font, $text);
$minx = min($info[0], $info[2], $info[4], $info[6]);
$maxx = max($info[0], $info[2], $info[4], $info[6]);
$miny = min($info[1], $info[3], $info[5], $info[7]);
$maxy = max($info[1], $info[3], $info[5], $info[7]);
/* 计算文字初始坐标和尺寸 */
$x = $minx;
$y = abs($miny);
$w = $maxx - $minx;
$h = $maxy - $miny;
/* 设定文字位置 */
switch ($locate) {
/* 右下角文字 */
case THINKIMAGE_WATER_SOUTHEAST:
$x += $this->info['width'] - $w;
$y += $this->info['height'] - $h;
break;
/* 左下角文字 */
case THINKIMAGE_WATER_SOUTHWEST:
$y += $this->info['height'] - $h;
break;
/* 左上角文字 */
case THINKIMAGE_WATER_NORTHWEST:
// 起始坐标即为左上角坐标,无需调整
break;
/* 右上角文字 */
case THINKIMAGE_WATER_NORTHEAST:
$x += $this->info['width'] - $w;
break;
/* 居中文字 */
case THINKIMAGE_WATER_CENTER:
$x += ($this->info['width'] - $w)/2;
$y += ($this->info['height'] - $h)/2;
break;
/* 下居中文字 */
case THINKIMAGE_WATER_SOUTH:
$x += ($this->info['width'] - $w)/2;
$y += $this->info['height'] - $h;
break;
/* 右居中文字 */
case THINKIMAGE_WATER_EAST:
$x += $this->info['width'] - $w;
$y += ($this->info['height'] - $h)/2;
break;
/* 上居中文字 */
case THINKIMAGE_WATER_NORTH:
$x += ($this->info['width'] - $w)/2;
break;
/* 左居中文字 */
case THINKIMAGE_WATER_WEST:
$y += ($this->info['height'] - $h)/2;
break;
default:
/* 自定义文字坐标 */
if(is_array($locate)){
list($posx, $posy) = $locate;
$x += $posx;
$y += $posy;
} else {
throw new \Exception('不支持的文字位置类型');
}
}
/* 设置偏移量 */
if(is_array($offset)){
$offset = array_map('intval', $offset);
list($ox, $oy) = $offset;
} else{
$offset = intval($offset);
$ox = $oy = $offset;
}
/* 设置颜色 */
if(is_string($color) && 0 === strpos($color, '#')){
$color = str_split(substr($color, 1), 2);
$color = array_map('hexdec', $color);
if(empty($color[3]) || $color[3] > 127){
$color[3] = 0;
}
} elseif (!is_array($color)) {
throw new \Exception('错误的颜色值');
}
do{
/* 写入文字 */
$col = imagecolorallocatealpha($this->im, $color[0], $color[1], $color[2], $color[3]);
imagettftext($this->im, $size, $angle, $x + $ox, $y + $oy, $col, $font, $text);
} while(!empty($this->gif) && $this->gifNext());
return $this;
}
/* 切换到GIF的下一帧并保存当前帧内部使用 */
private function gifNext(){
ob_start();
ob_implicit_flush(0);
imagegif($this->im);
$img = ob_get_clean();
$this->gif->image($img);
$next = $this->gif->nextImage();
if($next){
$this->im = imagecreatefromstring($next);
return $next;
} else {
$this->im = imagecreatefromstring($this->gif->image());
return false;
}
}
/**
* 析构方法,用于销毁图像资源
*/
public function __destruct() {
empty($this->im) || imagedestroy($this->im);
}
}

View File

@@ -1,570 +0,0 @@
<?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: 麦当苗儿 <zuojiazi.cn@gmail.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Think\Image\Driver;
class Gif{
/**
* GIF帧列表
* @var array
*/
private $frames = [];
/**
* 每帧等待时间列表
* @var array
*/
private $delays = [];
/**
* 构造方法用于解码GIF图片
* @param string $src GIF图片数据
* @param string $mod 图片数据类型
*/
public function __construct($src = null, $mod = 'url') {
if(!is_null($src)){
if('url' == $mod && is_file($src)){
$src = file_get_contents($src);
}
/* 解码GIF图片 */
try{
$de = new GIFDecoder($src);
$this->frames = $de->GIFGetFrames();
$this->delays = $de->GIFGetDelays();
} catch(Exception $e){
throw new \Exception("解码GIF图片出错");
}
}
}
/**
* 设置或获取当前帧的数据
* @param string $stream 二进制数据流
* @return boolean 获取到的数据
*/
public function image($stream = null){
if(is_null($stream)){
$current = current($this->frames);
return false === $current ? reset($this->frames) : $current;
} else {
$this->frames[key($this->frames)] = $stream;
}
}
/**
* 将当前帧移动到下一帧
* @return string 当前帧数据
*/
public function nextImage(){
return next($this->frames);
}
/**
* 编码并保存当前GIF图片
* @param string $gifname 图片名称
*/
public function save($gifname){
$gif = new GIFEncoder($this->frames, $this->delays, 0, 2, 0, 0, 0, 'bin');
file_put_contents($gifname, $gif->GetAnimation());
}
}
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GIFEncoder Version 2.0 by László Zsidi, http://gifs.hu
::
:: This class is a rewritten 'GifMerge.class.php' version.
::
:: Modification:
:: - Simplified and easy code,
:: - Ultra fast encoding,
:: - Built-in errors,
:: - Stable working
::
::
:: Updated at 2007. 02. 13. '00.05.AM'
::
::
::
:: Try on-line GIFBuilder Form demo based on GIFEncoder.
::
:: http://gifs.hu/phpclasses/demos/GifBuilder/
::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
*/
Class GIFEncoder {
var $GIF = "GIF89a"; /* GIF header 6 bytes */
var $VER = "GIFEncoder V2.05"; /* Encoder version */
var $BUF = array ( );
var $LOP = 0;
var $DIS = 2;
var $COL = -1;
var $IMG = -1;
var $ERR = array (
'ERR00'=>"Does not supported function for only one image!",
'ERR01'=>"Source is not a GIF image!",
'ERR02'=>"Unintelligible flag ",
'ERR03'=>"Does not make animation from animated GIF source",
);
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GIFEncoder...
::
*/
function GIFEncoder (
$GIF_src, $GIF_dly, $GIF_lop, $GIF_dis,
$GIF_red, $GIF_grn, $GIF_blu, $GIF_mod
) {
if ( ! is_array ( $GIF_src ) && ! is_array ( $GIF_tim ) ) {
printf ( "%s: %s", $this->VER, $this->ERR [ 'ERR00' ] );
exit ( 0 );
}
$this->LOP = ( $GIF_lop > -1 ) ? $GIF_lop : 0;
$this->DIS = ( $GIF_dis > -1 ) ? ( ( $GIF_dis < 3 ) ? $GIF_dis : 3 ) : 2;
$this->COL = ( $GIF_red > -1 && $GIF_grn > -1 && $GIF_blu > -1 ) ?
( $GIF_red | ( $GIF_grn << 8 ) | ( $GIF_blu << 16 ) ) : -1;
for ( $i = 0; $i < count ( $GIF_src ); $i++ ) {
if ( strToLower ( $GIF_mod ) == "url" ) {
$this->BUF [ ] = fread ( fopen ( $GIF_src [ $i ], "rb" ), filesize ( $GIF_src [ $i ] ) );
}
else if ( strToLower ( $GIF_mod ) == "bin" ) {
$this->BUF [ ] = $GIF_src [ $i ];
}
else {
printf ( "%s: %s ( %s )!", $this->VER, $this->ERR [ 'ERR02' ], $GIF_mod );
exit ( 0 );
}
if ( substr ( $this->BUF [ $i ], 0, 6 ) != "GIF87a" && substr ( $this->BUF [ $i ], 0, 6 ) != "GIF89a" ) {
printf ( "%s: %d %s", $this->VER, $i, $this->ERR [ 'ERR01' ] );
exit ( 0 );
}
for ( $j = ( 13 + 3 * ( 2 << ( ord ( $this->BUF [ $i ] { 10 } ) & 0x07 ) ) ), $k = TRUE; $k; $j++ ) {
switch ( $this->BUF [ $i ] { $j } ) {
case "!":
if ( ( substr ( $this->BUF [ $i ], ( $j + 3 ), 8 ) ) == "NETSCAPE" ) {
printf ( "%s: %s ( %s source )!", $this->VER, $this->ERR [ 'ERR03' ], ( $i + 1 ) );
exit ( 0 );
}
break;
case ";":
$k = FALSE;
break;
}
}
}
GIFEncoder::GIFAddHeader ( );
for ( $i = 0; $i < count ( $this->BUF ); $i++ ) {
GIFEncoder::GIFAddFrames ( $i, $GIF_dly [ $i ] );
}
GIFEncoder::GIFAddFooter ( );
}
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GIFAddHeader...
::
*/
function GIFAddHeader ( ) {
$cmap = 0;
if ( ord ( $this->BUF [ 0 ] { 10 } ) & 0x80 ) {
$cmap = 3 * ( 2 << ( ord ( $this->BUF [ 0 ] { 10 } ) & 0x07 ) );
$this->GIF .= substr ( $this->BUF [ 0 ], 6, 7 );
$this->GIF .= substr ( $this->BUF [ 0 ], 13, $cmap );
$this->GIF .= "!\377\13NETSCAPE2.0\3\1" . GIFEncoder::GIFWord ( $this->LOP ) . "\0";
}
}
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GIFAddFrames...
::
*/
function GIFAddFrames ( $i, $d ) {
$Locals_str = 13 + 3 * ( 2 << ( ord ( $this->BUF [ $i ] { 10 } ) & 0x07 ) );
$Locals_end = strlen ( $this->BUF [ $i ] ) - $Locals_str - 1;
$Locals_tmp = substr ( $this->BUF [ $i ], $Locals_str, $Locals_end );
$Global_len = 2 << ( ord ( $this->BUF [ 0 ] { 10 } ) & 0x07 );
$Locals_len = 2 << ( ord ( $this->BUF [ $i ] { 10 } ) & 0x07 );
$Global_rgb = substr ( $this->BUF [ 0 ], 13,
3 * ( 2 << ( ord ( $this->BUF [ 0 ] { 10 } ) & 0x07 ) ) );
$Locals_rgb = substr ( $this->BUF [ $i ], 13,
3 * ( 2 << ( ord ( $this->BUF [ $i ] { 10 } ) & 0x07 ) ) );
$Locals_ext = "!\xF9\x04" . chr ( ( $this->DIS << 2 ) + 0 ) .
chr ( ( $d >> 0 ) & 0xFF ) . chr ( ( $d >> 8 ) & 0xFF ) . "\x0\x0";
if ( $this->COL > -1 && ord ( $this->BUF [ $i ] { 10 } ) & 0x80 ) {
for ( $j = 0; $j < ( 2 << ( ord ( $this->BUF [ $i ] { 10 } ) & 0x07 ) ); $j++ ) {
if (
ord ( $Locals_rgb { 3 * $j + 0 } ) == ( ( $this->COL >> 16 ) & 0xFF ) &&
ord ( $Locals_rgb { 3 * $j + 1 } ) == ( ( $this->COL >> 8 ) & 0xFF ) &&
ord ( $Locals_rgb { 3 * $j + 2 } ) == ( ( $this->COL >> 0 ) & 0xFF )
) {
$Locals_ext = "!\xF9\x04" . chr ( ( $this->DIS << 2 ) + 1 ) .
chr ( ( $d >> 0 ) & 0xFF ) . chr ( ( $d >> 8 ) & 0xFF ) . chr ( $j ) . "\x0";
break;
}
}
}
switch ( $Locals_tmp { 0 } ) {
case "!":
$Locals_img = substr ( $Locals_tmp, 8, 10 );
$Locals_tmp = substr ( $Locals_tmp, 18, strlen ( $Locals_tmp ) - 18 );
break;
case ",":
$Locals_img = substr ( $Locals_tmp, 0, 10 );
$Locals_tmp = substr ( $Locals_tmp, 10, strlen ( $Locals_tmp ) - 10 );
break;
}
if ( ord ( $this->BUF [ $i ] { 10 } ) & 0x80 && $this->IMG > -1 ) {
if ( $Global_len == $Locals_len ) {
if ( GIFEncoder::GIFBlockCompare ( $Global_rgb, $Locals_rgb, $Global_len ) ) {
$this->GIF .= ( $Locals_ext . $Locals_img . $Locals_tmp );
}
else {
$byte = ord ( $Locals_img { 9 } );
$byte |= 0x80;
$byte &= 0xF8;
$byte |= ( ord ( $this->BUF [ 0 ] { 10 } ) & 0x07 );
$Locals_img { 9 } = chr ( $byte );
$this->GIF .= ( $Locals_ext . $Locals_img . $Locals_rgb . $Locals_tmp );
}
}
else {
$byte = ord ( $Locals_img { 9 } );
$byte |= 0x80;
$byte &= 0xF8;
$byte |= ( ord ( $this->BUF [ $i ] { 10 } ) & 0x07 );
$Locals_img { 9 } = chr ( $byte );
$this->GIF .= ( $Locals_ext . $Locals_img . $Locals_rgb . $Locals_tmp );
}
}
else {
$this->GIF .= ( $Locals_ext . $Locals_img . $Locals_tmp );
}
$this->IMG = 1;
}
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GIFAddFooter...
::
*/
function GIFAddFooter ( ) {
$this->GIF .= ";";
}
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GIFBlockCompare...
::
*/
function GIFBlockCompare ( $GlobalBlock, $LocalBlock, $Len ) {
for ( $i = 0; $i < $Len; $i++ ) {
if (
$GlobalBlock { 3 * $i + 0 } != $LocalBlock { 3 * $i + 0 } ||
$GlobalBlock { 3 * $i + 1 } != $LocalBlock { 3 * $i + 1 } ||
$GlobalBlock { 3 * $i + 2 } != $LocalBlock { 3 * $i + 2 }
) {
return ( 0 );
}
}
return ( 1 );
}
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GIFWord...
::
*/
function GIFWord ( $int ) {
return ( chr ( $int & 0xFF ) . chr ( ( $int >> 8 ) & 0xFF ) );
}
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GetAnimation...
::
*/
function GetAnimation ( ) {
return ( $this->GIF );
}
}
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GIFDecoder Version 2.0 by László Zsidi, http://gifs.hu
::
:: Created at 2007. 02. 01. '07.47.AM'
::
::
::
::
:: Try on-line GIFBuilder Form demo based on GIFDecoder.
::
:: http://gifs.hu/phpclasses/demos/GifBuilder/
::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
*/
Class GIFDecoder {
var $GIF_buffer = array ( );
var $GIF_arrays = array ( );
var $GIF_delays = array ( );
var $GIF_stream = "";
var $GIF_string = "";
var $GIF_bfseek = 0;
var $GIF_screen = array ( );
var $GIF_global = array ( );
var $GIF_sorted;
var $GIF_colorS;
var $GIF_colorC;
var $GIF_colorF;
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GIFDecoder ( $GIF_pointer )
::
*/
function GIFDecoder ( $GIF_pointer ) {
$this->GIF_stream = $GIF_pointer;
GIFDecoder::GIFGetByte ( 6 ); // GIF89a
GIFDecoder::GIFGetByte ( 7 ); // Logical Screen Descriptor
$this->GIF_screen = $this->GIF_buffer;
$this->GIF_colorF = $this->GIF_buffer [ 4 ] & 0x80 ? 1 : 0;
$this->GIF_sorted = $this->GIF_buffer [ 4 ] & 0x08 ? 1 : 0;
$this->GIF_colorC = $this->GIF_buffer [ 4 ] & 0x07;
$this->GIF_colorS = 2 << $this->GIF_colorC;
if ( $this->GIF_colorF == 1 ) {
GIFDecoder::GIFGetByte ( 3 * $this->GIF_colorS );
$this->GIF_global = $this->GIF_buffer;
}
/*
*
* 05.06.2007.
* Made a little modification
*
*
- for ( $cycle = 1; $cycle; ) {
+ if ( GIFDecoder::GIFGetByte ( 1 ) ) {
- switch ( $this->GIF_buffer [ 0 ] ) {
- case 0x21:
- GIFDecoder::GIFReadExtensions ( );
- break;
- case 0x2C:
- GIFDecoder::GIFReadDescriptor ( );
- break;
- case 0x3B:
- $cycle = 0;
- break;
- }
- }
+ else {
+ $cycle = 0;
+ }
- }
*/
for ( $cycle = 1; $cycle; ) {
if ( GIFDecoder::GIFGetByte ( 1 ) ) {
switch ( $this->GIF_buffer [ 0 ] ) {
case 0x21:
GIFDecoder::GIFReadExtensions ( );
break;
case 0x2C:
GIFDecoder::GIFReadDescriptor ( );
break;
case 0x3B:
$cycle = 0;
break;
}
}
else {
$cycle = 0;
}
}
}
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GIFReadExtension ( )
::
*/
function GIFReadExtensions ( ) {
GIFDecoder::GIFGetByte ( 1 );
for ( ; ; ) {
GIFDecoder::GIFGetByte ( 1 );
if ( ( $u = $this->GIF_buffer [ 0 ] ) == 0x00 ) {
break;
}
GIFDecoder::GIFGetByte ( $u );
/*
* 07.05.2007.
* Implemented a new line for a new function
* to determine the originaly delays between
* frames.
*
*/
if ( $u == 4 ) {
$this->GIF_delays [ ] = ( $this->GIF_buffer [ 1 ] | $this->GIF_buffer [ 2 ] << 8 );
}
}
}
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GIFReadExtension ( )
::
*/
function GIFReadDescriptor ( ) {
$GIF_screen = array ( );
GIFDecoder::GIFGetByte ( 9 );
$GIF_screen = $this->GIF_buffer;
$GIF_colorF = $this->GIF_buffer [ 8 ] & 0x80 ? 1 : 0;
if ( $GIF_colorF ) {
$GIF_code = $this->GIF_buffer [ 8 ] & 0x07;
$GIF_sort = $this->GIF_buffer [ 8 ] & 0x20 ? 1 : 0;
}
else {
$GIF_code = $this->GIF_colorC;
$GIF_sort = $this->GIF_sorted;
}
$GIF_size = 2 << $GIF_code;
$this->GIF_screen [ 4 ] &= 0x70;
$this->GIF_screen [ 4 ] |= 0x80;
$this->GIF_screen [ 4 ] |= $GIF_code;
if ( $GIF_sort ) {
$this->GIF_screen [ 4 ] |= 0x08;
}
$this->GIF_string = "GIF87a";
GIFDecoder::GIFPutByte ( $this->GIF_screen );
if ( $GIF_colorF == 1 ) {
GIFDecoder::GIFGetByte ( 3 * $GIF_size );
GIFDecoder::GIFPutByte ( $this->GIF_buffer );
}
else {
GIFDecoder::GIFPutByte ( $this->GIF_global );
}
$this->GIF_string .= chr ( 0x2C );
$GIF_screen [ 8 ] &= 0x40;
GIFDecoder::GIFPutByte ( $GIF_screen );
GIFDecoder::GIFGetByte ( 1 );
GIFDecoder::GIFPutByte ( $this->GIF_buffer );
for ( ; ; ) {
GIFDecoder::GIFGetByte ( 1 );
GIFDecoder::GIFPutByte ( $this->GIF_buffer );
if ( ( $u = $this->GIF_buffer [ 0 ] ) == 0x00 ) {
break;
}
GIFDecoder::GIFGetByte ( $u );
GIFDecoder::GIFPutByte ( $this->GIF_buffer );
}
$this->GIF_string .= chr ( 0x3B );
/*
Add frames into $GIF_stream array...
*/
$this->GIF_arrays [ ] = $this->GIF_string;
}
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GIFGetByte ( $len )
::
*/
/*
*
* 05.06.2007.
* Made a little modification
*
*
- function GIFGetByte ( $len ) {
- $this->GIF_buffer = array ( );
-
- for ( $i = 0; $i < $len; $i++ ) {
+ if ( $this->GIF_bfseek > strlen ( $this->GIF_stream ) ) {
+ return 0;
+ }
- $this->GIF_buffer [ ] = ord ( $this->GIF_stream { $this->GIF_bfseek++ } );
- }
+ return 1;
- }
*/
function GIFGetByte ( $len ) {
$this->GIF_buffer = array ( );
for ( $i = 0; $i < $len; $i++ ) {
if ( $this->GIF_bfseek > strlen ( $this->GIF_stream ) ) {
return 0;
}
$this->GIF_buffer [ ] = ord ( $this->GIF_stream { $this->GIF_bfseek++ } );
}
return 1;
}
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GIFPutByte ( $bytes )
::
*/
function GIFPutByte ( $bytes ) {
for ( $i = 0; $i < count ( $bytes ); $i++ ) {
$this->GIF_string .= chr ( $bytes [ $i ] );
}
}
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: PUBLIC FUNCTIONS
::
::
:: GIFGetFrames ( )
::
*/
function GIFGetFrames ( ) {
return ( $this->GIF_arrays );
}
/*
:::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: GIFGetDelays ( )
::
*/
function GIFGetDelays ( ) {
return ( $this->GIF_delays );
}
}

View File

@@ -1,591 +0,0 @@
<?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: 麦当苗儿 <zuojiazi.cn@gmail.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Think\Image\Driver;
class Imagick{
/**
* 图像资源对象
* @var resource
*/
private $im;
/**
* 图像信息包括width,height,type,mime,size
* @var array
*/
private $info;
/**
* 构造方法,可用于打开一张图像
* @param string $imgname 图像路径
*/
public function __construct($imgname = null) {
if ( !extension_loaded('Imagick') ) {
E(L('_NOT_SUPPERT_').':Imagick');
}
$imgname && $this->open($imgname);
}
/**
* 打开一张图像
* @param string $imgname 图像路径
*/
public function open($imgname){
//检测图像文件
if(!is_file($imgname)) throw new \Exception('不存在的图像文件');
//销毁已存在的图像
empty($this->im) || $this->im->destroy();
//载入图像
$this->im = new \Imagick(realpath($imgname));
//设置图像信息
$this->info = [
'width' => $this->im->getImageWidth(),
'height' => $this->im->getImageHeight(),
'type' => strtolower($this->im->getImageFormat()),
'mime' => $this->im->getImageMimeType(),
];
}
/**
* 保存图像
* @param string $imgname 图像保存名称
* @param string $type 图像类型
* @param boolean $interlace 是否对JPEG类型图像设置隔行扫描
*/
public function save($imgname, $type = null, $interlace = true){
if(empty($this->im)) throw new \Exception('没有可以被保存的图像资源');
//设置图片类型
if(is_null($type)){
$type = $this->info['type'];
} else {
$type = strtolower($type);
$this->im->setImageFormat($type);
}
//JPEG图像设置隔行扫描
if('jpeg' == $type || 'jpg' == $type){
$this->im->setImageInterlaceScheme(1);
}
//去除图像配置信息
$this->im->stripImage();
//保存图像
$imgname = realpath(dirname($imgname)) . '/' . basename($imgname); //强制绝对路径
if ('gif' == $type) {
$this->im->writeImages($imgname, true);
} else {
$this->im->writeImage($imgname);
}
}
/**
* 返回图像宽度
* @return integer 图像宽度
*/
public function width(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
return $this->info['width'];
}
/**
* 返回图像高度
* @return integer 图像高度
*/
public function height(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
return $this->info['height'];
}
/**
* 返回图像类型
* @return string 图像类型
*/
public function type(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
return $this->info['type'];
}
/**
* 返回图像MIME类型
* @return string 图像MIME类型
*/
public function mime(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
return $this->info['mime'];
}
/**
* 返回图像尺寸数组 0 - 图像宽度1 - 图像高度
* @return array 图像尺寸
*/
public function size(){
if(empty($this->im)) throw new \Exception('没有指定图像资源');
return [$this->info['width'], $this->info['height']];
}
/**
* 裁剪图像
* @param integer $w 裁剪区域宽度
* @param integer $h 裁剪区域高度
* @param integer $x 裁剪区域x坐标
* @param integer $y 裁剪区域y坐标
* @param integer $width 图像保存宽度
* @param integer $height 图像保存高度
*/
public function crop($w, $h, $x = 0, $y = 0, $width = null, $height = null){
if(empty($this->im)) throw new \Exception('没有可以被裁剪的图像资源');
//设置保存尺寸
empty($width) && $width = $w;
empty($height) && $height = $h;
//裁剪图片
if('gif' == $this->info['type']){
$img = $this->im->coalesceImages();
$this->im->destroy(); //销毁原图
//循环裁剪每一帧
do {
$this->_crop($w, $h, $x, $y, $width, $height, $img);
} while ($img->nextImage());
//压缩图片
$this->im = $img->deconstructImages();
$img->destroy(); //销毁零时图片
} else {
$this->_crop($w, $h, $x, $y, $width, $height);
}
}
/* 裁剪图片,内部调用 */
private function _crop($w, $h, $x, $y, $width, $height, $img = null){
is_null($img) && $img = $this->im;
//裁剪
$info = $this->info;
if($x != 0 || $y != 0 || $w != $info['width'] || $h != $info['height']){
$img->cropImage($w, $h, $x, $y);
$img->setImagePage($w, $h, 0, 0); //调整画布和图片一致
}
//调整大小
if($w != $width || $h != $height){
$img->scaleImage($width, $height);
}
//设置缓存尺寸
$this->info['width'] = $w;
$this->info['height'] = $h;
}
/**
* 生成缩略图
* @param integer $width 缩略图最大宽度
* @param integer $height 缩略图最大高度
* @param integer $type 缩略图裁剪类型
*/
public function thumb($width, $height, $type = THINKIMAGE_THUMB_SCALE){
if(empty($this->im)) throw new \Exception('没有可以被缩略的图像资源');
//原图宽度和高度
$w = $this->info['width'];
$h = $this->info['height'];
/* 计算缩略图生成的必要参数 */
switch ($type) {
/* 等比例缩放 */
case THINKIMAGE_THUMB_SCALING:
//原图尺寸小于缩略图尺寸则不进行缩略
if($w < $width && $h < $height) return;
//计算缩放比例
$scale = min($width/$w, $height/$h);
//设置缩略图的坐标及宽度和高度
$x = $y = 0;
$width = $w * $scale;
$height = $h * $scale;
break;
/* 居中裁剪 */
case THINKIMAGE_THUMB_CENTER:
//计算缩放比例
$scale = max($width/$w, $height/$h);
//设置缩略图的坐标及宽度和高度
$w = $width/$scale;
$h = $height/$scale;
$x = ($this->info['width'] - $w)/2;
$y = ($this->info['height'] - $h)/2;
break;
/* 左上角裁剪 */
case THINKIMAGE_THUMB_NORTHWEST:
//计算缩放比例
$scale = max($width/$w, $height/$h);
//设置缩略图的坐标及宽度和高度
$x = $y = 0;
$w = $width/$scale;
$h = $height/$scale;
break;
/* 右下角裁剪 */
case THINKIMAGE_THUMB_SOUTHEAST:
//计算缩放比例
$scale = max($width/$w, $height/$h);
//设置缩略图的坐标及宽度和高度
$w = $width/$scale;
$h = $height/$scale;
$x = $this->info['width'] - $w;
$y = $this->info['height'] - $h;
break;
/* 填充 */
case THINKIMAGE_THUMB_FILLED:
//计算缩放比例
if($w < $width && $h < $height){
$scale = 1;
} else {
$scale = min($width/$w, $height/$h);
}
//设置缩略图的坐标及宽度和高度
$neww = $w * $scale;
$newh = $h * $scale;
$posx = ($width - $w * $scale)/2;
$posy = ($height - $h * $scale)/2;
//创建一张新图像
$newimg = new Imagick();
$newimg->newImage($width, $height, 'white', $this->info['type']);
if('gif' == $this->info['type']){
$imgs = $this->im->coalesceImages();
$img = new Imagick();
$this->im->destroy(); //销毁原图
//循环填充每一帧
do {
//填充图像
$image = $this->_fill($newimg, $posx, $posy, $neww, $newh, $imgs);
$img->addImage($image);
$img->setImageDelay($imgs->getImageDelay());
$img->setImagePage($width, $height, 0, 0);
$image->destroy(); //销毁零时图片
} while ($imgs->nextImage());
//压缩图片
$this->im->destroy();
$this->im = $img->deconstructImages();
$imgs->destroy(); //销毁零时图片
$img->destroy(); //销毁零时图片
} else {
//填充图像
$img = $this->_fill($newimg, $posx, $posy, $neww, $newh);
//销毁原图
$this->im->destroy();
$this->im = $img;
}
//设置新图像属性
$this->info['width'] = $width;
$this->info['height'] = $height;
return;
/* 固定 */
case THINKIMAGE_THUMB_FIXED:
$x = $y = 0;
break;
default:
throw new \Exception('不支持的缩略图裁剪类型');
}
/* 裁剪图像 */
$this->crop($w, $h, $x, $y, $width, $height);
}
/* 填充指定图像,内部使用 */
private function _fill($newimg, $posx, $posy, $neww, $newh, $img = null){
is_null($img) && $img = $this->im;
/* 将指定图片绘入空白图片 */
$draw = new ImagickDraw();
$draw->composite($img->getImageCompose(), $posx, $posy, $neww, $newh, $img);
$image = $newimg->clone();
$image->drawImage($draw);
$draw->destroy();
return $image;
}
/**
* 添加水印
* @param string $source 水印图片路径
* @param integer $locate 水印位置
* @param integer $alpha 水印透明度
*/
public function water($source, $locate = THINKIMAGE_WATER_SOUTHEAST){
//资源检测
if(empty($this->im)) throw new \Exception('没有可以被添加水印的图像资源');
if(!is_file($source)) throw new \Exception('水印图像不存在');
//创建水印图像资源
$water = new Imagick(realpath($source));
$info = [$water->getImageWidth(), $water->getImageHeight()];
/* 设定水印位置 */
switch ($locate) {
/* 右下角水印 */
case THINKIMAGE_WATER_SOUTHEAST:
$x = $this->info['width'] - $info[0];
$y = $this->info['height'] - $info[1];
break;
/* 左下角水印 */
case THINKIMAGE_WATER_SOUTHWEST:
$x = 0;
$y = $this->info['height'] - $info[1];
break;
/* 左上角水印 */
case THINKIMAGE_WATER_NORTHWEST:
$x = $y = 0;
break;
/* 右上角水印 */
case THINKIMAGE_WATER_NORTHEAST:
$x = $this->info['width'] - $info[0];
$y = 0;
break;
/* 居中水印 */
case THINKIMAGE_WATER_CENTER:
$x = ($this->info['width'] - $info[0])/2;
$y = ($this->info['height'] - $info[1])/2;
break;
/* 下居中水印 */
case THINKIMAGE_WATER_SOUTH:
$x = ($this->info['width'] - $info[0])/2;
$y = $this->info['height'] - $info[1];
break;
/* 右居中水印 */
case THINKIMAGE_WATER_EAST:
$x = $this->info['width'] - $info[0];
$y = ($this->info['height'] - $info[1])/2;
break;
/* 上居中水印 */
case THINKIMAGE_WATER_NORTH:
$x = ($this->info['width'] - $info[0])/2;
$y = 0;
break;
/* 左居中水印 */
case THINKIMAGE_WATER_WEST:
$x = 0;
$y = ($this->info['height'] - $info[1])/2;
break;
default:
/* 自定义水印坐标 */
if(is_array($locate)){
list($x, $y) = $locate;
} else {
throw new \Exception('不支持的水印位置类型');
}
}
//创建绘图资源
$draw = new ImagickDraw();
$draw->composite($water->getImageCompose(), $x, $y, $info[0], $info[1], $water);
if('gif' == $this->info['type']){
$img = $this->im->coalesceImages();
$this->im->destroy(); //销毁原图
do{
//添加水印
$img->drawImage($draw);
} while ($img->nextImage());
//压缩图片
$this->im = $img->deconstructImages();
$img->destroy(); //销毁零时图片
} else {
//添加水印
$this->im->drawImage($draw);
}
//销毁水印资源
$draw->destroy();
$water->destroy();
}
/**
* 图像添加文字
* @param string $text 添加的文字
* @param string $font 字体路径
* @param integer $size 字号
* @param string $color 文字颜色
* @param integer $locate 文字写入位置
* @param integer $offset 文字相对当前位置的偏移量
* @param integer $angle 文字倾斜角度
*/
public function text($text, $font, $size, $color = '#00000000',
$locate = THINKIMAGE_WATER_SOUTHEAST, $offset = 0, $angle = 0){
//资源检测
if(empty($this->im)) throw new \Exception('没有可以被写入文字的图像资源');
if(!is_file($font)) throw new \Exception("不存在的字体文件:{$font}");
//获取颜色和透明度
if(is_array($color)){
$color = array_map('dechex', $color);
foreach ($color as &$value) {
$value = str_pad($value, 2, '0', STR_PAD_LEFT);
}
$color = '#' . implode('', $color);
} elseif(!is_string($color) || 0 !== strpos($color, '#')) {
throw new \Exception('错误的颜色值');
}
$col = substr($color, 0, 7);
$alp = strlen($color) == 9 ? substr($color, -2) : 0;
//获取文字信息
$draw = new ImagickDraw();
$draw->setFont(realpath($font));
$draw->setFontSize($size);
$draw->setFillColor($col);
$draw->setFillAlpha(1-hexdec($alp)/127);
$draw->setTextAntialias(true);
$draw->setStrokeAntialias(true);
$metrics = $this->im->queryFontMetrics($draw, $text);
/* 计算文字初始坐标和尺寸 */
$x = 0;
$y = $metrics['ascender'];
$w = $metrics['textWidth'];
$h = $metrics['textHeight'];
/* 设定文字位置 */
switch ($locate) {
/* 右下角文字 */
case THINKIMAGE_WATER_SOUTHEAST:
$x += $this->info['width'] - $w;
$y += $this->info['height'] - $h;
break;
/* 左下角文字 */
case THINKIMAGE_WATER_SOUTHWEST:
$y += $this->info['height'] - $h;
break;
/* 左上角文字 */
case THINKIMAGE_WATER_NORTHWEST:
// 起始坐标即为左上角坐标,无需调整
break;
/* 右上角文字 */
case THINKIMAGE_WATER_NORTHEAST:
$x += $this->info['width'] - $w;
break;
/* 居中文字 */
case THINKIMAGE_WATER_CENTER:
$x += ($this->info['width'] - $w)/2;
$y += ($this->info['height'] - $h)/2;
break;
/* 下居中文字 */
case THINKIMAGE_WATER_SOUTH:
$x += ($this->info['width'] - $w)/2;
$y += $this->info['height'] - $h;
break;
/* 右居中文字 */
case THINKIMAGE_WATER_EAST:
$x += $this->info['width'] - $w;
$y += ($this->info['height'] - $h)/2;
break;
/* 上居中文字 */
case THINKIMAGE_WATER_NORTH:
$x += ($this->info['width'] - $w)/2;
break;
/* 左居中文字 */
case THINKIMAGE_WATER_WEST:
$y += ($this->info['height'] - $h)/2;
break;
default:
/* 自定义文字坐标 */
if(is_array($locate)){
list($posx, $posy) = $locate;
$x += $posx;
$y += $posy;
} else {
throw new \Exception('不支持的文字位置类型');
}
}
/* 设置偏移量 */
if(is_array($offset)){
$offset = array_map('intval', $offset);
list($ox, $oy) = $offset;
} else{
$offset = intval($offset);
$ox = $oy = $offset;
}
/* 写入文字 */
if('gif' == $this->info['type']){
$img = $this->im->coalesceImages();
$this->im->destroy(); //销毁原图
do{
$img->annotateImage($draw, $x + $ox, $y + $oy, $angle, $text);
} while ($img->nextImage());
//压缩图片
$this->im = $img->deconstructImages();
$img->destroy(); //销毁零时图片
} else {
$this->im->annotateImage($draw, $x + $ox, $y + $oy, $angle, $text);
}
$draw->destroy();
}
/**
* 析构方法,用于销毁图像资源
*/
public function __destruct() {
empty($this->im) || $this->im->destroy();
}
}

View File

@@ -13,78 +13,160 @@ namespace Think;
class Input {
// 全局过滤规则
static $filter = NULL;
static $filter = null;
/**
* 获取系统变量 支持过滤和默认值
* @access public
* @param string $type 输入数据类型
* @param string $method 输入数据类型
* @param array $args 参数 array(key,filter,default)
* @return mixed
*/
static public function __callStatic($type,$args=[]) {
switch(strtolower($type)) {
case 'get': $input =& $_GET;break;
case 'post': $input =& $_POST;break;
case 'put' : parse_str(file_get_contents('php://input'), $input);break;
case 'param' :
static public function __callStatic($method,$args=[]) {
static $_PUT = null;
$name = $args[0];
$default = isset($args[2]) ? $args[2] : null;
if(strpos($name,'/')){ // 指定修饰符
list($name,$type) = explode('/',$name,2);
}else{ // 默认强制转换为字符串
$type = 's';
}
switch(strtolower($method)) {
case 'get' :
$input =& $_GET;
break;
case 'post' :
$input =& $_POST;
break;
case 'put' :
if(is_null($_PUT)){
parse_str(file_get_contents('php://input'), $_PUT);
}
$input = $_PUT;
break;
case 'param' :
switch($_SERVER['REQUEST_METHOD']) {
case 'POST':
$input = $_POST;
break;
case 'PUT':
parse_str(file_get_contents('php://input'), $input);
if(is_null($_PUT)){
parse_str(file_get_contents('php://input'), $_PUT);
}
$input = $_PUT;
break;
default:
$input = $_GET;
}
break;
case 'request': $input =& $_REQUEST;break;
case 'server': $input =& $_SERVER;break;
case 'cookie': $input =& $_COOKIE;break;
case 'session': $input =& $_SESSION;break;
case 'globals': $input =& $GLOBALS;break;
default:return NULL;
case 'path' :
$input = [];
if(!empty($_SERVER['PATH_INFO'])){
$depr = Config::get('url_pathinfo_depr');
$input = explode($depr,trim($_SERVER['PATH_INFO'],$depr));
}
break;
case 'request' :
$input =& $_REQUEST;
break;
case 'session' :
$input =& $_SESSION;
break;
case 'cookie' :
$input =& $_COOKIE;
break;
case 'server' :
$input =& $_SERVER;
break;
case 'globals' :
$input =& $GLOBALS;
break;
default:
return null;
}
// 变量全局过滤
array_walk_recursive($input,'self::filter_exp');
if(self::$filter) {
$_filters = explode(',',self::$filter);
foreach($_filters as $_filter){
// 全局参数过滤
array_walk_recursive($input,$_filter);
if(''==$name) { // 获取全部变量
$data = $input;
if(isset(self::$filter)) {
$filter = self::$filter;
if(is_string($filters)){
$filters = explode(',',$filters);
}
foreach($filters as $filter){
$data = self::filter($filter,$data); // 参数过滤
}
}
}
if(''== $args[0]) {
// 返回全部数据
return $input;
}elseif(isset($input[$args[0]])) {
$data = $input[$args[0]];
}elseif(isset($input[$name])) { // 取值操作
$data = $input[$name];
if(!empty($args[1])) {
$filters = explode(',',$args[1]);
foreach($filters as $filter){
if(is_callable($filter)) {
$data = is_array($data)?array_map($filter,$data):$filter($data); // 参数过滤
if(is_string($filters)){
if(0 === strpos($filters,'/') && 1 !== preg_match($filters,(string)$data)){
// 支持正则验证
return $default;
}else{
$data = filter_var($data,is_int($filter)?$filter:filter_id($filter));
if(false === $data) {
return isset($args[2])?$args[2]:NULL;
$filters = explode(',',$filters);
}
}elseif(is_int($filters)){
$filters = array($filters);
}
if(is_array($filters)){
foreach($filters as $filter){
if(function_exists($filter)) {
$data = is_array($data) ? self::filter($filter,$data) : $filter($data); // 参数过滤
}else{
$data = filter_var($data,is_int($filter) ? $filter : filter_id($filter));
if(false === $data) {
return $default;
}
}
}
}
}
if(!empty($type)){
switch(strtolower($type)){
case 'a': // 数组
$data = (array)$data;
break;
case 'd': // 数字
$data = (int)$data;
break;
case 'f': // 浮点
$data = (float)$data;
break;
case 'b': // 布尔
$data = (boolean)$data;
break;
case 's': // 字符串
default:
$data = (string)$data;
}
}
}else{
// 不存在指定输入
$data = isset($args[2])?$args[2]:NULL;
}else{ // 变量默认值
$data = $default;
}
is_array($data) && array_walk_recursive($data,'self::filterExp');
return $data;
}
// 过滤表单中的表达式
static private function filter_exp(&$value){
if (in_array(strtolower($value),['exp','or'])){
static public function filterExp(&$value){
// TODO 其他安全过滤
// 过滤查询特殊字符
if(preg_match('/^(EXP|NEQ|GT|EGT|LT|ELT|OR|XOR|LIKE|NOTLIKE|NOT BETWEEN|NOTBETWEEN|BETWEEN|NOTIN|NOT IN|IN)$/i',$value)){
$value .= ' ';
}
}
static public function filter($filter, $data) {
$result = array();
foreach ($data as $key => $val) {
$result[$key] = is_array($val)
? self::filter($filter, $val)
: call_user_func($filter, $val);
}
return $result;
}
}

View File

@@ -130,9 +130,13 @@ class Loader {
* @return Object
*/
static public function model($name = '', $layer = 'Model') {
if(empty($name)) return new Model;
if(empty($name)) {
return new Model;
}
static $_model = [];
if(isset($_model[$name . $layer])) return $_model[$name . $layer];
if(isset($_model[$name . $layer])) {
return $_model[$name . $layer];
}
if(strpos($name, '/')) {
list($module, $name) = explode('/', $name);
}else{
@@ -157,7 +161,9 @@ class Loader {
*/
static public function controller($name, $layer = 'Controller') {
static $_instance = [];
if(isset($_instance[$name.$layer])) return $_instance[$name . $layer];
if(isset($_instance[$name.$layer])) {
return $_instance[$name . $layer];
}
if(strpos($name, '/')) {
list($module,$name) = explode('/', $name);
}else{
@@ -226,7 +232,7 @@ class Loader {
$_instance[$identify] = $o;
}
else
E('_CLASS_NOT_EXIST_:' . $class);
throw new Exception('_CLASS_NOT_EXIST_:' . $class);
}
return $_instance[$identify];
}

View File

@@ -44,7 +44,7 @@ class Log {
* @return array
*/
static public function getLog($level=''){
return $level?self::$log[$level]:self::$log;
return $level ? self::$log[$level] : self::$log;
}
/**
@@ -55,7 +55,7 @@ class Log {
* @return void
*/
static public function save($destination='',$level='') {
$log = $level?self::$log[$level]:self::$log;
$log = self::getLog($level);
if(empty($log)) return ;
$message = '';
if($level) {

View File

@@ -83,11 +83,6 @@ class Model {
$this->dbName = $config['db_name'];
}
// 设置表前缀
if(empty($this->tablePrefix)) {
$this->tablePrefix = is_null($this->tablePrefix)?'':C('database.prefix');
}
// 数据库初始化操作
// 获取数据库操作对象
// 当前模型有独立的数据库连接信息
@@ -566,7 +561,7 @@ class Model {
$config = C($config);
}
$_db[$linkNum] = Db::instance($config);
}elseif(NULL === $config){
}elseif(null === $config){
$_db[$linkNum]->close(); // 关闭数据库连接
unset($_db[$linkNum]);
return ;
@@ -825,7 +820,7 @@ class Model {
* @param array $args 参数
* @return Model
*/
public function scope($scope='',$args=NULL){
public function scope($scope='',$args=null){
if('' === $scope) {
if(isset($this->scope['default'])) {
// 默认的命名范围

View File

@@ -69,7 +69,7 @@ class Baidu extends Driver{
if(!empty($this->token['openid']))
return $this->token['openid'];
$data = $this->call('passport/users/getLoggedInUser');
return !empty($data['uid'])?$data['uid']:NULL;
return !empty($data['uid'])?$data['uid']:null;
}
/**

View File

@@ -69,7 +69,7 @@ class Diandian extends Driver{
public function getOpenId(){
if(!empty($this->token['openid']))
return $this->token['openid'];
return NULL;
return null;
}
/**

View File

@@ -67,7 +67,7 @@ class Douban extends Driver{
public function getOpenId(){
if(!empty($this->token['openid']))
return $this->token['openid'];
return NULL;
return null;
}
/**

View File

@@ -69,7 +69,7 @@ class Github extends Driver{
return $this->token['openid'];
$data = $this->call('user');
return !empty($data['id'])?$data['id']:NULL;
return !empty($data['id'])?$data['id']:null;
}
/**

View File

@@ -75,7 +75,7 @@ class Google extends Driver{
return $this->token['openid'];
$data = $this->call('userinfo');
return !empty($data['id'])?$data['id']:NULL;
return !empty($data['id'])?$data['id']:null;
}
/**

View File

@@ -70,7 +70,7 @@ class Kaixin extends Driver{
return $this->token['openid'];
$data = $this->call('users/me');
return !empty($data['uid'])?$data['uid']:NULL;
return !empty($data['uid'])?$data['uid']:null;
}
/**

View File

@@ -76,7 +76,7 @@ class Msn extends Driver{
return $this->token['openid'];
$data = $this->call('me');
return !empty($data['id'])?$data['id']:NULL;
return !empty($data['id'])?$data['id']:null;
}
/**

View File

@@ -83,7 +83,7 @@ class Qq extends Driver{
if(isset($data['openid']))
return $data['openid'];
}
return NULL;
return null;
}
public function getOauthInfo(){

View File

@@ -93,7 +93,7 @@ class Renren extends Driver{
public function getOpenId(){
if(!empty($this->token['openid']))
return $this->token['openid'];
return NULL;
return null;
}
/**

View File

@@ -69,7 +69,7 @@ class Sina extends Driver{
public function getOpenId(){
if(!empty($this->token['openid']))
return $this->token['openid'];
return NULL;
return null;
}
/**

View File

@@ -69,7 +69,7 @@ class Sohu extends Driver{
public function getOpenId(){
if(!empty($this->token['openid']))
return $this->token['openid'];
return NULL;
return null;
}
/**

View File

@@ -71,7 +71,7 @@ class T163 extends Driver{
return $this->token['openid'];
$data = $this->call('users/show');
return !empty($data['id'])?$data['id']:NULL;
return !empty($data['id'])?$data['id']:null;
}
/**

View File

@@ -71,7 +71,7 @@ class Taobao extends Driver{
public function getOpenId(){
if(!empty($this->token['openid']))
return $this->token['openid'];
return NULL;
return null;
}
/**

View File

@@ -74,7 +74,7 @@ class Tencent extends Driver{
public function getOpenId(){
if(!empty($this->token['openid']))
return $this->token['openid'];
return NULL;
return null;
}
/**

View File

@@ -69,7 +69,7 @@ class X360 extends Driver{
if(!empty($this->token['openid']))
return $this->token['openid'];
$data = $this->call('user/me');
return !empty($data['id'])?$data['id']:NULL;
return !empty($data['id'])?$data['id']:null;
}
/**

View File

@@ -26,7 +26,7 @@ class Parser {
}
// 调用驱动类的方法
static public function __callStatic($method, $params){
static public function __callStatic($method, $params){
return self::parse($params[0],$method);
}
}
}

View File

@@ -20,6 +20,7 @@ class Route {
'DELETE' => [],
'*' => [],
];
// URL映射规则
static private $map = [];
// 子域名部署规则
@@ -86,7 +87,7 @@ class Route {
}
// 检测子域名部署
static public function checkDomain(){
static public function checkDomain($config=[]){
// 开启子域名部署 支持二级和三级域名
if(!empty(self::$domain)) {
$rules = self::$domain;
@@ -123,7 +124,7 @@ class Route {
exit;
}
if(is_array($rule)) {
$_GET[Config::get('var_module')] = $rule[0];
$_GET[$config['var_module']] = $rule[0];
if(isset($rule[1])) { // 传入参数
parse_str($rule[1], $parms);
if(isset($panDomain)) {
@@ -136,18 +137,20 @@ class Route {
$_GET = array_merge($_GET,$parms);
}
}else{
$_GET[Config::get('var_module')] = $rule;
$_GET[$config['var_module']] = $rule;
}
}
}
}
// 检测URL路由
static public function check($regx) {
static public function check($regx,$config) {
// 优先检测是否存在PATH_INFO
if(empty($regx)) $regx = '/' ;
// 分隔符替换 确保路由定义使用统一的分隔符
$regx = str_replace(Config::get('pathinfo_depr'), '/', $regx);
if('/' != $config['pathinfo_depr']){
$regx = str_replace($config['pathinfo_depr'], '/', $regx);
}
if(isset(self::$map[$regx])) { // URL映射
return self::parseUrl(self::$map[$regx]);
}
@@ -187,7 +190,7 @@ class Route {
self::invokeRegx($route, $matches);
exit;
}
return self::parseRegex($matches, $route, $regx);
return self::parseRegex($matches, $route, $regx,$config);
}else{ // 规则路由
$len1 = substr_count($regx, '/');
$len2 = substr_count($rule, '/');
@@ -210,13 +213,13 @@ class Route {
self::invokeRule($route, $var);
exit;
}
return self::parseRule($rule, $route, $regx);
return self::parseRule($rule, $route, $regx,$config);
}
}
}
}
}
return self::parseUrl($regx);
return self::parseUrl($regx,$config);
}
/**
@@ -265,33 +268,34 @@ class Route {
$reflect->invokeArgs($args);
}
// 解析模块的URL地址
static private function parseUrl($url) {
// 解析模块的URL地址 [模块/]控制器/操作
static private function parseUrl($url,$config=[]) {
if('/' == $url) {
return ;
}
$paths = explode('/', $url);
$var_g = Config::get('var_group');
$var_c = Config::get('var_controller');
$var_a = Config::get('var_action');
if(Config::get('require_group') && !isset($_GET[$var_g])) {
$_GET[$var_g] = array_shift($paths);
}
if(Config::get('require_controller') && !isset($_GET[$var_c])) {
$_GET[$var_c] = array_shift($paths);
$_GET[$config['var_action']] = array_pop($paths);
if(!defined('BIND_CONTROLLER') && !isset($_GET[$config['var_controller']])) {
$_GET[$config['var_controller']] = array_pop($paths);
}
if(!isset($_GET[$var_a])) {
$_GET[$var_a] = array_shift($paths);
if(!defined('BIND_MODULE') && !isset($_GET[$config['var_module']])) {
$_GET[$config['var_module']] = array_pop($paths);
}
// 解析剩余的URL参数
$var = [];
preg_replace('@(\w+)\/([^\/]+)@e', '$var[\'\\1\']=strip_tags(\'\\2\');', implode('/', $paths));
$_GET = array_merge($var, $_GET);
if(!empty($paths)) {
preg_replace_callback('/(\w+)\/([^\/]+)/', function($match) use(&$var){ $var[strtolower($match[1])]=strip_tags($match[2]);}, implode('/',$paths));
}
$_GET = array_merge($var, $_GET);
}
// 解析规范的路由地址
// 地址格式 [控制器/操作?]参数1=值1&参数2=值2...
static private function parseRoute($url) {
static private function parseRoute($url,$config=[]) {
$var = [];
if(false !== strpos($url, '?')) { // [控制器/操作?]参数1=值1&参数2=值2...
$info = parse_url($url);
@@ -304,9 +308,12 @@ class Route {
}
if(isset($path)) {
$action = array_pop($path);
$_GET[Config::get('var_action')] = '[rest]'==$action? REQUEST_METHOD : $action;
$_GET[$config['var_action']] = '[rest]'==$action ? REQUEST_METHOD : $action;
if(!empty($path)) {
$_GET[Config::get('var_controller')] = array_pop($path);
$_GET[$config['var_controller']] = array_pop($path);
}
if(!empty($path)) {
$_GET[$config['var_module']] = array_pop($path);
}
}
return $var;
@@ -352,7 +359,7 @@ class Route {
// 外部地址中可以用动态变量 采用 :1 :2 的方式
// 'news/:month/:day/:id'=>array('News/read?cate=1','status=1'),
// 'new/:id'=>array('/new.php?id=:1',301), 重定向
static private function parseRule($rule, $route, $regx) {
static private function parseRule($rule, $route, $regx,$config) {
// 获取路由地址规则
$url = is_array($route) ? $route[0] : $route;
// 获取URL地址中的参数
@@ -383,7 +390,7 @@ class Route {
exit;
}else{
// 解析路由地址
$var = self::parseRoute($url);
$var = self::parseRoute($url,$config);
// 解析路由地址里面的动态参数
$values = array_values($matches);
foreach ($var as $key => $val){
@@ -393,8 +400,10 @@ class Route {
}
$var = array_merge($matches, $var);
// 解析剩余的URL参数
if($paths) {
preg_replace('@(\w+)\/([^\/]+)@e', '$var[strtolower(\'\\1\')]=strip_tags(\'\\2\');', implode('/', $paths));
if(!empty($paths)) {
preg_replace_callback('/(\w+)\/([^\/]+)/', function($match) use(&$var){
$var[strtolower($match[1])] = strip_tags($match[2]);
}, implode('/',$paths));
}
// 解析路由自动传人参数
if(is_array($route) && isset($route[1])) {
@@ -413,7 +422,7 @@ class Route {
// 参数值和外部地址中可以用动态变量 采用 :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'), 重定向
static private function parseRegex($matches, $route, $regx) {
static private function parseRegex($matches, $route, $regx,$config) {
// 获取路由地址规则
$url = is_array($route) ? $route[0] : $route;
$url = preg_replace('/:(\d+)/e', '$matches[\\1]', $url);
@@ -422,11 +431,13 @@ class Route {
exit;
}else{
// 解析路由地址
$var = self::parseRoute($url);
$var = self::parseRoute($url,$config);
// 解析剩余的URL参数
$regx = substr_replace($regx, '', 0, strlen($matches[0]));
if($regx) {
preg_replace('@(\w+)\/([^,\/]+)@e', '$var[strtolower(\'\\1\')]=strip_tags(\'\\2\');', $regx);
preg_replace_callback('/(\w+)\/([^\/]+)/', function($match) use(&$var){
$var[strtolower($match[1])] = strip_tags($match[2]);
}, $regx);
}
// 解析路由自动传人参数
if(is_array($route) && isset($route[1])) {

View File

@@ -33,21 +33,32 @@ class Session {
* @return void
*/
static public function init($config=[]) {
if(isset($config['prefix'])) self::$prefix = $config['prefix'];
if(isset($config['prefix']))
self::$prefix = $config['prefix'];
if(isset($config['var_session_id']) && isset($_REQUEST[$config['var_session_id']])){
session_id($_REQUEST[$config['var_session_id']]);
}elseif(isset($config['id'])) {
session_id($config['id']);
}
ini_set('session.auto_start', 0);
if(isset($config['name'])) session_name($config['name']);
if(isset($config['path'])) session_save_path($config['path']);
if(isset($config['domain'])) ini_set('session.cookie_domain', $config['domain']);
if(isset($config['expire'])) ini_set('session.gc_maxlifetime', $config['expire']);
if(isset($config['use_trans_sid'])) ini_set('session.use_trans_sid', $config['use_trans_sid']?1:0);
if(isset($config['use_cookies'])) ini_set('session.use_cookies', $config['use_cookies']?1:0);
if(isset($config['cache_limiter'])) session_cache_limiter($config['cache_limiter']);
if(isset($config['cache_expire'])) session_cache_expire($config['cache_expire']);
if(isset($config['name']))
session_name($config['name']);
if(isset($config['path']))
session_save_path($config['path']);
if(isset($config['domain']))
ini_set('session.cookie_domain', $config['domain']);
if(isset($name['expire'])) {
ini_set('session.gc_maxlifetime', $name['expire']);
ini_set('session.cookie_lifetime', $name['expire']);
}
if(isset($config['use_trans_sid']))
ini_set('session.use_trans_sid', $config['use_trans_sid']?1:0);
if(isset($config['use_cookies']))
ini_set('session.use_cookies', $config['use_cookies']?1:0);
if(isset($config['cache_limiter']))
session_cache_limiter($config['cache_limiter']);
if(isset($config['cache_expire']))
session_cache_expire($config['cache_expire']);
if(!empty($config['type'])) { // 读取session驱动
$class = 'Think\\Session\\Driver\\'. ucwords(strtolower($config['type']));
// 检查驱动类
@@ -65,11 +76,16 @@ class Session {
* @return void
*/
static public function set($name,$value='',$prefix='') {
$prefix = $prefix?$prefix:self::$prefix;
if($prefix){
if (!is_array($_SESSION[$prefix])) {
$_SESSION[$prefix] = [];
$prefix = $prefix ? $prefix : self::$prefix;
if(strpos($name,'.')){
// 二维数组赋值
list($name1,$name2) = explode('.',$name);
if($prefix){
$_SESSION[$prefix][$name1][$name2] = $value;
}else{
$_SESSION[$name1][$name2] = $value;
}
}elseif($prefix){
$_SESSION[$prefix][$name] = $value;
}else{
$_SESSION[$name] = $value;
@@ -82,13 +98,27 @@ class Session {
* @param string $prefix 作用域(前缀)
* @return mixed
*/
static public function get($name,$prefix='') {
$prefix = $prefix?$prefix:self::$prefix;
if($prefix){ // 获取session
return isset($_SESSION[$prefix][$name])?$_SESSION[$prefix][$name]:null;
static public function get($name='',$prefix='') {
$prefix = $prefix ? $prefix : self::$prefix;
if(''==$name){
// 获取全部的session
$value = $prefix ? $_SESSION[$prefix] : $_SESSION;
}elseif($prefix){ // 获取session
if(strpos($name,'.')){
list($name1,$name2) = explode('.',$name);
$value = isset($_SESSION[$prefix][$name1][$name2])?$_SESSION[$prefix][$name1][$name2]:null;
}else{
$value = isset($_SESSION[$prefix][$name]) ? $_SESSION[$prefix][$name] : null;
}
}else{
return isset($_SESSION[$name])?$_SESSION[$name]:null;
if(strpos($name,'.')){
list($name1,$name2) = explode('.',$name);
$value = isset($_SESSION[$name1][$name2]) ? $_SESSION[$name1][$name2] : null;
}else{
$value = isset($_SESSION[$name]) ? $_SESSION[$name] : null;
}
}
return $value;
}
/**
@@ -99,10 +129,19 @@ class Session {
*/
static public function delete($name,$prefix='') {
$prefix = $prefix?$prefix:$this->prefix;
if($prefix){
unset($_SESSION[$prefix][$name]);
if(strpos($name,'.')){
list($name1,$name2) = explode('.',$name);
if($prefix){
unset($_SESSION[$prefix][$name1][$name2]);
}else{
unset($_SESSION[$name1][$name2]);
}
}else{
unset($_SESSION[$name]);
if($prefix){
unset($_SESSION[$prefix][$name]);
}else{
unset($_SESSION[$name]);
}
}
}
@@ -127,11 +166,12 @@ class Session {
* @return boolean
*/
static public function has($name,$prefix='') {
$prefix = $prefix?$prefix:self::$prefix;
if($prefix){
return isset($_SESSION[$prefix][$name]);
$prefix = $prefix ? $prefix : self::$prefix;
if(strpos($name,'.')){ // 支持数组
list($name1,$name2) = explode('.',$name);
return $prefix ? isset($_SESSION[$prefix][$name1][$name2]) : isset($_SESSION[$name1][$name2]);
}else{
return isset($_SESSION[$name]);
return $prefix ? isset($_SESSION[$prefix][$name]) : isset($_SESSION[$name]);
}
}
@@ -140,7 +180,7 @@ class Session {
* @param string $name session操作名称
* @return void
*/
static public function operate($name) {
static private function operate($name) {
if('pause'==$name){ // 暂停session
session_write_close();
}elseif('start'==$name){ // 启动session

40
Library/Think/Storage.php Normal file
View File

@@ -0,0 +1,40 @@
<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think;
// 分布式文件存储类
class Storage {
/**
* 操作句柄
* @var string
* @access protected
*/
static protected $handler;
/**
* 连接分布式文件系统
* @access public
* @param string $type 文件类型
* @param array $options 配置数组
* @return void
*/
static public function connect($type='File',$options=array()) {
$class = 'Think\\Storage\\Driver\\'.ucwords($type);
self::$handler = new $class($options);
}
static public function __callstatic($method,$args){
//调用缓存驱动的方法
if(method_exists(self::$handler, $method)){
return call_user_func_array(array(self::$handler,$method), $args);
}
}
}

View File

@@ -0,0 +1,125 @@
<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think\Storage\Driver;
use Think\Storage;
// 本地文件写入存储类
class File extends Storage{
private $contents=array();
/**
* 架构函数
* @access public
*/
public function __construct() {
}
/**
* 文件内容读取
* @access public
* @param string $filename 文件名
* @return string
*/
public function read($filename,$type=''){
return $this->get($filename,'content',$type);
}
/**
* 文件写入
* @access public
* @param string $filename 文件名
* @param string $content 文件内容
* @return boolean
*/
public function put($filename,$content,$type=''){
$dir = dirname($filename);
if(!is_dir($dir)){
mkdir($dir,0777,true);
}
if(false === file_put_contents($filename,$content)){
E(L('_STORAGE_WRITE_ERROR_').':'.$filename);
}else{
$this->contents[$filename]=$content;
return true;
}
}
/**
* 文件追加写入
* @access public
* @param string $filename 文件名
* @param string $content 追加的文件内容
* @return boolean
*/
public function append($filename,$content,$type=''){
if(is_file($filename)){
$content = $this->read($filename,$type).$content;
}
return $this->put($filename,$content,$type);
}
/**
* 加载文件
* @access public
* @param string $filename 文件名
* @param array $vars 传入变量
* @return void
*/
public function load($_filename,$vars=null){
if(!is_null($vars)){
extract($vars, EXTR_OVERWRITE);
}
include $_filename;
}
/**
* 文件是否存在
* @access public
* @param string $filename 文件名
* @return boolean
*/
public function has($filename,$type=''){
return is_file($filename);
}
/**
* 文件删除
* @access public
* @param string $filename 文件名
* @return boolean
*/
public function unlink($filename,$type=''){
unset($this->contents[$filename]);
return is_file($filename) ? unlink($filename) : false;
}
/**
* 读取文件信息
* @access public
* @param string $filename 文件名
* @param string $name 信息名 mtime或者content
* @return boolean
*/
public function get($filename,$name,$type=''){
if(!isset($this->contents[$filename])){
if(!is_file($filename)) {
return false;
}
$this->contents[$filename] = file_get_contents($filename);
}
$content=$this->contents[$filename];
$info = array(
'mtime' => filemtime($filename),
'content' => $content
);
return $info[$name];
}
}

View File

@@ -0,0 +1,194 @@
<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <weibo.com/luofei614>
// +----------------------------------------------------------------------
namespace Think\Storage\Driver;
use Think\Storage;
// SAE环境文件写入存储类
class Sae extends Storage{
/**
* 架构函数
* @access public
*/
private $mc;
private $kvs = array();
private $htmls = array();
private $contents = array();
public function __construct() {
if(!function_exists('memcache_init')){
header('Content-Type:text/html;charset=utf-8');
exit('请在SAE平台上运行代码。');
}
$this->mc = @memcache_init();
if(!$this->mc){
header('Content-Type:text/html;charset=utf-8');
exit('您未开通Memcache服务请在SAE管理平台初始化Memcache服务');
}
}
/**
* 获得SaeKv对象
*/
private function getKv(){
static $kv;
if(!$kv){
$kv = new \SaeKV();
if(!$kv->init())
E('您没有初始化KVDB请在SAE管理平台初始化KVDB服务');
}
return $kv;
}
/**
* 文件内容读取
* @access public
* @param string $filename 文件名
* @return string
*/
public function read($filename,$type=''){
switch(strtolower($type)){
case 'f':
$kv = $this->getKv();
if(!isset($this->kvs[$filename])){
$this->kvs[$filename]=$kv->get($filename);
}
return $this->kvs[$filename];
default:
return $this->get($filename,'content',$type);
}
}
/**
* 文件写入
* @access public
* @param string $filename 文件名
* @param string $content 文件内容
* @return boolean
*/
public function put($filename,$content,$type=''){
switch(strtolower($type)){
case 'f':
$kv = $this->getKv();
$this->kvs[$filename] = $content;
return $kv->set($filename,$content);
case 'html':
$kv = $this->getKv();
$content = time().$content;
$this->htmls[$filename] = $content;
return $kv->set($filename,$content);
default:
$content = time().$content;
if(!$this->mc->set($filename,$content,MEMCACHE_COMPRESSED,0)){
E(L('_STORAGE_WRITE_ERROR_').':'.$filename);
}else{
$this->contents[$filename] = $content;
return true;
}
}
}
/**
* 文件追加写入
* @access public
* @param string $filename 文件名
* @param string $content 追加的文件内容
* @return boolean
*/
public function append($filename,$content,$type=''){
if($old_content = $this->read($filename,$type)){
$content = $old_content.$content;
}
return $this->put($filename,$content,$type);
}
/**
* 加载文件
* @access public
* @param string $_filename 文件名
* @param array $vars 传入变量
* @return void
*/
public function load($_filename,$vars=null){
if(!is_null($vars)){
extract($vars, EXTR_OVERWRITE);
}
eval('?>'.$this->read($_filename));
}
/**
* 文件是否存在
* @access public
* @param string $filename 文件名
* @return boolean
*/
public function has($filename,$type=''){
if($this->read($filename,$type)){
return true;
}else{
return false;
}
}
/**
* 文件删除
* @access public
* @param string $filename 文件名
* @return boolean
*/
public function unlink($filename,$type=''){
switch(strtolower($type)){
case 'f':
$kv = $this->getKv();
unset($this->kvs[$filename]);
return $kv->delete($filename);
case 'html':
$kv = $this->getKv();
unset($this->htmls[$filename]);
return $kv->delete($filename);
default:
unset($this->contents[$filename]);
return $this->mc->delete($filename);
}
}
/**
* 读取文件信息
* @access public
* @param string $filename 文件名
* @param string $name 信息名 mtime或者content
* @return boolean
*/
public function get($filename,$name,$type=''){
switch(strtolower($type)){
case 'html':
if(!isset($this->htmls[$filename])){
$kv = $this->getKv();
$this->htmls[$filename] = $kv->get($filename);
}
$content = $this->htmls[$filename];
break;
default:
if(!isset($this->contents[$filename])){
$this->contents[$filename] = $this->mc->get($filename);
}
$content = $this->contents[$filename];
}
if(false===$content){
return false;
}
$info = array(
'mtime' => substr($content,0,10),
'content' => substr($content,10)
);
return $info[$name];
}
}

View File

@@ -17,9 +17,9 @@ namespace Think;
* 编译型模板引擎 支持动态缓存
*/
class Template {
protected $tVar = []; // 模板变量
protected $data = []; // 模板变量
protected $config = [ // 引擎配置
'tpl_path' => '',
'tpl_path' => '', // 模板路径
'tpl_suffix' => '.html', // 默认模板文件后缀
'cache_suffix' => '.php', // 默认模板缓存后缀
'tpl_deny_func_list' => 'echo,exit', // 模板引擎禁用函数
@@ -28,8 +28,8 @@ class Template {
'tpl_end' => '}', // 模板引擎普通标签结束标记
'strip_space' => false, // 是否去除模板文件里面的html空格与换行
'tpl_cache' => true, // 是否开启模板编译缓存,设为false则每次都会重新编译
'compile_type' => 'file',
'cache_path' => '',
'compile_type' => 'file', // 模板编译类型
'cache_path' => '', // 模板缓存目录
'cache_prefix' => '', // 模板缓存前缀标识,可以动态改变
'cache_time' => 0, // 模板缓存有效期 0 为永久,(以数字为值,单位:秒)
'layout_item' => '{__CONTENT__}', // 布局模板的内容替换标识
@@ -38,7 +38,7 @@ class Template {
'taglib_load' => true, // 是否使用内置标签库之外的其它标签库,默认自动检测
'taglib_build_in' => 'cx', // 内置标签库名称(标签使用不必指定标签库名称),以逗号分隔 注意解析顺序
'taglib_pre_load' => '', // 需要额外加载的标签库(须指定标签库名称),多个以逗号分隔
'display_cache' => false,
'display_cache' => false, // 模板渲染缓存
];
private $literal = [];
@@ -84,9 +84,9 @@ class Template {
*/
public function assign($name,$value=''){
if(is_array($name)) {
$this->tVar = array_merge($this->tVar,$name);
$this->data = array_merge($this->data,$name);
}else {
$this->tVar[$name] = $value;
$this->data[$name] = $value;
}
}
@@ -105,7 +105,7 @@ class Template {
}
public function get($name){
return $this->tVar[$name];
return $this->data[$name];
}
/**
@@ -118,7 +118,7 @@ class Template {
*/
public function display($template,$vars=[],$config=[]) {
if($vars){
$this->tVar = $vars;
$this->data = $vars;
}
if($config){
$this->config($config);
@@ -133,7 +133,7 @@ class Template {
ob_start();
ob_implicit_flush(0);
// 读取编译存储
$this->storage->read($cacheFile,$this->tVar);
$this->storage->read($cacheFile,$this->data);
// 获取并清空缓存
$content = ob_get_clean();
if($this->config['cache_id'] && $this->config['display_cache']) {
@@ -152,7 +152,7 @@ class Template {
*/
public function fetch($content,$vars=[]) {
if($vars){
$this->tVar = $vars;
$this->data = $vars;
}
$cacheFile = $this->config['cache_path'].$this->config['cache_prefix'].md5($content).$this->config['cache_suffix'];
if(!$this->checkCache($content,$cacheFile)) { // 缓存无效
@@ -160,7 +160,7 @@ class Template {
$this->compiler($content,$cacheFile);
}
// 读取编译存储
$this->storage->read($cacheFile,$this->tVar);
$this->storage->read($cacheFile,$this->data);
}
/**
@@ -591,22 +591,22 @@ class Template {
//模板函数过滤
$fun = strtolower(trim($args[0]));
switch($fun) {
case 'default': // 特殊模板函数
$name = '('.$name.')?('.$name.'):'.$args[1];
break;
default: // 通用模板函数
if(!in_array($fun,$template_deny_funs)){
if(isset($args[1])){
if(strstr($args[1],'###')){
$args[1] = str_replace('###',$name,$args[1]);
$name = "$fun($args[1])";
}else{
$name = "$fun($name,$args[1])";
case 'default': // 特殊模板函数
$name = '('.$name.')?('.$name.'):'.$args[1];
break;
default: // 通用模板函数
if(!in_array($fun,$template_deny_funs)){
if(isset($args[1])){
if(strstr($args[1],'###')){
$args[1] = str_replace('###',$name,$args[1]);
$name = "$fun($args[1])";
}else{
$name = "$fun($name,$args[1])";
}
}else if(!empty($args[0])){
$name = "$fun($name)";
}
}else if(!empty($args[0])){
$name = "$fun($name)";
}
}
}
}
return $name;
@@ -627,11 +627,14 @@ class Template {
$vars[2] = trim($vars[2]);
switch($vars[1]){
case 'SERVER':
$parseStr = '$_SERVER[\''.strtoupper($vars[2]).'\']';break;
$parseStr = '$_SERVER[\''.strtoupper($vars[2]).'\']';
break;
case 'GET':
$parseStr = '$_GET[\''.$vars[2].'\']';break;
$parseStr = '$_GET[\''.$vars[2].'\']';
break;
case 'POST':
$parseStr = '$_POST[\''.$vars[2].'\']';break;
$parseStr = '$_POST[\''.$vars[2].'\']';
break;
case 'COOKIE':
if(isset($vars[3])) {
$parseStr = '$_COOKIE[\''.$vars[2].'\'][\''.$vars[3].'\']';
@@ -647,19 +650,25 @@ class Template {
}
break;
case 'ENV':
$parseStr = '$_ENV[\''.strtoupper($vars[2]).'\']';break;
$parseStr = '$_ENV[\''.strtoupper($vars[2]).'\']';
break;
case 'REQUEST':
$parseStr = '$_REQUEST[\''.$vars[2].'\']';break;
$parseStr = '$_REQUEST[\''.$vars[2].'\']';
break;
case 'CONST':
$parseStr = strtoupper($vars[2]);break;
$parseStr = strtoupper($vars[2]);
break;
case 'LANG':
$parseStr = 'L("'.$vars[2].'")';break;
$parseStr = 'L("'.$vars[2].'")';
break;
case 'CONFIG':
if(isset($vars[3])) {
$vars[2] .= '.'.$vars[3];
}
$parseStr = 'C("'.$vars[2].'")';break;
default:break;
$parseStr = 'C("'.$vars[2].'")';
break;
default:
break;
}
}else if(count($vars)==2){
switch($vars[1]){
@@ -676,8 +685,9 @@ class Template {
$parseStr = $this->config['tpl_end'];
break;
default:
if(defined($vars[1]))
if(defined($vars[1])){
$parseStr = $vars[1];
}
}
}
return $parseStr;

View File

@@ -10,17 +10,20 @@
// +----------------------------------------------------------------------
namespace Think\Template\Driver;
use Think\Exception;
class File {
// 写入编译缓存
public function write($cacheFile,$content){
// 检测模板目录
$dir = dirname($cacheFile);
if(!is_dir($dir))
mkdir($dir,0755,true);
if(!is_dir($dir)){
mkdir($dir,0777,true);
}
// 生成模板缓存文件
if( false === file_put_contents($cacheFile,$content))
E('_CACHE_WRITE_ERROR_:'.$cacheFile);
if( false === file_put_contents($cacheFile,$content)){
throw new Exception('_CACHE_WRITE_ERROR_:'.$cacheFile);
}
}
// 读取编译编译

View File

@@ -10,24 +10,27 @@
// +----------------------------------------------------------------------
namespace Think;
use Think\Exception;
class View {
protected $engine = null; // 模板引擎实例
protected $theme = ''; // 模板主题名称
protected $data = []; // 模板变量
protected $config = [ // 视图参数
'http_output_content' => true,
'http_content_type' => 'text/html',
'http_charset' => 'utf-8',
'http_cache_control' => 'private',
'http_render_content' => false,
'theme_on' => false,
'auto_detect_theme' => false,
'var_theme' => 't',
'default_theme' => 'default',
'http_cache_id' => null,
'view_path' => '',
'view_suffix' => '.html',
'http_output_content' => true,
'http_content_type' => 'text/html',
'http_charset' => 'utf-8',
'http_cache_control' => 'private',
'http_render_content' => false,
'theme_on' => false,
'auto_detect_theme' => false,
'var_theme' => 't',
'default_theme' => 'default',
'http_cache_id' => null,
'view_path' => '',
'view_suffix' => '.html',
'view_depr' => '/',
'view_layer' => 'View',
];
/**
@@ -100,11 +103,11 @@ class View {
* @return mixed
*/
public function display($template = '', $vars = [], $cache_id = '') {
Tag::listen('view_begin', $template);
Hook::listen('view_begin', $template);
// 解析并获取模板内容
$content = $this->fetch($template, $vars, $cache_id);
// 输出内容过滤
Tag::listen('view_filter', $content);
Hook::listen('view_filter', $content);
// 输出模板内容
if($this->config['http_output_content']) {
$this->render($content);
@@ -123,10 +126,12 @@ class View {
*/
protected function fetch($template, $vars = [], $cache_id='') {
if(!$this->config['http_render_content']) {
// 获取模板文件名
$template = $this->parseTemplate($template);
// 模板不存在 抛出异常
if(!is_file($template))
E('template file not exists:' . $template);
if(!is_file($template)) {
throw new Exception('template file not exists:' . $template);
}
}
$vars = $vars ? $vars : $this->data;
// 页面缓存
@@ -152,17 +157,25 @@ class View {
if(is_file($template)) {
return $template;
}
$template = str_replace(':', '/', $template);
// 获取当前主题名称
$theme = $this->getTemplateTheme();
$depr = $this->config['view_depr'];
$template = str_replace(':', $depr, $template);
// 获取当前模块
$module = MODULE_NAME;
if(strpos($template,'@')){ // 跨模块调用模版文件
list($module,$template) = explode('@',$template);
}
// 获取当前主题的模版路径
defined('THEME_PATH') or define('THEME_PATH', $this->getThemePath($module));
// 分析模板文件规则
if('' == $template) {
// 如果模板文件名为空 按照默认规则定位
$template = CONTROLLER_NAME . '/' . ACTION_NAME;
}elseif(false === strpos($template, '/')){
$template = CONTROLLER_NAME . '/' . $template;
$template = CONTROLLER_NAME . $depr . ACTION_NAME;
}elseif(false === strpos($template, $depr)){
$template = CONTROLLER_NAME . $depr . $template;
}
return ($this->config['view_path'] ? $this->config['view_path'] : MODULE_PATH . 'View/').$theme.$template.$this->config['view_suffix'];
return THEME_PATH.$template.$this->config['view_suffix'];
}
/**
@@ -170,7 +183,7 @@ class View {
* @access private
* @return string
*/
private function getTemplateTheme() {
private function getTemplateTheme($module) {
if($this->config['theme_on']) {
if($this->theme) { // 指定模板主题
$theme = $this->theme;
@@ -182,7 +195,7 @@ class View {
}elseif(Cookie::get('think_theme')){
$theme = Cookie::get('think_theme');
}
if(!is_dir(MODULE_PATH . 'View/' . $theme)) {
if(!is_dir(APP_PATH.$module . '/'. $this->config['view_layer'].'/' . $theme)) {
$theme = $this->config['default_theme'];
}
Cookie::set('think_theme', $theme, 864000);
@@ -194,6 +207,24 @@ class View {
return '';
}
/**
* 获取当前的模板路径
* @access protected
* @param string $module 模块名
* @return string
*/
protected function getThemePath($module=MODULE_NAME){
// 获取当前主题名称
$theme = $this->getTemplateTheme($module);
// 获取当前主题的模版路径
$tmplPath = $this->config['view_path']; // 模块设置独立的视图目录
if(!$tmplPath){
// 定义TMPL_PATH 则改变全局的视图目录到模块之外
$tmplPath = defined('TMPL_PATH')? TMPL_PATH.$module.'/' : APP_PATH.$module.'/'.$this->config['view_layer'].'/';
}
return $tmplPath.$theme;
}
/**
* 视图输出参数设置
* @access public

39
Mode/Sae/convention.php Normal file
View File

@@ -0,0 +1,39 @@
<?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: luofei614 <weibo.com/luofei614>
// +----------------------------------------------------------------------
/**
* SAE模式惯例配置文件
* 该文件请不要修改,如果要覆盖惯例配置的值,可在应用配置文件中设定和惯例不符的配置项
* 配置名称大小写任意,系统会统一转换成小写
* 所有配置参数都可以在生效前动态改变
*/
defined('THINK_PATH') or exit();
$st = new SaeStorage();
return array(
//SAE下固定mysql配置
'DB_TYPE' => 'mysql', // 数据库类型
'DB_DEPLOY_TYPE' => 1,
'DB_RW_SEPARATE' => true,
'DB_HOST' => SAE_MYSQL_HOST_M.','.SAE_MYSQL_HOST_S, // 服务器地址
'DB_NAME' => SAE_MYSQL_DB, // 数据库名
'DB_USER' => SAE_MYSQL_USER, // 用户名
'DB_PWD' => SAE_MYSQL_PASS, // 密码
'DB_PORT' => SAE_MYSQL_PORT, // 端口
//更改模板替换变量,让普通能在所有平台下显示
'TMPL_PARSE_STRING' => array(
// __PUBLIC__/upload --> /Public/upload -->http://appname-public.stor.sinaapp.com/upload
'/Public/upload' => $st->getUrl('public','upload')
),
'LOG_TYPE' => 'Sae',
'DATA_CACHE_TYPE' => 'Memcachesae',
'CHECK_APP_DIR' => false,
'FILE_UPLOAD_TYPE' => 'Sae',
);

105
Mode/common.php Normal file
View File

@@ -0,0 +1,105 @@
<?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: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace Think;
/**
* ThinkPHP 普通模式定义
*/
// 加载框架底层语言包
Lang::set(include THINK_PATH.'Lang/'.strtolower(Config::get('default_lang')).EXT);
// 初始化操作可以在应用的公共文件中处理 下面只是示例
//---------------------------------------------------
// 日志初始化
Log::init(['type'=>'File','log_path'=> LOG_PATH]);
// 缓存初始化
Cache::connect(['type'=>'File','temp'=> CACHE_PATH]);
//------------------------------------------------------
// 启动session
if(!IS_CLI) {
Session::init(['prefix'=>'think','auto_start'=>true]);
}
if(is_file(APP_PATH.'build.php')) { // 自动化创建脚本
Create::build(include APP_PATH.'build.php');
}
return [
// 配置文件
'config' => [
'app_debug' => true, // 调试模式
'app_status' => 'debug',// 调试模式状态
'var_module' => 'm', // 模块变量名
'var_controller' => 'c', // 控制器变量名
'var_action' => 'a', // 操作变量名
'var_pathinfo' => 's', // PATHINFO变量名 用于兼容模式
'pathinfo_fetch' => 'ORIG_PATH_INFO,REDIRECT_PATH_INFO,REDIRECT_URL',
'pathinfo_depr' => '/', // pathinfo分隔符
'require_module' => true, // 是否显示模块
'default_module' => 'index', // 默认模块名
'require_controller' => true, // 是否显示控制器
'default_controller' => 'index', // 默认控制器名
'default_action' => 'index', // 默认操作名
'action_suffix' => '', // 操作方法后缀
'url_model' => 1, // URL模式
'base_url' => $_SERVER["SCRIPT_NAME"], // 基础URL路径
'url_html_suffix' => '.html',
'url_params_bind' => false, // url变量绑定
'exception_tmpl' => THINK_PATH.'Tpl/think_exception.tpl',// 异常页面的模板文件
'error_tmpl' => THINK_PATH.'Tpl/dispatch_jump.tpl', // 默认错误跳转对应的模板文件
'success_tmpl' => THINK_PATH.'Tpl/dispatch_jump.tpl', // 默认成功跳转对应的模板文件
'default_ajax_return' => 'JSON', // 默认AJAX 数据返回格式,可选JSON XML ...
'default_jsonp_handler' => 'jsonpReturn', // 默认JSONP格式返回的处理方法
'var_jsonp_handler' => 'callback',
'template_engine' => 'think',
/* 错误设置 */
'error_message' => '页面错误!请稍后再试~',//错误显示信息,非调试模式有效
'error_page' => '', // 错误定向页面
'show_error_msg' => false, // 显示错误信息
/* 数据库设置 */
'database' => [
'type' => 'mysql', // 数据库类型
'dsn' => '', //
'hostname' => 'localhost', // 服务器地址
'database' => '', // 数据库名
'username' => 'root', // 用户名
'password' => '', // 密码
'hostport' => '', // 端口
'params' => [], // 数据库连接参数
'charset' => 'utf8', // 数据库编码默认采用utf8
'prefix' => '', // 数据库表前缀
'debug' => false, // 数据库调试模式
'deploy' => 0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'rw_separate' => false, // 数据库读写是否分离 主从式有效
'master_num' => 1, // 读写分离后 主服务器数量
'slave_no' => '', // 指定从服务器序号
],
],
// 别名定义
'alias' => [
'Think\Log' => CORE_PATH . 'Log'.EXT,
'Think\Log\Driver\File' => CORE_PATH . 'Log/Driver/File'.EXT,
'Think\Exception' => CORE_PATH . 'Exception'.EXT,
'Think\Model' => CORE_PATH . 'Model'.EXT,
'Think\Db' => CORE_PATH . 'Db'.EXT,
'Think\Template' => CORE_PATH . 'Template'.EXT,
'Think\Cache' => CORE_PATH . 'Cache'.EXT,
'Think\Cache\Driver\File' => CORE_PATH . 'Cache/Driver/File'.EXT,
'Think\Storage' => CORE_PATH . 'Storage'.EXT,
],
'init' => [],
];

68
Mode/sae.php Normal file
View File

@@ -0,0 +1,68 @@
<?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: luofei614 <weibo.com/luofei614>
// +----------------------------------------------------------------------
/**
* ThinkPHP SAE应用模式定义文件
*/
return array(
// 配置文件
'config' => array(
THINK_PATH.'Conf/convention.php', // 系统惯例配置
CONF_PATH.'config'.CONF_EXT, // 应用公共配置
MODE_PATH.'Sae/convention.php',//[sae] sae的惯例配置
),
// 别名定义
'alias' => array(
'Think\Log' => CORE_PATH . 'Log'.EXT,
'Think\Log\Driver\File' => CORE_PATH . 'Log/Driver/File'.EXT,
'Think\Exception' => CORE_PATH . 'Exception'.EXT,
'Think\Model' => CORE_PATH . 'Model'.EXT,
'Think\Db' => CORE_PATH . 'Db'.EXT,
'Think\Template' => CORE_PATH . 'Template'.EXT,
'Think\Cache' => CORE_PATH . 'Cache'.EXT,
'Think\Cache\Driver\File' => CORE_PATH . 'Cache/Driver/File'.EXT,
'Think\Storage' => CORE_PATH . 'Storage'.EXT,
),
// 函数和类文件
'core' => array(
THINK_PATH.'Common/functions.php',
COMMON_PATH.'Common/function.php',
CORE_PATH . 'Hook'.EXT,
CORE_PATH . 'App'.EXT,
CORE_PATH . 'Dispatcher'.EXT,
//CORE_PATH . 'Log'.EXT,
CORE_PATH . 'Route'.EXT,
CORE_PATH . 'Controller'.EXT,
CORE_PATH . 'View'.EXT,
BEHAVIOR_PATH . 'ParseTemplateBehavior'.EXT,
BEHAVIOR_PATH . 'ContentReplaceBehavior'.EXT,
),
// 行为扩展定义
'tags' => array(
'app_begin' => array(
'Behavior\ReadHtmlCacheBehavior', // 读取静态缓存
),
'app_end' => array(
'Behavior\ShowPageTraceBehavior', // 页面Trace显示
),
'view_parse' => array(
'Behavior\ParseTemplateBehavior', // 模板解析 支持PHP、内置模板引擎和第三方模板引擎
),
'template_filter'=> array(
'Behavior\ContentReplaceBehavior', // 模板输出替换
),
'view_filter' => array(
'Behavior\WriteHtmlCacheBehavior', // 写入静态缓存
),
),
);

View File

@@ -190,8 +190,8 @@ trait Extend {
if(false !== ($value = F($guid))) { // 存在缓存写入数据
if(time()>S($guid.'_time')+$lazyTime) {
// 延时更新时间到了,删除缓存数据 并实际写入数据库
S($guid,NULL);
S($guid.'_time',NULL);
S($guid,null);
S($guid.'_time',null);
return $value+$step;
}else{
// 追加数据到缓存

View File

@@ -1,369 +0,0 @@
<?php
/**********************************************************\
| |
| The implementation of PHPRPC Protocol 3.0 |
| |
| bigint.php |
| |
| Release 3.0.1 |
| Copyright by Team-PHPRPC |
| |
| WebSite: http://www.phprpc.org/ |
| http://www.phprpc.net/ |
| http://www.phprpc.com/ |
| http://sourceforge.net/projects/php-rpc/ |
| |
| Authors: Ma Bingyao <andot@ujn.edu.cn> |
| |
| This file may be distributed and/or modified under the |
| terms of the GNU General Public License (GPL) version |
| 2.0 as published by the Free Software Foundation and |
| appearing in the included file LICENSE. |
| |
\**********************************************************/
/* Big integer expansion library.
*
* Copyright: Ma Bingyao <andot@ujn.edu.cn>
* mgccl <mgcclx@gmail.com>
* Version: 3.0.1
* LastModified: Apr 12, 2010
* This library is free. You can redistribute it and/or modify it under GPL.
*/
if (extension_loaded('gmp')) {
function bigint_dec2num($dec) {
return gmp_init($dec);
}
function bigint_num2dec($num) {
return gmp_strval($num);
}
function bigint_str2num($str) {
return gmp_init("0x".bin2hex($str));
}
function bigint_num2str($num) {
$str = gmp_strval($num, 16);
$len = strlen($str);
if ($len % 2 == 1) {
$str = '0'.$str;
}
return pack("H*", $str);
}
function bigint_random($n, $s) {
$result = gmp_init(0);
for ($i = 0; $i < $n; $i++) {
if (mt_rand(0, 1)) {
gmp_setbit($result, $i);
}
}
if ($s) {
gmp_setbit($result, $n - 1);
}
return $result;
}
function bigint_powmod($x, $y, $m) {
return gmp_powm($x, $y, $m);
}
}
else if (extension_loaded('big_int')) {
function bigint_dec2num($dec) {
return bi_from_str($dec);
}
function bigint_num2dec($num) {
return bi_to_str($num);
}
function bigint_str2num($str) {
return bi_from_str(bin2hex($str), 16);
}
function bigint_num2str($num) {
$str = bi_to_str($num, 16);
$len = strlen($str);
if ($len % 2 == 1) {
$str = '0'.$str;
}
return pack("H*", $str);
}
function bigint_random($n, $s) {
$result = bi_rand($n);
if ($s) {
$result = bi_set_bit($result, $n - 1);
}
return $result;
}
function bigint_powmod($x, $y, $m) {
return bi_powmod($x, $y, $m);
}
}
else if (extension_loaded('bcmath')) {
function bigint_dec2num($dec) {
return $dec;
}
function bigint_num2dec($num) {
return $num;
}
function bigint_str2num($str) {
bcscale(0);
$len = strlen($str);
$result = '0';
$m = '1';
for ($i = 0; $i < $len; $i++) {
$result = bcadd(bcmul($m, ord($str{$len - $i - 1})), $result);
$m = bcmul($m, '256');
}
return $result;
}
function bigint_num2str($num) {
bcscale(0);
$str = "";
while (bccomp($num, '0') == 1) {
$str = chr(bcmod($num, '256')) . $str;
$num = bcdiv($num, '256');
}
return $str;
}
// author of bcmath bigint_random: mgccl <mgcclx@gmail.com>
function bigint_pow($b, $e) {
if ($b == 2) {
$a[96] = '79228162514264337593543950336';
$a[128] = '340282366920938463463374607431768211456';
$a[160] = '1461501637330902918203684832716283019655932542976';
$a[192] = '6277101735386680763835789423207666416102355444464034512896';
$a[256] = '115792089237316195423570985008687907853269984665640564039457584007913129639936';
$a[512] = '13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096';
$a[768] = '1552518092300708935148979488462502555256886017116696611139052038026050952686376886330878408828646477950487730697131073206171580044114814391444287275041181139204454976020849905550265285631598444825262999193716468750892846853816057856';
$a[1024] = '179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216';
$a[1356] = '1572802244866018108182967249994981337399178505432223228293716677435703277129801955281491139254988030713172834803458459525011536776047399098682525970017006610187370020027540826048617586909475175880278263391147764612823746132583281588112028234096933800670620569966257212339315820309710495898777306979706509398705741430192541287726011814541176060679505247297118998085067003005943214893171428950699778511718055936';
$a[2048] = '32317006071311007300714876688669951960444102669715484032130345427524655138867890893197201411522913463688717960921898019494119559150490921095088152386448283120630877367300996091750197750389652106796057638384067568276792218642619756161838094338476170470581645852036305042887575891541065808607552399123930385521914333389668342420684974786564569494856176035326322058077805659331026192708460314150258592864177116725943603718461857357598351152301645904403697613233287231227125684710820209725157101726931323469678542580656697935045997268352998638215525166389437335543602135433229604645318478604952148193555853611059596230656';
$a[3072] = '5809605995369958062859502533304574370686975176362895236661486152287203730997110225737336044533118407251326157754980517443990529594540047121662885672187032401032111639706440498844049850989051627200244765807041812394729680540024104827976584369381522292361208779044769892743225751738076979568811309579125511333093243519553784816306381580161860200247492568448150242515304449577187604136428738580990172551573934146255830366405915000869643732053218566832545291107903722831634138599586406690325959725187447169059540805012310209639011750748760017095360734234945757416272994856013308616958529958304677637019181594088528345061285863898271763457294883546638879554311615446446330199254382340016292057090751175533888161918987295591531536698701292267685465517437915790823154844634780260102891718032495396075041899485513811126977307478969074857043710716150121315922024556759241239013152919710956468406379442914941614357107914462567329693696';
$a[4096] = '1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190336';
$a[8192] = '1090748135619415929462984244733782862448264161996232692431832786189721331849119295216264234525201987223957291796157025273109870820177184063610979765077554799078906298842192989538609825228048205159696851613591638196771886542609324560121290553901886301017900252535799917200010079600026535836800905297805880952350501630195475653911005312364560014847426035293551245843928918752768696279344088055617515694349945406677825140814900616105920256438504578013326493565836047242407382442812245131517757519164899226365743722432277368075027627883045206501792761700945699168497257879683851737049996900961120515655050115561271491492515342105748966629547032786321505730828430221664970324396138635251626409516168005427623435996308921691446181187406395310665404885739434832877428167407495370993511868756359970390117021823616749458620969857006263612082706715408157066575137281027022310927564910276759160520878304632411049364568754920967322982459184763427383790272448438018526977764941072715611580434690827459339991961414242741410599117426060556483763756314527611362658628383368621157993638020878537675545336789915694234433955666315070087213535470255670312004130725495834508357439653828936077080978550578912967907352780054935621561090795845172954115972927479877527738560008204118558930004777748727761853813510493840581861598652211605960308356405941821189714037868726219481498727603653616298856174822413033485438785324024751419417183012281078209729303537372804574372095228703622776363945290869806258422355148507571039619387449629866808188769662815778153079393179093143648340761738581819563002994422790754955061288818308430079648693232179158765918035565216157115402992120276155607873107937477466841528362987708699450152031231862594203085693838944657061346236704234026821102958954951197087076546186622796294536451620756509351018906023773821539532776208676978589731966330308893304665169436185078350641568336944530051437491311298834367265238595404904273455928723949525227184617404367854754610474377019768025576605881038077270707717942221977090385438585844095492116099852538903974655703943973086090930596963360767529964938414598185705963754561497355827813623833288906309004288017321424808663962671333528009232758350873059614118723781422101460198615747386855096896089189180441339558524822867541113212638793675567650340362970031930023397828465318547238244232028015189689660418822976000815437610652254270163595650875433851147123214227266605403581781469090806576468950587661997186505665475715792896';
return (isset($a[$e]) ? $a[$e] : bcpow(2, $e));
}
return bcpow($b, $e);
}
function bigint_random($n, $s) {
bcscale(0);
$t = bigint_pow(2, $n);
if ($s == 1) {
$m = bcdiv($t, 2);
$t = bcsub($m, 1);
}
else {
$m = 0;
$t = bcsub($t, 1);
}
$l = strlen($t);
$n = (int) ($l / 9) + 1;
$r = '';
while($n) {
$r .= substr('000000000' . mt_rand(0, 999999999), -9);
--$n;
}
$r = substr($r, 0, $l);
while (bccomp($r, $t) == 1) $r = substr($r, 1, $l) . mt_rand(0, 9);
return bcadd($r, $m);
}
if (!function_exists('bcpowmod')) {
function bcpowmod($x, $y, $modulus, $scale = 0) {
$t = '1';
while (bccomp($y, '0')) {
if (bccomp(bcmod($y, '2'), '0')) {
$t = bcmod(bcmul($t, $x), $modulus);
$y = bcsub($y, '1');
}
$x = bcmod(bcmul($x, $x), $modulus);
$y = bcdiv($y, '2');
}
return $t;
}
}
function bigint_powmod($x, $y, $m) {
return bcpowmod($x, $y, $m);
}
}
else {
function bigint_mul($a, $b) {
$n = count($a);
$m = count($b);
$nm = $n + $m;
$c = array_fill(0, $nm, 0);
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $m; $j++) {
$c[$i + $j] += $a[$i] * $b[$j];
$c[$i + $j + 1] += ($c[$i + $j] >> 15) & 0x7fff;
$c[$i + $j] &= 0x7fff;
}
}
return $c;
}
function bigint_div($a, $b, $is_mod = 0) {
$n = count($a);
$m = count($b);
$c = array();
$d = floor(0x8000 / ($b[$m - 1] + 1));
$a = bigint_mul($a, array($d));
$b = bigint_mul($b, array($d));
for ($j = $n - $m; $j >= 0; $j--) {
$tmp = $a[$j + $m] * 0x8000 + $a[$j + $m - 1];
$rr = $tmp % $b[$m - 1];
$qq = round(($tmp - $rr) / $b[$m - 1]);
if (($qq == 0x8000) || (($m > 1) && ($qq * $b[$m - 2] > 0x8000 * $rr + $a[$j + $m - 2]))) {
$qq--;
$rr += $b[$m - 1];
if (($rr < 0x8000) && ($qq * $b[$m - 2] > 0x8000 * $rr + $a[$j + $m - 2])) $qq--;
}
for ($i = 0; $i < $m; $i++) {
$tmp = $i + $j;
$a[$tmp] -= $b[$i] * $qq;
$a[$tmp + 1] += floor($a[$tmp] / 0x8000);
$a[$tmp] &= 0x7fff;
}
$c[$j] = $qq;
if ($a[$tmp + 1] < 0) {
$c[$j]--;
for ($i = 0; $i < $m; $i++) {
$tmp = $i + $j;
$a[$tmp] += $b[$i];
if ($a[$tmp] > 0x7fff) {
$a[$tmp + 1]++;
$a[$tmp] &= 0x7fff;
}
}
}
}
if (!$is_mod) return $c;
$b = array();
for ($i = 0; $i < $m; $i++) $b[$i] = $a[$i];
return bigint_div($b, array($d));
}
function bigint_zerofill($str, $num) {
return str_pad($str, $num, '0', STR_PAD_LEFT);
}
function bigint_dec2num($dec) {
$n = strlen($dec);
$a = array(0);
$n += 4 - ($n % 4);
$dec = bigint_zerofill($dec, $n);
$n >>= 2;
for ($i = 0; $i < $n; $i++) {
$a = bigint_mul($a, array(10000));
$a[0] += (int)substr($dec, 4 * $i, 4);
$m = count($a);
$j = 0;
$a[$m] = 0;
while ($j < $m && $a[$j] > 0x7fff) {
$a[$j++] &= 0x7fff;
$a[$j]++;
}
while ((count($a) > 1) && (!$a[count($a) - 1])) array_pop($a);
}
return $a;
}
function bigint_num2dec($num) {
$n = count($num) << 1;
$b = array();
for ($i = 0; $i < $n; $i++) {
$tmp = bigint_div($num, array(10000), 1);
$b[$i] = bigint_zerofill($tmp[0], 4);
$num = bigint_div($num, array(10000));
}
while ((count($b) > 1) && !(int)$b[count($b) - 1]) array_pop($b);
$n = count($b) - 1;
$b[$n] = (int)$b[$n];
$b = join('', array_reverse($b));
return $b;
}
function bigint_str2num($str) {
$n = strlen($str);
$n += 15 - ($n % 15);
$str = str_pad($str, $n, chr(0), STR_PAD_LEFT);
$j = 0;
$result = array();
for ($i = 0; $i < $n; $i++) {
$result[$j++] = (ord($str{$i++}) << 7) | (ord($str{$i}) >> 1);
$result[$j++] = ((ord($str{$i++}) & 0x01) << 14) | (ord($str{$i++}) << 6) | (ord($str{$i}) >> 2);
$result[$j++] = ((ord($str{$i++}) & 0x03) << 13) | (ord($str{$i++}) << 5) | (ord($str{$i}) >> 3);
$result[$j++] = ((ord($str{$i++}) & 0x07) << 12) | (ord($str{$i++}) << 4) | (ord($str{$i}) >> 4);
$result[$j++] = ((ord($str{$i++}) & 0x0f) << 11) | (ord($str{$i++}) << 3) | (ord($str{$i}) >> 5);
$result[$j++] = ((ord($str{$i++}) & 0x1f) << 10) | (ord($str{$i++}) << 2) | (ord($str{$i}) >> 6);
$result[$j++] = ((ord($str{$i++}) & 0x3f) << 9) | (ord($str{$i++}) << 1) | (ord($str{$i}) >> 7);
$result[$j++] = ((ord($str{$i++}) & 0x7f) << 8) | ord($str{$i});
}
$result = array_reverse($result);
$i = count($result) - 1;
while ($result[$i] == 0) {
array_pop($result);
$i--;
}
return $result;
}
function bigint_num2str($num) {
ksort($num, SORT_NUMERIC);
$n = count($num);
$n += 8 - ($n % 8);
$num = array_reverse(array_pad($num, $n, 0));
$s = '';
for ($i = 0; $i < $n; $i++) {
$s .= chr($num[$i] >> 7);
$s .= chr((($num[$i++] & 0x7f) << 1) | ($num[$i] >> 14));
$s .= chr(($num[$i] >> 6) & 0xff);
$s .= chr((($num[$i++] & 0x3f) << 2) | ($num[$i] >> 13));
$s .= chr(($num[$i] >> 5) & 0xff);
$s .= chr((($num[$i++] & 0x1f) << 3) | ($num[$i] >> 12));
$s .= chr(($num[$i] >> 4) & 0xff);
$s .= chr((($num[$i++] & 0x0f) << 4) | ($num[$i] >> 11));
$s .= chr(($num[$i] >> 3) & 0xff);
$s .= chr((($num[$i++] & 0x07) << 5) | ($num[$i] >> 10));
$s .= chr(($num[$i] >> 2) & 0xff);
$s .= chr((($num[$i++] & 0x03) << 6) | ($num[$i] >> 9));
$s .= chr(($num[$i] >> 1) & 0xff);
$s .= chr((($num[$i++] & 0x01) << 7) | ($num[$i] >> 8));
$s .= chr($num[$i] & 0xff);
}
return ltrim($s, chr(0));
}
function bigint_random($n, $s) {
$lowBitMasks = array(0x0000, 0x0001, 0x0003, 0x0007,
0x000f, 0x001f, 0x003f, 0x007f,
0x00ff, 0x01ff, 0x03ff, 0x07ff,
0x0fff, 0x1fff, 0x3fff);
$r = $n % 15;
$q = floor($n / 15);
$result = array();
for ($i = 0; $i < $q; $i++) {
$result[$i] = mt_rand(0, 0x7fff);
}
if ($r != 0) {
$result[$q] = mt_rand(0, $lowBitMasks[$r]);
if ($s) {
$result[$q] |= 1 << ($r - 1);
}
}
else if ($s) {
$result[$q - 1] |= 0x4000;
}
return $result;
}
function bigint_powmod($x, $y, $m) {
$n = count($y);
$p = array(1);
for ($i = 0; $i < $n - 1; $i++) {
$tmp = $y[$i];
for ($j = 0; $j < 0xf; $j++) {
if ($tmp & 1) $p = bigint_div(bigint_mul($p, $x), $m, 1);
$tmp >>= 1;
$x = bigint_div(bigint_mul($x, $x), $m, 1);
}
}
$tmp = $y[$i];
while ($tmp) {
if ($tmp & 1) $p = bigint_div(bigint_mul($p, $x), $m, 1);
$tmp >>= 1;
$x = bigint_div(bigint_mul($x, $x), $m, 1);
}
return $p;
}
}
?>

View File

@@ -1,241 +0,0 @@
<?php
/**********************************************************\
| |
| The implementation of PHPRPC Protocol 3.0 |
| |
| compat.php |
| |
| Release 3.0.1 |
| Copyright by Team-PHPRPC |
| |
| WebSite: http://www.phprpc.org/ |
| http://www.phprpc.net/ |
| http://www.phprpc.com/ |
| http://sourceforge.net/projects/php-rpc/ |
| |
| Authors: Ma Bingyao <andot@ujn.edu.cn> |
| |
| This file may be distributed and/or modified under the |
| terms of the GNU General Public License (GPL) version |
| 2.0 as published by the Free Software Foundation and |
| appearing in the included file LICENSE. |
| |
\**********************************************************/
/* Provides missing functionality for older versions of PHP.
*
* Copyright: Ma Bingyao <andot@ujn.edu.cn>
* Version: 1.5
* LastModified: Apr 12, 2010
* This library is free. You can redistribute it and/or modify it under GPL.
*/
require_once("phprpc_date.php");
if (!function_exists('file_get_contents')) {
function file_get_contents($filename, $incpath = false, $resource_context = null) {
if (false === $fh = fopen($filename, 'rb', $incpath)) {
user_error('file_get_contents() failed to open stream: No such file or directory',
E_USER_WARNING);
return false;
}
clearstatcache();
if ($fsize = @filesize($filename)) {
$data = fread($fh, $fsize);
}
else {
$data = '';
while (!feof($fh)) {
$data .= fread($fh, 8192);
}
}
fclose($fh);
return $data;
}
}
if (!function_exists('ob_get_clean')) {
function ob_get_clean() {
$contents = ob_get_contents();
if ($contents !== false) ob_end_clean();
return $contents;
}
}
/**
3 more bugs found and fixed:
1. failed to work when the gz contained a filename - FIXED
2. failed to work on 64-bit architecture (checksum) - FIXED
3. failed to work when the gz contained a comment - cannot verify.
Returns some errors (not all!) and filename.
*/
function gzdecode($data, &$filename = '', &$error = '', $maxlength = null) {
$len = strlen($data);
if ($len < 18 || strcmp(substr($data, 0, 2), "\x1f\x8b")) {
$error = "Not in GZIP format.";
return null; // Not GZIP format (See RFC 1952)
}
$method = ord(substr($data, 2, 1)); // Compression method
$flags = ord(substr($data, 3, 1)); // Flags
if ($flags & 31 != $flags) {
$error = "Reserved bits not allowed.";
return null;
}
// NOTE: $mtime may be negative (PHP integer limitations)
$mtime = unpack("V", substr($data, 4, 4));
$mtime = $mtime[1];
$xfl = substr($data, 8, 1);
$os = substr($data, 8, 1);
$headerlen = 10;
$extralen = 0;
$extra = "";
if ($flags & 4) {
// 2-byte length prefixed EXTRA data in header
if ($len - $headerlen - 2 < 8) {
return false; // invalid
}
$extralen = unpack("v", substr($data, 8, 2));
$extralen = $extralen[1];
if ($len - $headerlen - 2 - $extralen < 8) {
return false; // invalid
}
$extra = substr($data, 10, $extralen);
$headerlen += 2 + $extralen;
}
$filenamelen = 0;
$filename = "";
if ($flags & 8) {
// C-style string
if ($len - $headerlen - 1 < 8) {
return false; // invalid
}
$filenamelen = strpos(substr($data, $headerlen), chr(0));
if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {
return false; // invalid
}
$filename = substr($data, $headerlen, $filenamelen);
$headerlen += $filenamelen + 1;
}
$commentlen = 0;
$comment = "";
if ($flags & 16) {
// C-style string COMMENT data in header
if ($len - $headerlen - 1 < 8) {
return false; // invalid
}
$commentlen = strpos(substr($data, $headerlen), chr(0));
if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {
return false; // Invalid header format
}
$comment = substr($data, $headerlen, $commentlen);
$headerlen += $commentlen + 1;
}
$headercrc = "";
if ($flags & 2) {
// 2-bytes (lowest order) of CRC32 on header present
if ($len - $headerlen - 2 < 8) {
return false; // invalid
}
$calccrc = crc32(substr($data, 0, $headerlen)) & 0xffff;
$headercrc = unpack("v", substr($data, $headerlen, 2));
$headercrc = $headercrc[1];
if ($headercrc != $calccrc) {
$error = "Header checksum failed.";
return false; // Bad header CRC
}
$headerlen += 2;
}
// GZIP FOOTER
$datacrc = unpack("V", substr($data, -8, 4));
$datacrc = sprintf('%u', $datacrc[1] & 0xFFFFFFFF);
$isize = unpack("V", substr($data, -4));
$isize = $isize[1];
// decompression:
$bodylen = $len - $headerlen - 8;
if ($bodylen < 1) {
// IMPLEMENTATION BUG!
return null;
}
$body = substr($data, $headerlen, $bodylen);
$data = "";
if ($bodylen > 0) {
switch ($method) {
case 8:
// Currently the only supported compression method:
$data = gzinflate($body, $maxlength);
break;
default:
$error = "Unknown compression method.";
return false;
}
} // zero-byte body content is allowed
// Verifiy CRC32
$crc = sprintf("%u", crc32($data));
$crcOK = $crc == $datacrc;
$lenOK = $isize == strlen($data);
if (!$lenOK || !$crcOK) {
$error = ( $lenOK ? '' : 'Length check FAILED. ') . ( $crcOK ? '' : 'Checksum FAILED.');
return false;
}
return $data;
}
if (version_compare(phpversion(), "5", "<")) {
function serialize_fix($v) {
return str_replace('O:11:"phprpc_date":7:{', 'O:11:"PHPRPC_Date":7:{', serialize($v));
}
}
else {
function serialize_fix($v) {
return serialize($v);
}
}
function declare_empty_class($classname) {
static $callback = null;
$classname = preg_replace('/[^a-zA-Z0-9\_]/', '', $classname);
if ($callback===null) {
$callback = $classname;
return;
}
if ($callback) {
call_user_func($callback, $classname);
}
if (!class_exists($classname)) {
if (version_compare(phpversion(), "5", "<")) {
eval('class ' . $classname . ' { }');
}
else {
eval('
class ' . $classname . ' {
private function __get($name) {
$vars = (array)$this;
$protected_name = "\0*\0$name";
$private_name = "\0'.$classname.'\0$name";
if (array_key_exists($name, $vars)) {
return $this->$name;
}
else if (array_key_exists($protected_name, $vars)) {
return $vars[$protected_name];
}
else if (array_key_exists($private_name, $vars)) {
return $vars[$private_name];
}
else {
$keys = array_keys($vars);
$keys = array_values(preg_grep("/^\\\\x00.*?\\\\x00".$name."$/", $keys));
if (isset($keys[0])) {
return $vars[$keys[0]];
}
else {
return NULL;
}
}
}
}');
}
}
}
declare_empty_class(ini_get('unserialize_callback_func'));
ini_set('unserialize_callback_func', 'declare_empty_class');
?>

View File

@@ -1,77 +0,0 @@
<?php
/**********************************************************\
| |
| The implementation of PHPRPC Protocol 3.0 |
| |
| dhparams.php |
| |
| Release 3.0.1 |
| Copyright by Team-PHPRPC |
| |
| WebSite: http://www.phprpc.org/ |
| http://www.phprpc.net/ |
| http://www.phprpc.com/ |
| http://sourceforge.net/projects/php-rpc/ |
| |
| Authors: Ma Bingyao <andot@ujn.edu.cn> |
| |
| This file may be distributed and/or modified under the |
| terms of the GNU General Public License (GPL) version |
| 2.0 as published by the Free Software Foundation and |
| appearing in the included file LICENSE. |
| |
\**********************************************************/
/* Diffie-Hellman Parameters for PHPRPC.
*
* Copyright: Ma Bingyao <andot@ujn.edu.cn>
* Version: 1.2
* LastModified: Apr 12, 2010
* This library is free. You can redistribute it and/or modify it under GPL.
*/
class DHParams {
var $len;
var $dhParams;
function getNearest($n, $a) {
$j = 0;
$m = abs($a[0] - $n);
for ($i = 1; $i < count($a); $i++) {
$t = abs($a[$i] - $n);
if ($m > $t) {
$m = $t;
$j = $i;
}
}
return $a[$j];
}
function DHParams($len = 128) {
if (extension_loaded('gmp')) {
$a = array(96, 128, 160, 192, 256, 512, 768, 1024, 1536, 2048, 3072, 4096);
}
else if (extension_loaded('big_int')) {
$a = array(96, 128, 160, 192, 256, 512, 768, 1024, 1536);
}
else if (extension_loaded('bcmath')) {
$a = array(96, 128, 160, 192, 256, 512);
}
else {
$a = array(96, 128, 160);
}
$this->len = $this->getNearest($len, $a);
$dhParams = unserialize(file_get_contents("dhparams/{$this->len}.dhp", true));
$this->dhParams = $dhParams[mt_rand(0, count($dhParams) - 1)];
}
function getL() {
return $this->len;
}
function getP() {
return $this->dhParams['p'];
}
function getG() {
return $this->dhParams['g'];
}
function getDHParams() {
return $this->dhParams;
}
}
?>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,2 +0,0 @@
XXTEA PHP extension
Ma Bingyao (andot@coolcode.cn)

View File

@@ -1,66 +0,0 @@
Installing of XXTEA PHP package.
There are many ways to build the package. Below you can find details for most
useful ways of package building:
1. with PHP
2. with phpize utility
3. under Windows using Microsoft Visual C (.NET or VC6)
-----------------------------------------------------------------------------
Way 1: Building the package with PHP
-----------------------------------------------------------------------------
1. Create ext/xxtea folder in the php-source-folder. Copy all files
from the package into created folder.
2. Run
./buildconf
to rebuild PHP's configure script.
3. Compile php with option:
--enable-xxtea to build bundled into PHP module
--enable-xxtea=shared to build dinamycally loadable module
-----------------------------------------------------------------------------
Way 2: Building the package with phpize utility
-----------------------------------------------------------------------------
1. Unpack contents of the package.
2. Run
phpize
script, which will prepare environment for building XXTEA package.
3. Run
./configure --enable-xxtea=shared
to generate makefile
4. Run
make
to build XXTEA extension library. It will be placed into
./modules folder.
5. Run
make install
to install XXTEA extension library into PHP
-----------------------------------------------------------------------------
Way 3: Building the package under Windows using Microsoft Visual C (.NET or VC6)
-----------------------------------------------------------------------------
1. Create ext/xxtea folder in the php-source-folder. Copy all files
from the package into created folder.
2. Copy php4ts.lib (for PHP4) or php5ts.lib (for PHP5) static library from
your version of PHP into ext/xxtea folder.
3. Open php_xxtea.sln - solution file under MSVC.NET or php_xxtea.dsw -
workspace file under MSVC6. Try to build Release_php4 (for PHP4) or Release_php5
(for PHP5) configuration.
4. Copy php_xxtea.dll from ext/xxtea/Release_php4 or ext/xxtea/Release_php5
into {extension_dir} folder. Path to {extension_dir} can be found in php.ini
5. Add line
extension=php_xxtea.dll
into php.ini

View File

@@ -1,68 +0,0 @@
--------------------------------------------------------------------
The PHP License, version 3.01
Copyright (c) 1999 - 2006 The PHP Group. All rights reserved.
--------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, is permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The name "PHP" must not be used to endorse or promote products
derived from this software without prior written permission. For
written permission, please contact group@php.net.
4. Products derived from this software may not be called "PHP", nor
may "PHP" appear in their name, without prior written permission
from group@php.net. You may indicate that your software works in
conjunction with PHP by saying "Foo for PHP" instead of calling
it "PHP Foo" or "phpfoo"
5. The PHP Group may publish revised and/or new versions of the
license from time to time. Each version will be given a
distinguishing version number.
Once covered code has been published under a particular version
of the license, you may always continue to use it under the terms
of that version. You may also choose to use such covered code
under the terms of any subsequent version of the license
published by the PHP Group. No one other than the PHP Group has
the right to modify the terms applicable to covered code created
under this License.
6. Redistributions of any form whatsoever must retain the following
acknowledgment:
"This product includes PHP software, freely available from
<http://www.php.net/software/>".
THIS SOFTWARE IS PROVIDED BY THE PHP DEVELOPMENT TEAM ``AS IS'' AND
ANY EXPRESSED 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 PHP
DEVELOPMENT TEAM OR ITS 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.
--------------------------------------------------------------------
This software consists of voluntary contributions made by many
individuals on behalf of the PHP Group.
The PHP Group can be contacted via Email at group@php.net.
For more information on the PHP Group and the PHP project,
please see <http://www.php.net>.
PHP includes the Zend Engine, freely available at
<http://www.zend.com>.

View File

@@ -1,28 +0,0 @@
XXTEA PHP extension
What is it?
-----------------------------------------------
This extension based on xxtea library, which provides a set of functions
for encrypt or decrypt data with XXTEA algorithm.
How to install it?
-----------------------------------------------
See INSTALL for installation instructions.
How to use it?
-----------------------------------------------
string xxtea_encrypt(string data, string key)
Encrypt data using XXTEA algorithm. The key is a 16 bytes(128 bits) string.
string xxtea_decrypt(string data, string key)
Decrypt data using XXTEA algorithm. The key is a 16 bytes(128 bits) string.
string xxtea_info()
Get the version information.

View File

@@ -1,7 +0,0 @@
PHP_ARG_ENABLE(xxtea, xxtea module,
[ --enable-xxtea Enable xxtea module.])
if test "$PHP_XXTEA" != "no"; then
PHP_NEW_EXTENSION(xxtea, php_xxtea.c xxtea.c, $ext_shared)
AC_DEFINE(HAVE_XXTEA, 1, [Have XXTEA library])
fi

View File

@@ -1,6 +0,0 @@
ARG_ENABLE("xxtea", "xxtea module", "no");
if (PHP_XXTEA != "no") {
EXTENSION("xxtea", "php_xxtea.c xxtea.c");
}

View File

@@ -1,193 +0,0 @@
/***********************************************************************
Copyright 2006-2007 Ma Bingyao
These sources is free software. Redistributions of source code must
retain the above copyright notice. Redistributions in binary form
must reproduce the above copyright notice. You can redistribute it
freely. You can use it with any free or commercial software.
These sources is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY. Without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
You may contact the author by:
e-mail: andot@coolcode.cn
*************************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if HAVE_XXTEA
#include "php_xxtea.h"
#include "ext/standard/info.h" /* for phpinfo() functions */
#include "xxtea.h"
/* compiled function list so Zend knows what's in this module */
zend_function_entry xxtea_functions[] =
{
ZEND_FE(xxtea_encrypt, NULL)
ZEND_FE(xxtea_decrypt, NULL)
ZEND_FE(xxtea_info, NULL)
{NULL, NULL, NULL}
};
/* compiled module information */
zend_module_entry xxtea_module_entry =
{
STANDARD_MODULE_HEADER,
XXTEA_MODULE_NAME,
xxtea_functions,
ZEND_MINIT(xxtea),
ZEND_MSHUTDOWN(xxtea),
NULL,
NULL,
ZEND_MINFO(xxtea),
XXTEA_VERSION,
STANDARD_MODULE_PROPERTIES
};
/* implement standard "stub" routine to introduce ourselves to Zend */
#if defined(COMPILE_DL_XXTEA)
ZEND_GET_MODULE(xxtea)
#endif
static xxtea_long *xxtea_to_long_array(unsigned char *data, xxtea_long len, int include_length, xxtea_long *ret_len) {
xxtea_long i, n, *result;
n = len >> 2;
n = (((len & 3) == 0) ? n : n + 1);
if (include_length) {
result = (xxtea_long *)emalloc((n + 1) << 2);
result[n] = len;
*ret_len = n + 1;
} else {
result = (xxtea_long *)emalloc(n << 2);
*ret_len = n;
}
memset(result, 0, n << 2);
for (i = 0; i < len; i++) {
result[i >> 2] |= (xxtea_long)data[i] << ((i & 3) << 3);
}
return result;
}
static unsigned char *xxtea_to_byte_array(xxtea_long *data, xxtea_long len, int include_length, xxtea_long *ret_len) {
xxtea_long i, n, m;
unsigned char *result;
n = len << 2;
if (include_length) {
m = data[len - 1];
if ((m < n - 7) || (m > n - 4)) return NULL;
n = m;
}
result = (unsigned char *)emalloc(n + 1);
for (i = 0; i < n; i++) {
result[i] = (unsigned char)((data[i >> 2] >> ((i & 3) << 3)) & 0xff);
}
result[n] = '\0';
*ret_len = n;
return result;
}
static unsigned char *php_xxtea_encrypt(unsigned char *data, xxtea_long len, unsigned char *key, xxtea_long *ret_len) {
unsigned char *result;
xxtea_long *v, *k, v_len, k_len;
v = xxtea_to_long_array(data, len, 1, &v_len);
k = xxtea_to_long_array(key, 16, 0, &k_len);
xxtea_long_encrypt(v, v_len, k);
result = xxtea_to_byte_array(v, v_len, 0, ret_len);
efree(v);
efree(k);
return result;
}
static unsigned char *php_xxtea_decrypt(unsigned char *data, xxtea_long len, unsigned char *key, xxtea_long *ret_len) {
unsigned char *result;
xxtea_long *v, *k, v_len, k_len;
v = xxtea_to_long_array(data, len, 0, &v_len);
k = xxtea_to_long_array(key, 16, 0, &k_len);
xxtea_long_decrypt(v, v_len, k);
result = xxtea_to_byte_array(v, v_len, 1, ret_len);
efree(v);
efree(k);
return result;
}
/* {{{ proto string xxtea_encrypt(string data, string key)
Encrypt string using XXTEA algorithm */
ZEND_FUNCTION(xxtea_encrypt)
{
unsigned char *data, *key;
unsigned char *result;
xxtea_long data_len, key_len, ret_length;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &data, &data_len, &key, &key_len) == FAILURE) {
return;
}
if (data_len == 0) RETVAL_STRINGL(NULL, 0, 0);
if (key_len != 16) RETURN_FALSE;
result = php_xxtea_encrypt(data, data_len, key, &ret_length);
if (result != NULL) {
RETVAL_STRINGL((char *)result, ret_length, 0);
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto string xxtea_decrypt(string data, string key)
Decrypt string using XXTEA algorithm */
ZEND_FUNCTION(xxtea_decrypt)
{
unsigned char *data, *key;
unsigned char *result;
xxtea_long data_len, key_len, ret_length;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &data, &data_len, &key, &key_len) == FAILURE) {
return;
}
if (data_len == 0) RETVAL_STRINGL(NULL, 0, 0);
if (key_len != 16) RETURN_FALSE;
result = php_xxtea_decrypt(data, data_len, key, &ret_length);
if (result != NULL) {
RETVAL_STRINGL((char *)result, ret_length, 0);
} else {
RETURN_FALSE;
}
}
/* }}} */
ZEND_MINIT_FUNCTION(xxtea)
{
return SUCCESS;
}
ZEND_MSHUTDOWN_FUNCTION(xxtea)
{
return SUCCESS;
}
ZEND_MINFO_FUNCTION(xxtea)
{
php_info_print_table_start();
php_info_print_table_row(2, "xxtea support", "enabled");
php_info_print_table_row(2, "xxtea module version", XXTEA_VERSION);
php_info_print_table_row(2, "xxtea author", XXTEA_AUTHOR);
php_info_print_table_row(2, "xxtea homepage", XXTEA_HOMEPAGE);
php_info_print_table_end();
}
ZEND_FUNCTION(xxtea_info)
{
array_init(return_value);
add_assoc_string(return_value, "ext_version", XXTEA_VERSION, 1);
add_assoc_string(return_value, "ext_build_date", XXTEA_BUILD_DATE, 1);
add_assoc_string(return_value, "ext_author", XXTEA_AUTHOR, 1);
add_assoc_string(return_value, "ext_homepage", XXTEA_HOMEPAGE, 1);
}
#endif /* if HAVE_XXTEA */

View File

@@ -1,179 +0,0 @@
# Microsoft Developer Studio Project File - Name="php_xxtea" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
CFG=php_xxtea - Win32 Debug_php5
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "php_xxtea.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "php_xxtea.mak" CFG="php_xxtea - Win32 Debug_php5"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "php_xxtea - Win32 Debug_php5" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE "php_xxtea - Win32 Release_php5" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE "php_xxtea - Win32 Debug_php4" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE "php_xxtea - Win32 Release_php4" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
MTL=midl.exe
RSC=rc.exe
!IF "$(CFG)" == "php_xxtea - Win32 Debug_php5"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug_php5"
# PROP BASE Intermediate_Dir "Debug_php5"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug_php5"
# PROP Intermediate_Dir "Debug_php5"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MTd /I "../.." /I "../../main" /I "../../Zend" /I "../../TSRM" /ZI /W3 /Od /D "HAVE_XXTEA" /D "COMPILE_DL_XXTEA" /D "ZTS" /D "NDEBUG" /D "ZEND_WIN32" /D "PHP_WIN32" /D "WIN32" /D "ZEND_DEBUG=1" /D "_MBCS" /Gm /GZ /c /GX
# ADD CPP /nologo /MTd /I "../.." /I "../../main" /I "../../Zend" /I "../../TSRM" /ZI /W3 /Od /D "HAVE_XXTEA" /D "COMPILE_DL_XXTEA" /D "ZTS" /D "NDEBUG" /D "ZEND_WIN32" /D "PHP_WIN32" /D "WIN32" /D "ZEND_DEBUG=1" /D "_MBCS" /Gm /GZ /c /GX
# ADD BASE MTL /nologo /win32
# ADD MTL /nologo /win32
# ADD BASE RSC /l 1033
# ADD RSC /l 1033
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib php5ts.lib /nologo /dll /out:"Debug_php5\php_xxtea.dll" /incremental:yes /libpath:"../../Release_TS" /debug /pdb:"Debug_php5\php_xxtea.pdb" /pdbtype:sept /subsystem:windows /implib:"$(OutDir)/php_xxtea.lib" /machine:ix86
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib php5ts.lib /nologo /dll /out:"Debug_php5\php_xxtea.dll" /incremental:yes /libpath:"../../Release_TS" /debug /pdb:"Debug_php5\php_xxtea.pdb" /pdbtype:sept /subsystem:windows /implib:"$(OutDir)/php_xxtea.lib" /machine:ix86
!ELSEIF "$(CFG)" == "php_xxtea - Win32 Release_php5"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release_php5"
# PROP BASE Intermediate_Dir "Release_php5"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release_php5"
# PROP Intermediate_Dir "Release_php5"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MD /I "../.." /I "../../main" /I "../../Zend" /I "../../TSRM" /W3 /O1 /Og /Oi /Os /Oy /GT /G6 /GA /D "HAVE_XXTEA" /D "COMPILE_DL_XXTEA" /D "ZTS" /D "NDEBUG" /D "ZEND_WIN32" /D "PHP_WIN32" /D "WIN32" /D "ZEND_DEBUG=0" /D "_MBCS" /GF /Gy /TC /c /GX
# ADD CPP /nologo /MD /I "../.." /I "../../main" /I "../../Zend" /I "../../TSRM" /W3 /O1 /Og /Oi /Os /Oy /GT /G6 /GA /D "HAVE_XXTEA" /D "COMPILE_DL_XXTEA" /D "ZTS" /D "NDEBUG" /D "ZEND_WIN32" /D "PHP_WIN32" /D "WIN32" /D "ZEND_DEBUG=0" /D "_MBCS" /GF /Gy /TC /c /GX
# ADD BASE MTL /nologo /win32
# ADD MTL /nologo /win32
# ADD BASE RSC /l 1033
# ADD RSC /l 1033
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib php5ts.lib /nologo /dll /out:"Release_php5\php_xxtea.dll" /incremental:no /libpath:"../../Release_TS" /pdbtype:sept /subsystem:windows /opt:ref /opt:icf /implib:"$(OutDir)/php_xxtea.lib" /machine:ix86
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib php5ts.lib /nologo /dll /out:"Release_php5\php_xxtea.dll" /incremental:no /libpath:"../../Release_TS" /pdbtype:sept /subsystem:windows /opt:ref /opt:icf /implib:"$(OutDir)/php_xxtea.lib" /machine:ix86
!ELSEIF "$(CFG)" == "php_xxtea - Win32 Debug_php4"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug_php4"
# PROP BASE Intermediate_Dir "Debug_php4"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug_php4"
# PROP Intermediate_Dir "Debug_php4"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MTd /I "../.." /I "../../main" /I "../../Zend" /I "../../TSRM" /ZI /W3 /Od /D "HAVE_XXTEA" /D "COMPILE_DL_XXTEA" /D "ZTS" /D "NDEBUG" /D "ZEND_WIN32" /D "PHP_WIN32" /D "WIN32" /D "ZEND_DEBUG=1" /D "_MBCS" /Gm /GZ /c /GX
# ADD CPP /nologo /MTd /I "../.." /I "../../main" /I "../../Zend" /I "../../TSRM" /ZI /W3 /Od /D "HAVE_XXTEA" /D "COMPILE_DL_XXTEA" /D "ZTS" /D "NDEBUG" /D "ZEND_WIN32" /D "PHP_WIN32" /D "WIN32" /D "ZEND_DEBUG=1" /D "_MBCS" /Gm /GZ /c /GX
# ADD BASE MTL /nologo /win32
# ADD MTL /nologo /win32
# ADD BASE RSC /l 1033
# ADD RSC /l 1033
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib php4ts.lib /nologo /dll /out:"Debug_php4\php_xxtea.dll" /incremental:yes /libpath:"../../Release_TS" /debug /pdb:"Debug_php4\php_xxtea.pdb" /pdbtype:sept /subsystem:windows /implib:"$(OutDir)/php_xxtea.lib" /machine:ix86
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib php4ts.lib /nologo /dll /out:"Debug_php4\php_xxtea.dll" /incremental:yes /libpath:"../../Release_TS" /debug /pdb:"Debug_php4\php_xxtea.pdb" /pdbtype:sept /subsystem:windows /implib:"$(OutDir)/php_xxtea.lib" /machine:ix86
!ELSEIF "$(CFG)" == "php_xxtea - Win32 Release_php4"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release_php4"
# PROP BASE Intermediate_Dir "Release_php4"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release_php4"
# PROP Intermediate_Dir "Release_php4"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MD /I "../.." /I "../../main" /I "../../Zend" /I "../../TSRM" /W3 /O1 /Og /Oi /Os /Oy /GT /G6 /GA /D "HAVE_XXTEA" /D "COMPILE_DL_XXTEA" /D "ZTS" /D "NDEBUG" /D "ZEND_WIN32" /D "PHP_WIN32" /D "WIN32" /D "ZEND_DEBUG=0" /D "_MBCS" /GF /Gy /TC /c /GX
# ADD CPP /nologo /MD /I "../.." /I "../../main" /I "../../Zend" /I "../../TSRM" /W3 /O1 /Og /Oi /Os /Oy /GT /G6 /GA /D "HAVE_XXTEA" /D "COMPILE_DL_XXTEA" /D "ZTS" /D "NDEBUG" /D "ZEND_WIN32" /D "PHP_WIN32" /D "WIN32" /D "ZEND_DEBUG=0" /D "_MBCS" /GF /Gy /TC /c /GX
# ADD BASE MTL /nologo /win32
# ADD MTL /nologo /win32
# ADD BASE RSC /l 1033
# ADD RSC /l 1033
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib php4ts.lib /nologo /dll /out:"Release_php4\php_xxtea.dll" /incremental:no /libpath:"../../Release_TS" /pdbtype:sept /subsystem:windows /opt:ref /opt:icf /implib:"$(OutDir)/php_xxtea.lib" /machine:ix86
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib php4ts.lib /nologo /dll /out:"Release_php4\php_xxtea.dll" /incremental:no /libpath:"../../Release_TS" /pdbtype:sept /subsystem:windows /opt:ref /opt:icf /implib:"$(OutDir)/php_xxtea.lib" /machine:ix86
!ENDIF
# Begin Target
# Name "php_xxtea - Win32 Debug_php5"
# Name "php_xxtea - Win32 Release_php5"
# Name "php_xxtea - Win32 Debug_php4"
# Name "php_xxtea - Win32 Release_php4"
# Begin Group "Source Files"
# PROP Default_Filter "cpp;c;cxx;def;odl;idl;hpj;bat;asm"
# Begin Source File
SOURCE=php_xxtea.c
# End Source File
# Begin Group "lib_xxtea"
# PROP Default_Filter ""
# Begin Source File
SOURCE=xxtea.c
# End Source File
# End Group
# End Group
# Begin Group "Header Files"
# PROP Default_Filter "h;hpp;hxx;hm;inl;inc"
# Begin Source File
SOURCE=php_xxtea.h
# End Source File
# Begin Group "lib_xxtea"
# PROP Default_Filter ""
# Begin Source File
SOURCE=xxtea.h
# End Source File
# End Group
# End Group
# Begin Group "Resource Files"
# PROP Default_Filter "rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
# End Group
# End Target
# End Project

View File

@@ -1,49 +0,0 @@
/***********************************************************************
Copyright 2006-2007 Ma Bingyao
These sources is free software. Redistributions of source code must
retain the above copyright notice. Redistributions in binary form
must reproduce the above copyright notice. You can redistribute it
freely. You can use it with any free or commercial software.
These sources is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY. Without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
You may contact the author by:
e-mail: andot@coolcode.cn
*************************************************************************/
#ifndef PHP_XXTEA_H
#define PHP_XXTEA_H
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if HAVE_XXTEA
extern zend_module_entry xxtea_module_entry;
#define phpext_xxtea_ptr &xxtea_module_entry
#define XXTEA_MODULE_NAME "xxtea"
#define XXTEA_BUILD_DATE __DATE__ " " __TIME__
#define XXTEA_VERSION "1.0.3"
#define XXTEA_AUTHOR "Ma Bingyao"
#define XXTEA_HOMEPAGE "http://www.coolcode.cn/?p=209"
ZEND_MINIT_FUNCTION(xxtea);
ZEND_MSHUTDOWN_FUNCTION(xxtea);
ZEND_MINFO_FUNCTION(xxtea);
/* declaration of functions to be exported */
ZEND_FUNCTION(xxtea_encrypt);
ZEND_FUNCTION(xxtea_decrypt);
ZEND_FUNCTION(xxtea_info);
#else /* if HAVE_XXTEA */
#define phpext_xxtea_ptr NULL
#endif
#endif /* ifndef PHP_XXTEA_H */

View File

@@ -1,25 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "php_xxtea", "php_xxtea.vcproj", "{71165FA5-1EBC-4021-AA17-0CCBC7CD5204}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug_php4|Win32 = Debug_php4|Win32
Debug_php5|Win32 = Debug_php5|Win32
Release_php4|Win32 = Release_php4|Win32
Release_php5|Win32 = Release_php5|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{71165FA5-1EBC-4021-AA17-0CCBC7CD5204}.Debug_php4|Win32.ActiveCfg = Debug_php4|Win32
{71165FA5-1EBC-4021-AA17-0CCBC7CD5204}.Debug_php4|Win32.Build.0 = Debug_php4|Win32
{71165FA5-1EBC-4021-AA17-0CCBC7CD5204}.Debug_php5|Win32.ActiveCfg = Debug_php5|Win32
{71165FA5-1EBC-4021-AA17-0CCBC7CD5204}.Debug_php5|Win32.Build.0 = Debug_php5|Win32
{71165FA5-1EBC-4021-AA17-0CCBC7CD5204}.Release_php4|Win32.ActiveCfg = Release_php4|Win32
{71165FA5-1EBC-4021-AA17-0CCBC7CD5204}.Release_php4|Win32.Build.0 = Release_php4|Win32
{71165FA5-1EBC-4021-AA17-0CCBC7CD5204}.Release_php5|Win32.ActiveCfg = Release_php5|Win32
{71165FA5-1EBC-4021-AA17-0CCBC7CD5204}.Release_php5|Win32.Build.0 = Release_php5|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -1,520 +0,0 @@
<?xml version="1.0" encoding="gb2312"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="8.00"
Name="php_xxtea"
ProjectGUID="{71165FA5-1EBC-4021-AA17-0CCBC7CD5204}"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug_php5|Win32"
OutputDirectory=".\Debug_php5"
IntermediateDirectory=".\Debug_php5"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\Debug_php5/php_xxtea.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="../..,../../main,../../Zend,../../TSRM"
PreprocessorDefinitions="HAVE_XXTEA;COMPILE_DL_XXTEA;ZTS;NDEBUG;ZEND_WIN32;PHP_WIN32;WIN32;ZEND_DEBUG=1"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
PrecompiledHeaderFile=".\Debug_php5/php_xxtea.pch"
AssemblerListingLocation=".\Debug_php5/"
ObjectFile=".\Debug_php5/"
ProgramDataBaseFileName=".\Debug_php5/"
WarningLevel="3"
SuppressStartupBanner="true"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1033"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="odbc32.lib odbccp32.lib php5ts.lib"
OutputFile="Debug_php5\php_xxtea.dll"
LinkIncremental="2"
SuppressStartupBanner="true"
AdditionalLibraryDirectories="../../Release_TS"
GenerateDebugInformation="true"
ProgramDatabaseFile="Debug_php5\php_xxtea.pdb"
SubSystem="2"
ImportLibrary="$(OutDir)/php_xxtea.lib"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
SuppressStartupBanner="true"
OutputFile=".\Debug_php5/php_xxtea.bsc"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release_php4|Win32"
OutputDirectory=".\Release_php4"
IntermediateDirectory=".\Release_php4"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\Release_php4/php_xxtea.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
AdditionalOptions="/GT /GA "
Optimization="4"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="2"
OmitFramePointers="true"
AdditionalIncludeDirectories="../..,../../main,../../Zend,../../TSRM"
PreprocessorDefinitions="HAVE_XXTEA;COMPILE_DL_XXTEA;ZTS;NDEBUG;ZEND_WIN32;PHP_WIN32;WIN32;ZEND_DEBUG=0"
StringPooling="true"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
PrecompiledHeaderFile=".\Release_php4/php_xxtea.pch"
AssemblerListingLocation=".\Release_php4/"
ObjectFile=".\Release_php4/"
ProgramDataBaseFileName=".\Release_php4/"
WarningLevel="3"
SuppressStartupBanner="true"
CompileAs="1"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1033"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="odbc32.lib odbccp32.lib php4ts.lib"
OutputFile="Release_php4\php_xxtea.dll"
LinkIncremental="1"
SuppressStartupBanner="true"
AdditionalLibraryDirectories="../../Release_TS"
ProgramDatabaseFile=".\Release_php4/php_xxtea.pdb"
SubSystem="2"
OptimizeReferences="2"
EnableCOMDATFolding="2"
ImportLibrary="$(OutDir)/php_xxtea.lib"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
SuppressStartupBanner="true"
OutputFile=".\Release_php4/php_xxtea.bsc"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release_php5|Win32"
OutputDirectory=".\Release_php5"
IntermediateDirectory=".\Release_php5"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\Release_php5/php_xxtea.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
AdditionalOptions="/GT /GA "
Optimization="4"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="2"
OmitFramePointers="true"
AdditionalIncludeDirectories="../..,../../main,../../Zend,../../TSRM"
PreprocessorDefinitions="HAVE_XXTEA;COMPILE_DL_XXTEA;ZTS;NDEBUG;ZEND_WIN32;PHP_WIN32;WIN32;ZEND_DEBUG=0"
StringPooling="true"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
PrecompiledHeaderFile=".\Release_php5/php_xxtea.pch"
AssemblerListingLocation=".\Release_php5/"
ObjectFile=".\Release_php5/"
ProgramDataBaseFileName=".\Release_php5/"
WarningLevel="3"
SuppressStartupBanner="true"
CompileAs="1"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1033"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="odbc32.lib odbccp32.lib php5ts.lib"
OutputFile="Release_php5\php_xxtea.dll"
LinkIncremental="1"
SuppressStartupBanner="true"
AdditionalLibraryDirectories="../../Release_TS"
ProgramDatabaseFile=".\Release_php5/php_xxtea.pdb"
SubSystem="2"
OptimizeReferences="2"
EnableCOMDATFolding="2"
ImportLibrary="$(OutDir)/php_xxtea.lib"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
SuppressStartupBanner="true"
OutputFile=".\Release_php5/php_xxtea.bsc"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug_php4|Win32"
OutputDirectory=".\Debug_php4"
IntermediateDirectory=".\Debug_php4"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\Debug_php4/php_xxtea.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="../..,../../main,../../Zend,../../TSRM"
PreprocessorDefinitions="HAVE_XXTEA;COMPILE_DL_XXTEA;ZTS;NDEBUG;ZEND_WIN32;PHP_WIN32;WIN32;ZEND_DEBUG=1"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
PrecompiledHeaderFile=".\Debug_php4/php_xxtea.pch"
AssemblerListingLocation=".\Debug_php4/"
ObjectFile=".\Debug_php4/"
ProgramDataBaseFileName=".\Debug_php4/"
WarningLevel="3"
SuppressStartupBanner="true"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1033"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="odbc32.lib odbccp32.lib php4ts.lib"
OutputFile="Debug_php4\php_xxtea.dll"
LinkIncremental="2"
SuppressStartupBanner="true"
AdditionalLibraryDirectories="../../Release_TS"
GenerateDebugInformation="true"
ProgramDatabaseFile="Debug_php4\php_xxtea.pdb"
SubSystem="2"
ImportLibrary="$(OutDir)/php_xxtea.lib"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
SuppressStartupBanner="true"
OutputFile=".\Debug_php4/php_xxtea.bsc"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm"
>
<File
RelativePath="php_xxtea.c"
>
<FileConfiguration
Name="Debug_php5|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="Release_php4|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="Release_php5|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="Debug_php4|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
</File>
<Filter
Name="lib_xxtea"
>
<File
RelativePath="xxtea.c"
>
<FileConfiguration
Name="Debug_php5|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="Release_php4|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="Release_php5|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="Debug_php4|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
</File>
</Filter>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc"
>
<File
RelativePath="php_xxtea.h"
>
</File>
<Filter
Name="lib_xxtea"
>
<File
RelativePath="xxtea.h"
>
</File>
</Filter>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -1,8 +0,0 @@
<?php
echo xxtea_decrypt(xxtea_encrypt("", ""), "");
echo xxtea_decrypt(xxtea_encrypt("1", ""), "");
echo xxtea_decrypt(xxtea_encrypt("1", "1"), "1");
echo xxtea_decrypt(xxtea_encrypt("12222222222222", "2222222222222222"), "2222222222222222");
echo xxtea_decrypt(xxtea_encrypt("12222222222222", "22222222222"), "22222222222");
print_r(xxtea_info());
?>

View File

@@ -1,54 +0,0 @@
/***********************************************************************
Copyright 2006-2007 Ma Bingyao
These sources is free software. Redistributions of source code must
retain the above copyright notice. Redistributions in binary form
must reproduce the above copyright notice. You can redistribute it
freely. You can use it with any free or commercial software.
These sources is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY. Without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
You may contact the author by:
e-mail: andot@coolcode.cn
*************************************************************************/
#include "xxtea.h"
void xxtea_long_encrypt(xxtea_long *v, xxtea_long len, xxtea_long *k) {
xxtea_long n = len - 1;
xxtea_long z = v[n], y = v[0], p, q = 6 + 52 / (n + 1), sum = 0, e;
if (n < 1) {
return;
}
while (0 < q--) {
sum += XXTEA_DELTA;
e = sum >> 2 & 3;
for (p = 0; p < n; p++) {
y = v[p + 1];
z = v[p] += XXTEA_MX;
}
y = v[0];
z = v[n] += XXTEA_MX;
}
}
void xxtea_long_decrypt(xxtea_long *v, xxtea_long len, xxtea_long *k) {
xxtea_long n = len - 1;
xxtea_long z = v[n], y = v[0], p, q = 6 + 52 / (n + 1), sum = q * XXTEA_DELTA, e;
if (n < 1) {
return;
}
while (sum != 0) {
e = sum >> 2 & 3;
for (p = n; p > 0; p--) {
z = v[p - 1];
y = v[p] -= XXTEA_MX;
}
z = v[n];
y = v[0] -= XXTEA_MX;
sum -= XXTEA_DELTA;
}
}

View File

@@ -1,47 +0,0 @@
/***********************************************************************
Copyright 2006-2007 Ma Bingyao
These sources is free software. Redistributions of source code must
retain the above copyright notice. Redistributions in binary form
must reproduce the above copyright notice. You can redistribute it
freely. You can use it with any free or commercial software.
These sources is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY. Without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
You may contact the author by:
e-mail: andot@coolcode.cn
*************************************************************************/
#ifndef XXTEA_H
#define XXTEA_H
#include <stddef.h> /* for size_t & NULL declarations */
#if defined(_MSC_VER)
typedef unsigned __int32 xxtea_long;
#else
#if defined(__FreeBSD__) && __FreeBSD__ < 5
/* FreeBSD 4 doesn't have stdint.h file */
#include <inttypes.h>
#else
#include <stdint.h>
#endif
typedef uint32_t xxtea_long;
#endif /* end of if defined(_MSC_VER) */
#define XXTEA_MX (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z)
#define XXTEA_DELTA 0x9e3779b9
void xxtea_long_encrypt(xxtea_long *v, xxtea_long len, xxtea_long *k);
void xxtea_long_decrypt(xxtea_long *v, xxtea_long len, xxtea_long *k);
#endif

View File

@@ -1,583 +0,0 @@
<?php
/**********************************************************\
| |
| The implementation of PHPRPC Protocol 3.0 |
| |
| phprpc_client.php |
| |
| Release 3.0.1 |
| Copyright by Team-PHPRPC |
| |
| WebSite: http://www.phprpc.org/ |
| http://www.phprpc.net/ |
| http://www.phprpc.com/ |
| http://sourceforge.net/projects/php-rpc/ |
| |
| Authors: Ma Bingyao <andot@ujn.edu.cn> |
| |
| This file may be distributed and/or modified under the |
| terms of the GNU General Public License (GPL) version |
| 2.0 as published by the Free Software Foundation and |
| appearing in the included file LICENSE. |
| |
\**********************************************************/
/* PHPRPC Client for PHP.
*
* Copyright: Ma Bingyao <andot@ujn.edu.cn>
* Version: 3.0
* LastModified: Apr 12, 2010
* This library is free. You can redistribute it and/or modify it under GPL.
*
/*
* Interfaces
*
* $rpc_client = new PHPRPC_Client();
* $rpc_client->setProxy(NULL);
* $rpc_client->useService('http://www.phprpc.org/server.php');
* $rpc_client->setKeyLength(1024);
* $rpc_client->setEncryptMode(3);
* $args = array(1, 2);
* echo $rpc_client->invoke('add', &$args);
* echo "<br />";
* $n = 3;
* $args = array(&$n);
* echo $rpc_client->invoke('inc', &$args, true);
* echo "<br />";
* echo $rpc_client->sub(3, 2);
* echo "<br />";
* // error handle
* $result = $rpc_client->mul(1, 2); // no mul function
* if (is_a($result, "PHPRPC_Error")) {
* echo $result->toString();
* }
*/
$_PHPRPC_COOKIES = array();
$_PHPRPC_COOKIE = '';
$_PHPRPC_SID = 0;
if (defined('KEEP_PHPRPC_COOKIE_IN_SESSION')) {
if (isset($_SESSION['phprpc_cookies']) and isset($_SESSION['phprpc_cookie'])) {
$_PHPRPC_COOKIES = $_SESSION['phprpc_cookies'];
$_PHPRPC_COOKIE = $_SESSION['phprpc_cookie'];
}
function keep_phprpc_cookie_in_session() {
global $_PHPRPC_COOKIES, $_PHPRPC_COOKIE;
$_SESSION['phprpc_cookies'] = $_PHPRPC_COOKIES;
$_SESSION['phprpc_cookie'] = $_PHPRPC_COOKIE;
}
register_shutdown_function('keep_phprpc_cookie_in_session');
}
class PHPRPC_Error {
var $Number;
var $Message;
function PHPRPC_Error($errno, $errstr) {
$this->Number = $errno;
$this->Message = $errstr;
}
function toString() {
return $this->Number . ":" . $this->Message;
}
function __toString() {
return $this->toString();
}
function getNumber() {
return $this->Number;
}
function getMessage() {
return $this->Message;
}
}
class _PHPRPC_Client {
var $_server;
var $_timeout;
var $_output;
var $_warning;
var $_proxy;
var $_key;
var $_keylen;
var $_encryptMode;
var $_charset;
var $_socket;
var $_clientid;
var $_http_version;
var $_keep_alive;
// Public Methods
function _PHPRPC_Client($serverURL = '') {
global $_PHPRPC_SID;
require_once('compat.php');
//register_shutdown_function(array(&$this, "_disconnect"));
$this->_proxy = NULL;
$this->_timeout = 30;
$this->_clientid = 'php' . rand(1 << 30, 1 << 31) . time() . $_PHPRPC_SID;
$_PHPRPC_SID++;
$this->_socket = false;
if ($serverURL != '') {
$this->useService($serverURL);
}
}
function useService($serverURL, $username = NULL, $password = NULL) {
$this->_disconnect();
$this->_http_version = "1.1";
$this->_keep_alive = true;
$this->_server = array();
$this->_key = NULL;
$this->_keylen = 128;
$this->_encryptMode = 0;
$this->_charset = 'utf-8';
$urlparts = parse_url($serverURL);
if (!isset($urlparts['host'])) {
if (isset($_SERVER["HTTP_HOST"])) {
$urlparts['host'] = $_SERVER["HTTP_HOST"];
}
else if (isset($_SERVER["SERVER_NAME"])) {
$urlparts['host'] = $_SERVER["SERVER_NAME"];
}
else {
$urlparts['host'] = "localhost";
}
if (!isset($_SERVER["HTTPS"]) ||
$_SERVER["HTTPS"] == "off" ||
$_SERVER["HTTPS"] == "") {
$urlparts['scheme'] = "http";
}
else {
$urlparts['scheme'] = "https";
}
$urlparts['port'] = $_SERVER["SERVER_PORT"];
}
if (!isset($urlparts['port'])) {
if ($urlparts['scheme'] == "https") {
$urlparts['port'] = 443;
}
else {
$urlparts['port'] = 80;
}
}
if (!isset($urlparts['path'])) {
$urlparts['path'] = "/";
}
else if (($urlparts['path']{0} != '/') && ($_SERVER["PHP_SELF"]{0} == '/')) {
$urlparts['path'] = substr($_SERVER["PHP_SELF"], 0, strrpos($_SERVER["PHP_SELF"], '/') + 1) . $urlparts['path'];
}
if (isset($urlparts['query'])) {
$urlparts['path'] .= '?' . $urlparts['query'];
}
if (!isset($urlparts['user']) || !is_null($username)) {
$urlparts['user'] = $username;
}
if (!isset($urlparts['pass']) || !is_null($password)) {
$urlparts['pass'] = $password;
}
$this->_server['scheme'] = $urlparts['scheme'];
$this->_server['host'] = $urlparts['host'];
$this->_server['port'] = $urlparts['port'];
$this->_server['path'] = $urlparts['path'];
$this->_server['user'] = $urlparts['user'];
$this->_server['pass'] = $urlparts['pass'];
}
function setProxy($host, $port = NULL, $username = NULL, $password = NULL) {
if (is_null($host)) {
$this->_proxy = NULL;
}
else {
if (is_null($port)) {
$urlparts = parse_url($host);
if (isset($urlparts['host'])) {
$host = $urlparts['host'];
}
if (isset($urlparts['port'])) {
$port = $urlparts['port'];
}
else {
$port = 80;
}
if (isset($urlparts['user']) && is_null($username)) {
$username = $urlparts['user'];
}
if (isset($urlparts['pass']) && is_null($password)) {
$password = $urlparts['pass'];
}
}
$this->_proxy = array();
$this->_proxy['host'] = $host;
$this->_proxy['port'] = $port;
$this->_proxy['user'] = $username;
$this->_proxy['pass'] = $password;
}
}
function setKeyLength($keylen) {
if (!is_null($this->_key)) {
return false;
}
else {
$this->_keylen = $keylen;
return true;
}
}
function getKeyLength() {
return $this->_keylen;
}
function setEncryptMode($encryptMode) {
if (($encryptMode >= 0) && ($encryptMode <= 3)) {
$this->_encryptMode = (int)($encryptMode);
return true;
}
else {
$this->_encryptMode = 0;
return false;
}
}
function getEncryptMode() {
return $this->_encryptMode;
}
function setCharset($charset) {
$this->_charset = $charset;
}
function getCharset() {
return $this->_charset;
}
function setTimeout($timeout) {
$this->_timeout = $timeout;
}
function getTimeout() {
return $this->_timeout;
}
function invoke($funcname, &$args, $byRef = false) {
$result = $this->_key_exchange();
if (is_a($result, 'PHPRPC_Error')) {
return $result;
}
$request = "phprpc_func=$funcname";
if (count($args) > 0) {
$request .= "&phprpc_args=" . base64_encode($this->_encrypt(serialize_fix($args), 1));
}
$request .= "&phprpc_encrypt={$this->_encryptMode}";
if (!$byRef) {
$request .= "&phprpc_ref=false";
}
$request = str_replace('+', '%2B', $request);
$result = $this->_post($request);
if (is_a($result, 'PHPRPC_Error')) {
return $result;
}
$phprpc_errno = 0;
$phprpc_errstr = NULL;
if (isset($result['phprpc_errno'])) {
$phprpc_errno = intval($result['phprpc_errno']);
}
if (isset($result['phprpc_errstr'])) {
$phprpc_errstr = base64_decode($result['phprpc_errstr']);
}
$this->_warning = new PHPRPC_Error($phprpc_errno, $phprpc_errstr);
if (array_key_exists('phprpc_output', $result)) {
$this->_output = base64_decode($result['phprpc_output']);
if ($this->_server['version'] >= 3) {
$this->_output = $this->_decrypt($this->_output, 3);
}
}
else {
$this->_output = '';
}
if (array_key_exists('phprpc_result', $result)) {
if (array_key_exists('phprpc_args', $result)) {
$arguments = unserialize($this->_decrypt(base64_decode($result['phprpc_args']), 1));
for ($i = 0; $i < count($arguments); $i++) {
$args[$i] = $arguments[$i];
}
}
$result = unserialize($this->_decrypt(base64_decode($result['phprpc_result']), 2));
}
else {
$result = $this->_warning;
}
return $result;
}
function getOutput() {
return $this->_output;
}
function getWarning() {
return $this->_warning;
}
function _connect() {
if (is_null($this->_proxy)) {
$host = (($this->_server['scheme'] == "https") ? "ssl://" : "") . $this->_server['host'];
$this->_socket = @pfsockopen($host, $this->_server['port'], $errno, $errstr, $this->_timeout);
}
else {
$host = (($this->_server['scheme'] == "https") ? "ssl://" : "") . $this->_proxy['host'];
$this->_socket = @pfsockopen($host, $this->_proxy['port'], $errno, $errstr, $this->_timeout);
}
if ($this->_socket === false) {
return new PHPRPC_Error($errno, $errstr);
}
stream_set_write_buffer($this->_socket, 0);
socket_set_timeout($this->_socket, $this->_timeout);
return true;
}
function _disconnect() {
if ($this->_socket !== false) {
fclose($this->_socket);
$this->_socket = false;
}
}
function _socket_read($size) {
$content = "";
while (!feof($this->_socket) && ($size > 0)) {
$str = fread($this->_socket, $size);
$content .= $str;
$size -= strlen($str);
}
return $content;
}
function _post($request_body) {
global $_PHPRPC_COOKIE;
$request_body = 'phprpc_id=' . $this->_clientid . '&' . $request_body;
if ($this->_socket === false) {
$error = $this->_connect();
if (is_a($error, 'PHPRPC_Error')) {
return $error;
}
}
if (is_null($this->_proxy)) {
$url = $this->_server['path'];
$connection = "Connection: " . ($this->_keep_alive ? 'Keep-Alive' : 'Close') . "\r\n" .
"Cache-Control: no-cache\r\n";
}
else {
$url = "{$this->_server['scheme']}://{$this->_server['host']}:{$this->_server['port']}{$this->_server['path']}";
$connection = "Proxy-Connection: " . ($this->_keep_alive ? 'keep-alive' : 'close') . "\r\n";
if (!is_null($this->_proxy['user'])) {
$connection .= "Proxy-Authorization: Basic " . base64_encode($this->_proxy['user'] . ":" . $this->_proxy['pass']) . "\r\n";
}
}
$auth = '';
if (!is_null($this->_server['user'])) {
$auth = "Authorization: Basic " . base64_encode($this->_server['user'] . ":" . $this->_server['pass']) . "\r\n";
}
$cookie = '';
if ($_PHPRPC_COOKIE) {
$cookie = "Cookie: " . $_PHPRPC_COOKIE . "\r\n";
}
$content_len = strlen($request_body);
$request =
"POST $url HTTP/{$this->_http_version}\r\n" .
"Host: {$this->_server['host']}:{$this->_server['port']}\r\n" .
"User-Agent: PHPRPC Client 3.0 for PHP\r\n" .
$auth .
$connection .
$cookie .
"Accept: */*\r\n" .
"Accept-Encoding: gzip,deflate\r\n" .
"Content-Type: application/x-www-form-urlencoded; charset={$this->_charset}\r\n" .
"Content-Length: {$content_len}\r\n" .
"\r\n" .
$request_body;
fputs($this->_socket, $request, strlen($request));
while (!feof($this->_socket)) {
$line = fgets($this->_socket);
if (preg_match('/HTTP\/(\d\.\d)\s+(\d+)([^(\r|\n)]*)(\r\n|$)/i', $line, $match)) {
$this->_http_version = $match[1];
$status = (int)$match[2];
$status_message = trim($match[3]);
if ($status != 100 && $status != 200) {
$this->_disconnect();
return new PHPRPC_Error($status, $status_message);
}
}
else {
$this->_disconnect();
return new PHPRPC_Error(E_ERROR, "Illegal HTTP server.");
}
$header = array();
while (!feof($this->_socket) && (($line = fgets($this->_socket)) != "\r\n")) {
$line = explode(':', $line, 2);
$header[strtolower($line[0])][] =trim($line[1]);
}
if ($status == 100) continue;
$response_header = $this->_parseHeader($header);
if (is_a($response_header, 'PHPRPC_Error')) {
$this->_disconnect();
return $response_header;
}
break;
}
$response_body = '';
if (isset($response_header['transfer_encoding']) && (strtolower($response_header['transfer_encoding']) == 'chunked')) {
$s = fgets($this->_socket);
if ($s == "") {
$this->_disconnect();
return array();
}
$chunk_size = (int)hexdec($s);
while ($chunk_size > 0) {
$response_body .= $this->_socket_read($chunk_size);
if (fgets($this->_socket) != "\r\n") {
$this->_disconnect();
return new PHPRPC_Error(1, "Response is incorrect.");
}
$chunk_size = (int)hexdec(fgets($this->_socket));
}
fgets($this->_socket);
}
elseif (isset($response_header['content_length']) && !is_null($response_header['content_length'])) {
$response_body = $this->_socket_read($response_header['content_length']);
}
else {
while (!feof($this->_socket)) {
$response_body .= fread($this->_socket, 4096);
}
$this->_keep_alive = false;
$this->_disconnect();
}
if (isset($response_header['content_encoding']) && (strtolower($response_header['content_encoding']) == 'gzip')) {
$response_body = gzdecode($response_body);
}
if (!$this->_keep_alive) $this->_disconnect();
if ($this->_keep_alive && strtolower($response_header['connection']) == 'close') {
$this->_keep_alive = false;
$this->_disconnect();
}
return $this->_parseBody($response_body);
}
function _parseHeader($header) {
global $_PHPRPC_COOKIE, $_PHPRPC_COOKIES;
if (preg_match('/PHPRPC Server\/([^,]*)(,|$)/i', implode(',', $header['x-powered-by']), $match)) {
$this->_server['version'] = (float)$match[1];
}
else {
return new PHPRPC_Error(E_ERROR, "Illegal PHPRPC server.");
}
if (preg_match('/text\/plain\; charset\=([^,;]*)([,;]|$)/i', $header['content-type'][0], $match)) {
$this->_charset = $match[1];
}
if (isset($header['set-cookie'])) {
foreach ($header['set-cookie'] as $cookie) {
foreach (preg_split('/[;,]\s?/', $cookie) as $c) {
list($name, $value) = explode('=', $c, 2);
if (!in_array($name, array('domain', 'expires', 'path', 'secure'))) {
$_PHPRPC_COOKIES[$name] = $value;
}
}
}
$cookies = array();
foreach ($_PHPRPC_COOKIES as $name => $value) {
$cookies[] = "$name=$value";
}
$_PHPRPC_COOKIE = join('; ', $cookies);
}
if (isset($header['content-length'])) {
$content_length = (int)$header['content-length'][0];
}
else {
$content_length = NULL;
}
$transfer_encoding = isset($header['transfer-encoding']) ? $header['transfer-encoding'][0] : '';
$content_encoding = isset($header['content-encoding']) ? $header['content-encoding'][0] : '';
$connection = isset($header['connection']) ? $header['connection'][0] : 'close';
return array('transfer_encoding' => $transfer_encoding,
'content_encoding' => $content_encoding,
'content_length' => $content_length,
'connection' => $connection);
}
function _parseBody($body) {
$body = explode(";\r\n", $body);
$result = array();
$n = count($body);
for ($i = 0; $i < $n; $i++) {
$p = strpos($body[$i], '=');
if ($p !== false) {
$l = substr($body[$i], 0, $p);
$r = substr($body[$i], $p + 1);
$result[$l] = trim($r, '"');
}
}
return $result;
}
function _key_exchange() {
if (!is_null($this->_key) || ($this->_encryptMode == 0)) return true;
$request = "phprpc_encrypt=true&phprpc_keylen={$this->_keylen}";
$result = $this->_post($request);
if (is_a($result, 'PHPRPC_Error')) {
return $result;
}
if (array_key_exists('phprpc_keylen', $result)) {
$this->_keylen = (int)$result['phprpc_keylen'];
}
else {
$this->_keylen = 128;
}
if (array_key_exists('phprpc_encrypt', $result)) {
$encrypt = unserialize(base64_decode($result['phprpc_encrypt']));
require_once('bigint.php');
require_once('xxtea.php');
$x = bigint_random($this->_keylen - 1, true);
$key = bigint_powmod(bigint_dec2num($encrypt['y']), $x, bigint_dec2num($encrypt['p']));
if ($this->_keylen == 128) {
$key = bigint_num2str($key);
}
else {
$key = pack('H*', md5(bigint_num2dec($key)));
}
$this->_key = str_pad($key, 16, "\0", STR_PAD_LEFT);
$encrypt = bigint_num2dec(bigint_powmod(bigint_dec2num($encrypt['g']), $x, bigint_dec2num($encrypt['p'])));
$request = "phprpc_encrypt=$encrypt";
$result = $this->_post($request);
if (is_a($result, 'PHPRPC_Error')) {
return $result;
}
}
else {
$this->_key = NULL;
$this->_encryptMode = 0;
}
return true;
}
function _encrypt($str, $level) {
if (!is_null($this->_key) && ($this->_encryptMode >= $level)) {
$str = xxtea_encrypt($str, $this->_key);
}
return $str;
}
function _decrypt($str, $level) {
if (!is_null($this->_key) && ($this->_encryptMode >= $level)) {
$str = xxtea_decrypt($str, $this->_key);
}
return $str;
}
}
if (function_exists("overload") && version_compare(phpversion(), "5", "<")) {
eval('
class PHPRPC_Client extends _PHPRPC_Client {
function __call($function, $arguments, &$return) {
$return = $this->invoke($function, $arguments);
return true;
}
}
overload("phprpc_client");
');
}
else {
class PHPRPC_Client extends _PHPRPC_Client {
function __call($function, $arguments) {
return $this->invoke($function, $arguments);
}
}
}
?>

View File

@@ -1,522 +0,0 @@
<?php
/**********************************************************\
| |
| The implementation of PHPRPC Protocol 3.0 |
| |
| phprpc_date.php |
| |
| Release 3.0.1 |
| Copyright by Team-PHPRPC |
| |
| WebSite: http://www.phprpc.org/ |
| http://www.phprpc.net/ |
| http://www.phprpc.com/ |
| http://sourceforge.net/projects/php-rpc/ |
| |
| Authors: Ma Bingyao <andot@ujn.edu.cn> |
| |
| This file may be distributed and/or modified under the |
| terms of the GNU General Public License (GPL) version |
| 2.0 as published by the Free Software Foundation and |
| appearing in the included file LICENSE. |
| |
\**********************************************************/
/* PHPRPC_Date Class for PHP.
*
* Copyright: Ma Bingyao <andot@ujn.edu.cn>
* Version: 1.2
* LastModified: Apr 12, 2010
* This library is free. You can redistribute it and/or modify it under GPL.
*/
class PHPRPC_Date {
// public fields
var $year = 1;
var $month = 1;
var $day = 1;
var $hour = 0;
var $minute = 0;
var $second = 0;
var $millisecond = 0;
// constructor
function PHPRPC_Date() {
$num = func_num_args();
$time = false;
if ($num == 0) {
$time = getdate();
}
if ($num == 1) {
$arg = func_get_arg(0);
if (is_int($arg)) {
$time = getdate($arg);
}
elseif (is_string($arg)) {
$time = getdate(strtotime($arg));
}
}
if (is_array($time)) {
$this->year = $time['year'];
$this->month = $time['mon'];
$this->day = $time['mday'];
$this->hour = $time['hours'];
$this->minute = $time['minutes'];
$this->second = $time['seconds'];
}
}
// public instance methods
function addMilliseconds($milliseconds) {
if (!is_int($milliseconds)) return false;
if ($milliseconds == 0) return true;
$millisecond = $this->millisecond + $milliseconds;
$milliseconds = $millisecond % 1000;
if ($milliseconds < 0) {
$milliseconds += 1000;
}
$seconds = (int)(($millisecond - $milliseconds) / 1000);
$millisecond = (int)$milliseconds;
if ($this->addSeconds($seconds)) {
$this->millisecond = (int)$milliseconds;
return true;
}
else {
return false;
}
}
function addSeconds($seconds) {
if (!is_int($seconds)) return false;
if ($seconds == 0) return true;
$second = $this->second + $seconds;
$seconds = $second % 60;
if ($seconds < 0) {
$seconds += 60;
}
$minutes = (int)(($second - $seconds) / 60);
if ($this->addMinutes($minutes)) {
$this->second = (int)$seconds;
return true;
}
else {
return false;
}
}
function addMinutes($minutes) {
if (!is_int($minutes)) return false;
if ($minutes == 0) return true;
$minute = $this->minute + $minutes;
$minutes = $minute % 60;
if ($minutes < 0) {
$minutes += 60;
}
$hours = (int)(($minute - $minutes) / 60);
if ($this->addHours($hours)) {
$this->minute = (int)$minutes;
return true;
}
else {
return false;
}
}
function addHours($hours) {
if (!is_int($hours)) return false;
if ($hours == 0) return true;
$hour = $this->hour + $hours;
$hours = $hour % 24;
if ($hours < 0) {
$hours += 24;
}
$days = (int)(($hour - $hours) / 24);
if ($this->addDays($days)) {
$this->hour = (int)$hours;
return true;
}
else {
return false;
}
}
function addDays($days) {
if (!is_int($days)) return false;
$year = $this->year;
if ($days == 0) return true;
if ($days >= 146097 || $days <= -146097) {
$remainder = $days % 146097;
if ($remainder < 0) {
$remainder += 146097;
}
$years = 400 * (int)(($days - $remainder) / 146097);
$year += $years;
if ($year < 1 || $year > 9999) return false;
$days = $remainder;
}
if ($days >= 36524 || $days <= -36524) {
$remainder = $days % 36524;
if ($remainder < 0) {
$remainder += 36524;
}
$years = 100 * (int)(($days - $remainder) / 36524);
$year += $years;
if ($year < 1 || $year > 9999) return false;
$days = $remainder;
}
if ($days >= 1461 || $days <= -1461) {
$remainder = $days % 1461;
if ($remainder < 0) {
$remainder += 1461;
}
$years = 4 * (int)(($days - $remainder) / 1461);
$year += $years;
if ($year < 1 || $year > 9999) return false;
$days = $remainder;
}
$month = $this->month;
while ($days >= 365) {
if ($year >= 9999) return false;
if ($month <= 2) {
if ((($year % 4) == 0) ? (($year % 100) == 0) ? (($year % 400) == 0) : true : false) {
$days -= 366;
}
else {
$days -= 365;
}
$year++;
}
else {
$year++;
if ((($year % 4) == 0) ? (($year % 100) == 0) ? (($year % 400) == 0) : true : false) {
$days -= 366;
}
else {
$days -= 365;
}
}
}
while ($days < 0) {
if ($year <= 1) return false;
if ($month <= 2) {
$year--;
if ((($year % 4) == 0) ? (($year % 100) == 0) ? (($year % 400) == 0) : true : false) {
$days += 366;
}
else {
$days += 365;
}
}
else {
if ((($year % 4) == 0) ? (($year % 100) == 0) ? (($year % 400) == 0) : true : false) {
$days += 366;
}
else {
$days += 365;
}
$year--;
}
}
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$day = $this->day;
while ($day + $days > $daysInMonth) {
$days -= $daysInMonth - $day + 1;
$month++;
if ($month > 12) {
if ($year >= 9999) return false;
$year++;
$month = 1;
}
$day = 1;
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
}
$day += $days;
$this->year = $year;
$this->month = $month;
$this->day = $day;
return true;
}
function addMonths($months) {
if (!is_int($months)) return false;
if ($months == 0) return true;
$month = $this->month + $months;
$months = ($month - 1) % 12 + 1;
if ($months < 1) {
$months += 12;
}
$years = (int)(($month - $months) / 12);
if ($this->addYears($years)) {
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $months, $this->year);
if ($this->day > $daysInMonth) {
$months++;
$this->day -= $daysInMonth;
}
$this->month = (int)$months;
return true;
}
else {
return false;
}
}
function addYears($years) {
if (!is_int($years)) return false;
if ($years == 0) return true;
$year = $this->year + $years;
if ($year < 1 || $year > 9999) return false;
$this->year = $year;
return true;
}
function after($when) {
if (!is_a($when, 'PHPRPC_Date')) {
$when = PHPRPC_Date::parse($when);
}
if ($this->year < $when->year) return false;
if ($this->year > $when->year) return true;
if ($this->month < $when->month) return false;
if ($this->month > $when->month) return true;
if ($this->day < $when->day) return false;
if ($this->day > $when->day) return true;
if ($this->hour < $when->hour) return false;
if ($this->hour > $when->hour) return true;
if ($this->minute < $when->minute) return false;
if ($this->minute > $when->minute) return true;
if ($this->second < $when->second) return false;
if ($this->second > $when->second) return true;
if ($this->millisecond < $when->millisecond) return false;
if ($this->millisecond > $when->millisecond) return true;
return false;
}
function before($when) {
if (!is_a($when, 'PHPRPC_Date')) {
$when = new PHPRPC_Date($when);
}
if ($this->year < $when->year) return true;
if ($this->year > $when->year) return false;
if ($this->month < $when->month) return true;
if ($this->month > $when->month) return false;
if ($this->day < $when->day) return true;
if ($this->day > $when->day) return false;
if ($this->hour < $when->hour) return true;
if ($this->hour > $when->hour) return false;
if ($this->minute < $when->minute) return true;
if ($this->minute > $when->minute) return false;
if ($this->second < $when->second) return true;
if ($this->second > $when->second) return false;
if ($this->millisecond < $when->millisecond) return true;
if ($this->millisecond > $when->millisecond) return false;
return false;
}
function equals($when) {
if (!is_a($when, 'PHPRPC_Date')) {
$when = new PHPRPC_Date($when);
}
return (($this->year == $when->year) &&
($this->month == $when->month) &&
($this->day == $when->day) &&
($this->hour == $when->hour) &&
($this->minute == $when->minute) &&
($this->second == $when->second) &&
($this->millisecond == $when->millisecond));
}
function set() {
$num = func_num_args();
$args = func_get_args();
if ($num >= 3) {
if (!PHPRPC_Date::isValidDate($args[0], $args[1], $args[2])) {
return false;
}
$this->year = (int)$args[0];
$this->month = (int)$args[1];
$this->day = (int)$args[2];
if ($num == 3) {
return true;
}
}
if ($num >= 6) {
if (!PHPRPC_Date::isValidTime($args[3], $args[4], $args[5])) {
return false;
}
$this->hour = (int)$args[3];
$this->minute = (int)$args[4];
$this->second = (int)$args[5];
if ($num == 6) {
return true;
}
}
if (($num == 7) && ($args[6] >= 0 && $args[6] <= 999)) {
$this->millisecond = (int)$args[6];
return true;
}
return false;
}
function time() {
return mktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year);
}
function toString() {
return sprintf('%04d-%02d-%02d %02d:%02d:%02d.%03d',
$this->year, $this->month, $this->day,
$this->hour, $this->minute, $this->second,
$this->millisecond);
}
// magic method for PHP 5
function __toString() {
return $this->toString();
}
// public instance & static methods
function dayOfWeek() {
$num = func_num_args();
if ($num == 3) {
$args = func_get_args();
$y = $args[0];
$m = $args[1];
$d = $args[2];
}
else {
$y = $this->year;
$m = $this->month;
$d = $this->day;
}
$d += $m < 3 ? $y-- : $y - 2;
return ((int)(23 * $m / 9) + $d + 4 + (int)($y / 4) - (int)($y / 100) + (int)($y / 400)) % 7;
}
function dayOfYear() {
static $daysToMonth365 = array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365);
static $daysToMonth366 = array(0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366);
$num = func_num_args();
if ($num == 3) {
$args = func_get_args();
$y = $args[0];
$m = $args[1];
$d = $args[2];
}
else {
$y = $this->year;
$m = $this->month;
$d = $this->day;
}
$days = PHPRPC_Date::isLeapYear($y) ? $daysToMonth365 : $daysToMonth366;
return $days[$m - 1] + $d;
}
// public static methods
function now() {
$date = new PHPRPC_Date();
return $date;
}
function today() {
$date = PHPRPC_Date::now();
$date->hour = 0;
$date->minute = 0;
$date->second = 0;
return $date;
}
function parse($dt) {
if (is_a($dt, 'PHPRPC_Date')) {
return $dt;
}
if (is_int($dt)) {
return new PHPRPC_Date($dt);
}
$shortFormat = '(\d|\d{2}|\d{3}|\d{4})-([1-9]|0[1-9]|1[012])-([1-9]|0[1-9]|[12]\d|3[01])';
if (preg_match("/^$shortFormat$/", $dt, $match)) {
$year = intval($match[1]);
$month = intval($match[2]);
$day = intval($match[3]);
if (PHPRPC_Date::isValidDate($year, $month, $day)) {
$date = new PHPRPC_Date(false);
$date->year = $year;
$date->month = $month;
$date->day = $day;
return $date;
}
else {
return false;
}
}
$longFormat = $shortFormat . ' (\d|0\d|1\d|2[0-3]):(\d|[0-5]\d):(\d|[0-5]\d)';
if (preg_match("/^$longFormat$/", $dt, $match)) {
$year = intval($match[1]);
$month = intval($match[2]);
$day = intval($match[3]);
if (PHPRPC_Date::isValidDate($year, $month, $day)) {
$date = new PHPRPC_Date(false);
$date->year = $year;
$date->month = $month;
$date->day = $day;
$date->hour = intval($match[4]);
$date->minute = intval($match[5]);
$date->second = intval($match[6]);
return $date;
}
else {
return false;
}
}
$fullFormat = $longFormat . '\.(\d|\d{2}|\d{3})';
if (preg_match("/^$fullFormat$/", $dt, $match)) {
$year = intval($match[1]);
$month = intval($match[2]);
$day = intval($match[3]);
if (PHPRPC_Date::isValidDate($year, $month, $day)) {
$date = new PHPRPC_Date(false);
$date->year = $year;
$date->month = $month;
$date->day = $day;
$date->hour = intval($match[4]);
$date->minute = intval($match[5]);
$date->second = intval($match[6]);
$date->millisecond = intval($match[7]);
return $date;
}
else {
return false;
}
}
return false;
}
function isLeapYear($year) {
return (($year % 4) == 0) ? (($year % 100) == 0) ? (($year % 400) == 0) : true : false;
}
function daysInMonth($year, $month) {
if (($month < 1) || ($month > 12)) {
return false;
}
return cal_days_in_month(CAL_GREGORIAN, $month, $year);
}
function isValidDate($year, $month, $day) {
if (($year >= 1) && ($year <= 9999)) {
return checkdate($month, $day, $year);
}
return false;
}
function isValidTime($hour, $minute, $second) {
return !(($hour < 0) || ($hour > 23) ||
($minute < 0) || ($minute > 59) ||
($second < 0) || ($second > 59));
}
}
?>

View File

@@ -1,496 +0,0 @@
<?php
/**********************************************************\
| |
| The implementation of PHPRPC Protocol 3.0 |
| |
| phprpc_server.php |
| |
| Release 3.0.1 |
| Copyright by Team-PHPRPC |
| |
| WebSite: http://www.phprpc.org/ |
| http://www.phprpc.net/ |
| http://www.phprpc.com/ |
| http://sourceforge.net/projects/php-rpc/ |
| |
| Authors: Ma Bingyao <andot@ujn.edu.cn> |
| |
| This file may be distributed and/or modified under the |
| terms of the GNU General Public License (GPL) version |
| 2.0 as published by the Free Software Foundation and |
| appearing in the included file LICENSE. |
| |
\**********************************************************/
/* PHPRPC Server for PHP.
*
* Copyright: Ma Bingyao <andot@ujn.edu.cn>
* Version: 3.0
* LastModified: Apr 12, 2010
* This library is free. You can redistribute it and/or modify it under GPL.
*
/*
* Interfaces
*
* function add($a, $b) {
* return $a + $b;
* }
* function sub($a, $b) {
* return $a - $b;
* }
* function inc(&$n) {
* return $n++;
* }
* include('phprpc_server.php');
* $server = new PHPRPC_Server();
* $server->add(array('add', 'sub'));
* $server->add('inc');
* $server->setCharset('UTF-8');
* $server->setDebugMode(true);
* $server->start();
*
*/
class PHPRPC_Server {
var $callback;
var $charset;
var $encode;
var $ref;
var $encrypt;
var $enableGZIP;
var $debug;
var $keylen;
var $key;
var $errno;
var $errstr;
var $functions;
var $cid;
var $buffer;
// Private Methods
function addJsSlashes($str, $flag) {
if ($flag) {
$str = addcslashes($str, "\0..\006\010..\012\014..\037\042\047\134\177..\377");
}
else {
$str = addcslashes($str, "\0..\006\010..\012\014..\037\042\047\134\177");
}
return str_replace(array(chr(7), chr(11)), array('\007', '\013'), $str);
}
function encodeString($str, $flag = true) {
if ($this->encode) {
return base64_encode($str);
}
else {
return $this->addJsSlashes($str, $flag);
}
}
function encryptString($str, $level) {
if ($this->encrypt >= $level) {
$str = xxtea_encrypt($str, $this->key);
}
return $str;
}
function decryptString($str, $level) {
if ($this->encrypt >= $level) {
$str = xxtea_decrypt($str, $this->key);
}
return $str;
}
function sendHeader() {
header("HTTP/1.1 200 OK");
header("Content-Type: text/plain; charset={$this->charset}");
header("X-Powered-By: PHPRPC Server/3.0");
header('P3P: CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV"');
header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
}
function getRequestURL() {
if (!isset($_SERVER['HTTPS']) ||
$_SERVER['HTTPS'] == 'off' ||
$_SERVER['HTTPS'] == '') {
$scheme = 'http';
}
else {
$scheme = 'https';
}
$host = $_SERVER['SERVER_NAME'];
$port = $_SERVER['SERVER_PORT'];
$path = $_SERVER['SCRIPT_NAME'];
return $scheme . '://' . $host . (($port == 80) ? '' : ':' . $port) . $path;
}
function sendURL() {
if (SID != "") {
$url = $this->getRequestURL();
if (count($_GET) > 0) {
$url .= '?' . strip_tags(SID);
foreach ($_GET as $key => $value) {
if (strpos(strtolower($key), 'phprpc_') !== 0) {
$url .= '&' . $key . '=' . urlencode($value);
}
}
}
$this->buffer .= "phprpc_url=\"" . $this->encodeString($url) . "\";\r\n";
}
}
function gzip($buffer) {
$len = strlen($buffer);
if ($this->enableGZIP && strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip,deflate')) {
$gzbuffer = gzencode($buffer);
$gzlen = strlen($gzbuffer);
if ($len > $gzlen) {
header("Content-Length: $gzlen");
header("Content-Encoding: gzip");
return $gzbuffer;
}
}
header("Content-Length: $len");
return $buffer;
}
function sendCallback() {
$this->buffer .= $this->callback;
echo $this->gzip($this->buffer);
ob_end_flush();
restore_error_handler();
if (function_exists('restore_exception_handler')) {
restore_exception_handler();
}
exit();
}
function sendFunctions() {
$this->buffer .= "phprpc_functions=\"" . $this->encodeString(serialize_fix(array_keys($this->functions))) . "\";\r\n";
$this->sendCallback();
}
function sendOutput($output) {
if ($this->encrypt >= 3) {
$this->buffer .= "phprpc_output=\"" . $this->encodeString(xxtea_encrypt($output, $this->key)) . "\";\r\n";
}
else {
$this->buffer .= "phprpc_output=\"" . $this->encodeString($output, false) . "\";\r\n";
}
}
function sendError($output = NULL) {
if (is_null($output)) {
$output = ob_get_clean();
}
$this->buffer .= "phprpc_errno=\"{$this->errno}\";\r\n";
$this->buffer .= "phprpc_errstr=\"" . $this->encodeString($this->errstr, false) . "\";\r\n";
$this->sendOutput($output);
$this->sendCallback();
}
function fatalErrorHandler($buffer) {
if (preg_match('/<b>(.*?) error<\/b>:(.*?)<br/', $buffer, $match)) {
if ($match[1] == 'Fatal') {
$errno = E_ERROR;
}
else {
$errno = E_COMPILE_ERROR;
}
if ($this->debug) {
$errstr = preg_replace('/<.*?>/', '', $match[2]);
}
else {
$errstr = preg_replace('/ in <b>.*<\/b>$/', '', $match[2]);
}
$buffer = "phprpc_errno=\"{$errno}\";\r\n" .
"phprpc_errstr=\"" . $this->encodeString(trim($errstr), false) . "\";\r\n" .
"phprpc_output=\"\";\r\n" .
$this->callback;
$buffer = $this->gzip($buffer);
}
return $buffer;
}
function errorHandler($errno, $errstr, $errfile, $errline) {
if ($this->debug) {
$errstr .= " in $errfile on line $errline";
}
if (($errno == E_ERROR) or ($errno == E_CORE_ERROR) or
($errno == E_COMPILE_ERROR) or ($errno == E_USER_ERROR)) {
$this->errno = $errno;
$this->errstr = $errstr;
$this->sendError();
}
else {
if (($errno == E_NOTICE) or ($errno == E_USER_NOTICE)) {
if ($this->errno == 0) {
$this->errno = $errno;
$this->errstr = $errstr;
}
}
else {
if (($this->errno == 0) or
($this->errno == E_NOTICE) or
($this->errno == E_USER_NOTICE)) {
$this->errno = $errno;
$this->errstr = $errstr;
}
}
}
return true;
}
function exceptionHandler($exception) {
$this->errno = $exception->getCode();
$this->errstr = $exception->getMessage();
if ($this->debug) {
$this->errstr .= "\nfile: " . $exception->getFile() .
"\nline: " . $exception->getLine() .
"\ntrace: " . $exception->getTraceAsString();
}
$this->sendError();
}
function initErrorHandler() {
$this->errno = 0;
$this->errstr = "";
set_error_handler(array(&$this, 'errorHandler'));
if (function_exists('set_exception_handler')) {
set_exception_handler(array(&$this, 'exceptionHandler'));
}
}
function call($function, &$args) {
if ($this->ref) {
$arguments = array();
for ($i = 0; $i < count($args); $i++) {
$arguments[$i] = &$args[$i];
}
}
else {
$arguments = $args;
}
return call_user_func_array($function, $arguments);
}
function getRequest($name) {
$result = $_REQUEST[$name];
if (get_magic_quotes_gpc()) {
$result = stripslashes($result);
}
return $result;
}
function getBooleanRequest($name) {
$var = true;
if (isset($_REQUEST[$name])) {
$var = strtolower($this->getRequest($name));
if ($var == "false") {
$var = false;
}
}
return $var;
}
function initEncode() {
$this->encode = $this->getBooleanRequest('phprpc_encode');
}
function initRef() {
$this->ref = $this->getBooleanRequest('phprpc_ref');
}
function initCallback() {
if (isset($_REQUEST['phprpc_callback'])) {
$this->callback = base64_decode($this->getRequest('phprpc_callback'));
}
else {
$this->callback = "";
}
}
function initKeylen() {
if (isset($_REQUEST['phprpc_keylen'])) {
$this->keylen = (int)$this->getRequest('phprpc_keylen');
}
else if (isset($_SESSION[$this->cid])) {
$session = unserialize(base64_decode($_SESSION[$this->cid]));
if (isset($session['keylen'])) {
$this->keylen = $session['keylen'];
}
else {
$this->keylen = 128;
}
}
else {
$this->keylen = 128;
}
}
function initClientID() {
$this->cid = 0;
if (isset($_REQUEST['phprpc_id'])) {
$this->cid = $this->getRequest('phprpc_id');
}
$this->cid = "phprpc_" . $this->cid;
}
function initEncrypt() {
$this->encrypt = false;
if (isset($_REQUEST['phprpc_encrypt'])) {
$this->encrypt = $this->getRequest('phprpc_encrypt');
if ($this->encrypt === "true") $this->encrypt = true;
if ($this->encrypt === "false") $this->encrypt = false;
}
}
function initKey() {
if ($this->encrypt == 0) {
return;
}
else if (isset($_SESSION[$this->cid])) {
$session = unserialize(base64_decode($_SESSION[$this->cid]));
if (isset($session['key'])) {
$this->key = $session['key'];
require_once('xxtea.php');
return;
}
}
$this->errno = E_ERROR;
$this->errstr = "Can't find the key for decryption.";
$this->encrypt = 0;
$this->sendError();
}
function getArguments() {
if (isset($_REQUEST['phprpc_args'])) {
$arguments = unserialize($this->decryptString(base64_decode($this->getRequest('phprpc_args')), 1));
ksort($arguments);
}
else {
$arguments = array();
}
return $arguments;
}
function callFunction() {
$this->initKey();
$function = strtolower($this->getRequest('phprpc_func'));
if (array_key_exists($function, $this->functions)) {
$function = $this->functions[$function];
$arguments = $this->getArguments();
$result = $this->encodeString($this->encryptString(serialize_fix($this->call($function, $arguments)), 2));
$output = ob_get_clean();
$this->buffer .= "phprpc_result=\"$result\";\r\n";
if ($this->ref) {
$arguments = $this->encodeString($this->encryptString(serialize_fix($arguments), 1));
$this->buffer .= "phprpc_args=\"$arguments\";\r\n";
}
}
else {
$this->errno = E_ERROR;
$this->errstr = "Can't find this function $function().";
$output = ob_get_clean();
}
$this->sendError($output);
}
function keyExchange() {
require_once('bigint.php');
$this->initKeylen();
if (isset($_SESSION[$this->cid])) {
$session = unserialize(base64_decode($_SESSION[$this->cid]));
}
else {
$session = array();
}
if ($this->encrypt === true) {
require_once('dhparams.php');
$DHParams = new DHParams($this->keylen);
$this->keylen = $DHParams->getL();
$encrypt = $DHParams->getDHParams();
$x = bigint_random($this->keylen - 1, true);
$session['x'] = bigint_num2dec($x);
$session['p'] = $encrypt['p'];
$session['keylen'] = $this->keylen;
$encrypt['y'] = bigint_num2dec(bigint_powmod(bigint_dec2num($encrypt['g']), $x, bigint_dec2num($encrypt['p'])));
$this->buffer .= "phprpc_encrypt=\"" . $this->encodeString(serialize_fix($encrypt)) . "\";\r\n";
if ($this->keylen != 128) {
$this->buffer .= "phprpc_keylen=\"{$this->keylen}\";\r\n";
}
$this->sendURL();
}
else {
$y = bigint_dec2num($this->encrypt);
$x = bigint_dec2num($session['x']);
$p = bigint_dec2num($session['p']);
$key = bigint_powmod($y, $x, $p);
if ($this->keylen == 128) {
$key = bigint_num2str($key);
}
else {
$key = pack('H*', md5(bigint_num2dec($key)));
}
$session['key'] = str_pad($key, 16, "\0", STR_PAD_LEFT);
}
$_SESSION[$this->cid] = base64_encode(serialize($session));
$this->sendCallback();
}
function initSession() {
@ob_start();
ob_implicit_flush(0);
session_start();
}
function initOutputBuffer() {
@ob_start(array(&$this, "fatalErrorHandler"));
ob_implicit_flush(0);
$this->buffer = "";
}
// Public Methods
function PHPRPC_Server() {
require_once('compat.php');
$this->functions = array();
$this->charset = 'UTF-8';
$this->debug = false;
$this->enableGZIP = false;
}
function add($functions, $obj = NULL, $aliases = NULL) {
if (is_null($functions) || (gettype($functions) != gettype($aliases) && !is_null($aliases))) {
return false;
}
if (is_object($functions)) {
$obj = $functions;
$functions = get_class_methods(get_class($obj));
$aliases = $functions;
}
if (is_null($aliases)) {
$aliases = $functions;
}
if (is_string($functions)) {
if (is_null($obj)) {
$this->functions[strtolower($aliases)] = $functions;
}
else if (is_object($obj)) {
$this->functions[strtolower($aliases)] = array(&$obj, $functions);
}
else if (is_string($obj)) {
$this->functions[strtolower($aliases)] = array($obj, $functions);
}
}
else {
if (count($functions) != count($aliases)) {
return false;
}
foreach ($functions as $key => $function) {
$this->add($function, $obj, $aliases[$key]);
}
}
return true;
}
function setCharset($charset) {
$this->charset = $charset;
}
function setDebugMode($debug) {
$this->debug = $debug;
}
function setEnableGZIP($enableGZIP) {
$this->enableGZIP = $enableGZIP;
}
function start() {
while(ob_get_length() !== false) @ob_end_clean();
$this->initOutputBuffer();
$this->sendHeader();
$this->initErrorHandler();
$this->initEncode();
$this->initCallback();
$this->initRef();
$this->initClientID();
$this->initEncrypt();
if (isset($_REQUEST['phprpc_func'])) {
$this->callFunction();
}
else if ($this->encrypt != false) {
$this->keyExchange();
}
else {
$this->sendFunctions();
}
}
}
PHPRPC_Server::initSession();
?>

View File

@@ -1,134 +0,0 @@
<?php
/**********************************************************\
| |
| The implementation of PHPRPC Protocol 3.0 |
| |
| xxtea.php |
| |
| Release 3.0.1 |
| Copyright by Team-PHPRPC |
| |
| WebSite: http://www.phprpc.org/ |
| http://www.phprpc.net/ |
| http://www.phprpc.com/ |
| http://sourceforge.net/projects/php-rpc/ |
| |
| Authors: Ma Bingyao <andot@ujn.edu.cn> |
| |
| This file may be distributed and/or modified under the |
| terms of the GNU General Public License (GPL) version |
| 2.0 as published by the Free Software Foundation and |
| appearing in the included file LICENSE. |
| |
\**********************************************************/
/* XXTEA encryption arithmetic library.
*
* Copyright: Ma Bingyao <andot@ujn.edu.cn>
* Version: 1.6
* LastModified: Apr 12, 2010
* This library is free. You can redistribute it and/or modify it under GPL.
*/
if (!extension_loaded('xxtea')) {
function long2str($v, $w) {
$len = count($v);
$n = ($len - 1) << 2;
if ($w) {
$m = $v[$len - 1];
if (($m < $n - 3) || ($m > $n)) return false;
$n = $m;
}
$s = array();
for ($i = 0; $i < $len; $i++) {
$s[$i] = pack("V", $v[$i]);
}
if ($w) {
return substr(join('', $s), 0, $n);
}
else {
return join('', $s);
}
}
function str2long($s, $w) {
$v = unpack("V*", $s. str_repeat("\0", (4 - strlen($s) % 4) & 3));
$v = array_values($v);
if ($w) {
$v[count($v)] = strlen($s);
}
return $v;
}
function int32($n) {
while ($n >= 2147483648) $n -= 4294967296;
while ($n <= -2147483649) $n += 4294967296;
return (int)$n;
}
function xxtea_encrypt($str, $key) {
if ($str == "") {
return "";
}
$v = str2long($str, true);
$k = str2long($key, false);
if (count($k) < 4) {
for ($i = count($k); $i < 4; $i++) {
$k[$i] = 0;
}
}
$n = count($v) - 1;
$z = $v[$n];
$y = $v[0];
$delta = 0x9E3779B9;
$q = floor(6 + 52 / ($n + 1));
$sum = 0;
while (0 < $q--) {
$sum = int32($sum + $delta);
$e = $sum >> 2 & 3;
for ($p = 0; $p < $n; $p++) {
$y = $v[$p + 1];
$mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$z = $v[$p] = int32($v[$p] + $mx);
}
$y = $v[0];
$mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$z = $v[$n] = int32($v[$n] + $mx);
}
return long2str($v, false);
}
function xxtea_decrypt($str, $key) {
if ($str == "") {
return "";
}
$v = str2long($str, false);
$k = str2long($key, false);
if (count($k) < 4) {
for ($i = count($k); $i < 4; $i++) {
$k[$i] = 0;
}
}
$n = count($v) - 1;
$z = $v[$n];
$y = $v[0];
$delta = 0x9E3779B9;
$q = floor(6 + 52 / ($n + 1));
$sum = int32($q * $delta);
while ($sum != 0) {
$e = $sum >> 2 & 3;
for ($p = $n; $p > 0; $p--) {
$z = $v[$p - 1];
$mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$y = $v[$p] = int32($v[$p] - $mx);
}
$z = $v[$n];
$mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
$y = $v[0] = int32($v[0] - $mx);
$sum = int32($sum - $delta);
}
return long2str($v, true);
}
}
?>

View File

@@ -24,7 +24,7 @@ return [
'Think\Error' => CORE_PATH . 'Error.php',
'Think\Cache' => CORE_PATH . 'Cache.php',
'Think\Cache\Driver\File' => CORE_PATH . 'Cache/Driver/File.php',
'Think\Tag' => CORE_PATH . 'Tag.php',
'Think\Hook' => CORE_PATH . 'Hook.php',
'Think\Session' => CORE_PATH . 'Session.php',
'Think\Cookie' => CORE_PATH . 'Cookie.php',
'Think\Controller' => CORE_PATH . 'Controller.php',

View File

@@ -17,6 +17,7 @@ define('THINK_VERSION', '4.0beta');
// 系统常量
defined('THINK_PATH') or define('THINK_PATH', dirname(__FILE__).'/');
defined('LIB_PATH') or define('LIB_PATH', THINK_PATH.'Library/');
defined('MODE_PATH') or define('MODE_PATH', THINK_PATH.'Mode/'); // 系统应用模式目录
defined('TRAIT_PATH') or define('TRAIT_PATH', THINK_PATH.'Traits/');
defined('CORE_PATH') or define('CORE_PATH', LIB_PATH.'Think/');
defined('ORG_PATH') or define('ORG_PATH', LIB_PATH.'Org/');
@@ -29,6 +30,14 @@ defined('VENDOR_PATH') or define('VENDOR_PATH', THINK_PATH.'Vendor/');
defined('EXT') or define('EXT', '.php');
defined('APP_DEBUG') or define('APP_DEBUG', false); // 是否调试模式
if(function_exists('saeAutoLoader')){// 自动识别SAE环境
defined('APP_MODE') or define('APP_MODE', 'sae');
defined('STORAGE_TYPE') or define('STORAGE_TYPE', 'Sae');
}else{
defined('APP_MODE') or define('APP_MODE', 'common'); // 应用模式 默认为普通模式
defined('STORAGE_TYPE') or define('STORAGE_TYPE', 'File'); // 存储类型 默认为File
}
// 环境常量
define('MEMORY_LIMIT_ON', function_exists('memory_get_usage'));
define('IS_CGI', strpos(PHP_SAPI, 'cgi') === 0 ? 1 : 0);
@@ -167,7 +176,7 @@ function E($msg, $code=0) {
/**
* 浏览器友好的变量输出
* @param mixed $var 变量
* @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
* @param boolean $echo 是否输出 默认为true 如果为false 则返回输出字符串
* @param string $label 标签 默认为空
* @return void|string
*/
@@ -182,7 +191,7 @@ function dump($var, $echo=true, $label=null) {
* @return void
*/
function W($name, $data=[]) {
echo Think\Loader::action($name,$data,'Widget');
return Think\Loader::action($name,$data,'Widget');
}
/**
@@ -208,9 +217,9 @@ function S($name,$value='',$options=null) {
return $cache->rm($name);
}else { // 缓存数据
if(is_array($options)) {
$expire = isset($options['expire'])?$options['expire']:NULL; //修复查询缓存无法设置过期时间
$expire = isset($options['expire'])?$options['expire']:null; //修复查询缓存无法设置过期时间
}else{
$expire = is_numeric($options)?$options:NULL; //默认快捷缓存设置过期时间
$expire = is_numeric($options)?$options:null; //默认快捷缓存设置过期时间
}
return $cache->set($name, $value, $expire);
}

View File

@@ -14,7 +14,6 @@ return [
'app_debug' => true, // 调试模式
'app_status' => 'debug',// 调试模式状态
'var_module' => 'm', // 模块变量名
'var_group' => 'g', // 分组变量名
'var_controller' => 'c', // 控制器变量名
'var_action' => 'a', // 操作变量名
'var_pathinfo' => 's', // PATHINFO变量名 用于兼容模式
@@ -22,8 +21,6 @@ return [
'pathinfo_depr' => '/', // pathinfo分隔符
'require_module' => true, // 是否显示模块
'default_module' => 'index', // 默认模块名
'require_group' => false, // 控制器是否需要分组
'default_group' => '', // 默认分组名
'require_controller' => true, // 是否显示控制器
'default_controller' => 'index', // 默认控制器名
'default_action' => 'index', // 默认操作名
@@ -38,6 +35,7 @@ return [
'default_ajax_return' => 'JSON', // 默认AJAX 数据返回格式,可选JSON XML ...
'default_jsonp_handler' => 'jsonpReturn', // 默认JSONP格式返回的处理方法
'var_jsonp_handler' => 'callback',
'template_engine' => 'think',
/* 错误设置 */
'error_message' => '页面错误!请稍后再试~',//错误显示信息,非调试模式有效

View File

@@ -21,36 +21,29 @@ require CORE_PATH.'Loader.php';
// 注册自动加载
Loader::register();
// 导入系统别名
Loader::addMap(include THINK_PATH.'alias.php');
// 加载应用类
//require CORE_PATH.'App.php';
// 加载错误类
//require CORE_PATH.'Error.php';
// 注册错误和异常处理机制
register_shutdown_function(['Think\Error','appShutdown']);
set_error_handler(['Think\Error','appError']);
set_exception_handler(['Think\Error','appException']);
// 导入系统惯例
Config::load(THINK_PATH.'convention.php');
// 加载模式定义文件
$mode = require MODE_PATH.APP_MODE.EXT;
// 初始化操作可以在应用的公共文件中处理 下面只是示例
//---------------------------------------------------
// 日志初始化
Log::init(['type'=>'File','log_path'=> LOG_PATH]);
// 缓存初始化
Cache::connect(['type'=>'File','temp'=> CACHE_PATH]);
//------------------------------------------------------
// 启动session
if(!IS_CLI) {
Session::init(['prefix'=>'think','auto_start'=>true]);
// 加载模式配置文件
if(isset($mode['config'])){
is_array($mode['config']) ? Config::set($mode['config']) : Config::load($mode['config']);
}
if(is_file(APP_PATH.'build.php')) { // 自动化创建脚本
Create::build(include APP_PATH.'build.php');
// 加载模式别名定义
if(isset($mode['alias'])){
Loader::addMap(is_array($mode['alias']) ? $mode['alias'] : include $mode['alias']);
}
// 加载模式行为定义
if(isset($mode['tags'])) {
Hook::import(is_array($mode['tags']) ? $mode['tags'] : include $mode['tags']);
}
// 执行应用
App::run();
App::run(Config::get());