code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: amf.php 2504 2011-12-28 07:35:29Z liu21st $
// AMF模式定义文件
return array(
'core' => array(
THINK_PATH.'Common/functions.php', // 系统函数库
CORE_PATH.'Core/Log.class.php',// 日志处理
MODE_PATH.'Amf/App.class.php', // 应用程序类
MODE_PATH.'Amf/Action.class.php',// 控制器类
),
// 项目别名定义文件 [支持数组直接定义或者文件名定义]
'alias' => array(
'Model' => MODE_PATH.'Amf/Model.class.php',
'Db' => MODE_PATH.'Amf/Db.class.php',
),
// 系统行为定义文件 [必须 支持数组直接定义或者文件名定义 ]
'extends' => array(),
// 项目应用行为定义文件 [支持数组直接定义或者文件名定义]
'tags' => array(),
); | 10npsite | trunk/DThinkPHP/Extend/Mode/amf.php | PHP | asf20 | 1,483 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: functions.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* Think 命令行模式公共函数库
+------------------------------------------------------------------------------
* @category Think
* @package Common
* @author liu21st <liu21st@gmail.com>
* @version $Id: functions.php 2702 2012-02-02 12:35:01Z liu21st $
+------------------------------------------------------------------------------
*/
// 错误输出
function halt($error) {
exit($error);
}
// 自定义异常处理
function throw_exception($msg, $type='ThinkException', $code=0) {
halt($msg);
}
// 浏览器友好的变量输出
function dump($var, $echo=true, $label=null, $strict=true) {
$label = ($label === null) ? '' : rtrim($label) . ' ';
if (!$strict) {
if (ini_get('html_errors')) {
$output = print_r($var, true);
$output = "<pre>" . $label . htmlspecialchars($output, ENT_QUOTES) . "</pre>";
} else {
$output = $label . print_r($var, true);
}
} else {
ob_start();
var_dump($var);
$output = ob_get_clean();
if (!extension_loaded('xdebug')) {
$output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
}
}
if ($echo) {
echo($output);
return null;
}else
return $output;
}
// 区间调试开始
function debug_start($label='') {
$GLOBALS[$label]['_beginTime'] = microtime(TRUE);
if (MEMORY_LIMIT_ON)
$GLOBALS[$label]['_beginMem'] = memory_get_usage();
}
// 区间调试结束,显示指定标记到当前位置的调试
function debug_end($label='') {
$GLOBALS[$label]['_endTime'] = microtime(TRUE);
echo '<div style="text-align:center;width:100%">Process ' . $label . ': Times ' . number_format($GLOBALS[$label]['_endTime'] - $GLOBALS[$label]['_beginTime'], 6) . 's ';
if (MEMORY_LIMIT_ON) {
$GLOBALS[$label]['_endMem'] = memory_get_usage();
echo ' Memories ' . number_format(($GLOBALS[$label]['_endMem'] - $GLOBALS[$label]['_beginMem']) / 1024) . ' k';
}
echo '</div>';
}
// 全局缓存设置和读取
function S($name, $value='', $expire='', $type='',$options=null) {
static $_cache = array();
alias_import('Cache');
//取得缓存对象实例
$cache = Cache::getInstance($type,$options);
if ('' !== $value) {
if (is_null($value)) {
// 删除缓存
$result = $cache->rm($name);
if ($result)
unset($_cache[$type . '_' . $name]);
return $result;
}else {
// 缓存数据
$cache->set($name, $value, $expire);
$_cache[$type . '_' . $name] = $value;
}
return;
}
if (isset($_cache[$type . '_' . $name]))
return $_cache[$type . '_' . $name];
// 获取缓存数据
$value = $cache->get($name);
$_cache[$type . '_' . $name] = $value;
return $value;
}
// 快速文件数据读取和保存 针对简单类型数据 字符串、数组
function F($name, $value='', $path=DATA_PATH) {
static $_cache = array();
$filename = $path . $name . '.php';
if ('' !== $value) {
if (is_null($value)) {
// 删除缓存
return unlink($filename);
} else {
// 缓存数据
$dir = dirname($filename);
// 目录不存在则创建
if (!is_dir($dir))
mkdir($dir);
return file_put_contents($filename, strip_whitespace("<?php\nreturn " . var_export($value, true) . ";\n?>"));
}
}
if (isset($_cache[$name]))
return $_cache[$name];
// 获取缓存数据
if (is_file($filename)) {
$value = include $filename;
$_cache[$name] = $value;
} else {
$value = false;
}
return $value;
}
// 取得对象实例 支持调用类的静态方法
function get_instance_of($name, $method='', $args=array()) {
static $_instance = array();
$identify = empty($args) ? $name . $method : $name . $method . to_guid_string($args);
if (!isset($_instance[$identify])) {
if (class_exists($name)) {
$o = new $name();
if (method_exists($o, $method)) {
if (!empty($args)) {
$_instance[$identify] = call_user_func_array(array(&$o, $method), $args);
} else {
$_instance[$identify] = $o->$method();
}
}
else
$_instance[$identify] = $o;
}
else
halt(L('_CLASS_NOT_EXIST_') . ':' . $name);
}
return $_instance[$identify];
}
// 根据PHP各种类型变量生成唯一标识号
function to_guid_string($mix) {
if (is_object($mix) && function_exists('spl_object_hash')) {
return spl_object_hash($mix);
} elseif (is_resource($mix)) {
$mix = get_resource_type($mix) . strval($mix);
} else {
$mix = serialize($mix);
}
return md5($mix);
}
// 加载扩展配置文件
function load_ext_file() {
// 加载自定义外部文件
if(C('LOAD_EXT_FILE')) {
$files = explode(',',C('LOAD_EXT_FILE'));
foreach ($files as $file){
$file = COMMON_PATH.$file.'.php';
if(is_file($file)) include $file;
}
}
// 加载自定义的动态配置文件
if(C('LOAD_EXT_CONFIG')) {
$configs = C('LOAD_EXT_CONFIG');
if(is_string($configs)) $configs = explode(',',$configs);
foreach ($configs as $key=>$config){
$file = CONF_PATH.$config.'.php';
if(is_file($file)) {
is_numeric($key)?C(include $file):C($key,include $file);
}
}
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Cli/functions.php | PHP | asf20 | 6,709 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Log.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* 日志处理类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: Log.class.php 2702 2012-02-02 12:35:01Z liu21st $
+------------------------------------------------------------------------------
*/
class Log {
// 日志级别 从上到下,由低到高
const EMERG = 'EMERG'; // 严重错误: 导致系统崩溃无法使用
const ALERT = 'ALERT'; // 警戒性错误: 必须被立即修改的错误
const CRIT = 'CRIT'; // 临界值错误: 超过临界值的错误,例如一天24小时,而输入的是25小时这样
const ERR = 'ERR'; // 一般错误: 一般性错误
const WARN = 'WARN'; // 警告性错误: 需要发出警告的错误
const NOTICE = 'NOTIC'; // 通知: 程序可以运行但是还不够完美的错误
const INFO = 'INFO'; // 信息: 程序输出信息
const DEBUG = 'DEBUG'; // 调试: 调试信息
const SQL = 'SQL'; // SQL:SQL语句 注意只在调试模式开启时有效
// 日志记录方式
const SYSTEM = 0;
const MAIL = 1;
const TCP = 2;
const FILE = 3;
// 日志信息
static $log = array();
// 日期格式
static $format = '[ c ]';
/**
+----------------------------------------------------------
* 记录日志 并且会过滤未经设置的级别
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $message 日志信息
* @param string $level 日志级别
* @param boolean $record 是否强制记录
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function record($message,$level=self::ERR,$record=false) {
if($record || strpos(C('LOG_RECORD_LEVEL'),$level)) {
$now = date(self::$format);
self::$log[] = "{$now} {$level}: {$message}\r\n";
}
}
/**
+----------------------------------------------------------
* 日志保存
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param integer $type 日志记录方式
* @param string $destination 写入目标
* @param string $extra 额外参数
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function save($type=self::FILE,$destination='',$extra='') {
if(empty($destination))
$destination = LOG_PATH.date('y_m_d').".log";
if(self::FILE == $type) { // 文件方式记录日志信息
//检测日志文件大小,超过配置大小则备份日志文件重新生成
if(is_file($destination) && floor(C('LOG_FILE_SIZE')) <= filesize($destination) )
rename($destination,dirname($destination).'/'.time().'-'.basename($destination));
}
error_log(implode("",self::$log), $type,$destination ,$extra);
// 保存后清空日志缓存
self::$log = array();
//clearstatcache();
}
/**
+----------------------------------------------------------
* 日志直接写入
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $message 日志信息
* @param string $level 日志级别
* @param integer $type 日志记录方式
* @param string $destination 写入目标
* @param string $extra 额外参数
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function write($message,$level=self::ERR,$type=self::FILE,$destination='',$extra='') {
$now = date(self::$format);
if(empty($destination))
$destination = LOG_PATH.date('y_m_d').".log";
if(self::FILE == $type) { // 文件方式记录日志
//检测日志文件大小,超过配置大小则备份日志文件重新生成
if(is_file($destination) && floor(C('LOG_FILE_SIZE')) <= filesize($destination) )
rename($destination,dirname($destination).'/'.time().'-'.basename($destination));
}
error_log("{$now} {$level}: {$message}\r\n", $type,$destination,$extra );
//clearstatcache();
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Cli/Log.class.php | PHP | asf20 | 5,681 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: App.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP 命令模式应用程序类
+------------------------------------------------------------------------------
*/
class App {
/**
+----------------------------------------------------------
* 执行应用程序
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function run() {
if(C('URL_MODEL')==1) {// PATHINFO 模式URL下面 采用 index.php module/action/id/4
$depr = C('URL_PATHINFO_DEPR');
$path = isset($_SERVER['argv'][1])?$_SERVER['argv'][1]:'';
if(!empty($path)) {
$params = explode($depr,trim($path,$depr));
}
// 取得模块和操作名称
define('MODULE_NAME', !empty($params)?array_shift($params):C('DEFAULT_MODULE'));
define('ACTION_NAME', !empty($params)?array_shift($params):C('DEFAULT_ACTION'));
if(count($params)>1) {
// 解析剩余参数 并采用GET方式获取
preg_replace('@(\w+),([^,\/]+)@e', '$_GET[\'\\1\']="\\2";', implode(',',$params));
}
}else{// 默认URL模式 采用 index.php module action id 4
// 取得模块和操作名称
define('MODULE_NAME', isset($_SERVER['argv'][1])?$_SERVER['argv'][1]:C('DEFAULT_MODULE'));
define('ACTION_NAME', isset($_SERVER['argv'][2])?$_SERVER['argv'][2]:C('DEFAULT_ACTION'));
if($_SERVER['argc']>3) {
// 解析剩余参数 并采用GET方式获取
preg_replace('@(\w+),([^,\/]+)@e', '$_GET[\'\\1\']="\\2";', implode(',',array_slice($_SERVER['argv'],3)));
}
}
// 执行操作
$module = A(MODULE_NAME);
if(!$module) {
// 是否定义Empty模块
$module = A("Empty");
if(!$module){
// 模块不存在 抛出异常
throw_exception(L('_MODULE_NOT_EXIST_').MODULE_NAME);
}
}
call_user_func(array(&$module,ACTION_NAME));
// 保存日志记录
if(C('LOG_RECORD')) Log::save();
return ;
}
}; | 10npsite | trunk/DThinkPHP/Extend/Mode/Cli/App.class.php | PHP | asf20 | 3,134 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Db.class.php 2702 2012-02-02 12:35:01Z liu21st $
define('CLIENT_MULTI_RESULTS', 131072);
/**
+------------------------------------------------------------------------------
* ThinkPHP 精简模式数据库中间层实现类 只支持Mysql
+------------------------------------------------------------------------------
*/
class Db {
static private $_instance = null;
// 是否自动释放查询结果
protected $autoFree = false;
// 是否显示调试信息 如果启用会在日志文件记录sql语句
public $debug = false;
// 是否使用永久连接
protected $pconnect = false;
// 当前SQL指令
protected $queryStr = '';
// 最后插入ID
protected $lastInsID = null;
// 返回或者影响记录数
protected $numRows = 0;
// 返回字段数
protected $numCols = 0;
// 事务指令数
protected $transTimes = 0;
// 错误信息
protected $error = '';
// 当前连接ID
protected $linkID = null;
// 当前查询ID
protected $queryID = null;
// 是否已经连接数据库
protected $connected = false;
// 数据库连接参数配置
protected $config = '';
// 数据库表达式
protected $comparison = array('eq'=>'=','neq'=>'!=','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE');
// 查询表达式
protected $selectSql = 'SELECT%DISTINCT% %FIELDS% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT%';
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 数据库配置数组
+----------------------------------------------------------
*/
public function __construct($config=''){
if ( !extension_loaded('mysql') ) {
throw_exception(L('_NOT_SUPPERT_').':mysql');
}
$this->config = $this->parseConfig($config);
if(APP_DEBUG) {
$this->debug = true;
}
}
/**
+----------------------------------------------------------
* 连接数据库方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function connect() {
if(!$this->connected) {
$config = $this->config;
// 处理不带端口号的socket连接情况
$host = $config['hostname'].($config['hostport']?":{$config['hostport']}":'');
$pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;
if($pconnect) {
$this->linkID = mysql_pconnect( $host, $config['username'], $config['password'],CLIENT_MULTI_RESULTS);
}else{
$this->linkID = mysql_connect( $host, $config['username'], $config['password'],true,CLIENT_MULTI_RESULTS);
}
if ( !$this->linkID || (!empty($config['database']) && !mysql_select_db($config['database'], $this->linkID)) ) {
throw_exception(mysql_error());
}
$dbVersion = mysql_get_server_info($this->linkID);
if ($dbVersion >= "4.1") {
//使用UTF8存取数据库 需要mysql 4.1.0以上支持
mysql_query("SET NAMES '".C('DB_CHARSET')."'", $this->linkID);
}
//设置 sql_model
if($dbVersion >'5.0.1'){
mysql_query("SET sql_mode=''",$this->linkID);
}
// 标记连接成功
$this->connected = true;
// 注销数据库连接配置信息
unset($this->config);
}
}
/**
+----------------------------------------------------------
* 释放查询结果
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function free() {
mysql_free_result($this->queryID);
$this->queryID = 0;
}
/**
+----------------------------------------------------------
* 执行查询 主要针对 SELECT, SHOW 等指令
* 返回数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function query($str='') {
$this->connect();
if ( !$this->linkID ) return false;
if ( $str != '' ) $this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) { $this->free(); }
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID = mysql_query($this->queryStr, $this->linkID);
$this->debug();
if ( !$this->queryID ) {
if ( $this->debug )
throw_exception($this->error());
else
return false;
} else {
$this->numRows = mysql_num_rows($this->queryID);
return $this->getAll();
}
}
/**
+----------------------------------------------------------
* 执行语句 针对 INSERT, UPDATE 以及DELETE
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function execute($str='') {
$this->connect();
if ( !$this->linkID ) return false;
if ( $str != '' ) $this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) { $this->free(); }
N('db_write',1);
$result = mysql_query($this->queryStr, $this->linkID) ;
$this->debug();
if ( false === $result) {
if ( $this->debug )
throw_exception($this->error());
else
return false;
} else {
$this->numRows = mysql_affected_rows($this->linkID);
$this->lastInsID = mysql_insert_id($this->linkID);
return $this->numRows;
}
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function startTrans() {
$this->connect(true);
if ( !$this->linkID ) return false;
//数据rollback 支持
if ($this->transTimes == 0) {
mysql_query('START TRANSACTION', $this->linkID);
}
$this->transTimes++;
return ;
}
/**
+----------------------------------------------------------
* 用于非自动提交状态下面的查询提交
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function commit() {
if ($this->transTimes > 0) {
$result = mysql_query('COMMIT', $this->linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
return false;
}
}
return true;
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function rollback() {
if ($this->transTimes > 0) {
$result = mysql_query('ROLLBACK', $this->linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
return false;
}
}
return true;
}
/**
+----------------------------------------------------------
* 获得所有的查询数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function getAll() {
if ( !$this->queryID ) {
throw_exception($this->error());
return false;
}
//返回数据集
$result = array();
if($this->numRows >0) {
while($row = mysql_fetch_assoc($this->queryID)){
$result[] = $row;
}
mysql_data_seek($this->queryID,0);
}
return $result;
}
/**
+----------------------------------------------------------
* 取得数据表的字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function getFields($tableName) {
$result = $this->query('SHOW COLUMNS FROM '.$tableName);
$info = array();
foreach ($result as $key => $val) {
$info[$val['Field']] = array(
'name' => $val['Field'],
'type' => $val['Type'],
'notnull' => (bool) ($val['Null'] === ''), // not null is empty, null is yes
'default' => $val['Default'],
'primary' => (strtolower($val['Key']) == 'pri'),
'autoinc' => (strtolower($val['Extra']) == 'auto_increment'),
);
}
return $info;
}
/**
+----------------------------------------------------------
* 取得数据库的表信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function getTables($dbName='') {
if(!empty($dbName)) {
$sql = 'SHOW TABLES FROM '.$dbName;
}else{
$sql = 'SHOW TABLES ';
}
$result = $this->query($sql);
$info = array();
foreach ($result as $key => $val) {
$info[$key] = current($val);
}
return $info;
}
/**
+----------------------------------------------------------
* 关闭数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function close() {
if (!empty($this->queryID))
mysql_free_result($this->queryID);
if ($this->linkID && !mysql_close($this->linkID)){
throw_exception($this->error());
}
$this->linkID = 0;
}
/**
+----------------------------------------------------------
* 数据库错误信息
* 并显示当前的SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function error() {
$this->error = mysql_error($this->linkID);
if($this->queryStr!=''){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
return $this->error;
}
/**
+----------------------------------------------------------
* SQL指令安全过滤
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str SQL字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function escapeString($str) {
return mysql_escape_string($str);
}
/**
+----------------------------------------------------------
* 析构方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __destruct() {
// 关闭连接
$this->close();
}
/**
+----------------------------------------------------------
* 取得数据库类实例
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return mixed 返回数据库驱动类
+----------------------------------------------------------
*/
public static function getInstance($db_config='') {
if ( self::$_instance==null ){
self::$_instance = new Db($db_config);
}
return self::$_instance;
}
/**
+----------------------------------------------------------
* 分析数据库配置信息,支持数组和DSN
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param mixed $db_config 数据库配置信息
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function parseConfig($db_config='') {
if ( !empty($db_config) && is_string($db_config)) {
// 如果DSN字符串则进行解析
$db_config = $this->parseDSN($db_config);
}else if(empty($db_config)){
// 如果配置为空,读取配置文件设置
$db_config = array (
'dbms' => C('DB_TYPE'),
'username' => C('DB_USER'),
'password' => C('DB_PWD'),
'hostname' => C('DB_HOST'),
'hostport' => C('DB_PORT'),
'database' => C('DB_NAME'),
'dsn' => C('DB_DSN'),
'params' => C('DB_PARAMS'),
);
}
return $db_config;
}
/**
+----------------------------------------------------------
* DSN解析
* 格式: mysql://username:passwd@localhost:3306/DbName
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $dsnStr
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function parseDSN($dsnStr) {
if( empty($dsnStr) ){return false;}
$info = parse_url($dsnStr);
if($info['scheme']){
$dsn = array(
'dbms' => $info['scheme'],
'username' => isset($info['user']) ? $info['user'] : '',
'password' => isset($info['pass']) ? $info['pass'] : '',
'hostname' => isset($info['host']) ? $info['host'] : '',
'hostport' => isset($info['port']) ? $info['port'] : '',
'database' => isset($info['path']) ? substr($info['path'],1) : ''
);
}else {
preg_match('/^(.*?)\:\/\/(.*?)\:(.*?)\@(.*?)\:([0-9]{1, 6})\/(.*?)$/',trim($dsnStr),$matches);
$dsn = array (
'dbms' => $matches[1],
'username' => $matches[2],
'password' => $matches[3],
'hostname' => $matches[4],
'hostport' => $matches[5],
'database' => $matches[6]
);
}
return $dsn;
}
/**
+----------------------------------------------------------
* 数据库调试 记录当前SQL
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
*/
protected function debug() {
// 记录操作结束时间
if ( $this->debug ) {
G('queryEndTime');
Log::record($this->queryStr." [ RunTime:".G('queryStartTime','queryEndTime',6)."s ]",Log::SQL);
}
}
/**
+----------------------------------------------------------
* 设置锁机制
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseLock($lock=false) {
if(!$lock) return '';
if('ORACLE' == $this->dbType) {
return ' FOR UPDATE NOWAIT ';
}
return ' FOR UPDATE ';
}
/**
+----------------------------------------------------------
* set分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseSet($data) {
foreach ($data as $key=>$val){
$value = $this->parseValue($val);
if(is_scalar($value)) // 过滤非标量数据
$set[] = $this->parseKey($key).'='.$value;
}
return ' SET '.implode(',',$set);
}
/**
+----------------------------------------------------------
* value分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $value
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseValue($value) {
if(is_string($value)) {
$value = '\''.$this->escapeString($value).'\'';
}elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){
$value = $this->escapeString($value[1]);
}elseif(is_null($value)){
$value = 'null';
}
return $value;
}
/**
+----------------------------------------------------------
* field分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $fields
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseField($fields) {
if(is_array($fields)) {
// 完善数组方式传字段名的支持
// 支持 'field1'=>'field2' 这样的字段别名定义
$array = array();
foreach ($fields as $key=>$field){
if(!is_numeric($key))
$array[] = $this->parseKey($key).' AS '.$this->parseKey($field);
else
$array[] = $this->parseKey($field);
}
$fieldsStr = implode(',', $array);
}elseif(is_string($fields) && !empty($fields)) {
$fieldsStr = $this->parseKey($fields);
}else{
$fieldsStr = '*';
}
return $fieldsStr;
}
/**
+----------------------------------------------------------
* table分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $table
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseTable($tables) {
if(is_string($tables))
$tables = explode(',',$tables);
array_walk($tables, array(&$this, 'parseKey'));
return implode(',',$tables);
}
/**
+----------------------------------------------------------
* where分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $where
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseWhere($where) {
$whereStr = '';
if(is_string($where)) {
// 直接使用字符串条件
$whereStr = $where;
}else{ // 使用数组条件表达式
if(isset($where['_logic'])) {
// 定义逻辑运算规则 例如 OR XOR AND NOT
$operate = ' '.strtoupper($where['_logic']).' ';
unset($where['_logic']);
}else{
// 默认进行 AND 运算
$operate = ' AND ';
}
foreach ($where as $key=>$val){
$whereStr .= "( ";
if(0===strpos($key,'_')) {
// 解析特殊条件表达式
$whereStr .= $this->parseThinkWhere($key,$val);
}else{
$key = $this->parseKey($key);
if(is_array($val)) {
if(is_string($val[0])) {
if(preg_match('/^(EQ|NEQ|GT|EGT|LT|ELT|NOTLIKE|LIKE)$/i',$val[0])) { // 比较运算
$whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' '.$this->parseValue($val[1]);
}elseif('exp'==strtolower($val[0])){ // 使用表达式
$whereStr .= ' ('.$key.' '.$val[1].') ';
}elseif(preg_match('/IN/i',$val[0])){ // IN 运算
$zone = is_array($val[1])? implode(',',$this->parseValue($val[1])):$val[1];
$whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')';
}elseif(preg_match('/BETWEEN/i',$val[0])){ // BETWEEN运算
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
$whereStr .= ' ('.$key.' BETWEEN '.$data[0].' AND '.$data[1].' )';
}else{
throw_exception(L('_EXPRESS_ERROR_').':'.$val[0]);
}
}else {
$count = count($val);
if(in_array(strtoupper(trim($val[$count-1])),array('AND','OR','XOR'))) {
$rule = strtoupper(trim($val[$count-1]));
$count = $count -1;
}else{
$rule = 'AND';
}
for($i=0;$i<$count;$i++) {
$data = is_array($val[$i])?$val[$i][1]:$val[$i];
if('exp'==strtolower($val[$i][0])) {
$whereStr .= '('.$key.' '.$data.') '.$rule.' ';
}else{
$op = is_array($val[$i])?$this->comparison[strtolower($val[$i][0])]:'=';
$whereStr .= '('.$key.' '.$op.' '.$this->parseValue($data).') '.$rule.' ';
}
}
$whereStr = substr($whereStr,0,-4);
}
}else {
//对字符串类型字段采用模糊匹配
if(C('LIKE_MATCH_FIELDS') && preg_match('/('.C('LIKE_MATCH_FIELDS').')/i',$key)) {
$val = '%'.$val.'%';
$whereStr .= $key." LIKE ".$this->parseValue($val);
}else {
$whereStr .= $key." = ".$this->parseValue($val);
}
}
}
$whereStr .= ' )'.$operate;
}
$whereStr = substr($whereStr,0,-strlen($operate));
}
return empty($whereStr)?'':' WHERE '.$whereStr;
}
/**
+----------------------------------------------------------
* 特殊条件分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $key
* @param mixed $val
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseThinkWhere($key,$val) {
$whereStr = '';
switch($key) {
case '_string':
// 字符串模式查询条件
$whereStr = $val;
break;
case '_complex':
// 复合查询条件
$whereStr = substr($this->parseWhere($val),6);
break;
case '_query':
// 字符串模式查询条件
parse_str($val,$where);
if(isset($where['_logic'])) {
$op = ' '.strtoupper($where['_logic']).' ';
unset($where['_logic']);
}else{
$op = ' AND ';
}
$array = array();
foreach ($where as $field=>$data)
$array[] = $this->parseKey($field).' = '.$this->parseValue($data);
$whereStr = implode($op,$array);
break;
}
return $whereStr;
}
/**
+----------------------------------------------------------
* limit分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $lmit
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseLimit($limit) {
return !empty($limit)? ' LIMIT '.$limit.' ':'';
}
/**
+----------------------------------------------------------
* join分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $join
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseJoin($join) {
$joinStr = '';
if(!empty($join)) {
if(is_array($join)) {
foreach ($join as $key=>$_join){
if(false !== stripos($_join,'JOIN'))
$joinStr .= ' '.$_join;
else
$joinStr .= ' LEFT JOIN ' .$_join;
}
}else{
$joinStr .= ' LEFT JOIN ' .$join;
}
}
return $joinStr;
}
/**
+----------------------------------------------------------
* order分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $order
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseOrder($order) {
return !empty($order)? ' ORDER BY '.$order:'';
}
/**
+----------------------------------------------------------
* group分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $group
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseGroup($group) {
return !empty($group)? ' GROUP BY '.$group:'';
}
/**
+----------------------------------------------------------
* having分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $having
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseHaving($having) {
return !empty($having)? ' HAVING '.$having:'';
}
/**
+----------------------------------------------------------
* distinct分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $distinct
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseDistinct($distinct) {
return !empty($distinct)? ' DISTINCT ' :'';
}
/**
+----------------------------------------------------------
* 插入记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 参数表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function insert($data,$options=array()) {
foreach ($data as $key=>$val){
$value = $this->parseValue($val);
if(is_scalar($value)) { // 过滤非标量数据
$values[] = $value;
$fields[] = $this->parseKey($key);
}
}
$sql = 'INSERT INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')';
$sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 更新记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function update($data,$options) {
$sql = 'UPDATE '
.$this->parseTable($options['table'])
.$this->parseSet($data)
.$this->parseWhere(isset($options['where'])?$options['where']:'')
.$this->parseOrder(isset($options['order'])?$options['order']:'')
.$this->parseLimit(isset($options['limit'])?$options['limit']:'')
.$this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 删除记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function delete($options=array()) {
$sql = 'DELETE FROM '
.$this->parseTable($options['table'])
.$this->parseWhere(isset($options['where'])?$options['where']:'')
.$this->parseOrder(isset($options['order'])?$options['order']:'')
.$this->parseLimit(isset($options['limit'])?$options['limit']:'')
.$this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 查找记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function select($options=array()) {
if(isset($options['page'])) {
// 根据页数计算limit
list($page,$listRows) = explode(',',$options['page']);
$listRows = $listRows?$listRows:($options['limit']?$options['limit']:20);
$offset = $listRows*((int)$page-1);
$options['limit'] = $offset.','.$listRows;
}
$sql = str_replace(
array('%TABLE%','%DISTINCT%','%FIELDS%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%'),
array(
$this->parseTable($options['table']),
$this->parseDistinct(isset($options['distinct'])?$options['distinct']:false),
$this->parseField(isset($options['field'])?$options['field']:'*'),
$this->parseJoin(isset($options['join'])?$options['join']:''),
$this->parseWhere(isset($options['where'])?$options['where']:''),
$this->parseGroup(isset($options['group'])?$options['group']:''),
$this->parseHaving(isset($options['having'])?$options['having']:''),
$this->parseOrder(isset($options['order'])?$options['order']:''),
$this->parseLimit(isset($options['limit'])?$options['limit']:'')
),$this->selectSql);
$sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->query($sql);
}
/**
+----------------------------------------------------------
* 字段和表名添加`
* 保证指令中使用关键字不出错 针对mysql
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $value
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
protected function parseKey(&$value) {
$value = trim($value);
if( false !== strpos($value,' ') || false !== strpos($value,',') || false !== strpos($value,'*') || false !== strpos($value,'(') || false !== strpos($value,'.') || false !== strpos($value,'`')) {
//如果包含* 或者 使用了sql方法 则不作处理
}else{
$value = '`'.$value.'`';
}
return $value;
}
/**
+----------------------------------------------------------
* 获取最近一次查询的sql语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastSql() {
return $this->queryStr;
}
/**
+----------------------------------------------------------
* 获取最近插入的ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastInsID(){
return $this->lastInsID;
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Cli/Db.class.php | PHP | asf20 | 39,553 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Model.class.php 2779 2012-02-24 02:56:57Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP CLI模式Model模型类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: Model.class.php 2779 2012-02-24 02:56:57Z liu21st $
+------------------------------------------------------------------------------
*/
class Model {
// 当前数据库操作对象
protected $db = null;
// 主键名称
protected $pk = 'id';
// 数据表前缀
protected $tablePrefix = '';
// 模型名称
protected $name = '';
// 数据库名称
protected $dbName = '';
// 数据表名(不包含表前缀)
protected $tableName = '';
// 实际数据表名(包含表前缀)
protected $trueTableName ='';
// 最近错误信息
protected $error = '';
// 字段信息
protected $fields = array();
// 数据信息
protected $data = array();
// 查询表达式参数
protected $options = array();
protected $_validate = array(); // 自动验证定义
protected $_auto = array(); // 自动完成定义
// 是否自动检测数据表字段信息
protected $autoCheckFields = true;
// 是否批处理验证
protected $patchValidate = false;
/**
+----------------------------------------------------------
* 架构函数
* 取得DB类的实例对象 字段检查
+----------------------------------------------------------
* @param string $name 模型名称
* @param string $tablePrefix 表前缀
* @param mixed $connection 数据库连接信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($name='',$tablePrefix='',$connection='') {
// 模型初始化
$this->_initialize();
// 获取模型名称
if(!empty($name)) {
if(strpos($name,'.')) { // 支持 数据库名.模型名的 定义
list($this->dbName,$this->name) = explode('.',$name);
}else{
$this->name = $name;
}
}elseif(empty($this->name)){
$this->name = $this->getModelName();
}
if(!empty($tablePrefix)) {
$this->tablePrefix = $tablePrefix;
}
// 设置表前缀
$this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX');
// 数据库初始化操作
// 获取数据库操作对象
// 当前模型有独立的数据库连接信息
$this->db(0,empty($this->connection)?$connection:$this->connection);
// 字段检测
if(!empty($this->name) && $this->autoCheckFields) $this->_checkTableInfo();
}
/**
+----------------------------------------------------------
* 自动检测数据表信息
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function _checkTableInfo() {
// 如果不是Model类 自动记录数据表信息
// 只在第一次执行记录
if(empty($this->fields)) {
// 如果数据表字段没有定义则自动获取
if(C('DB_FIELDS_CACHE')) {
$db = $this->dbName?$this->dbName:C('DB_NAME');
$this->fields = F('_fields/'.$db.'.'.$this->name);
if(!$this->fields) $this->flush();
}else{
// 每次都会读取数据表信息
$this->flush();
}
}
}
/**
+----------------------------------------------------------
* 获取字段信息并缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function flush() {
// 缓存不存在则查询数据表信息
$fields = $this->db->getFields($this->getTableName());
if(!$fields) { // 无法获取字段信息
return false;
}
$this->fields = array_keys($fields);
$this->fields['_autoinc'] = false;
foreach ($fields as $key=>$val){
// 记录字段类型
$type[$key] = $val['type'];
if($val['primary']) {
$this->fields['_pk'] = $key;
if($val['autoinc']) $this->fields['_autoinc'] = true;
}
}
// 记录字段类型信息
if(C('DB_FIELDTYPE_CHECK')) $this->fields['_type'] = $type;
// 2008-3-7 增加缓存开关控制
if(C('DB_FIELDS_CACHE')){
// 永久缓存数据表信息
$db = $this->dbName?$this->dbName:C('DB_NAME');
F('_fields/'.$db.'.'.$this->name,$this->fields);
}
}
/**
+----------------------------------------------------------
* 设置数据对象的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
* @param mixed $value 值
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function __set($name,$value) {
// 设置数据对象属性
$this->data[$name] = $value;
}
/**
+----------------------------------------------------------
* 获取数据对象的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __get($name) {
return isset($this->data[$name])?$this->data[$name]:null;
}
/**
+----------------------------------------------------------
* 检测数据对象的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function __isset($name) {
return isset($this->data[$name]);
}
/**
+----------------------------------------------------------
* 销毁数据对象的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function __unset($name) {
unset($this->data[$name]);
}
/**
+----------------------------------------------------------
* 利用__call方法实现一些特殊的Model方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名称
* @param array $args 调用参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$args) {
if(in_array(strtolower($method),array('table','where','order','limit','page','alias','having','group','lock','distinct'),true)) {
// 连贯操作的实现
$this->options[strtolower($method)] = $args[0];
return $this;
}elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){
// 统计查询的实现
$field = isset($args[0])?$args[0]:'*';
return $this->getField(strtoupper($method).'('.$field.') AS tp_'.$method);
}elseif(strtolower(substr($method,0,5))=='getby') {
// 根据某个字段获取记录
$field = parse_name(substr($method,5));
$where[$field] = $args[0];
return $this->where($where)->find();
}else{
throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
return;
}
}
// 回调方法 初始化模型
protected function _initialize() {}
/**
+----------------------------------------------------------
* 对保存到数据库的数据进行处理
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 要操作的数据
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
protected function _facade($data) {
// 检查非数据字段
if(!empty($this->fields)) {
foreach ($data as $key=>$val){
if(!in_array($key,$this->fields,true)){
unset($data[$key]);
}elseif(C('DB_FIELDTYPE_CHECK') && is_scalar($val)) {
// 字段类型检查
$this->_parseType($data,$key);
}
}
}
return $data;
}
/**
+----------------------------------------------------------
* 新增数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function add($data='',$options=array()) {
if(empty($data)) {
// 没有传递数据,获取当前数据对象的值
if(!empty($this->data)) {
$data = $this->data;
}else{
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
}
// 分析表达式
$options = $this->_parseOptions($options);
// 数据处理
$data = $this->_facade($data);
// 写入数据到数据库
$result = $this->db->insert($data,$options);
if(false !== $result ) {
$insertId = $this->getLastInsID();
if($insertId) {
// 自增主键返回插入ID
return $insertId;
}
}
return $result;
}
/**
+----------------------------------------------------------
* 保存数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function save($data='',$options=array()) {
if(empty($data)) {
// 没有传递数据,获取当前数据对象的值
if(!empty($this->data)) {
$data = $this->data;
}else{
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
}
// 数据处理
$data = $this->_facade($data);
// 分析表达式
$options = $this->_parseOptions($options);
if(!isset($options['where']) ) {
// 如果存在主键数据 则自动作为更新条件
if(isset($data[$this->getPk()])) {
$pk = $this->getPk();
$where[$pk] = $data[$pk];
$options['where'] = $where;
unset($data[$pk]);
}else{
// 如果没有任何更新条件则不执行
$this->error = L('_OPERATION_WRONG_');
return false;
}
}
$result = $this->db->update($data,$options);
return $result;
}
/**
+----------------------------------------------------------
* 删除数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $options 表达式
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function delete($options=array()) {
if(empty($options) && empty($this->options['where'])) {
// 如果删除条件为空 则删除当前数据对象所对应的记录
if(!empty($this->data) && isset($this->data[$this->getPk()]))
return $this->delete($this->data[$this->getPk()]);
else
return false;
}
if(is_numeric($options) || is_string($options)) {
// 根据主键删除记录
$pk = $this->getPk();
if(strpos($options,',')) {
$where[$pk] = array('IN', $options);
}else{
$where[$pk] = $options;
$pkValue = $options;
}
$options = array();
$options['where'] = $where;
}
// 分析表达式
$options = $this->_parseOptions($options);
$result= $this->db->delete($options);
// 返回删除记录个数
return $result;
}
/**
+----------------------------------------------------------
* 查询数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function select($options=array()) {
if(is_string($options) || is_numeric($options)) {
// 根据主键查询
$pk = $this->getPk();
if(strpos($options,',')) {
$where[$pk] = array('IN',$options);
}else{
$where[$pk] = $options;
}
$options = array();
$options['where'] = $where;
}
// 分析表达式
$options = $this->_parseOptions($options);
$resultSet = $this->db->select($options);
if(false === $resultSet) {
return false;
}
if(empty($resultSet)) { // 查询结果为空
return null;
}
return $resultSet;
}
/**
+----------------------------------------------------------
* 分析表达式
+----------------------------------------------------------
* @access proteced
+----------------------------------------------------------
* @param array $options 表达式参数
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function _parseOptions($options=array()) {
if(is_array($options))
$options = array_merge($this->options,$options);
// 查询过后清空sql表达式组装 避免影响下次查询
$this->options = array();
if(!isset($options['table']))
// 自动获取表名
$options['table'] =$this->getTableName();
if(!empty($options['alias'])) {
$options['table'] .= ' '.$options['alias'];
}
// 字段类型验证
if(C('DB_FIELDTYPE_CHECK')) {
if(isset($options['where']) && is_array($options['where'])) {
// 对数组查询条件进行字段类型检查
foreach ($options['where'] as $key=>$val){
if(in_array($key,$this->fields,true) && is_scalar($val)){
$this->_parseType($options['where'],$key);
}
}
}
}
return $options;
}
/**
+----------------------------------------------------------
* 数据类型检测
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 数据
* @param string $key 字段名
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function _parseType(&$data,$key) {
$fieldType = strtolower($this->fields['_type'][$key]);
if(false !== strpos($fieldType,'int')) {
$data[$key] = intval($data[$key]);
}elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){
$data[$key] = floatval($data[$key]);
}elseif(false !== strpos($fieldType,'bool')){
$data[$key] = (bool)$data[$key];
}
}
/**
+----------------------------------------------------------
* 查询数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $options 表达式参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function find($options=array()) {
if(is_numeric($options) || is_string($options)) {
$where[$this->getPk()] =$options;
$options = array();
$options['where'] = $where;
}
// 总是查找一条记录
$options['limit'] = 1;
// 分析表达式
$options = $this->_parseOptions($options);
$resultSet = $this->db->select($options);
if(false === $resultSet) {
return false;
}
if(empty($resultSet)) {// 查询结果为空
return null;
}
$this->data = $resultSet[0];
return $this->data;
}
/**
+----------------------------------------------------------
* 设置记录的某个字段值
* 支持使用数据库字段和方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string|array $field 字段名
* @param string|array $value 字段值
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function setField($field,$value) {
if(is_array($field)) {
$data = $field;
}else{
$data[$field] = $value;
}
return $this->save($data);
}
/**
+----------------------------------------------------------
* 字段值增长
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $field 字段名
* @param integer $step 增长值
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function setInc($field,$step=1) {
return $this->setField($field,array('exp',$field.'+'.$step));
}
/**
+----------------------------------------------------------
* 字段值减少
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $field 字段名
* @param integer $step 减少值
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function setDec($field,$step=1) {
return $this->setField($field,array('exp',$field.'-'.$step));
}
/**
+----------------------------------------------------------
* 获取一条记录的某个字段值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $field 字段名
* @param string $spea 字段数据间隔符号
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function getField($field,$sepa=null) {
$options['field'] = $field;
$options = $this->_parseOptions($options);
if(strpos($field,',')) { // 多字段
$resultSet = $this->db->select($options);
if(!empty($resultSet)) {
$_field = explode(',', $field);
$field = array_keys($resultSet[0]);
$move = $_field[0]==$_field[1]?false:true;
$key = array_shift($field);
$key2 = array_shift($field);
$cols = array();
$count = count($_field);
foreach ($resultSet as $result){
$name = $result[$key];
if($move) { // 删除键值记录
unset($result[$key]);
}
if(2==$count) {
$cols[$name] = $result[$key2];
}else{
$cols[$name] = is_null($sepa)?$result:implode($sepa,$result);
}
}
return $cols;
}
}else{ // 查找一条记录
$options['limit'] = 1;
$result = $this->db->select($options);
if(!empty($result)) {
return reset($result[0]);
}
}
return null;
}
/**
+----------------------------------------------------------
* 创建数据对象 但不保存到数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 创建数据
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function create($data='') {
// 如果没有传值默认取POST数据
if(empty($data)) {
$data = $_POST;
}elseif(is_object($data)){
$data = get_object_vars($data);
}
// 验证数据
if(empty($data) || !is_array($data)) {
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
// 验证完成生成数据对象
if($this->autoCheckFields) { // 开启字段检测 则过滤非法字段数据
$vo = array();
foreach ($this->fields as $key=>$name){
if(substr($key,0,1)=='_') continue;
$val = isset($data[$name])?$data[$name]:null;
//保证赋值有效
if(!is_null($val)){
$vo[$name] = (MAGIC_QUOTES_GPC && is_string($val))? stripslashes($val) : $val;
}
}
}else{
$vo = $data;
}
// 赋值当前数据对象
$this->data = $vo;
// 返回创建的数据以供其他调用
return $vo;
}
/**
+----------------------------------------------------------
* SQL查询
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $sql SQL指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function query($sql) {
if(!empty($sql)) {
if(strpos($sql,'__TABLE__'))
$sql = str_replace('__TABLE__',$this->getTableName(),$sql);
return $this->db->query($sql);
}else{
return false;
}
}
/**
+----------------------------------------------------------
* 执行SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $sql SQL指令
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function execute($sql) {
if(!empty($sql)) {
if(strpos($sql,'__TABLE__'))
$sql = str_replace('__TABLE__',$this->getTableName(),$sql);
return $this->db->execute($sql);
}else {
return false;
}
}
/**
+----------------------------------------------------------
* 切换当前的数据库连接
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param integer $linkNum 连接序号
* @param mixed $config 数据库连接信息
* @param array $params 模型参数
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function db($linkNum,$config='',$params=array()){
static $_db = array();
if(!isset($_db[$linkNum])) {
// 创建一个新的实例
if(!empty($config) && false === strpos($config,'/')) { // 支持读取配置参数
$config = C($config);
}
$_db[$linkNum] = Db::getInstance($config);
}elseif(NULL === $config){
$_db[$linkNum]->close(); // 关闭数据库连接
unset($_db[$linkNum]);
return ;
}
if(!empty($params)) {
if(is_string($params)) parse_str($params,$params);
foreach ($params as $name=>$value){
$this->setProperty($name,$value);
}
}
// 切换数据库连接
$this->db = $_db[$linkNum];
return $this;
}
/**
+----------------------------------------------------------
* 得到当前的数据对象名称
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getModelName() {
if(empty($this->name))
$this->name = substr(get_class($this),0,-5);
return $this->name;
}
/**
+----------------------------------------------------------
* 得到完整的数据表名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getTableName() {
if(empty($this->trueTableName)) {
$tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
if(!empty($this->tableName)) {
$tableName .= $this->tableName;
}else{
$tableName .= parse_name($this->name);
}
$this->trueTableName = strtolower($tableName);
}
return (!empty($this->dbName)?$this->dbName.'.':'').$this->trueTableName;
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function startTrans() {
$this->commit();
$this->db->startTrans();
return ;
}
/**
+----------------------------------------------------------
* 提交事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function commit() {
return $this->db->commit();
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function rollback() {
return $this->db->rollback();
}
/**
+----------------------------------------------------------
* 返回模型的错误信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getError(){
return $this->error;
}
/**
+----------------------------------------------------------
* 返回数据库的错误信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getDbError() {
return $this->db->getError();
}
/**
+----------------------------------------------------------
* 返回最后插入的ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastInsID() {
return $this->db->getLastInsID();
}
/**
+----------------------------------------------------------
* 返回最后执行的sql语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastSql() {
return $this->db->getLastSql();
}
// 鉴于getLastSql比较常用 增加_sql 别名
public function _sql(){
return $this->getLastSql();
}
/**
+----------------------------------------------------------
* 获取主键名称
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getPk() {
return isset($this->fields['_pk'])?$this->fields['_pk']:$this->pk;
}
/**
+----------------------------------------------------------
* 获取数据表字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getDbFields(){
if($this->fields) {
$fields = $this->fields;
unset($fields['_autoinc'],$fields['_pk'],$fields['_type']);
return $fields;
}
return false;
}
/**
+----------------------------------------------------------
* 指定查询字段 支持字段排除
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $field
* @param boolean $except 是否排除
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function field($field,$except=false){
if($except) {// 字段排除
if(is_string($field)) {
$field = explode(',',$field);
}
$fields = $this->getDbFields();
$field = $fields?array_diff($fields,$field):$field;
}
$this->options['field'] = $field;
return $this;
}
/**
+----------------------------------------------------------
* 设置数据对象值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function data($data){
if(is_object($data)){
$data = get_object_vars($data);
}elseif(is_string($data)){
parse_str($data,$data);
}elseif(!is_array($data)){
throw_exception(L('_DATA_TYPE_INVALID_'));
}
$this->data = $data;
return $this;
}
/**
+----------------------------------------------------------
* 查询SQL组装 join
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $join
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function join($join) {
if(is_array($join))
$this->options['join'] = $join;
else
$this->options['join'][] = $join;
return $this;
}
/**
+----------------------------------------------------------
* 查询SQL组装 union
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $union
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function union($union) {
if(empty($union)) return $this;
// 转换union表达式
if($union instanceof Model) {
$options = $union->getProperty('options');
if(!isset($options['table'])){
// 自动获取表名
$options['table'] =$union->getTableName();
}
if(!isset($options['field'])) {
$options['field'] =$this->options['field'];
}
}elseif(is_object($union)) {
$options = get_object_vars($union);
}elseif(!is_array($union)){
throw_exception(L('_DATA_TYPE_INVALID_'));
}
$this->options['union'][] = $options;
return $this;
}
/**
+----------------------------------------------------------
* 设置模型的属性值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
* @param mixed $value 值
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function setProperty($name,$value) {
if(property_exists($this,$name))
$this->$name = $value;
return $this;
}
/**
+----------------------------------------------------------
* 获取模型的属性值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function getProperty($name){
if(property_exists($this,$name))
return $this->$name;
else
return NULL;
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Cli/Model.class.php | PHP | asf20 | 39,481 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Action.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP 命令模式Action控制器基类
+------------------------------------------------------------------------------
*/
abstract class Action {
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct() {
//控制器初始化
if(method_exists($this,'_initialize')) {
$this->_initialize();
}
}
/**
+----------------------------------------------------------
* 魔术方法 有不存在的操作的时候执行
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名
* @param array $parms 参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$parms) {
if(strtolower($method) == strtolower(ACTION_NAME)) {
// 如果定义了_empty操作 则调用
if(method_exists($this,'_empty')) {
$this->_empty($method,$parms);
}else {
// 抛出异常
exit(L('_ERROR_ACTION_').ACTION_NAME);
}
}else{
exit(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
}
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Cli/Action.class.php | PHP | asf20 | 2,363 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: rest.php 2702 2012-02-02 12:35:01Z liu21st $
// REST模式定义文件
return array(
'core' => array(
THINK_PATH.'Common/functions.php', // 标准模式函数库
CORE_PATH.'Core/Log.class.php', // 日志处理类
CORE_PATH.'Core/Dispatcher.class.php', // URL调度类
CORE_PATH.'Core/App.class.php', // 应用程序类
CORE_PATH.'Core/View.class.php', // 视图类
MODE_PATH.'Rest/Action.class.php',// 控制器类
),
// 系统行为定义文件 [必须 支持数组直接定义或者文件名定义 ]
'extends' => MODE_PATH.'Rest/tags.php',
// 模式配置文件 [支持数组直接定义或者文件名定义](如有相同则覆盖项目配置文件中的配置)
'config' => MODE_PATH.'Rest/config.php',
); | 10npsite | trunk/DThinkPHP/Extend/Mode/rest.php | PHP | asf20 | 1,449 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: App.class.php 2504 2011-12-28 07:35:29Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP AMF模式应用程序类
+------------------------------------------------------------------------------
*/
class App {
/**
+----------------------------------------------------------
* 应用程序初始化
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function run() {
//导入类库
Vendor('Zend.Amf.Server');
//实例化AMF
$server = new Zend_Amf_Server();
$actions = explode(',',C('APP_AMF_ACTIONS'));
foreach ($actions as $action)
$server -> setClass($action.'Action');
echo $server -> handle();
// 保存日志记录
if(C('LOG_RECORD')) Log::save();
return ;
}
}; | 10npsite | trunk/DThinkPHP/Extend/Mode/Amf/App.class.php | PHP | asf20 | 1,681 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Db.class.php 2779 2012-02-24 02:56:57Z liu21st $
define('CLIENT_MULTI_RESULTS', 131072);
/**
+------------------------------------------------------------------------------
* ThinkPHP AMF模式数据库中间层实现类 只支持Mysql
+------------------------------------------------------------------------------
*/
class Db {
static private $_instance = null;
// 是否自动释放查询结果
protected $autoFree = false;
// 是否显示调试信息 如果启用会在日志文件记录sql语句
public $debug = false;
// 是否使用永久连接
protected $pconnect = false;
// 当前SQL指令
protected $queryStr = '';
// 最后插入ID
protected $lastInsID = null;
// 返回或者影响记录数
protected $numRows = 0;
// 返回字段数
protected $numCols = 0;
// 事务指令数
protected $transTimes = 0;
// 错误信息
protected $error = '';
// 当前连接ID
protected $linkID = null;
// 当前查询ID
protected $queryID = null;
// 是否已经连接数据库
protected $connected = false;
// 数据库连接参数配置
protected $config = '';
// 数据库表达式
protected $comparison = array('eq'=>'=','neq'=>'!=','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE');
// 查询表达式
protected $selectSql = 'SELECT%DISTINCT% %FIELDS% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT%';
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 数据库配置数组
+----------------------------------------------------------
*/
public function __construct($config=''){
if ( !extension_loaded('mysql') ) {
throw_exception(L('_NOT_SUPPERT_').':mysql');
}
$this->config = $this->parseConfig($config);
}
/**
+----------------------------------------------------------
* 连接数据库方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function connect() {
if(!$this->connected) {
$config = $this->config;
// 处理不带端口号的socket连接情况
$host = $config['hostname'].($config['hostport']?":{$config['hostport']}":'');
if($this->pconnect) {
$this->linkID = mysql_pconnect( $host, $config['username'], $config['password'],CLIENT_MULTI_RESULTS);
}else{
$this->linkID = mysql_connect( $host, $config['username'], $config['password'],true,CLIENT_MULTI_RESULTS);
}
if ( !$this->linkID || (!empty($config['database']) && !mysql_select_db($config['database'], $this->linkID)) ) {
throw_exception(mysql_error());
}
$dbVersion = mysql_get_server_info($this->linkID);
if ($dbVersion >= "4.1") {
//使用UTF8存取数据库 需要mysql 4.1.0以上支持
mysql_query("SET NAMES '".C('DB_CHARSET')."'", $this->linkID);
}
//设置 sql_model
if($dbVersion >'5.0.1'){
mysql_query("SET sql_mode=''",$this->linkID);
}
// 标记连接成功
$this->connected = true;
// 注销数据库连接配置信息
unset($this->config);
}
}
/**
+----------------------------------------------------------
* 释放查询结果
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function free() {
mysql_free_result($this->queryID);
$this->queryID = 0;
}
/**
+----------------------------------------------------------
* 执行查询 主要针对 SELECT, SHOW 等指令
* 返回数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function query($str='') {
$this->connect();
if ( !$this->linkID ) return false;
if ( $str != '' ) $this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) { $this->free(); }
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID = mysql_query($this->queryStr, $this->linkID);
$this->debug();
if ( !$this->queryID ) {
if ( $this->debug )
throw_exception($this->error());
else
return false;
} else {
$this->numRows = mysql_num_rows($this->queryID);
return $this->getAll();
}
}
/**
+----------------------------------------------------------
* 执行语句 针对 INSERT, UPDATE 以及DELETE
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function execute($str='') {
$this->connect();
if ( !$this->linkID ) return false;
if ( $str != '' ) $this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) { $this->free(); }
N('db_write',1);
// 记录开始执行时间
G('queryStartTime');
$result = mysql_query($this->queryStr, $this->linkID) ;
$this->debug();
if ( false === $result) {
if ( $this->debug )
throw_exception($this->error());
else
return false;
} else {
$this->numRows = mysql_affected_rows($this->linkID);
$this->lastInsID = mysql_insert_id($this->linkID);
return $this->numRows;
}
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function startTrans() {
$this->connect(true);
if ( !$this->linkID ) return false;
//数据rollback 支持
if ($this->transTimes == 0) {
mysql_query('START TRANSACTION', $this->linkID);
}
$this->transTimes++;
return ;
}
/**
+----------------------------------------------------------
* 用于非自动提交状态下面的查询提交
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function commit()
{
if ($this->transTimes > 0) {
$result = mysql_query('COMMIT', $this->linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
return false;
}
}
return true;
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function rollback()
{
if ($this->transTimes > 0) {
$result = mysql_query('ROLLBACK', $this->linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
return false;
}
}
return true;
}
/**
+----------------------------------------------------------
* 获得所有的查询数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function getAll() {
if ( !$this->queryID ) {
throw_exception($this->error());
return false;
}
//返回数据集
$result = array();
if($this->numRows >0) {
while($row = mysql_fetch_assoc($this->queryID)){
$result[] = $row;
}
mysql_data_seek($this->queryID,0);
}
return $result;
}
/**
+----------------------------------------------------------
* 取得数据表的字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function getFields($tableName) {
$result = $this->query('SHOW COLUMNS FROM '.$tableName);
$info = array();
foreach ($result as $key => $val) {
$info[$val['Field']] = array(
'name' => $val['Field'],
'type' => $val['Type'],
'notnull' => (bool) ($val['Null'] === ''), // not null is empty, null is yes
'default' => $val['Default'],
'primary' => (strtolower($val['Key']) == 'pri'),
'autoinc' => (strtolower($val['Extra']) == 'auto_increment'),
);
}
return $info;
}
/**
+----------------------------------------------------------
* 取得数据库的表信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function getTables($dbName='') {
if(!empty($dbName)) {
$sql = 'SHOW TABLES FROM '.$dbName;
}else{
$sql = 'SHOW TABLES ';
}
$result = $this->query($sql);
$info = array();
foreach ($result as $key => $val) {
$info[$key] = current($val);
}
return $info;
}
/**
+----------------------------------------------------------
* 关闭数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function close() {
if (!empty($this->queryID))
mysql_free_result($this->queryID);
if ($this->linkID && !mysql_close($this->linkID)){
throw_exception($this->error());
}
$this->linkID = 0;
}
/**
+----------------------------------------------------------
* 数据库错误信息
* 并显示当前的SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function error() {
$this->error = mysql_error($this->linkID);
if($this->queryStr!=''){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
return $this->error;
}
/**
+----------------------------------------------------------
* SQL指令安全过滤
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str SQL字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function escape_string($str) {
return mysql_escape_string($str);
}
/**
+----------------------------------------------------------
* 析构方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __destruct()
{
// 关闭连接
$this->close();
}
/**
+----------------------------------------------------------
* 取得数据库类实例
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return mixed 返回数据库驱动类
+----------------------------------------------------------
*/
public static function getInstance($db_config='')
{
if ( self::$_instance==null ){
self::$_instance = new Db($db_config);
}
return self::$_instance;
}
/**
+----------------------------------------------------------
* 分析数据库配置信息,支持数组和DSN
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param mixed $db_config 数据库配置信息
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function parseConfig($db_config='') {
if ( !empty($db_config) && is_string($db_config)) {
// 如果DSN字符串则进行解析
$db_config = $this->parseDSN($db_config);
}else if(empty($db_config)){
// 如果配置为空,读取配置文件设置
$db_config = array (
'dbms' => C('DB_TYPE'),
'username' => C('DB_USER'),
'password' => C('DB_PWD'),
'hostname' => C('DB_HOST'),
'hostport' => C('DB_PORT'),
'database' => C('DB_NAME'),
'dsn' => C('DB_DSN'),
'params' => C('DB_PARAMS'),
);
}
return $db_config;
}
/**
+----------------------------------------------------------
* DSN解析
* 格式: mysql://username:passwd@localhost:3306/DbName
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $dsnStr
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function parseDSN($dsnStr)
{
if( empty($dsnStr) ){return false;}
$info = parse_url($dsnStr);
if($info['scheme']){
$dsn = array(
'dbms' => $info['scheme'],
'username' => isset($info['user']) ? $info['user'] : '',
'password' => isset($info['pass']) ? $info['pass'] : '',
'hostname' => isset($info['host']) ? $info['host'] : '',
'hostport' => isset($info['port']) ? $info['port'] : '',
'database' => isset($info['path']) ? substr($info['path'],1) : ''
);
}else {
preg_match('/^(.*?)\:\/\/(.*?)\:(.*?)\@(.*?)\:([0-9]{1, 6})\/(.*?)$/',trim($dsnStr),$matches);
$dsn = array (
'dbms' => $matches[1],
'username' => $matches[2],
'password' => $matches[3],
'hostname' => $matches[4],
'hostport' => $matches[5],
'database' => $matches[6]
);
}
return $dsn;
}
/**
+----------------------------------------------------------
* 数据库调试 记录当前SQL
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
*/
protected function debug() {
// 记录操作结束时间
if ( $this->debug ) {
G('queryEndTime');
Log::record($this->queryStr." [ RunTime:".G('queryStartTime','queryEndTime',6)."s ]",Log::SQL);
}
}
/**
+----------------------------------------------------------
* 设置锁机制
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseLock($lock=false) {
if(!$lock) return '';
if('ORACLE' == $this->dbType) {
return ' FOR UPDATE NOWAIT ';
}
return ' FOR UPDATE ';
}
/**
+----------------------------------------------------------
* set分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseSet($data) {
foreach ($data as $key=>$val){
$value = $this->parseValue($val);
if(is_scalar($value)) // 过滤非标量数据
$set[] = $this->parseKey($key).'='.$value;
}
return ' SET '.implode(',',$set);
}
/**
+----------------------------------------------------------
* value分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $value
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseValue($value) {
if(is_string($value)) {
$value = '\''.$this->escape_string($value).'\'';
}elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){
$value = $this->escape_string($value[1]);
}elseif(is_null($value)){
$value = 'null';
}
return $value;
}
/**
+----------------------------------------------------------
* field分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $fields
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseField($fields) {
if(is_array($fields)) {
// 完善数组方式传字段名的支持
// 支持 'field1'=>'field2' 这样的字段别名定义
$array = array();
foreach ($fields as $key=>$field){
if(!is_numeric($key))
$array[] = $this->parseKey($key).' AS '.$this->parseKey($field);
else
$array[] = $this->parseKey($field);
}
$fieldsStr = implode(',', $array);
}elseif(is_string($fields) && !empty($fields)) {
$fieldsStr = $this->parseKey($fields);
}else{
$fieldsStr = '*';
}
return $fieldsStr;
}
/**
+----------------------------------------------------------
* table分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $table
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseTable($tables) {
if(is_string($tables))
$tables = explode(',',$tables);
array_walk($tables, array(&$this, 'parseKey'));
return implode(',',$tables);
}
/**
+----------------------------------------------------------
* where分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $where
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseWhere($where) {
$whereStr = '';
if(is_string($where)) {
// 直接使用字符串条件
$whereStr = $where;
}else{ // 使用数组条件表达式
if(isset($where['_logic'])) {
// 定义逻辑运算规则 例如 OR XOR AND NOT
$operate = ' '.strtoupper($where['_logic']).' ';
unset($where['_logic']);
}else{
// 默认进行 AND 运算
$operate = ' AND ';
}
foreach ($where as $key=>$val){
$whereStr .= "( ";
if(0===strpos($key,'_')) {
// 解析特殊条件表达式
$whereStr .= $this->parseThinkWhere($key,$val);
}else{
$key = $this->parseKey($key);
if(is_array($val)) {
if(is_string($val[0])) {
if(preg_match('/^(EQ|NEQ|GT|EGT|LT|ELT|NOTLIKE|LIKE)$/i',$val[0])) { // 比较运算
$whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' '.$this->parseValue($val[1]);
}elseif('exp'==strtolower($val[0])){ // 使用表达式
$whereStr .= ' ('.$key.' '.$val[1].') ';
}elseif(preg_match('/IN/i',$val[0])){ // IN 运算
$zone = is_array($val[1])? implode(',',$this->parseValue($val[1])):$val[1];
$whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')';
}elseif(preg_match('/BETWEEN/i',$val[0])){ // BETWEEN运算
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
$whereStr .= ' ('.$key.' BETWEEN '.$data[0].' AND '.$data[1].' )';
}else{
throw_exception(L('_EXPRESS_ERROR_').':'.$val[0]);
}
}else {
$count = count($val);
if(in_array(strtoupper(trim($val[$count-1])),array('AND','OR','XOR'))) {
$rule = strtoupper(trim($val[$count-1]));
$count = $count -1;
}else{
$rule = 'AND';
}
for($i=0;$i<$count;$i++) {
$data = is_array($val[$i])?$val[$i][1]:$val[$i];
if('exp'==strtolower($val[$i][0])) {
$whereStr .= '('.$key.' '.$data.') '.$rule.' ';
}else{
$op = is_array($val[$i])?$this->comparison[strtolower($val[$i][0])]:'=';
$whereStr .= '('.$key.' '.$op.' '.$this->parseValue($data).') '.$rule.' ';
}
}
$whereStr = substr($whereStr,0,-4);
}
}else {
//对字符串类型字段采用模糊匹配
if(C('LIKE_MATCH_FIELDS') && preg_match('/('.C('LIKE_MATCH_FIELDS').')/i',$key)) {
$val = '%'.$val.'%';
$whereStr .= $key." LIKE ".$this->parseValue($val);
}else {
$whereStr .= $key." = ".$this->parseValue($val);
}
}
}
$whereStr .= ' )'.$operate;
}
$whereStr = substr($whereStr,0,-strlen($operate));
}
return empty($whereStr)?'':' WHERE '.$whereStr;
}
/**
+----------------------------------------------------------
* 特殊条件分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $key
* @param mixed $val
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseThinkWhere($key,$val) {
$whereStr = '';
switch($key) {
case '_string':
// 字符串模式查询条件
$whereStr = $val;
break;
case '_complex':
// 复合查询条件
$whereStr = substr($this->parseWhere($val),6);
break;
case '_query':
// 字符串模式查询条件
parse_str($val,$where);
if(isset($where['_logic'])) {
$op = ' '.strtoupper($where['_logic']).' ';
unset($where['_logic']);
}else{
$op = ' AND ';
}
$array = array();
foreach ($where as $field=>$data)
$array[] = $this->parseKey($field).' = '.$this->parseValue($data);
$whereStr = implode($op,$array);
break;
}
return $whereStr;
}
/**
+----------------------------------------------------------
* limit分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $lmit
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseLimit($limit) {
return !empty($limit)? ' LIMIT '.$limit.' ':'';
}
/**
+----------------------------------------------------------
* join分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $join
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseJoin($join) {
$joinStr = '';
if(!empty($join)) {
if(is_array($join)) {
foreach ($join as $key=>$_join){
if(false !== stripos($_join,'JOIN'))
$joinStr .= ' '.$_join;
else
$joinStr .= ' LEFT JOIN ' .$_join;
}
}else{
$joinStr .= ' LEFT JOIN ' .$join;
}
}
return $joinStr;
}
/**
+----------------------------------------------------------
* order分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $order
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseOrder($order) {
return !empty($order)? ' ORDER BY '.$order:'';
}
/**
+----------------------------------------------------------
* group分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $group
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseGroup($group)
{
return !empty($group)? ' GROUP BY '.$group:'';
}
/**
+----------------------------------------------------------
* having分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $having
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseHaving($having)
{
return !empty($having)? ' HAVING '.$having:'';
}
/**
+----------------------------------------------------------
* distinct分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $distinct
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseDistinct($distinct) {
return !empty($distinct)? ' DISTINCT ' :'';
}
/**
+----------------------------------------------------------
* 插入记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 参数表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function insert($data,$options=array()) {
foreach ($data as $key=>$val){
$value = $this->parseValue($val);
if(is_scalar($value)) { // 过滤非标量数据
$values[] = $value;
$fields[] = $this->parseKey($key);
}
}
$sql = 'INSERT INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')';
$sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 更新记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function update($data,$options) {
$sql = 'UPDATE '
.$this->parseTable($options['table'])
.$this->parseSet($data)
.$this->parseWhere(isset($options['where'])?$options['where']:'')
.$this->parseOrder(isset($options['order'])?$options['order']:'')
.$this->parseLimit(isset($options['limit'])?$options['limit']:'')
.$this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 删除记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function delete($options=array()) {
$sql = 'DELETE FROM '
.$this->parseTable($options['table'])
.$this->parseWhere(isset($options['where'])?$options['where']:'')
.$this->parseOrder(isset($options['order'])?$options['order']:'')
.$this->parseLimit(isset($options['limit'])?$options['limit']:'')
.$this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 查找记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function select($options=array()) {
if(isset($options['page'])) {
// 根据页数计算limit
list($page,$listRows) = explode(',',$options['page']);
$listRows = $listRows?$listRows:($options['limit']?$options['limit']:20);
$offset = $listRows*((int)$page-1);
$options['limit'] = $offset.','.$listRows;
}
$sql = str_replace(
array('%TABLE%','%DISTINCT%','%FIELDS%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%'),
array(
$this->parseTable($options['table']),
$this->parseDistinct(isset($options['distinct'])?$options['distinct']:false),
$this->parseField(isset($options['field'])?$options['field']:'*'),
$this->parseJoin(isset($options['join'])?$options['join']:''),
$this->parseWhere(isset($options['where'])?$options['where']:''),
$this->parseGroup(isset($options['group'])?$options['group']:''),
$this->parseHaving(isset($options['having'])?$options['having']:''),
$this->parseOrder(isset($options['order'])?$options['order']:''),
$this->parseLimit(isset($options['limit'])?$options['limit']:'')
),$this->selectSql);
$sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->query($sql);
}
/**
+----------------------------------------------------------
* 字段和表名添加`
* 保证指令中使用关键字不出错 针对mysql
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $value
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
protected function parseKey(&$value) {
$value = trim($value);
if( false !== strpos($value,' ') || false !== strpos($value,',') || false !== strpos($value,'*') || false !== strpos($value,'(') || false !== strpos($value,'.') || false !== strpos($value,'`')) {
//如果包含* 或者 使用了sql方法 则不作处理
}else{
$value = '`'.$value.'`';
}
return $value;
}
/**
+----------------------------------------------------------
* 获取最近一次查询的sql语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastSql() {
return $this->queryStr;
}
/**
+----------------------------------------------------------
* 获取最近插入的ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastInsID(){
return $this->lastInsID;
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Amf/Db.class.php | PHP | asf20 | 39,473 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Model.class.php 2779 2012-02-24 02:56:57Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP AMF模式Model模型类
* 只支持CURD和连贯操作 以及常用查询 去掉回调接口
+------------------------------------------------------------------------------
*/
class Model {
// 当前数据库操作对象
protected $db = null;
// 主键名称
protected $pk = 'id';
// 数据表前缀
protected $tablePrefix = '';
// 模型名称
protected $name = '';
// 数据库名称
protected $dbName = '';
// 数据表名(不包含表前缀)
protected $tableName = '';
// 实际数据表名(包含表前缀)
protected $trueTableName ='';
// 数据信息
protected $data = array();
// 查询表达式参数
protected $options = array();
// 最近错误信息
protected $error = '';
/**
+----------------------------------------------------------
* 架构函数
* 取得DB类的实例对象
+----------------------------------------------------------
* @param string $name 模型名称
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($name='') {
// 模型初始化
$this->_initialize();
// 获取模型名称
if(!empty($name)) {
$this->name = $name;
}elseif(empty($this->name)){
$this->name = $this->getModelName();
}
// 数据库初始化操作
import("Db");
// 获取数据库操作对象
$this->db = Db::getInstance(empty($this->connection)?'':$this->connection);
// 设置表前缀
$this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX');
// 字段检测
if(!empty($this->name)) $this->_checkTableInfo();
}
/**
+----------------------------------------------------------
* 自动检测数据表信息
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function _checkTableInfo() {
// 如果不是Model类 自动记录数据表信息
// 只在第一次执行记录
if(empty($this->fields)) {
// 如果数据表字段没有定义则自动获取
if(C('DB_FIELDS_CACHE')) {
$this->fields = F('_fields/'.$this->name);
if(!$this->fields) $this->flush();
}else{
// 每次都会读取数据表信息
$this->flush();
}
}
}
/**
+----------------------------------------------------------
* 获取字段信息并缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function flush() {
// 缓存不存在则查询数据表信息
$fields = $this->db->getFields($this->getTableName());
$this->fields = array_keys($fields);
$this->fields['_autoinc'] = false;
foreach ($fields as $key=>$val){
// 记录字段类型
$type[$key] = $val['type'];
if($val['primary']) {
$this->fields['_pk'] = $key;
if($val['autoinc']) $this->fields['_autoinc'] = true;
}
}
// 记录字段类型信息
if(C('DB_FIELDTYPE_CHECK')) $this->fields['_type'] = $type;
// 2008-3-7 增加缓存开关控制
if(C('DB_FIELDS_CACHE'))
// 永久缓存数据表信息
F('_fields/'.$this->name,$this->fields);
}
// 回调方法 初始化模型
protected function _initialize() {}
/**
+----------------------------------------------------------
* 利用__call方法实现一些特殊的Model方法 (魔术方法)
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名称
* @param array $args 调用参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$args) {
if(in_array(strtolower($method),array('field','table','where','order','limit','page','having','group','lock','distinct'),true)) {
// 连贯操作的实现
$this->options[strtolower($method)] = $args[0];
return $this;
}elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){
// 统计查询的实现
$field = isset($args[0])?$args[0]:'*';
return $this->getField(strtoupper($method).'('.$field.') AS tp_'.$method);
}elseif(strtolower(substr($method,0,5))=='getby') {
// 根据某个字段获取记录
$field = parse_name(substr($method,5));
$options['where'] = $field.'=\''.$args[0].'\'';
return $this->find($options);
}else{
throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
return;
}
}
/**
+----------------------------------------------------------
* 设置数据对象的值 (魔术方法)
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
* @param mixed $value 值
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function __set($name,$value) {
// 设置数据对象属性
$this->data[$name] = $value;
}
/**
+----------------------------------------------------------
* 获取数据对象的值 (魔术方法)
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __get($name) {
return isset($this->data[$name])?$this->data[$name]:null;
}
/**
+----------------------------------------------------------
* 新增数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function add($data='',$options=array()) {
if(empty($data)) {
// 没有传递数据,获取当前数据对象的值
if(!empty($this->data)) {
$data = $this->data;
}else{
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
}
// 分析表达式
$options = $this->_parseOptions($options);
// 写入数据到数据库
$result = $this->db->insert($data,$options);
$insertId = $this->getLastInsID();
if($insertId) {
return $insertId;
}
//成功后返回插入ID
return $result;
}
/**
+----------------------------------------------------------
* 保存数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function save($data='',$options=array()) {
if(empty($data)) {
// 没有传递数据,获取当前数据对象的值
if(!empty($this->data)) {
$data = $this->data;
}else{
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
}
// 分析表达式
$options = $this->_parseOptions($options);
if(!isset($options['where']) ) {
// 如果存在主键数据 则自动作为更新条件
if(isset($data[$this->getPk()])) {
$pk = $this->getPk();
$options['where'] = $pk.'=\''.$data[$pk].'\'';
$pkValue = $data[$pk];
unset($data[$pk]);
}else{
// 如果没有任何更新条件则不执行
$this->error = L('_OPERATION_WRONG_');
return false;
}
}
return $this->db->update($data,$options);
}
/**
+----------------------------------------------------------
* 删除数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $options 表达式
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function delete($options=array()) {
if(empty($options) && empty($this->options['where'])) {
// 如果删除条件为空 则删除当前数据对象所对应的记录
if(!empty($this->data) && isset($this->data[$this->getPk()]))
return $this->delete($this->data[$this->getPk()]);
else
return false;
}
if(is_numeric($options) || is_string($options)) {
// 根据主键删除记录
$pk = $this->getPk();
$where = $pk.'=\''.$options.'\'';
$pkValue = $options;
$options = array();
$options['where'] = $where;
}
// 分析表达式
$options = $this->_parseOptions($options);
return $this->db->delete($options);
}
/**
+----------------------------------------------------------
* 查询数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function select($options=array()) {
// 分析表达式
$options = $this->_parseOptions($options);
$resultSet = $this->db->select($options);
if(empty($resultSet)) { // 查询结果为空
return false;
}
return $resultSet;
}
/**
+----------------------------------------------------------
* 查询数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $options 表达式参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function find($options=array()) {
if(is_numeric($options) || is_string($options)) {
$where = $this->getPk().'=\''.$options.'\'';
$options = array();
$options['where'] = $where;
}
// 总是查找一条记录
$options['limit'] = 1;
// 分析表达式
$options = $this->_parseOptions($options);
$resultSet = $this->db->select($options);
if(empty($resultSet)) {// 查询结果为空
return false;
}
$this->data = $resultSet[0];
return $this->data;
}
/**
+----------------------------------------------------------
* 分析表达式
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $options 表达式参数
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
private function _parseOptions($options) {
if(is_array($options))
$options = array_merge($this->options,$options);
// 查询过后清空sql表达式组装 避免影响下次查询
$this->options = array();
if(!isset($options['table']))
// 自动获取表名
$options['table'] =$this->getTableName();
return $options;
}
/**
+----------------------------------------------------------
* 创建数据对象 但不保存到数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 创建数据
* @param string $type 状态
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function create($data='',$type='') {
// 如果没有传值默认取POST数据
if(empty($data)) {
$data = $_POST;
}elseif(is_object($data)){
$data = get_object_vars($data);
}elseif(!is_array($data)){
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
// 生成数据对象
$vo = array();
foreach ($this->fields as $key=>$name){
if(substr($key,0,1)=='_') continue;
$val = isset($data[$name])?$data[$name]:null;
//保证赋值有效
if(!is_null($val)){
$vo[$name] = (MAGIC_QUOTES_GPC && is_string($val))? stripslashes($val) : $val;
if(C('DB_FIELDTYPE_CHECK')) {
// 字段类型检查
$fieldType = strtolower($this->fields['_type'][$name]);
if(false !== strpos($fieldType,'int')) {
$vo[$name] = intval($vo[$name]);
}elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){
$vo[$name] = floatval($vo[$name]);
}
}
}
}
// 赋值当前数据对象
$this->data = $vo;
// 返回创建的数据以供其他调用
return $vo;
}
/**
+----------------------------------------------------------
* SQL查询
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $sql SQL指令
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function query($sql) {
if(!empty($sql)) {
if(strpos($sql,'__TABLE__'))
$sql = str_replace('__TABLE__',$this->getTableName(),$sql);
return $this->db->query($sql);
}else{
return false;
}
}
/**
+----------------------------------------------------------
* 执行SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $sql SQL指令
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function execute($sql='') {
if(!empty($sql)) {
if(strpos($sql,'__TABLE__'))
$sql = str_replace('__TABLE__',$this->getTableName(),$sql);
return $this->db->execute($sql);
}else {
return false;
}
}
/**
+----------------------------------------------------------
* 得到当前的数据对象名称
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getModelName() {
if(empty($this->name)) {
$this->name = substr(get_class($this),0,-5);
}
return $this->name;
}
/**
+----------------------------------------------------------
* 得到完整的数据表名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getTableName() {
if(empty($this->trueTableName)) {
$tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
if(!empty($this->tableName)) {
$tableName .= $this->tableName;
}else{
$tableName .= parse_name($this->name);
}
if(!empty($this->dbName)) {
$tableName = $this->dbName.'.'.$tableName;
}
$this->trueTableName = strtolower($tableName);
}
return $this->trueTableName;
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function startTrans() {
$this->commit();
$this->db->startTrans();
return ;
}
/**
+----------------------------------------------------------
* 提交事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function commit() {
return $this->db->commit();
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function rollback() {
return $this->db->rollback();
}
/**
+----------------------------------------------------------
* 获取主键名称
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getPk() {
return isset($this->fields['_pk'])?$this->fields['_pk']:$this->pk;
}
/**
+----------------------------------------------------------
* 返回最后执行的sql语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastSql() {
return $this->db->getLastSql();
}
/**
+----------------------------------------------------------
* 返回最后插入的ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastInsID() {
return $this->db->getLastInsID();
}
}; | 10npsite | trunk/DThinkPHP/Extend/Mode/Amf/Model.class.php | PHP | asf20 | 22,108 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Action.class.php 2504 2011-12-28 07:35:29Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP AMF模式Action控制器基类
+------------------------------------------------------------------------------
*/
abstract class Action {
/**
+----------------------------------------------------------
* 魔术方法 有不存在的操作的时候执行
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名
* @param array $parms 参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$parms) {
// 如果定义了_empty操作 则调用
if(method_exists($this,'_empty')) {
$this->_empty($method,$parms);
}
}
}//类定义结束
?> | 10npsite | trunk/DThinkPHP/Extend/Mode/Amf/Action.class.php | PHP | asf20 | 1,664 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CheckUrlExtBehavior.class.php 2807 2012-03-08 03:23:57Z liu21st $
/**
+------------------------------------------------------------------------------
* 行为扩展 URL资源类型检测
+------------------------------------------------------------------------------
*/
class CheckUrlExtBehavior extends Behavior {
/**
+----------------------------------------------------------
* 检测URL地址中资源扩展
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function run(&$params) {
// 获取资源类型
if(!empty($_SERVER['PATH_INFO'])) {
$part = pathinfo($_SERVER['PATH_INFO']);
if(isset($part['extension'])) { // 判断扩展名
define('__EXT__', strtolower($part['extension']));
$_SERVER['PATH_INFO'] = preg_replace('/.'.__EXT__.'$/i','',$_SERVER['PATH_INFO']);
}
}
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Rest/Behavior/CheckUrlExtBehavior.class.php | PHP | asf20 | 1,750 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: CheckRestRouteBehavior.class.php 2732 2012-02-14 04:36:48Z liu21st $
/**
+------------------------------------------------------------------------------
* 系统行为扩展 REST路由检测
+------------------------------------------------------------------------------
*/
class CheckRestRouteBehavior extends Behavior {
// 行为参数定义(默认值) 可在项目配置中覆盖
protected $options = array(
'URL_ROUTER_ON' => false, // 是否开启URL路由
'URL_ROUTE_RULES' => array(), // 默认路由规则,注:分组配置无法替代
);
/**
+----------------------------------------------------------
* 路由检测
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function run(&$return) {
$regx = trim($_SERVER['PATH_INFO'],'/');
// 是否开启路由使用
if(empty($regx) || !C('URL_ROUTER_ON')) $return = false;
// 路由定义文件优先于config中的配置定义
$routes = C('URL_ROUTE_RULES');
if(is_array(C('routes'))) $routes = C('routes');
// 路由处理
if(!empty($routes)) {
$depr = C('URL_PATHINFO_DEPR');
foreach ($routes as $key=>$route){
// 定义格式: array('路由规则或者正则','路由地址','路由参数','提交类型','资源类型')
if(isset($route[3]) && strtolower($_SERVER['REQUEST_METHOD']) != strtolower($route[3])) {
continue; // 如果设置了提交类型则过滤
}
if(isset($route[4]) && !in_array(__EXT__,explode(',',$route[4]),true)) {
continue; // 如果设置了扩展名则过滤
}
if(0===strpos($route[0],'/') && preg_match($route[0],$regx,$matches)) { // 正则路由
return self::parseRegex($matches,$route,$regx);
}else{ // 规则路由
$len1= substr_count($regx,'/');
$len2 = substr_count($route[0],'/');
if($len1>=$len2) {
if('$' == substr($route[0],-1,1)) {// 完整匹配
if($len1 != $len2) {
continue;
}else{
$route[0] = substr($route[0],0,-1);
}
}
$match = self::checkUrlMatch($regx,$route[0]);
if($match) return $return = self::parseRule($route,$regx);
}
}
}
}
$return = false;
}
// 检测URL和规则路由是否匹配
static private function checkUrlMatch($regx,$rule) {
$m1 = explode('/',$regx);
$m2 = explode('/',$rule);
$match = true; // 是否匹配
foreach ($m2 as $key=>$val){
if(':' == substr($val,0,1)) {// 动态变量
if(strpos($val,'\\')) {
$type = substr($val,-1);
if('d'==$type && !is_numeric($m1[$key])) {
$match = false;
break;
}
}elseif(strpos($val,'^')){
$array = explode('|',substr(strstr($val,'^'),1));
if(in_array($m1[$key],$array)) {
$match = false;
break;
}
}
}elseif(0 !== strcasecmp($val,$m1[$key])){
$match = false;
break;
}
}
return $match;
}
static private function parseUrl($url) {
$var = array();
if(false !== strpos($url,'?')) { // [分组/模块/操作?]参数1=值1&参数2=值2...
$info = parse_url($url);
$path = explode('/',$info['path']);
parse_str($info['query'],$var);
}elseif(strpos($url,'/')){ // [分组/模块/操作]
$path = explode('/',$url);
}else{ // 参数1=值1&参数2=值2...
parse_str($url,$var);
}
if(isset($path)) {
$var[C('VAR_ACTION')] = array_pop($path);
if(!empty($path)) {
$var[C('VAR_MODULE')] = array_pop($path);
}
if(!empty($path)) {
$var[C('VAR_GROUP')] = array_pop($path);
}
}
return $var;
}
// 解析规则路由
// array('路由规则','[分组/模块/操作]','额外参数1=值1&额外参数2=值2...','请求类型','资源类型')
// array('路由规则','外部地址','重定向代码','请求类型','资源类型')
// 路由规则中 :开头 表示动态变量
// 外部地址中可以用动态变量 采用 :1 :2 的方式
// array('news/:month/:day/:id','News/read?cate=1','status=1','post','html,xml'),
// array('new/:id','/new.php?id=:1',301,'get','xml'), 重定向
static private function parseRule($route,$regx) {
// 获取路由地址规则
$url = $route[1];
// 获取URL地址中的参数
$paths = explode('/',$regx);
// 解析路由规则
$matches = array();
$rule = explode('/',$route[0]);
foreach ($rule as $item){
if(0===strpos($item,':')) { // 动态变量获取
if($pos = strpos($item,'^') ) {
$var = substr($item,1,$pos-1);
}elseif(strpos($item,'\\')){
$var = substr($item,1,-2);
}else{
$var = substr($item,1);
}
$matches[$var] = array_shift($paths);
}else{ // 过滤URL中的静态变量
array_shift($paths);
}
}
if(0=== strpos($url,'/') || 0===strpos($url,'http')) { // 路由重定向跳转
if(strpos($url,':')) { // 传递动态参数
$values = array_values($matches);
$url = preg_replace('/:(\d)/e','$values[\\1-1]',$url);
}
header("Location: $url", true,isset($route[2])?$route[2]:301);
exit;
}else{
// 解析路由地址
$var = self::parseUrl($url);
// 解析路由地址里面的动态参数
$values = array_values($matches);
foreach ($var as $key=>$val){
if(0===strpos($val,':')) {
$var[$key] = $values[substr($val,1)-1];
}
}
$var = array_merge($matches,$var);
// 解析剩余的URL参数
if($paths) {
preg_replace('@(\w+)\/([^,\/]+)@e', '$var[strtolower(\'\\1\')]="\\2";', implode('/',$paths));
}
// 解析路由自动传人参数
if(isset($route[2])) {
parse_str($route[2],$params);
$var = array_merge($var,$params);
}
$_GET = array_merge($var,$_GET);
}
return true;
}
// 解析正则路由
// array('路由正则','[分组/模块/操作]?参数1=值1&参数2=值2...','额外参数','请求类型','资源类型')
// array('路由正则','外部地址','重定向代码','请求类型','资源类型')
// 参数值和外部地址中可以用动态变量 采用 :1 :2 的方式
// array('/new\/(\d+)\/(\d+)/','News/read?id=:1&page=:2&cate=1','status=1','post','html,xml'),
// array('/new\/(\d+)/','/new.php?id=:1&page=:2&status=1','301','get','html,xml'), 重定向
static private function parseRegex($matches,$route,$regx) {
// 获取路由地址规则
$url = preg_replace('/:(\d)/e','$matches[\\1]',$route[1]);
if(0=== strpos($url,'/') || 0===strpos($url,'http')) { // 路由重定向跳转
header("Location: $url", true,isset($route[1])?$route[2]:301);
exit;
}else{
// 解析路由地址
$var = self::parseUrl($url);
// 解析剩余的URL参数
$regx = substr_replace($regx,'',0,strlen($matches[0]));
if($regx) {
preg_replace('@(\w+)\/([^,\/]+)@e', '$var[strtolower(\'\\1\')]="\\2";', $regx);
}
// 解析路由自动传人参数
if(isset($route[2])) {
parse_str($route[2],$params);
$var = array_merge($var,$params);
}
$_GET = array_merge($var,$_GET);
}
return true;
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Rest/Behavior/CheckRestRouteBehavior.class.php | PHP | asf20 | 9,620 |
<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: config.php 2668 2012-01-26 13:07:16Z liu21st $
return array(
'REST_METHOD_LIST' => 'get,post,put,delete', // 允许的请求类型列表
'REST_DEFAULT_METHOD' => 'get', // 默认请求类型
'REST_CONTENT_TYPE_LIST' => 'html,xml,json,rss', // REST允许请求的资源类型列表
'REST_DEFAULT_TYPE' => 'html', // 默认的资源类型
'REST_OUTPUT_TYPE' => array( // REST允许输出的资源类型列表
'xml' => 'application/xml',
'json' => 'application/json',
'html' => 'text/html',
),
); | 10npsite | trunk/DThinkPHP/Extend/Mode/Rest/config.php | PHP | asf20 | 1,212 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: tags.php 2802 2012-03-06 06:19:07Z liu21st $
// Rest 系统行为扩展列表文件
return array(
'app_begin'=>array(
'ReadHtmlCache', // 读取静态缓存
),
'route_check'=>array(
'CheckRestRoute', // 路由检测
),
'view_end'=>array(
'ShowPageTrace', // 页面Trace显示
),
'view_template'=>array(
'LocationTemplate', // 自动定位模板文件
),
'view_parse'=>array(
'ParseTemplate', // 模板解析 支持PHP、内置模板引擎和第三方模板引擎
),
'view_filter'=>array(
'ContentReplace', // 模板输出替换
'TokenBuild', // 表单令牌
'WriteHtmlCache', // 写入静态缓存
'ShowRuntime', // 运行时间显示
),
'path_info'=>array(
'CheckUrlExt'
),
); | 10npsite | trunk/DThinkPHP/Extend/Mode/Rest/tags.php | PHP | asf20 | 1,460 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Action.class.php 2832 2012-03-21 01:05:36Z huangdijia $
/**
+------------------------------------------------------------------------------
* ThinkPHP RESTFul 控制器基类 抽象类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: Action.class.php 2832 2012-03-21 01:05:36Z huangdijia $
+------------------------------------------------------------------------------
*/
abstract class Action {
// 当前Action名称
private $name = '';
// 视图实例
protected $view = null;
protected $_method = ''; // 当前请求类型
protected $_type = ''; // 当前资源类型
// 输出类型
protected $_types = array();
/**
+----------------------------------------------------------
* 架构函数 取得模板对象实例
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct() {
//实例化视图类
$this->view = Think::instance('View');
defined('__EXT__') or define('__EXT__','');
if(''== __EXT__ || false === stripos(C('REST_CONTENT_TYPE_LIST'),__EXT__)) {
// 资源类型没有指定或者非法 则用默认资源类型访问
$this->_type = C('REST_DEFAULT_TYPE');
}else{
$this->_type = __EXT__;
}
// 请求方式检测
$method = strtolower($_SERVER['REQUEST_METHOD']);
if(false === stripos(C('REST_METHOD_LIST'),$method)) {
// 请求方式非法 则用默认请求方法
$method = C('REST_DEFAULT_METHOD');
}
$this->_method = $method;
// 允许输出的资源类型
$this->_types = C('REST_OUTPUT_TYPE');
//控制器初始化
if(method_exists($this,'_initialize'))
$this->_initialize();
}
/**
+----------------------------------------------------------
* 获取当前Action名称
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
*/
protected function getActionName() {
if(empty($this->name)) {
// 获取Action名称
$this->name = substr(get_class($this),0,-6);
}
return $this->name;
}
/**
+----------------------------------------------------------
* 是否AJAX请求
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return bool
+----------------------------------------------------------
*/
protected function isAjax() {
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) ) {
if('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH']))
return true;
}
if(!empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')]))
// 判断Ajax方式提交
return true;
return false;
}
/**
+----------------------------------------------------------
* 魔术方法 有不存在的操作的时候执行
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名
* @param array $args 参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$args) {
if( 0 === strcasecmp($method,ACTION_NAME)) {
if(method_exists($this,$method.'_'.$this->_method.'_'.$this->_type)) { // RESTFul方法支持
$fun = $method.'_'.$this->_method.'_'.$this->_type;
$this->$fun();
}elseif($this->_method == C('REST_DEFAULT_METHOD') && method_exists($this,$method.'_'.$this->_type) ){
$fun = $method.'_'.$this->_type;
$this->$fun();
}elseif($this->_type == C('REST_DEFAULT_TYPE') && method_exists($this,$method.'_'.$this->_method) ){
$fun = $method.'_'.$this->_method;
$this->$fun();
}elseif(method_exists($this,'_empty')) {
// 如果定义了_empty操作 则调用
$this->_empty($method,$args);
}elseif(file_exists_case(C('TMPL_FILE_NAME'))){
// 检查是否存在默认模版 如果有直接输出模版
$this->display();
}else{
// 抛出异常
throw_exception(L('_ERROR_ACTION_').ACTION_NAME);
}
}else{
switch(strtolower($method)) {
// 获取变量 支持过滤和默认值 调用方式 $this->_post($key,$filter,$default);
case '_get': $input =& $_GET;break;
case '_post':$input =& $_POST;break;
case '_put':
case '_delete':parse_str(file_get_contents('php://input'), $input);break;
case '_request': $input =& $_REQUEST;break;
case '_session': $input =& $_SESSION;break;
case '_cookie': $input =& $_COOKIE;break;
case '_server': $input =& $_SERVER;break;
default:
throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
}
if(isset($input[$args[0]])) { // 取值操作
$data = $input[$args[0]];
$fun = $args[1]?$args[1]:C('DEFAULT_FILTER');
$data = $fun($data); // 参数过滤
}else{ // 变量默认值
$data = isset($args[2])?$args[2]:NULL;
}
return $data;
}
}
/**
+----------------------------------------------------------
* 模板显示
* 调用内置的模板引擎显示方法,
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $templateFile 指定要调用的模板文件
* 默认为空 由系统自动定位模板文件
* @param string $charset 输出编码
* @param string $contentType 输出类型
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function display($templateFile='',$charset='',$contentType='') {
$this->view->display($templateFile,$charset,$contentType);
}
/**
+----------------------------------------------------------
* 模板变量赋值
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $name 要显示的模板变量
* @param mixed $value 变量的值
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function assign($name,$value='') {
$this->view->assign($name,$value);
}
public function __set($name,$value) {
$this->view->assign($name,$value);
}
/**
+----------------------------------------------------------
* 设置页面输出的CONTENT_TYPE和编码
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $type content_type 类型对应的扩展名
* @param string $charset 页面输出编码
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function setContentType($type, $charset=''){
if(headers_sent()) return;
if(empty($charset)) $charset = C('DEFAULT_CHARSET');
$type = strtolower($type);
if(isset($this->_types[$type])) //过滤content_type
header('Content-Type: '.$this->_types[$type].'; charset='.$charset);
}
/**
+----------------------------------------------------------
* 输出返回数据
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 要返回的数据
* @param String $type 返回类型 JSON XML
* @param integer $code HTTP状态
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function response($data,$type='',$code=200) {
$this->sendHttpStatus($code);
exit($this->encodeData($data,strtolower($type)));
}
/**
+----------------------------------------------------------
* 编码数据
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 要返回的数据
* @param String $type 返回类型 JSON XML
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function encodeData($data,$type='') {
if(empty($data)) return '';
if(empty($type)) $type = $this->_type;
if('json' == $type) {
// 返回JSON数据格式到客户端 包含状态信息
$data = json_encode($data);
}elseif('xml' == $type){
// 返回xml格式数据
$data = xml_encode($data);
}elseif('php'==$type){
$data = serialize($data);
}// 默认直接输出
$this->setContentType($type);
header('Content-Length: ' . strlen($data));
return $data;
}
// 发送Http状态信息
protected function sendHttpStatus($code) {
static $_status = array(
// Informational 1xx
100 => 'Continue',
101 => 'Switching Protocols',
// Success 2xx
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
// Redirection 3xx
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Moved Temporarily ', // 1.1
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
// 306 is deprecated but reserved
307 => 'Temporary Redirect',
// Client Error 4xx
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
// Server Error 5xx
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
509 => 'Bandwidth Limit Exceeded'
);
if(isset($_status[$code])) {
header('HTTP/1.1 '.$code.' '.$_status[$code]);
// 确保FastCGI模式下正常
header('Status:'.$code.' '.$_status[$code]);
}
}
/**
+----------------------------------------------------------
* 析构方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __destruct() {
// 保存日志
if(C('LOG_RECORD')) Log::save();
// 执行后续操作
tag('action_end');
}
}
| 10npsite | trunk/DThinkPHP/Extend/Mode/Rest/Action.class.php | PHP | asf20 | 13,758 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: cli.php 2702 2012-02-02 12:35:01Z liu21st $
// 命令行模式定义文件
return array(
'core' => array(
MODE_PATH.'Cli/functions.php', // 命令行系统函数库
MODE_PATH.'Cli/Log.class.php',
MODE_PATH.'Cli/App.class.php',
MODE_PATH.'Cli/Action.class.php',
),
// 项目别名定义文件 [支持数组直接定义或者文件名定义]
'alias' => array(
'Model' => MODE_PATH.'Cli/Model.class.php',
'Db' => MODE_PATH.'Cli/Db.class.php',
'Cache' => CORE_PATH.'Core/Cache.class.php',
'Debug' => CORE_PATH.'Util/Debug.class.php',
),
// 系统行为定义文件 [必须 支持数组直接定义或者文件名定义 ]
'extends' => array(),
// 项目应用行为定义文件 [支持数组直接定义或者文件名定义]
'tags' => array(),
); | 10npsite | trunk/DThinkPHP/Extend/Mode/cli.php | PHP | asf20 | 1,560 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: App.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP 应用程序类 精简模式
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: App.class.php 2702 2012-02-02 12:35:01Z liu21st $
+------------------------------------------------------------------------------
*/
class App {
/**
+----------------------------------------------------------
* 运行应用实例 入口文件使用的快捷方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function run() {
// 设置系统时区
date_default_timezone_set(C('DEFAULT_TIMEZONE'));
// 加载动态项目公共文件和配置
load_ext_file();
// 项目初始化标签
tag('app_init');
// URL调度
Dispatcher::dispatch();
// 项目开始标签
tag('app_begin');
// Session初始化 支持其他客户端
if(isset($_REQUEST[C("VAR_SESSION_ID")]))
session_id($_REQUEST[C("VAR_SESSION_ID")]);
if(C('SESSION_AUTO_START')) session_start();
// 记录应用初始化时间
if(C('SHOW_RUN_TIME')) G('initTime');
App::exec();
// 项目结束标签
tag('app_end');
// 保存日志记录
if(C('LOG_RECORD')) Log::save();
return ;
}
/**
+----------------------------------------------------------
* 执行应用程序
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
static public function exec() {
// 安全检测
if(!preg_match('/^[A-Za-z_0-9]+$/',MODULE_NAME)){
throw_exception(L('_MODULE_NOT_EXIST_'));
}
//创建Action控制器实例
$group = defined('GROUP_NAME') ? GROUP_NAME.'/' : '';
$module = A($group.MODULE_NAME);
if(!$module) {
// 是否定义Empty模块
$module = A("Empty");
if(!$module)
// 模块不存在 抛出异常
throw_exception(L('_MODULE_NOT_EXIST_').MODULE_NAME);
}
//执行当前操作
call_user_func(array(&$module,ACTION_NAME));
return ;
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Lite/App.class.php | PHP | asf20 | 3,552 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Db.class.php 2702 2012-02-02 12:35:01Z liu21st $
define('CLIENT_MULTI_RESULTS', 131072);
/**
+------------------------------------------------------------------------------
* ThinkPHP 精简模式数据库中间层实现类 只支持Mysql
+------------------------------------------------------------------------------
*/
class Db {
static private $_instance = null;
// 是否自动释放查询结果
protected $autoFree = false;
// 是否显示调试信息 如果启用会在日志文件记录sql语句
public $debug = false;
// 是否使用永久连接
protected $pconnect = false;
// 当前SQL指令
protected $queryStr = '';
// 最后插入ID
protected $lastInsID = null;
// 返回或者影响记录数
protected $numRows = 0;
// 返回字段数
protected $numCols = 0;
// 事务指令数
protected $transTimes = 0;
// 错误信息
protected $error = '';
// 当前连接ID
protected $linkID = null;
// 当前查询ID
protected $queryID = null;
// 是否已经连接数据库
protected $connected = false;
// 数据库连接参数配置
protected $config = '';
// 数据库表达式
protected $comparison = array('eq'=>'=','neq'=>'!=','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE');
// 查询表达式
protected $selectSql = 'SELECT%DISTINCT% %FIELDS% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT%';
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 数据库配置数组
+----------------------------------------------------------
*/
public function __construct($config=''){
if ( !extension_loaded('mysql') ) {
throw_exception(L('_NOT_SUPPERT_').':mysql');
}
$this->config = $this->parseConfig($config);
if(APP_DEBUG) {
$this->debug = true;
}
}
/**
+----------------------------------------------------------
* 连接数据库方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function connect() {
if(!$this->connected) {
$config = $this->config;
// 处理不带端口号的socket连接情况
$host = $config['hostname'].($config['hostport']?":{$config['hostport']}":'');
$pconnect = !empty($config['params']['persist'])? $config['params']['persist']:$this->pconnect;
if($pconnect) {
$this->linkID = mysql_pconnect( $host, $config['username'], $config['password'],CLIENT_MULTI_RESULTS);
}else{
$this->linkID = mysql_connect( $host, $config['username'], $config['password'],true,CLIENT_MULTI_RESULTS);
}
if ( !$this->linkID || (!empty($config['database']) && !mysql_select_db($config['database'], $this->linkID)) ) {
throw_exception(mysql_error());
}
$dbVersion = mysql_get_server_info($this->linkID);
if ($dbVersion >= "4.1") {
//使用UTF8存取数据库 需要mysql 4.1.0以上支持
mysql_query("SET NAMES '".C('DB_CHARSET')."'", $this->linkID);
}
//设置 sql_model
if($dbVersion >'5.0.1'){
mysql_query("SET sql_mode=''",$this->linkID);
}
// 标记连接成功
$this->connected = true;
// 注销数据库连接配置信息
unset($this->config);
}
}
/**
+----------------------------------------------------------
* 释放查询结果
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function free() {
mysql_free_result($this->queryID);
$this->queryID = 0;
}
/**
+----------------------------------------------------------
* 执行查询 主要针对 SELECT, SHOW 等指令
* 返回数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function query($str='') {
$this->connect();
if ( !$this->linkID ) return false;
if ( $str != '' ) $this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) { $this->free(); }
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID = mysql_query($this->queryStr, $this->linkID);
$this->debug();
if ( !$this->queryID ) {
if ( $this->debug )
throw_exception($this->error());
else
return false;
} else {
$this->numRows = mysql_num_rows($this->queryID);
return $this->getAll();
}
}
/**
+----------------------------------------------------------
* 执行语句 针对 INSERT, UPDATE 以及DELETE
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function execute($str='') {
$this->connect();
if ( !$this->linkID ) return false;
if ( $str != '' ) $this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) { $this->free(); }
N('db_write',1);
$result = mysql_query($this->queryStr, $this->linkID) ;
$this->debug();
if ( false === $result) {
if ( $this->debug )
throw_exception($this->error());
else
return false;
} else {
$this->numRows = mysql_affected_rows($this->linkID);
$this->lastInsID = mysql_insert_id($this->linkID);
return $this->numRows;
}
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function startTrans() {
$this->connect(true);
if ( !$this->linkID ) return false;
//数据rollback 支持
if ($this->transTimes == 0) {
mysql_query('START TRANSACTION', $this->linkID);
}
$this->transTimes++;
return ;
}
/**
+----------------------------------------------------------
* 用于非自动提交状态下面的查询提交
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function commit() {
if ($this->transTimes > 0) {
$result = mysql_query('COMMIT', $this->linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
return false;
}
}
return true;
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function rollback() {
if ($this->transTimes > 0) {
$result = mysql_query('ROLLBACK', $this->linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
return false;
}
}
return true;
}
/**
+----------------------------------------------------------
* 获得所有的查询数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function getAll() {
if ( !$this->queryID ) {
throw_exception($this->error());
return false;
}
//返回数据集
$result = array();
if($this->numRows >0) {
while($row = mysql_fetch_assoc($this->queryID)){
$result[] = $row;
}
mysql_data_seek($this->queryID,0);
}
return $result;
}
/**
+----------------------------------------------------------
* 取得数据表的字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function getFields($tableName) {
$result = $this->query('SHOW COLUMNS FROM '.$tableName);
$info = array();
foreach ($result as $key => $val) {
$info[$val['Field']] = array(
'name' => $val['Field'],
'type' => $val['Type'],
'notnull' => (bool) ($val['Null'] === ''), // not null is empty, null is yes
'default' => $val['Default'],
'primary' => (strtolower($val['Key']) == 'pri'),
'autoinc' => (strtolower($val['Extra']) == 'auto_increment'),
);
}
return $info;
}
/**
+----------------------------------------------------------
* 取得数据库的表信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function getTables($dbName='') {
if(!empty($dbName)) {
$sql = 'SHOW TABLES FROM '.$dbName;
}else{
$sql = 'SHOW TABLES ';
}
$result = $this->query($sql);
$info = array();
foreach ($result as $key => $val) {
$info[$key] = current($val);
}
return $info;
}
/**
+----------------------------------------------------------
* 关闭数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function close() {
if (!empty($this->queryID))
mysql_free_result($this->queryID);
if ($this->linkID && !mysql_close($this->linkID)){
throw_exception($this->error());
}
$this->linkID = 0;
}
/**
+----------------------------------------------------------
* 数据库错误信息
* 并显示当前的SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function error() {
$this->error = mysql_error($this->linkID);
if($this->queryStr!=''){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
return $this->error;
}
/**
+----------------------------------------------------------
* SQL指令安全过滤
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str SQL字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function escapeString($str) {
return mysql_escape_string($str);
}
/**
+----------------------------------------------------------
* 析构方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __destruct() {
// 关闭连接
$this->close();
}
/**
+----------------------------------------------------------
* 取得数据库类实例
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return mixed 返回数据库驱动类
+----------------------------------------------------------
*/
public static function getInstance($db_config='') {
if ( self::$_instance==null ){
self::$_instance = new Db($db_config);
}
return self::$_instance;
}
/**
+----------------------------------------------------------
* 分析数据库配置信息,支持数组和DSN
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param mixed $db_config 数据库配置信息
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function parseConfig($db_config='') {
if ( !empty($db_config) && is_string($db_config)) {
// 如果DSN字符串则进行解析
$db_config = $this->parseDSN($db_config);
}else if(empty($db_config)){
// 如果配置为空,读取配置文件设置
$db_config = array (
'dbms' => C('DB_TYPE'),
'username' => C('DB_USER'),
'password' => C('DB_PWD'),
'hostname' => C('DB_HOST'),
'hostport' => C('DB_PORT'),
'database' => C('DB_NAME'),
'dsn' => C('DB_DSN'),
'params' => C('DB_PARAMS'),
);
}
return $db_config;
}
/**
+----------------------------------------------------------
* DSN解析
* 格式: mysql://username:passwd@localhost:3306/DbName
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $dsnStr
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function parseDSN($dsnStr) {
if( empty($dsnStr) ){return false;}
$info = parse_url($dsnStr);
if($info['scheme']){
$dsn = array(
'dbms' => $info['scheme'],
'username' => isset($info['user']) ? $info['user'] : '',
'password' => isset($info['pass']) ? $info['pass'] : '',
'hostname' => isset($info['host']) ? $info['host'] : '',
'hostport' => isset($info['port']) ? $info['port'] : '',
'database' => isset($info['path']) ? substr($info['path'],1) : ''
);
}else {
preg_match('/^(.*?)\:\/\/(.*?)\:(.*?)\@(.*?)\:([0-9]{1, 6})\/(.*?)$/',trim($dsnStr),$matches);
$dsn = array (
'dbms' => $matches[1],
'username' => $matches[2],
'password' => $matches[3],
'hostname' => $matches[4],
'hostport' => $matches[5],
'database' => $matches[6]
);
}
return $dsn;
}
/**
+----------------------------------------------------------
* 数据库调试 记录当前SQL
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
*/
protected function debug() {
// 记录操作结束时间
if ( $this->debug ) {
G('queryEndTime');
Log::record($this->queryStr." [ RunTime:".G('queryStartTime','queryEndTime',6)."s ]",Log::SQL);
}
}
/**
+----------------------------------------------------------
* 设置锁机制
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseLock($lock=false) {
if(!$lock) return '';
if('ORACLE' == $this->dbType) {
return ' FOR UPDATE NOWAIT ';
}
return ' FOR UPDATE ';
}
/**
+----------------------------------------------------------
* set分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseSet($data) {
foreach ($data as $key=>$val){
$value = $this->parseValue($val);
if(is_scalar($value)) // 过滤非标量数据
$set[] = $this->parseKey($key).'='.$value;
}
return ' SET '.implode(',',$set);
}
/**
+----------------------------------------------------------
* value分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $value
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseValue($value) {
if(is_string($value)) {
$value = '\''.$this->escapeString($value).'\'';
}elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){
$value = $this->escapeString($value[1]);
}elseif(is_null($value)){
$value = 'null';
}
return $value;
}
/**
+----------------------------------------------------------
* field分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $fields
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseField($fields) {
if(is_array($fields)) {
// 完善数组方式传字段名的支持
// 支持 'field1'=>'field2' 这样的字段别名定义
$array = array();
foreach ($fields as $key=>$field){
if(!is_numeric($key))
$array[] = $this->parseKey($key).' AS '.$this->parseKey($field);
else
$array[] = $this->parseKey($field);
}
$fieldsStr = implode(',', $array);
}elseif(is_string($fields) && !empty($fields)) {
$fieldsStr = $this->parseKey($fields);
}else{
$fieldsStr = '*';
}
return $fieldsStr;
}
/**
+----------------------------------------------------------
* table分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $table
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseTable($tables) {
if(is_string($tables))
$tables = explode(',',$tables);
array_walk($tables, array(&$this, 'parseKey'));
return implode(',',$tables);
}
/**
+----------------------------------------------------------
* where分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $where
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseWhere($where) {
$whereStr = '';
if(is_string($where)) {
// 直接使用字符串条件
$whereStr = $where;
}else{ // 使用数组条件表达式
if(isset($where['_logic'])) {
// 定义逻辑运算规则 例如 OR XOR AND NOT
$operate = ' '.strtoupper($where['_logic']).' ';
unset($where['_logic']);
}else{
// 默认进行 AND 运算
$operate = ' AND ';
}
foreach ($where as $key=>$val){
$whereStr .= "( ";
if(0===strpos($key,'_')) {
// 解析特殊条件表达式
$whereStr .= $this->parseThinkWhere($key,$val);
}else{
$key = $this->parseKey($key);
if(is_array($val)) {
if(is_string($val[0])) {
if(preg_match('/^(EQ|NEQ|GT|EGT|LT|ELT|NOTLIKE|LIKE)$/i',$val[0])) { // 比较运算
$whereStr .= $key.' '.$this->comparison[strtolower($val[0])].' '.$this->parseValue($val[1]);
}elseif('exp'==strtolower($val[0])){ // 使用表达式
$whereStr .= ' ('.$key.' '.$val[1].') ';
}elseif(preg_match('/IN/i',$val[0])){ // IN 运算
$zone = is_array($val[1])? implode(',',$this->parseValue($val[1])):$val[1];
$whereStr .= $key.' '.strtoupper($val[0]).' ('.$zone.')';
}elseif(preg_match('/BETWEEN/i',$val[0])){ // BETWEEN运算
$data = is_string($val[1])? explode(',',$val[1]):$val[1];
$whereStr .= ' ('.$key.' BETWEEN '.$data[0].' AND '.$data[1].' )';
}else{
throw_exception(L('_EXPRESS_ERROR_').':'.$val[0]);
}
}else {
$count = count($val);
if(in_array(strtoupper(trim($val[$count-1])),array('AND','OR','XOR'))) {
$rule = strtoupper(trim($val[$count-1]));
$count = $count -1;
}else{
$rule = 'AND';
}
for($i=0;$i<$count;$i++) {
$data = is_array($val[$i])?$val[$i][1]:$val[$i];
if('exp'==strtolower($val[$i][0])) {
$whereStr .= '('.$key.' '.$data.') '.$rule.' ';
}else{
$op = is_array($val[$i])?$this->comparison[strtolower($val[$i][0])]:'=';
$whereStr .= '('.$key.' '.$op.' '.$this->parseValue($data).') '.$rule.' ';
}
}
$whereStr = substr($whereStr,0,-4);
}
}else {
//对字符串类型字段采用模糊匹配
if(C('LIKE_MATCH_FIELDS') && preg_match('/('.C('LIKE_MATCH_FIELDS').')/i',$key)) {
$val = '%'.$val.'%';
$whereStr .= $key." LIKE ".$this->parseValue($val);
}else {
$whereStr .= $key." = ".$this->parseValue($val);
}
}
}
$whereStr .= ' )'.$operate;
}
$whereStr = substr($whereStr,0,-strlen($operate));
}
return empty($whereStr)?'':' WHERE '.$whereStr;
}
/**
+----------------------------------------------------------
* 特殊条件分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $key
* @param mixed $val
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseThinkWhere($key,$val) {
$whereStr = '';
switch($key) {
case '_string':
// 字符串模式查询条件
$whereStr = $val;
break;
case '_complex':
// 复合查询条件
$whereStr = substr($this->parseWhere($val),6);
break;
case '_query':
// 字符串模式查询条件
parse_str($val,$where);
if(isset($where['_logic'])) {
$op = ' '.strtoupper($where['_logic']).' ';
unset($where['_logic']);
}else{
$op = ' AND ';
}
$array = array();
foreach ($where as $field=>$data)
$array[] = $this->parseKey($field).' = '.$this->parseValue($data);
$whereStr = implode($op,$array);
break;
}
return $whereStr;
}
/**
+----------------------------------------------------------
* limit分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $lmit
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseLimit($limit) {
return !empty($limit)? ' LIMIT '.$limit.' ':'';
}
/**
+----------------------------------------------------------
* join分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $join
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseJoin($join) {
$joinStr = '';
if(!empty($join)) {
if(is_array($join)) {
foreach ($join as $key=>$_join){
if(false !== stripos($_join,'JOIN'))
$joinStr .= ' '.$_join;
else
$joinStr .= ' LEFT JOIN ' .$_join;
}
}else{
$joinStr .= ' LEFT JOIN ' .$join;
}
}
return $joinStr;
}
/**
+----------------------------------------------------------
* order分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $order
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseOrder($order) {
return !empty($order)? ' ORDER BY '.$order:'';
}
/**
+----------------------------------------------------------
* group分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $group
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseGroup($group) {
return !empty($group)? ' GROUP BY '.$group:'';
}
/**
+----------------------------------------------------------
* having分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $having
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseHaving($having) {
return !empty($having)? ' HAVING '.$having:'';
}
/**
+----------------------------------------------------------
* distinct分析
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $distinct
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseDistinct($distinct) {
return !empty($distinct)? ' DISTINCT ' :'';
}
/**
+----------------------------------------------------------
* 插入记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 参数表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function insert($data,$options=array()) {
foreach ($data as $key=>$val){
$value = $this->parseValue($val);
if(is_scalar($value)) { // 过滤非标量数据
$values[] = $value;
$fields[] = $this->parseKey($key);
}
}
$sql = 'INSERT INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES ('.implode(',', $values).')';
$sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 更新记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function update($data,$options) {
$sql = 'UPDATE '
.$this->parseTable($options['table'])
.$this->parseSet($data)
.$this->parseWhere(isset($options['where'])?$options['where']:'')
.$this->parseOrder(isset($options['order'])?$options['order']:'')
.$this->parseLimit(isset($options['limit'])?$options['limit']:'')
.$this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 删除记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function delete($options=array()) {
$sql = 'DELETE FROM '
.$this->parseTable($options['table'])
.$this->parseWhere(isset($options['where'])?$options['where']:'')
.$this->parseOrder(isset($options['order'])?$options['order']:'')
.$this->parseLimit(isset($options['limit'])?$options['limit']:'')
.$this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->execute($sql);
}
/**
+----------------------------------------------------------
* 查找记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function select($options=array()) {
if(isset($options['page'])) {
// 根据页数计算limit
list($page,$listRows) = explode(',',$options['page']);
$listRows = $listRows?$listRows:($options['limit']?$options['limit']:20);
$offset = $listRows*((int)$page-1);
$options['limit'] = $offset.','.$listRows;
}
$sql = str_replace(
array('%TABLE%','%DISTINCT%','%FIELDS%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%'),
array(
$this->parseTable($options['table']),
$this->parseDistinct(isset($options['distinct'])?$options['distinct']:false),
$this->parseField(isset($options['field'])?$options['field']:'*'),
$this->parseJoin(isset($options['join'])?$options['join']:''),
$this->parseWhere(isset($options['where'])?$options['where']:''),
$this->parseGroup(isset($options['group'])?$options['group']:''),
$this->parseHaving(isset($options['having'])?$options['having']:''),
$this->parseOrder(isset($options['order'])?$options['order']:''),
$this->parseLimit(isset($options['limit'])?$options['limit']:'')
),$this->selectSql);
$sql .= $this->parseLock(isset($options['lock'])?$options['lock']:false);
return $this->query($sql);
}
/**
+----------------------------------------------------------
* 字段和表名添加`
* 保证指令中使用关键字不出错 针对mysql
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $value
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
protected function parseKey(&$value) {
$value = trim($value);
if( false !== strpos($value,' ') || false !== strpos($value,',') || false !== strpos($value,'*') || false !== strpos($value,'(') || false !== strpos($value,'.') || false !== strpos($value,'`')) {
//如果包含* 或者 使用了sql方法 则不作处理
}else{
$value = '`'.$value.'`';
}
return $value;
}
/**
+----------------------------------------------------------
* 获取最近一次查询的sql语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastSql() {
return $this->queryStr;
}
/**
+----------------------------------------------------------
* 获取最近插入的ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastInsID(){
return $this->lastInsID;
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Lite/Db.class.php | PHP | asf20 | 39,553 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Model.class.php 2779 2012-02-24 02:56:57Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP 精简模式Model模型类
* 只支持CURD和连贯操作 以及常用查询 去掉回调接口
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: Model.class.php 2779 2012-02-24 02:56:57Z liu21st $
+------------------------------------------------------------------------------
*/
class Model {
// 操作状态
const MODEL_INSERT = 1; // 插入模型数据
const MODEL_UPDATE = 2; // 更新模型数据
const MODEL_BOTH = 3; // 包含上面两种方式
const MUST_VALIDATE = 1;// 必须验证
const EXISTS_VAILIDATE = 0;// 表单存在字段则验证
const VALUE_VAILIDATE = 2;// 表单值不为空则验证
// 当前数据库操作对象
protected $db = null;
// 主键名称
protected $pk = 'id';
// 数据表前缀
protected $tablePrefix = '';
// 模型名称
protected $name = '';
// 数据库名称
protected $dbName = '';
// 数据表名(不包含表前缀)
protected $tableName = '';
// 实际数据表名(包含表前缀)
protected $trueTableName ='';
// 最近错误信息
protected $error = '';
// 字段信息
protected $fields = array();
// 数据信息
protected $data = array();
// 查询表达式参数
protected $options = array();
protected $_validate = array(); // 自动验证定义
protected $_auto = array(); // 自动完成定义
// 是否自动检测数据表字段信息
protected $autoCheckFields = true;
// 是否批处理验证
protected $patchValidate = false;
/**
+----------------------------------------------------------
* 架构函数
* 取得DB类的实例对象 字段检查
+----------------------------------------------------------
* @param string $name 模型名称
* @param string $tablePrefix 表前缀
* @param mixed $connection 数据库连接信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($name='',$tablePrefix='',$connection='') {
// 模型初始化
$this->_initialize();
// 获取模型名称
if(!empty($name)) {
if(strpos($name,'.')) { // 支持 数据库名.模型名的 定义
list($this->dbName,$this->name) = explode('.',$name);
}else{
$this->name = $name;
}
}elseif(empty($this->name)){
$this->name = $this->getModelName();
}
if(!empty($tablePrefix)) {
$this->tablePrefix = $tablePrefix;
}
// 设置表前缀
$this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX');
// 数据库初始化操作
// 获取数据库操作对象
// 当前模型有独立的数据库连接信息
$this->db(0,empty($this->connection)?$connection:$this->connection);
// 字段检测
if(!empty($this->name) && $this->autoCheckFields) $this->_checkTableInfo();
}
/**
+----------------------------------------------------------
* 自动检测数据表信息
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function _checkTableInfo() {
// 如果不是Model类 自动记录数据表信息
// 只在第一次执行记录
if(empty($this->fields)) {
// 如果数据表字段没有定义则自动获取
if(C('DB_FIELDS_CACHE')) {
$db = $this->dbName?$this->dbName:C('DB_NAME');
$this->fields = F('_fields/'.$db.'.'.$this->name);
if(!$this->fields) $this->flush();
}else{
// 每次都会读取数据表信息
$this->flush();
}
}
}
/**
+----------------------------------------------------------
* 获取字段信息并缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function flush() {
// 缓存不存在则查询数据表信息
$fields = $this->db->getFields($this->getTableName());
if(!$fields) { // 无法获取字段信息
return false;
}
$this->fields = array_keys($fields);
$this->fields['_autoinc'] = false;
foreach ($fields as $key=>$val){
// 记录字段类型
$type[$key] = $val['type'];
if($val['primary']) {
$this->fields['_pk'] = $key;
if($val['autoinc']) $this->fields['_autoinc'] = true;
}
}
// 记录字段类型信息
if(C('DB_FIELDTYPE_CHECK')) $this->fields['_type'] = $type;
// 2008-3-7 增加缓存开关控制
if(C('DB_FIELDS_CACHE')){
// 永久缓存数据表信息
$db = $this->dbName?$this->dbName:C('DB_NAME');
F('_fields/'.$db.'.'.$this->name,$this->fields);
}
}
/**
+----------------------------------------------------------
* 设置数据对象的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
* @param mixed $value 值
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function __set($name,$value) {
// 设置数据对象属性
$this->data[$name] = $value;
}
/**
+----------------------------------------------------------
* 获取数据对象的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __get($name) {
return isset($this->data[$name])?$this->data[$name]:null;
}
/**
+----------------------------------------------------------
* 检测数据对象的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function __isset($name) {
return isset($this->data[$name]);
}
/**
+----------------------------------------------------------
* 销毁数据对象的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function __unset($name) {
unset($this->data[$name]);
}
/**
+----------------------------------------------------------
* 利用__call方法实现一些特殊的Model方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名称
* @param array $args 调用参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$args) {
if(in_array(strtolower($method),array('table','where','order','limit','page','alias','having','group','lock','distinct'),true)) {
// 连贯操作的实现
$this->options[strtolower($method)] = $args[0];
return $this;
}elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){
// 统计查询的实现
$field = isset($args[0])?$args[0]:'*';
return $this->getField(strtoupper($method).'('.$field.') AS tp_'.$method);
}elseif(strtolower(substr($method,0,5))=='getby') {
// 根据某个字段获取记录
$field = parse_name(substr($method,5));
$where[$field] = $args[0];
return $this->where($where)->find();
}else{
throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
return;
}
}
// 回调方法 初始化模型
protected function _initialize() {}
/**
+----------------------------------------------------------
* 对保存到数据库的数据进行处理
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 要操作的数据
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
protected function _facade($data) {
// 检查非数据字段
if(!empty($this->fields)) {
foreach ($data as $key=>$val){
if(!in_array($key,$this->fields,true)){
unset($data[$key]);
}elseif(C('DB_FIELDTYPE_CHECK') && is_scalar($val)) {
// 字段类型检查
$this->_parseType($data,$key);
}
}
}
return $data;
}
/**
+----------------------------------------------------------
* 新增数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function add($data='',$options=array()) {
if(empty($data)) {
// 没有传递数据,获取当前数据对象的值
if(!empty($this->data)) {
$data = $this->data;
}else{
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
}
// 分析表达式
$options = $this->_parseOptions($options);
// 数据处理
$data = $this->_facade($data);
// 写入数据到数据库
$result = $this->db->insert($data,$options);
if(false !== $result ) {
$insertId = $this->getLastInsID();
if($insertId) {
// 自增主键返回插入ID
return $insertId;
}
}
return $result;
}
/**
+----------------------------------------------------------
* 保存数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
* @param array $options 表达式
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function save($data='',$options=array()) {
if(empty($data)) {
// 没有传递数据,获取当前数据对象的值
if(!empty($this->data)) {
$data = $this->data;
}else{
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
}
// 数据处理
$data = $this->_facade($data);
// 分析表达式
$options = $this->_parseOptions($options);
if(!isset($options['where']) ) {
// 如果存在主键数据 则自动作为更新条件
if(isset($data[$this->getPk()])) {
$pk = $this->getPk();
$where[$pk] = $data[$pk];
$options['where'] = $where;
unset($data[$pk]);
}else{
// 如果没有任何更新条件则不执行
$this->error = L('_OPERATION_WRONG_');
return false;
}
}
$result = $this->db->update($data,$options);
return $result;
}
/**
+----------------------------------------------------------
* 删除数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $options 表达式
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function delete($options=array()) {
if(empty($options) && empty($this->options['where'])) {
// 如果删除条件为空 则删除当前数据对象所对应的记录
if(!empty($this->data) && isset($this->data[$this->getPk()]))
return $this->delete($this->data[$this->getPk()]);
else
return false;
}
if(is_numeric($options) || is_string($options)) {
// 根据主键删除记录
$pk = $this->getPk();
if(strpos($options,',')) {
$where[$pk] = array('IN', $options);
}else{
$where[$pk] = $options;
$pkValue = $options;
}
$options = array();
$options['where'] = $where;
}
// 分析表达式
$options = $this->_parseOptions($options);
$result= $this->db->delete($options);
// 返回删除记录个数
return $result;
}
/**
+----------------------------------------------------------
* 查询数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 表达式参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function select($options=array()) {
if(is_string($options) || is_numeric($options)) {
// 根据主键查询
$pk = $this->getPk();
if(strpos($options,',')) {
$where[$pk] = array('IN',$options);
}else{
$where[$pk] = $options;
}
$options = array();
$options['where'] = $where;
}
// 分析表达式
$options = $this->_parseOptions($options);
$resultSet = $this->db->select($options);
if(false === $resultSet) {
return false;
}
if(empty($resultSet)) { // 查询结果为空
return null;
}
return $resultSet;
}
/**
+----------------------------------------------------------
* 分析表达式
+----------------------------------------------------------
* @access proteced
+----------------------------------------------------------
* @param array $options 表达式参数
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function _parseOptions($options=array()) {
if(is_array($options))
$options = array_merge($this->options,$options);
// 查询过后清空sql表达式组装 避免影响下次查询
$this->options = array();
if(!isset($options['table']))
// 自动获取表名
$options['table'] =$this->getTableName();
if(!empty($options['alias'])) {
$options['table'] .= ' '.$options['alias'];
}
// 字段类型验证
if(C('DB_FIELDTYPE_CHECK')) {
if(isset($options['where']) && is_array($options['where'])) {
// 对数组查询条件进行字段类型检查
foreach ($options['where'] as $key=>$val){
if(in_array($key,$this->fields,true) && is_scalar($val)){
$this->_parseType($options['where'],$key);
}
}
}
}
return $options;
}
/**
+----------------------------------------------------------
* 数据类型检测
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 数据
* @param string $key 字段名
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function _parseType(&$data,$key) {
$fieldType = strtolower($this->fields['_type'][$key]);
if(false !== strpos($fieldType,'int')) {
$data[$key] = intval($data[$key]);
}elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){
$data[$key] = floatval($data[$key]);
}elseif(false !== strpos($fieldType,'bool')){
$data[$key] = (bool)$data[$key];
}
}
/**
+----------------------------------------------------------
* 查询数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $options 表达式参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function find($options=array()) {
if(is_numeric($options) || is_string($options)) {
$where[$this->getPk()] =$options;
$options = array();
$options['where'] = $where;
}
// 总是查找一条记录
$options['limit'] = 1;
// 分析表达式
$options = $this->_parseOptions($options);
$resultSet = $this->db->select($options);
if(false === $resultSet) {
return false;
}
if(empty($resultSet)) {// 查询结果为空
return null;
}
$this->data = $resultSet[0];
return $this->data;
}
/**
+----------------------------------------------------------
* 设置记录的某个字段值
* 支持使用数据库字段和方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string|array $field 字段名
* @param string|array $value 字段值
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function setField($field,$value) {
if(is_array($field)) {
$data = $field;
}else{
$data[$field] = $value;
}
return $this->save($data);
}
/**
+----------------------------------------------------------
* 字段值增长
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $field 字段名
* @param integer $step 增长值
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function setInc($field,$step=1) {
return $this->setField($field,array('exp',$field.'+'.$step));
}
/**
+----------------------------------------------------------
* 字段值减少
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $field 字段名
* @param integer $step 减少值
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function setDec($field,$step=1) {
return $this->setField($field,array('exp',$field.'-'.$step));
}
/**
+----------------------------------------------------------
* 获取一条记录的某个字段值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $field 字段名
* @param string $spea 字段数据间隔符号
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function getField($field,$sepa=null) {
$options['field'] = $field;
$options = $this->_parseOptions($options);
if(strpos($field,',')) { // 多字段
$resultSet = $this->db->select($options);
if(!empty($resultSet)) {
$_field = explode(',', $field);
$field = array_keys($resultSet[0]);
$move = $_field[0]==$_field[1]?false:true;
$key = array_shift($field);
$key2 = array_shift($field);
$cols = array();
$count = count($_field);
foreach ($resultSet as $result){
$name = $result[$key];
if($move) { // 删除键值记录
unset($result[$key]);
}
if(2==$count) {
$cols[$name] = $result[$key2];
}else{
$cols[$name] = is_null($sepa)?$result:implode($sepa,$result);
}
}
return $cols;
}
}else{ // 查找一条记录
$options['limit'] = 1;
$result = $this->db->select($options);
if(!empty($result)) {
return reset($result[0]);
}
}
return null;
}
/**
+----------------------------------------------------------
* 创建数据对象 但不保存到数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 创建数据
* @param string $type 状态
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function create($data='',$type='') {
// 如果没有传值默认取POST数据
if(empty($data)) {
$data = $_POST;
}elseif(is_object($data)){
$data = get_object_vars($data);
}
// 验证数据
if(empty($data) || !is_array($data)) {
$this->error = L('_DATA_TYPE_INVALID_');
return false;
}
// 状态
$type = $type?$type:(!empty($data[$this->getPk()])?self::MODEL_UPDATE:self::MODEL_INSERT);
// 数据自动验证
if(!$this->autoValidation($data,$type)) return false;
// 验证完成生成数据对象
if($this->autoCheckFields) { // 开启字段检测 则过滤非法字段数据
$vo = array();
foreach ($this->fields as $key=>$name){
if(substr($key,0,1)=='_') continue;
$val = isset($data[$name])?$data[$name]:null;
//保证赋值有效
if(!is_null($val)){
$vo[$name] = (MAGIC_QUOTES_GPC && is_string($val))? stripslashes($val) : $val;
}
}
}else{
$vo = $data;
}
// 创建完成对数据进行自动处理
$this->autoOperation($vo,$type);
// 赋值当前数据对象
$this->data = $vo;
// 返回创建的数据以供其他调用
return $vo;
}
/**
+----------------------------------------------------------
* 使用正则验证数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $value 要验证的数据
* @param string $rule 验证规则
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function regex($value,$rule) {
$validate = array(
'require'=> '/.+/',
'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
'url' => '/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/',
'currency' => '/^\d+(\.\d+)?$/',
'number' => '/^\d+$/',
'zip' => '/^[1-9]\d{5}$/',
'integer' => '/^[-\+]?\d+$/',
'double' => '/^[-\+]?\d+(\.\d+)?$/',
'english' => '/^[A-Za-z]+$/',
);
// 检查是否有内置的正则表达式
if(isset($validate[strtolower($rule)]))
$rule = $validate[strtolower($rule)];
return preg_match($rule,$value)===1;
}
/**
+----------------------------------------------------------
* 自动表单处理
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $data 创建数据
* @param string $type 创建类型
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
private function autoOperation(&$data,$type) {
// 自动填充
if(!empty($this->_auto)) {
foreach ($this->_auto as $auto){
// 填充因子定义格式
// array('field','填充内容','填充条件','附加规则',[额外参数])
if(empty($auto[2])) $auto[2] = self::MODEL_INSERT; // 默认为新增的时候自动填充
if( $type == $auto[2] || $auto[2] == self::MODEL_BOTH) {
switch($auto[3]) {
case 'function': // 使用函数进行填充 字段的值作为参数
case 'callback': // 使用回调方法
$args = isset($auto[4])?$auto[4]:array();
if(isset($data[$auto[0]])) {
array_unshift($args,$data[$auto[0]]);
}
if('function'==$auto[3]) {
$data[$auto[0]] = call_user_func_array($auto[1], $args);
}else{
$data[$auto[0]] = call_user_func_array(array(&$this,$auto[1]), $args);
}
break;
case 'field': // 用其它字段的值进行填充
$data[$auto[0]] = $data[$auto[1]];
break;
case 'string':
default: // 默认作为字符串填充
$data[$auto[0]] = $auto[1];
}
if(false === $data[$auto[0]] ) unset($data[$auto[0]]);
}
}
}
return $data;
}
/**
+----------------------------------------------------------
* 自动表单验证
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data 创建数据
* @param string $type 创建类型
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
protected function autoValidation($data,$type) {
// 属性验证
if(!empty($this->_validate)) { // 如果设置了数据自动验证则进行数据验证
if($this->patchValidate) { // 重置验证错误信息
$this->error = array();
}
foreach($this->_validate as $key=>$val) {
// 验证因子定义格式
// array(field,rule,message,condition,type,when,params)
// 判断是否需要执行验证
if(empty($val[5]) || $val[5]== self::MODEL_BOTH || $val[5]== $type ) {
if(0==strpos($val[2],'{%') && strpos($val[2],'}'))
// 支持提示信息的多语言 使用 {%语言定义} 方式
$val[2] = L(substr($val[2],2,-1));
$val[3] = isset($val[3])?$val[3]:self::EXISTS_VAILIDATE;
$val[4] = isset($val[4])?$val[4]:'regex';
// 判断验证条件
switch($val[3]) {
case self::MUST_VALIDATE: // 必须验证 不管表单是否有设置该字段
if(false === $this->_validationField($data,$val))
return false;
break;
case self::VALUE_VAILIDATE: // 值不为空的时候才验证
if('' != trim($data[$val[0]]))
if(false === $this->_validationField($data,$val))
return false;
break;
default: // 默认表单存在该字段就验证
if(isset($data[$val[0]]))
if(false === $this->_validationField($data,$val))
return false;
}
}
}
// 批量验证的时候最后返回错误
if(!empty($this->error)) return false;
}
return true;
}
/**
+----------------------------------------------------------
* 验证表单字段 支持批量验证
* 如果批量验证返回错误的数组信息
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data 创建数据
* @param array $val 验证因子
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
protected function _validationField($data,$val) {
if(false === $this->_validationFieldItem($data,$val)){
if($this->patchValidate) {
$this->error[$val[0]] = $val[2];
}else{
$this->error = $val[2];
return false;
}
}
return ;
}
/**
+----------------------------------------------------------
* 根据验证因子验证字段
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data 创建数据
* @param array $val 验证因子
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
protected function _validationFieldItem($data,$val) {
switch($val[4]) {
case 'function':// 使用函数进行验证
case 'callback':// 调用方法进行验证
$args = isset($val[6])?$val[6]:array();
array_unshift($args,$data[$val[0]]);
if('function'==$val[4]) {
return call_user_func_array($val[1], $args);
}else{
return call_user_func_array(array(&$this, $val[1]), $args);
}
case 'confirm': // 验证两个字段是否相同
return $data[$val[0]] == $data[$val[1]];
case 'unique': // 验证某个值是否唯一
if(is_string($val[0]) && strpos($val[0],','))
$val[0] = explode(',',$val[0]);
$map = array();
if(is_array($val[0])) {
// 支持多个字段验证
foreach ($val[0] as $field)
$map[$field] = $data[$field];
}else{
$map[$val[0]] = $data[$val[0]];
}
if(!empty($data[$this->getPk()])) { // 完善编辑的时候验证唯一
$map[$this->getPk()] = array('neq',$data[$this->getPk()]);
}
if($this->where($map)->find()) return false;
return true;
default: // 检查附加规则
return $this->check($data[$val[0]],$val[1],$val[4]);
}
}
/**
+----------------------------------------------------------
* 验证数据 支持 in between equal length regex expire ip_allow ip_deny
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $value 验证数据
* @param mixed $rule 验证表达式
* @param string $type 验证方式 默认为正则验证
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function check($value,$rule,$type='regex'){
switch(strtolower($type)) {
case 'in': // 验证是否在某个指定范围之内 逗号分隔字符串或者数组
$range = is_array($rule)?$rule:explode(',',$rule);
return in_array($value ,$range);
case 'between': // 验证是否在某个范围
list($min,$max) = explode(',',$rule);
return $value>=$min && $value<=$max;
case 'equal': // 验证是否等于某个值
return $value == $rule;
case 'length': // 验证长度
$length = mb_strlen($value,'utf-8'); // 当前数据长度
if(strpos($rule,',')) { // 长度区间
list($min,$max) = explode(',',$rule);
return $length >= $min && $length <= $max;
}else{// 指定长度
return $length == $rule;
}
case 'expire':
list($start,$end) = explode(',',$rule);
if(!is_numeric($start)) $start = strtotime($start);
if(!is_numeric($end)) $end = strtotime($end);
return $_SERVER['REQUEST_TIME'] >= $start && $_SERVER['REQUEST_TIME'] <= $end;
case 'ip_allow': // IP 操作许可验证
return in_array(get_client_ip(),explode(',',$rule));
case 'ip_deny': // IP 操作禁止验证
return !in_array(get_client_ip(),explode(',',$rule));
case 'regex':
default: // 默认使用正则验证 可以使用验证类中定义的验证名称
// 检查附加规则
return $this->regex($value,$rule);
}
}
/**
+----------------------------------------------------------
* SQL查询
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $sql SQL指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function query($sql) {
if(!empty($sql)) {
if(strpos($sql,'__TABLE__'))
$sql = str_replace('__TABLE__',$this->getTableName(),$sql);
return $this->db->query($sql);
}else{
return false;
}
}
/**
+----------------------------------------------------------
* 执行SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $sql SQL指令
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function execute($sql) {
if(!empty($sql)) {
if(strpos($sql,'__TABLE__'))
$sql = str_replace('__TABLE__',$this->getTableName(),$sql);
return $this->db->execute($sql);
}else {
return false;
}
}
/**
+----------------------------------------------------------
* 切换当前的数据库连接
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param integer $linkNum 连接序号
* @param mixed $config 数据库连接信息
* @param array $params 模型参数
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function db($linkNum,$config='',$params=array()){
static $_db = array();
if(!isset($_db[$linkNum])) {
// 创建一个新的实例
if(!empty($config) && false === strpos($config,'/')) { // 支持读取配置参数
$config = C($config);
}
$_db[$linkNum] = Db::getInstance($config);
}elseif(NULL === $config){
$_db[$linkNum]->close(); // 关闭数据库连接
unset($_db[$linkNum]);
return ;
}
if(!empty($params)) {
if(is_string($params)) parse_str($params,$params);
foreach ($params as $name=>$value){
$this->setProperty($name,$value);
}
}
// 切换数据库连接
$this->db = $_db[$linkNum];
return $this;
}
/**
+----------------------------------------------------------
* 得到当前的数据对象名称
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getModelName() {
if(empty($this->name))
$this->name = substr(get_class($this),0,-5);
return $this->name;
}
/**
+----------------------------------------------------------
* 得到完整的数据表名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getTableName() {
if(empty($this->trueTableName)) {
$tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
if(!empty($this->tableName)) {
$tableName .= $this->tableName;
}else{
$tableName .= parse_name($this->name);
}
$this->trueTableName = strtolower($tableName);
}
return (!empty($this->dbName)?$this->dbName.'.':'').$this->trueTableName;
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function startTrans() {
$this->commit();
$this->db->startTrans();
return ;
}
/**
+----------------------------------------------------------
* 提交事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function commit() {
return $this->db->commit();
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function rollback() {
return $this->db->rollback();
}
/**
+----------------------------------------------------------
* 返回模型的错误信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getError() {
return $this->error;
}
/**
+----------------------------------------------------------
* 返回数据库的错误信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getDbError() {
return $this->db->getError();
}
/**
+----------------------------------------------------------
* 返回最后插入的ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastInsID() {
return $this->db->getLastInsID();
}
/**
+----------------------------------------------------------
* 返回最后执行的sql语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastSql() {
return $this->db->getLastSql();
}
// 鉴于getLastSql比较常用 增加_sql 别名
public function _sql(){
return $this->getLastSql();
}
/**
+----------------------------------------------------------
* 获取主键名称
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getPk() {
return isset($this->fields['_pk'])?$this->fields['_pk']:$this->pk;
}
/**
+----------------------------------------------------------
* 获取数据表字段信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getDbFields(){
if($this->fields) {
$fields = $this->fields;
unset($fields['_autoinc'],$fields['_pk'],$fields['_type']);
return $fields;
}
return false;
}
/**
+----------------------------------------------------------
* 指定查询字段 支持字段排除
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $field
* @param boolean $except 是否排除
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function field($field,$except=false){
if($except) {// 字段排除
if(is_string($field)) {
$field = explode(',',$field);
}
$fields = $this->getDbFields();
$field = $fields?array_diff($fields,$field):$field;
}
$this->options['field'] = $field;
return $this;
}
/**
+----------------------------------------------------------
* 设置数据对象值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $data 数据
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function data($data){
if(is_object($data)){
$data = get_object_vars($data);
}elseif(is_string($data)){
parse_str($data,$data);
}elseif(!is_array($data)){
throw_exception(L('_DATA_TYPE_INVALID_'));
}
$this->data = $data;
return $this;
}
/**
+----------------------------------------------------------
* 查询SQL组装 join
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $join
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function join($join) {
if(is_array($join))
$this->options['join'] = $join;
else
$this->options['join'][] = $join;
return $this;
}
/**
+----------------------------------------------------------
* 查询SQL组装 union
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $union
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function union($union) {
if(empty($union)) return $this;
// 转换union表达式
if($union instanceof Model) {
$options = $union->getProperty('options');
if(!isset($options['table'])){
// 自动获取表名
$options['table'] =$union->getTableName();
}
if(!isset($options['field'])) {
$options['field'] =$this->options['field'];
}
}elseif(is_object($union)) {
$options = get_object_vars($union);
}elseif(!is_array($union)){
throw_exception(L('_DATA_TYPE_INVALID_'));
}
$this->options['union'][] = $options;
return $this;
}
/**
+----------------------------------------------------------
* 设置模型的属性值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
* @param mixed $value 值
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function setProperty($name,$value) {
if(property_exists($this,$name))
$this->$name = $value;
return $this;
}
/**
+----------------------------------------------------------
* 获取模型的属性值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 名称
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function getProperty($name){
if(property_exists($this,$name))
return $this->$name;
else
return NULL;
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Lite/Model.class.php | PHP | asf20 | 51,992 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: tags.php 2702 2012-02-02 12:35:01Z liu21st $
// 核心行为扩展列表文件
return array(
'app_begin'=>array(
'CheckTemplate', // 模板检测
),
'route_check'=>array('CheckRoute', // 路由检测
),
'app_end'=>array(
'ShowPageTrace', // 页面Trace显示
),
'view_template'=>array(
'LocationTemplate', // 自动定位模板文件
),
'view_parse'=>array(
'ParseTemplate', // 模板解析 支持PHP、内置模板引擎和第三方模板引擎
),
'view_filter'=>array(
'ContentReplace', // 模板输出替换
'ShowRuntime', // 运行时间显示
),
); | 10npsite | trunk/DThinkPHP/Extend/Mode/Lite/tags.php | PHP | asf20 | 1,288 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Dispatcher.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP内置的Dispatcher类 用于精简模式
* 完成URL解析、路由和调度
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id: Dispatcher.class.php 2702 2012-02-02 12:35:01Z liu21st $
+------------------------------------------------------------------------------
*/
class Dispatcher {
/**
+----------------------------------------------------------
* URL映射到控制器
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function dispatch() {
$urlMode = C('URL_MODEL');
if($urlMode == URL_COMPAT || !empty($_GET[C('VAR_PATHINFO')])){
// 兼容模式判断
define('PHP_FILE',_PHP_FILE_.'?'.C('VAR_PATHINFO').'=');
$_SERVER['PATH_INFO'] = $_GET[C('VAR_PATHINFO')];
unset($_GET[C('VAR_PATHINFO')]);
}elseif($urlMode == URL_REWRITE ) {
//当前项目地址
$url = dirname(_PHP_FILE_);
if($url == '/' || $url == '\\')
$url = '';
define('PHP_FILE',$url);
}else {
//当前项目地址
define('PHP_FILE',_PHP_FILE_);
}
// 分析PATHINFO信息
tag('path_info');
// 分析PATHINFO信息
$depr = C('URL_PATHINFO_DEPR');
if(!empty($_SERVER['PATH_INFO'])) {
if(C('URL_HTML_SUFFIX') && !empty($_SERVER['PATH_INFO'])) {
$_SERVER['PATH_INFO'] = preg_replace('/\.'.trim(C('URL_HTML_SUFFIX'),'.').'$/', '', $_SERVER['PATH_INFO']);
}
if(!self::routerCheck()){ // 检测路由规则 如果没有则按默认规则调度URL
$paths = explode($depr,trim($_SERVER['PATH_INFO'],'/'));
$var = array();
if (C('APP_GROUP_LIST') && !isset($_GET[C('VAR_GROUP')])){
$var[C('VAR_GROUP')] = in_array(strtolower($paths[0]),explode(',',strtolower(C('APP_GROUP_LIST'))))? array_shift($paths) : '';
}
if(!isset($_GET[C('VAR_MODULE')])) {// 还没有定义模块名称
$var[C('VAR_MODULE')] = array_shift($paths);
}
$var[C('VAR_ACTION')] = array_shift($paths);
// 解析剩余的URL参数
$res = preg_replace('@(\w+)'.$depr.'([^'.$depr.'\/]+)@e', '$var[\'\\1\']="\\2";', implode($depr,$paths));
$_GET = array_merge($var,$_GET);
}
}
// 获取分组 模块和操作名称
if (C('APP_GROUP_LIST')) {
define('GROUP_NAME', self::getGroup(C('VAR_GROUP')));
}
define('MODULE_NAME',self::getModule(C('VAR_MODULE')));
define('ACTION_NAME',self::getAction(C('VAR_ACTION')));
// URL常量
define('__SELF__',$_SERVER['REQUEST_URI']);
// 当前项目地址
define('__APP__',PHP_FILE);
// 当前模块和分组地址
$module = defined('P_MODULE_NAME')?P_MODULE_NAME:MODULE_NAME;
if(defined('GROUP_NAME')) {
$group = C('URL_CASE_INSENSITIVE') ?strtolower(GROUP_NAME):GROUP_NAME;
define('__GROUP__', GROUP_NAME == C('DEFAULT_GROUP') ?__APP__ : __APP__.'/'.$group);
define('__URL__', __GROUP__.$depr.$module);
}else{
define('__URL__',__APP__.'/'.$module);
}
// 当前操作地址
define('__ACTION__',__URL__.$depr.ACTION_NAME);
//保证$_REQUEST正常取值
$_REQUEST = array_merge($_POST,$_GET);
}
/**
+----------------------------------------------------------
* 路由检测
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function routerCheck() {
$return = false;
// 路由检测标签
tag('route_check',$return);
return $return;
}
/**
+----------------------------------------------------------
* 获得实际的模块名称
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static private function getModule($var) {
$module = (!empty($_GET[$var])? $_GET[$var]:C('DEFAULT_MODULE'));
unset($_GET[$var]);
if(C('URL_CASE_INSENSITIVE')) {
// URL地址不区分大小写
define('P_MODULE_NAME',strtolower($module));
// 智能识别方式 index.php/user_type/index/ 识别到 UserTypeAction 模块
$module = ucfirst(parse_name(P_MODULE_NAME,1));
}
return $module;
}
/**
+----------------------------------------------------------
* 获得实际的操作名称
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static private function getAction($var) {
$action = !empty($_POST[$var]) ?
$_POST[$var] :
(!empty($_GET[$var])?$_GET[$var]:C('DEFAULT_ACTION'));
unset($_POST[$var],$_GET[$var]);
define('P_ACTION_NAME',$action);
return C('URL_CASE_INSENSITIVE')?strtolower($action):$action;
}
/**
+----------------------------------------------------------
* 获得实际的分组名称
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static private function getGroup($var) {
$group = (!empty($_GET[$var])?$_GET[$var]:C('DEFAULT_GROUP'));
unset($_GET[$var]);
return ucfirst(strtolower($group));
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Lite/Dispatcher.class.php | PHP | asf20 | 7,392 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Action.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP Action控制器基类 精简模式
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: Action.class.php 2702 2012-02-02 12:35:01Z liu21st $
+------------------------------------------------------------------------------
*/
abstract class Action {
// 当前Action名称
private $name = '';
protected $tVar = array(); // 模板输出变量
/**
+----------------------------------------------------------
* 架构函数 取得模板对象实例
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct() {
tag('action_begin');
//控制器初始化
if(method_exists($this,'_initialize'))
$this->_initialize();
}
/**
+----------------------------------------------------------
* 获取当前Action名称
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
*/
protected function getActionName() {
if(empty($this->name)) {
// 获取Action名称
$this->name = substr(get_class($this),0,-6);
}
return $this->name;
}
/**
+----------------------------------------------------------
* 是否AJAX请求
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return bool
+----------------------------------------------------------
*/
protected function isAjax() {
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) ) {
if('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH']))
return true;
}
if(!empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')]))
// 判断Ajax方式提交
return true;
return false;
}
/**
+----------------------------------------------------------
* 模板变量赋值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $name
* @param mixed $value
+----------------------------------------------------------
*/
public function assign($name,$value=''){
if(is_array($name)) {
$this->tVar = array_merge($this->tVar,$name);
}elseif(is_object($name)){
foreach($name as $key =>$val)
$this->tVar[$key] = $val;
}else {
$this->tVar[$name] = $value;
}
}
public function __set($name,$value) {
$this->assign($name,$value);
}
/**
+----------------------------------------------------------
* 取得模板变量的值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function get($name){
if(isset($this->tVar[$name]))
return $this->tVar[$name];
else
return false;
}
/**
+----------------------------------------------------------
* 魔术方法 有不存在的操作的时候执行
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名
* @param array $args 参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$args) {
if( 0 === strcasecmp($method,ACTION_NAME)) {
if(method_exists($this,'_empty')) {
// 如果定义了_empty操作 则调用
$this->_empty($method,$args);
}elseif(file_exists_case(C('TEMPLATE_NAME'))){
// 检查是否存在默认模版 如果有直接输出模版
$this->display();
}else{
// 抛出异常
throw_exception(L('_ERROR_ACTION_').ACTION_NAME);
}
}else{
switch(strtolower($method)) {
// 判断提交方式
case 'ispost':
case 'isget':
case 'ishead':
case 'isdelete':
case 'isput':
return strtolower($_SERVER['REQUEST_METHOD']) == strtolower(substr($method,2));
// 获取变量 支持过滤和默认值 调用方式 $this->_post($key,$filter,$default);
case '_get': $input =& $_GET;break;
case '_post':$input =& $_POST;break;
case '_put': parse_str(file_get_contents('php://input'), $input);break;
case '_request': $input =& $_REQUEST;break;
case '_session': $input =& $_SESSION;break;
case '_cookie': $input =& $_COOKIE;break;
case '_server': $input =& $_SERVER;break;
case '_globals': $input =& $GLOBALS;break;
default:
throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
}
if(isset($input[$args[0]])) { // 取值操作
$data = $input[$args[0]];
$fun = $args[1]?$args[1]:C('DEFAULT_FILTER');
$data = $fun($data); // 参数过滤
}else{ // 变量默认值
$data = isset($args[2])?$args[2]:NULL;
}
return $data;
}
}
/**
+----------------------------------------------------------
* 操作错误跳转的快捷方法
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $message 错误信息
* @param string $jumpUrl 页面跳转地址
* @param Boolean $ajax 是否为Ajax方式
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function error($message,$jumpUrl='',$ajax=false) {
$this->dispatchJump($message,0,$jumpUrl,$ajax);
}
/**
+----------------------------------------------------------
* 操作成功跳转的快捷方法
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $message 提示信息
* @param string $jumpUrl 页面跳转地址
* @param Boolean $ajax 是否为Ajax方式
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function success($message,$jumpUrl='',$ajax=false) {
$this->dispatchJump($message,1,$jumpUrl,$ajax);
}
/**
+----------------------------------------------------------
* Ajax方式返回数据到客户端
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 要返回的数据
* @param String $info 提示信息
* @param boolean $status 返回状态
* @param String $status ajax返回类型 JSON XML
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function ajaxReturn($data,$info='',$status=1,$type='') {
$result = array();
$result['status'] = $status;
$result['info'] = $info;
$result['data'] = $data;
//扩展ajax返回数据, 在Action中定义function ajaxAssign(&$result){} 方法 扩展ajax返回数据。
if(method_exists($this,"ajaxAssign"))
$this->ajaxAssign($result);
if(empty($type)) $type = C('DEFAULT_AJAX_RETURN');
if(strtoupper($type)=='JSON') {
// 返回JSON数据格式到客户端 包含状态信息
header("Content-Type:text/html; charset=utf-8");
exit(json_encode($result));
}elseif(strtoupper($type)=='XML'){
// 返回xml格式数据
header("Content-Type:text/xml; charset=utf-8");
exit(xml_encode($result));
}
}
/**
+----------------------------------------------------------
* Action跳转(URL重定向) 支持指定模块和延时跳转
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $url 跳转的URL表达式
* @param array $params 其它URL参数
* @param integer $delay 延时跳转的时间 单位为秒
* @param string $msg 跳转提示信息
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function redirect($url,$params=array(),$delay=0,$msg='') {
$url = U($url,$params);
redirect($url,$delay,$msg);
}
/**
+----------------------------------------------------------
* 默认跳转操作 支持错误导向和正确跳转
* 调用模板显示 默认为public目录下面的success页面
* 提示页面为可配置 支持模板标签
+----------------------------------------------------------
* @param string $message 提示信息
* @param Boolean $status 状态
* @param string $jumpUrl 页面跳转地址
* @param Boolean $ajax 是否为Ajax方式
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
private function dispatchJump($message,$status=1,$jumpUrl='',$ajax=false) {
// 判断是否为AJAX返回
if($ajax || $this->isAjax()) $this->ajaxReturn($ajax,$message,$status);
if(!empty($jumpUrl)) $this->assign('jumpUrl',$jumpUrl);
// 提示标题
$this->assign('msgTitle',$status? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_'));
//如果设置了关闭窗口,则提示完毕后自动关闭窗口
if($this->get('closeWin')) $this->assign('jumpUrl','javascript:window.close();');
$this->assign('status',$status); // 状态
//保证输出不受静态缓存影响
C('HTML_CACHE_ON',false);
if($status) { //发送成功信息
$this->assign('message',$message);// 提示信息
// 成功操作后默认停留1秒
if(!$this->get('waitSecond')) $this->assign('waitSecond',"1");
// 默认操作成功自动返回操作前页面
if(!$this->get('jumpUrl')) $this->assign("jumpUrl",$_SERVER["HTTP_REFERER"]);
$this->display(C('TMPL_ACTION_SUCCESS'));
}else{
$this->assign('error',$message);// 提示信息
//发生错误时候默认停留3秒
if(!$this->get('waitSecond')) $this->assign('waitSecond',"3");
// 默认发生错误的话自动返回上页
if(!$this->get('jumpUrl')) $this->assign('jumpUrl',"javascript:history.back(-1);");
$this->display(C('TMPL_ACTION_ERROR'));
// 中止执行 避免出错后继续执行
exit ;
}
}
/**
+----------------------------------------------------------
* 加载模板和页面输出 可以返回输出内容
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $templateFile 模板文件名
* @param string $charset 模板输出字符集
* @param string $contentType 输出类型
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function display($templateFile='',$charset='',$contentType='') {
G('viewStartTime');
// 视图开始标签
tag('view_begin',$templateFile);
// 解析并获取模板内容
$content = $this->fetch($templateFile);
// 输出模板内容
$this->show($content,$charset,$contentType);
// 视图结束标签
tag('view_end');
}
/**
+----------------------------------------------------------
* 输出内容文本可以包括Html
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $content 输出内容
* @param string $charset 模板输出字符集
* @param string $contentType 输出类型
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function show($content,$charset='',$contentType=''){
if(empty($charset)) $charset = C('DEFAULT_CHARSET');
if(empty($contentType)) $contentType = C('TMPL_CONTENT_TYPE');
// 网页字符编码
header("Content-Type:".$contentType."; charset=".$charset);
header("Cache-control: private"); //支持页面回跳
header("X-Powered-By:TOPThink/".THINK_VERSION);
// 输出模板文件
echo $content;
}
/**
+----------------------------------------------------------
* 解析和获取模板内容 用于输出
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $templateFile 模板文件名
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function fetch($templateFile='') {
// 模板文件解析标签
tag('view_template',$templateFile);
// 模板文件不存在直接返回
if(!is_file($templateFile)) return NULL;
// 页面缓存
ob_start();
ob_implicit_flush(0);
// 视图解析标签
$params = array('var'=>$this->tVar,'file'=>$templateFile);
$result = tag('view_parse',$params);
if(false === $result) { // 未定义行为 则采用PHP原生模板
// 模板阵列变量分解成为独立变量
extract($this->tVar, EXTR_OVERWRITE);
// 直接载入PHP模板
include $templateFile;
}
// 获取并清空缓存
$content = ob_get_clean();
// 内容过滤标签
tag('view_filter',$content);
// 输出模板文件
return $content;
}
/**
+----------------------------------------------------------
* 析构方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __destruct() {
// 保存日志
if(C('LOG_RECORD')) Log::save();
// 执行后续操作
tag('action_end');
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Lite/Action.class.php | PHP | asf20 | 17,153 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: thin.php 2702 2012-02-02 12:35:01Z liu21st $
// 简洁模式核心定义文件列表
return array(
'core' => array(
THINK_PATH.'Common/functions.php', // 系统函数库
CORE_PATH.'Core/Log.class.php',// 日志处理
MODE_PATH.'Thin/App.class.php', // 应用程序类
MODE_PATH.'Thin/Action.class.php',// 控制器类
),
// 项目别名定义文件 [支持数组直接定义或者文件名定义]
'alias' => array(
'Model' => MODE_PATH.'Thin/Model.class.php',
'Db' => MODE_PATH.'Thin/Db.class.php',
),
// 系统行为定义文件 [必须 支持数组直接定义或者文件名定义 ]
'extends' => array(),
// 项目应用行为定义文件 [支持数组直接定义或者文件名定义]
'tags' => array(),
); | 10npsite | trunk/DThinkPHP/Extend/Mode/thin.php | PHP | asf20 | 1,512 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: phprpc.php 2504 2011-12-28 07:35:29Z liu21st $
// PHPRPC模式定义文件
return array(
'core' => array(
THINK_PATH.'Common/functions.php', // 系统函数库
CORE_PATH.'Core/Log.class.php',// 日志处理
MODE_PATH.'Phprpc/App.class.php', // 应用程序类
MODE_PATH.'Phprpc/Action.class.php',// 控制器类
CORE_PATH.'Core/Model.class.php', // 模型类
),
// 项目别名定义文件 [支持数组直接定义或者文件名定义]
'alias' => array(
'Model' => MODE_PATH.'Amf/Model.class.php',
'Db' => MODE_PATH.'Phprpc/Db.class.php',
),
// 系统行为定义文件 [必须 支持数组直接定义或者文件名定义 ]
'extends' => array(),
// 项目应用行为定义文件 [支持数组直接定义或者文件名定义]
'tags' => array(),
); | 10npsite | trunk/DThinkPHP/Extend/Mode/phprpc.php | PHP | asf20 | 1,558 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: lite.php 2702 2012-02-02 12:35:01Z liu21st $
// Lite模式定义文件
return array(
'core' => array(
THINK_PATH.'Common/functions.php', // 系统函数库
CORE_PATH.'Core/Log.class.php',// 日志处理
MODE_PATH.'Lite/App.class.php', // 应用程序类
MODE_PATH.'Lite/Action.class.php',// 控制器类
MODE_PATH.'Lite/Dispatcher.class.php',
),
// 项目别名定义文件 [支持数组直接定义或者文件名定义]
'alias' => array(
'Model' => MODE_PATH.'Lite/Model.class.php',
'Db' => MODE_PATH.'Lite/Db.class.php',
'ThinkTemplate' => CORE_PATH.'Template/ThinkTemplate.class.php',
'TagLib' => CORE_PATH.'Template/TagLib.class.php',
'Cache' => CORE_PATH.'Core/Cache.class.php',
'Debug' => CORE_PATH.'Util/Debug.class.php',
'Session' => CORE_PATH.'Util/Session.class.php',
'TagLibCx' => CORE_PATH.'Driver/TagLib/TagLibCx.class.php',
),
// 系统行为定义文件 [必须 支持数组直接定义或者文件名定义 ]
'extends' => MODE_PATH.'Lite/tags.php',
); | 10npsite | trunk/DThinkPHP/Extend/Mode/lite.php | PHP | asf20 | 1,840 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: App.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP 精简模式应用程序类
+------------------------------------------------------------------------------
*/
class App {
/**
+----------------------------------------------------------
* 应用程序初始化
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function run() {
// 取得模块和操作名称
define('MODULE_NAME', App::getModule()); // Module名称
define('ACTION_NAME', App::getAction()); // Action操作
// 记录应用初始化时间
if(C('SHOW_RUN_TIME')) $GLOBALS['_initTime'] = microtime(TRUE);
// 执行操作
R(MODULE_NAME.'/'.ACTION_NAME);
// 保存日志记录
if(C('LOG_RECORD')) Log::save();
return ;
}
/**
+----------------------------------------------------------
* 获得实际的模块名称
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static private function getModule() {
$var = C('VAR_MODULE');
$module = !empty($_POST[$var]) ?
$_POST[$var] :
(!empty($_GET[$var])? $_GET[$var]:C('DEFAULT_MODULE'));
if(C('URL_CASE_INSENSITIVE')) {
// URL地址不区分大小写
define('P_MODULE_NAME',strtolower($module));
// 智能识别方式 index.php/user_type/index/ 识别到 UserTypeAction 模块
$module = ucfirst(parse_name(strtolower($module),1));
}
unset($_POST[$var],$_GET[$var]);
return $module;
}
/**
+----------------------------------------------------------
* 获得实际的操作名称
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static private function getAction() {
$var = C('VAR_ACTION');
$action = !empty($_POST[$var]) ?
$_POST[$var] :
(!empty($_GET[$var])?$_GET[$var]:C('DEFAULT_ACTION'));
unset($_POST[$var],$_GET[$var]);
return $action;
}
}; | 10npsite | trunk/DThinkPHP/Extend/Mode/Thin/App.class.php | PHP | asf20 | 3,397 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Db.class.php 2702 2012-02-02 12:35:01Z liu21st $
define('CLIENT_MULTI_RESULTS', 131072);
/**
+------------------------------------------------------------------------------
* ThinkPHP 简洁模式数据库中间层实现类
* 只支持mysql
+------------------------------------------------------------------------------
*/
class Db {
static private $_instance = null;
// 是否自动释放查询结果
protected $autoFree = false;
// 是否显示调试信息 如果启用会在日志文件记录sql语句
public $debug = false;
// 是否使用永久连接
protected $pconnect = false;
// 当前SQL指令
protected $queryStr = '';
// 最后插入ID
protected $lastInsID = null;
// 返回或者影响记录数
protected $numRows = 0;
// 返回字段数
protected $numCols = 0;
// 事务指令数
protected $transTimes = 0;
// 错误信息
protected $error = '';
// 当前连接ID
protected $linkID = null;
// 当前查询ID
protected $queryID = null;
// 是否已经连接数据库
protected $connected = false;
// 数据库连接参数配置
protected $config = '';
// 数据库表达式
protected $comparison = array('eq'=>'=','neq'=>'!=','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE');
// 查询表达式
protected $selectSql = 'SELECT%DISTINCT% %FIELDS% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT%';
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 数据库配置数组
+----------------------------------------------------------
*/
public function __construct($config=''){
if ( !extension_loaded('mysql') ) {
throw_exception(L('_NOT_SUPPERT_').':mysql');
}
$this->config = $this->parseConfig($config);
}
/**
+----------------------------------------------------------
* 连接数据库方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function connect() {
if(!$this->connected) {
$config = $this->config;
// 处理不带端口号的socket连接情况
$host = $config['hostname'].($config['hostport']?":{$config['hostport']}":'');
if($this->pconnect) {
$this->linkID = mysql_pconnect( $host, $config['username'], $config['password'],CLIENT_MULTI_RESULTS);
}else{
$this->linkID = mysql_connect( $host, $config['username'], $config['password'],true,CLIENT_MULTI_RESULTS);
}
if ( !$this->linkID || (!empty($config['database']) && !mysql_select_db($config['database'], $this->linkID)) ) {
throw_exception(mysql_error());
}
$dbVersion = mysql_get_server_info($this->linkID);
if ($dbVersion >= "4.1") {
//使用UTF8存取数据库 需要mysql 4.1.0以上支持
mysql_query("SET NAMES '".C('DB_CHARSET')."'", $this->linkID);
}
//设置 sql_model
if($dbVersion >'5.0.1'){
mysql_query("SET sql_mode=''",$this->linkID);
}
// 标记连接成功
$this->connected = true;
// 注销数据库连接配置信息
unset($this->config);
}
}
/**
+----------------------------------------------------------
* 释放查询结果
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function free() {
mysql_free_result($this->queryID);
$this->queryID = 0;
}
/**
+----------------------------------------------------------
* 执行查询 主要针对 SELECT, SHOW 等指令
* 返回数据集
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function query($str='') {
$this->connect();
if ( !$this->linkID ) return false;
if ( $str != '' ) $this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) { $this->free(); }
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID = mysql_query($this->queryStr, $this->linkID);
$this->debug();
if ( !$this->queryID ) {
if ( $this->debug )
throw_exception($this->error());
else
return false;
} else {
$this->numRows = mysql_num_rows($this->queryID);
return $this->getAll();
}
}
/**
+----------------------------------------------------------
* 执行语句 针对 INSERT, UPDATE 以及DELETE
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str sql指令
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function execute($str='') {
$this->connect();
if ( !$this->linkID ) return false;
if ( $str != '' ) $this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) { $this->free(); }
N('db_write',1);
// 记录开始执行时间
G('queryStartTime');
$result = mysql_query($this->queryStr, $this->linkID) ;
$this->debug();
if ( false === $result) {
if ( $this->debug )
throw_exception($this->error());
else
return false;
} else {
$this->numRows = mysql_affected_rows($this->linkID);
$this->lastInsID = mysql_insert_id($this->linkID);
return $this->numRows;
}
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function startTrans() {
$this->connect(true);
if ( !$this->linkID ) return false;
//数据rollback 支持
if ($this->transTimes == 0) {
mysql_query('START TRANSACTION', $this->linkID);
}
$this->transTimes++;
return ;
}
/**
+----------------------------------------------------------
* 用于非自动提交状态下面的查询提交
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function commit() {
if ($this->transTimes > 0) {
$result = mysql_query('COMMIT', $this->linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
return false;
}
}
return true;
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function rollback() {
if ($this->transTimes > 0) {
$result = mysql_query('ROLLBACK', $this->linkID);
$this->transTimes = 0;
if(!$result){
throw_exception($this->error());
return false;
}
}
return true;
}
/**
+----------------------------------------------------------
* 获得所有的查询数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function getAll() {
if ( !$this->queryID ) {
throw_exception($this->error());
return false;
}
//返回数据集
$result = array();
if($this->numRows >0) {
while($row = mysql_fetch_assoc($this->queryID)){
$result[] = $row;
}
mysql_data_seek($this->queryID,0);
}
return $result;
}
/**
+----------------------------------------------------------
* 关闭数据库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function close() {
if (!empty($this->queryID))
mysql_free_result($this->queryID);
if ($this->linkID && !mysql_close($this->linkID)){
throw_exception($this->error());
}
$this->linkID = 0;
}
/**
+----------------------------------------------------------
* 数据库错误信息
* 并显示当前的SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function error() {
$this->error = mysql_error($this->linkID);
if($this->queryStr!=''){
$this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
}
return $this->error;
}
/**
+----------------------------------------------------------
* SQL指令安全过滤
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $str SQL字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function escapeString($str) {
return mysql_escape_string($str);
}
/**
+----------------------------------------------------------
* 析构方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __destruct() {
// 关闭连接
$this->close();
}
/**
+----------------------------------------------------------
* 取得数据库类实例
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @return mixed 返回数据库驱动类
+----------------------------------------------------------
*/
public static function getInstance($db_config='') {
if ( self::$_instance==null ){
self::$_instance = new Db($db_config);
}
return self::$_instance;
}
/**
+----------------------------------------------------------
* 分析数据库配置信息,支持数组和DSN
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param mixed $db_config 数据库配置信息
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function parseConfig($db_config='') {
if ( !empty($db_config) && is_string($db_config)) {
// 如果DSN字符串则进行解析
$db_config = $this->parseDSN($db_config);
}else if(empty($db_config)){
// 如果配置为空,读取配置文件设置
$db_config = array (
'dbms' => C('DB_TYPE'),
'username' => C('DB_USER'),
'password' => C('DB_PWD'),
'hostname' => C('DB_HOST'),
'hostport' => C('DB_PORT'),
'database' => C('DB_NAME'),
'dsn' => C('DB_DSN'),
'params' => C('DB_PARAMS'),
);
}
return $db_config;
}
/**
+----------------------------------------------------------
* DSN解析
* 格式: mysql://username:passwd@localhost:3306/DbName
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $dsnStr
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function parseDSN($dsnStr) {
if( empty($dsnStr) ){return false;}
$info = parse_url($dsnStr);
if($info['scheme']){
$dsn = array(
'dbms' => $info['scheme'],
'username' => isset($info['user']) ? $info['user'] : '',
'password' => isset($info['pass']) ? $info['pass'] : '',
'hostname' => isset($info['host']) ? $info['host'] : '',
'hostport' => isset($info['port']) ? $info['port'] : '',
'database' => isset($info['path']) ? substr($info['path'],1) : ''
);
}else {
preg_match('/^(.*?)\:\/\/(.*?)\:(.*?)\@(.*?)\:([0-9]{1, 6})\/(.*?)$/',trim($dsnStr),$matches);
$dsn = array (
'dbms' => $matches[1],
'username' => $matches[2],
'password' => $matches[3],
'hostname' => $matches[4],
'hostport' => $matches[5],
'database' => $matches[6]
);
}
return $dsn;
}
/**
+----------------------------------------------------------
* 数据库调试 记录当前SQL
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
*/
protected function debug() {
// 记录操作结束时间
if ( $this->debug ) {
G('queryEndTime');
Log::record($this->queryStr." [ RunTime:".G('queryStartTime','queryEndTime',6)."s ]",Log::SQL);
}
}
/**
+----------------------------------------------------------
* 获取最近一次查询的sql语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastSql() {
return $this->queryStr;
}
/**
+----------------------------------------------------------
* 获取最近插入的ID
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getLastInsID(){
return $this->lastInsID;
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Thin/Db.class.php | PHP | asf20 | 18,093 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Model.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP 简洁模式Model模型类
* 只支持原生SQL操作 支持多数据库连接和切换
+------------------------------------------------------------------------------
*/
class Model {
// 当前数据库操作对象
protected $db = null;
// 数据表前缀
protected $tablePrefix = '';
// 模型名称
protected $name = '';
// 数据库名称
protected $dbName = '';
// 数据表名(不包含表前缀)
protected $tableName = '';
// 实际数据表名(包含表前缀)
protected $trueTableName ='';
// 最近错误信息
protected $error = '';
/**
+----------------------------------------------------------
* 架构函数
* 取得DB类的实例对象
+----------------------------------------------------------
* @param string $name 模型名称
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($name='') {
// 模型初始化
$this->_initialize();
// 获取模型名称
if(!empty($name)) {
$this->name = $name;
}elseif(empty($this->name)){
$this->name = $this->getModelName();
}
// 数据库初始化操作
// 获取数据库操作对象
// 当前模型有独立的数据库连接信息
$this->db(0,empty($this->connection)?$connection:$this->connection);
// 设置表前缀
$this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX');
}
// 回调方法 初始化模型
protected function _initialize() {}
/**
+----------------------------------------------------------
* SQL查询
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $sql SQL指令
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function query($sql) {
if(is_array($sql)) {
return $this->patchQuery($sql);
}
if(!empty($sql)) {
if(strpos($sql,'__TABLE__')) {
$sql = str_replace('__TABLE__',$this->getTableName(),$sql);
}
return $this->db->query($sql);
}else{
return false;
}
}
/**
+----------------------------------------------------------
* 执行SQL语句
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $sql SQL指令
+----------------------------------------------------------
* @return false | integer
+----------------------------------------------------------
*/
public function execute($sql='') {
if(!empty($sql)) {
if(strpos($sql,'__TABLE__')) {
$sql = str_replace('__TABLE__',$this->getTableName(),$sql);
}
$result = $this->db->execute($sql);
return $result;
}else {
return false;
}
}
/**
+----------------------------------------------------------
* 得到当前的数据对象名称
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getModelName() {
if(empty($this->name)) {
$this->name = substr(get_class($this),0,-5);
}
return $this->name;
}
/**
+----------------------------------------------------------
* 得到完整的数据表名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getTableName() {
if(empty($this->trueTableName)) {
$tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
if(!empty($this->tableName)) {
$tableName .= $this->tableName;
}else{
$tableName .= parse_name($this->name);
}
$this->trueTableName = strtolower($tableName);
}
return (!empty($this->dbName)?$this->dbName.'.':'').$this->trueTableName;
}
/**
+----------------------------------------------------------
* 启动事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function startTrans() {
$this->commit();
$this->db->startTrans();
return ;
}
/**
+----------------------------------------------------------
* 提交事务
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function commit() {
return $this->db->commit();
}
/**
+----------------------------------------------------------
* 事务回滚
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function rollback() {
return $this->db->rollback();
}
/**
+----------------------------------------------------------
* 切换当前的数据库连接
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param integer $linkNum 连接序号
* @param mixed $config 数据库连接信息
* @param array $params 模型参数
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function db($linkNum,$config='',$params=array()){
static $_db = array();
if(!isset($_db[$linkNum])) {
// 创建一个新的实例
$_db[$linkNum] = Db::getInstance($config);
}elseif(NULL === $config){
$_db[$linkNum]->close(); // 关闭数据库连接
unset($_db[$linkNum]);
return ;
}
if(!empty($params)) {
if(is_string($params)) parse_str($params,$params);
foreach ($params as $name=>$value){
$this->setProperty($name,$value);
}
}
// 切换数据库连接
$this->db = $_db[$linkNum];
return $this;
}
};
?> | 10npsite | trunk/DThinkPHP/Extend/Mode/Thin/Model.class.php | PHP | asf20 | 8,267 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Action.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP 简洁模式Action控制器基类
+------------------------------------------------------------------------------
*/
abstract class Action {
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct() {
//控制器初始化
if(method_exists($this,'_initialize')) {
$this->_initialize();
}
}
/**
+----------------------------------------------------------
* 魔术方法 有不存在的操作的时候执行
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名
* @param array $parms 参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$parms) {
if(strtolower($method) == strtolower(ACTION_NAME)) {
// 如果定义了_empty操作 则调用
if(method_exists($this,'_empty')) {
$this->_empty($method,$parms);
}else {
// 抛出异常
throw_exception(L('_ERROR_ACTION_').ACTION_NAME);
}
}else{
throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
}
}
} | 10npsite | trunk/DThinkPHP/Extend/Mode/Thin/Action.class.php | PHP | asf20 | 2,385 |
<?php
class SaeMysql extends SaeObject {
static $link;
static $charset;
function __construct() {
global $sae_config;
self::$charset = $sae_config['db_charset'];
$this->connect();
parent::__construct();
}
//连接数据库
protected function connect() {
global $sae_config;
if(empty($sae_config['db_name'])) die(Imit_L('_SAE_PLEASE_CONFIG_DB_'));
self::$link = mysql_connect(SAE_MYSQL_HOST_M, SAE_MYSQL_USER, SAE_MYSQL_PASS) or die(Imit_L('_SAE_CONNECT_DB_ERR_'));
mysql_select_db(SAE_MYSQL_DB, self::$link);
mysql_query("set names " . self::$charset, self::$link);
if (!mysql_select_db(SAE_MYSQL_DB, self::$link)) {
//如果数据库不存在,自动建立
mysql_query('create database ' . SAE_MYSQL_DB, self::$link);
mysql_select_db(SAE_MYSQL_DB, self::$link) or Imit_L('_SAE_DATABASE_NOT_EXIST_');
}
}
//返回影响条数
public function affectedRows() {
return mysql_affected_rows(self::$link);
}
//关闭数据库
public function closeDb() {
mysql_close(self::$link);
}
//escape
public function escape($str) {
return mysql_real_escape_string($str, self::$link);
}
//获得数据,返回数组
public function getData($sql) {
$this->last_sql = $sql;
$result = mysql_query($sql, self::$link);
if(!$result){
return false;
}
$this->save_error();
$data = array();
while ($arr = mysql_fetch_array($result)) {
$data[] = $arr;
}
mysql_free_result($result);
return $data;
}
//返回第一条数据
public function getLine($sql) {
$data = $this->getData($sql);
if ($data) {
return @reset($data);
} else {
return false;
}
}
//返回第一条记录的第一个字段值
public function getVar($sql) {
$data = $this->getLine($sql);
if ($data) {
return $data[@reset(@array_keys($data))];
} else {
return false;
}
}
//返回最后一个id
public function lastId() {
return mysql_insert_id(self::$link);
}
//运行sql语句
public function runSql($sql) {
$ret = mysql_query($sql);
$this->save_error();
return $ret;
}
//设置项目名
public function setAppname($appname) {
}
//设置字符集
public function setCharset($charset) {
self::$charset = $charset;
mysql_query("set names " . self::$charset, self::$link);
}
//设置端口
public function setPort($port) {
}
protected function save_error() {
$this->errmsg = mysql_error(self::$link);
$this->errno = mysql_errno(self::$link);
}
}
| 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/SaeMysql.class.php | PHP | asf20 | 3,025 |
<?php
class SaeImage extends SaeObject {
private $_img_data = ''; //图片数据
private $_options = array(); //图片选项
private $_width = 0;
private $_height = 0;
private $_image = null; //存储image资源
const image_limitsize = 2097152;
public function __construct($img_data='') {
parent::__construct();
return $this->setData($img_data);
}
//添加文字注释
public function annotate($txt, $opacity=0.5, $gravity=SAE_Static, $font=array()) {
$opacity = floatval($opacity);
if ($this->imageNull())
return false;
//设置默认字体样式
$font_default = array('name' => SAE_SimSun, 'size' => 15, 'weight' => 300, 'color' => 'black');
$font = array_merge($font_default, $font);
array_push($this->_options, array('act' => 'annotate', "txt" => $txt, "opacity" => $opacity,
"gravity" => $gravity, "font" => array("name" => $font['name'], "size" => $font["size"],
"weight" => $font["weight"], "color" => $font["color"])));
return true;
}
//数据重新初始化
public function clean() {
$this->_img_data = '';
$this->_options = array();
$this->_width = 0;
$this->_height = 0;
$this->_image = null;
}
//图片合成, data为数组,在其他操作执行前进行操作
public function composite($width, $height, $color="black") {
$width = intval($width);
$height = intval($height);
if ($this->imageNull())
return false;
array_push($this->_options, array('act' => 'composite', "width" => $width, "height" => $height, "color" => $color));
return true;
}
//裁剪图片
public function crop($lx=0.25, $rx=0.75, $by=0.25, $ty=0.75) {
$lx = floatval($lx);
$rx = floatval($rx);
$by = floatval($by);
$ty = floatval($ty);
if ($this->imageNull())
return false;
array_push($this->_options, array('act' => 'crop', "lx" => $lx, "rx" => $rx, "by" => $by, "ty" => $ty));
return true;
}
//进行图片处理操作
public function exec($format='jpg', $display=false) {
if ($this->imageNull())
return false;
if (!in_array($format, array('jpg', 'gif', 'png'))) {
$this->errno = SAE_ErrParameter;
$this->errmsg = "format must be one of 'jpg', 'gif' and 'png'";
return false;
}
if ($format == "jpg")
$format = "jpeg";
if ($this->_options[0]["act"] == "composite" && !is_array($this->_img_data)) {
$this->errno = SAE_ErrParameter;
$this->errmsg = "composite imagedata must be an array, pls see doc:";
return false;
}
if ($this->_options[0]["act"] != "composite" && is_array($this->_img_data)) {
$this->errno = SAE_ErrParameter;
$this->errmsg = "imagedata is array only when composite image and composite must be the first operation";
return false;
}
if (!$this->_image_create())
return false;
//循环处理
foreach ($this->_options as $options) {
call_user_func(array($this, "_" . $options['act']), $options);
}
$imgFun = 'image' . $format;
if ($display) {
header("Content-Type: image/" . $format);
$imgFun($this->_image);
} else {
ob_start();
$imgFun($this->_image);
return ob_get_clean();
}
imagedestroy($this->_image);
}
//创建画布
private function _image_create() {
if ($this->_options[0]["act"] == "composite") {
//合并多张图片
$w = $this->_options[0]["width"];
$h = $this->_options[0]["height"];
$this->_width=$w;
$this->_height=$h;
$_image = imagecreatetruecolor($w, $h);
//设置背景颜色
$color = $this->toRGB($this->_options[0]['color']);
$bg = imagecolorallocate($_image, $color['r'], $color['g'], $color['b']);
imagefill($_image, 0, 0, $bg);
foreach ($this->_img_data as $data) {
$img_data = $data[0];
$x = isset($data[1]) ? $data[1] : 0;
$y = isset($data[2]) ? $data[2] : 0;
$o = isset($data[3]) ? $data[3] * 100 : 100;
$p = isset($data[4]) ? $data[4] : SAE_TOP_LEFT;
$tmp_file = tempnam(SAE_TMP_PATH, "SAE_IMAGE");
if (!file_put_contents($tmp_file, $img_data)) {
$this->errmsg = "file_put_contents to SAETMP_PATH failed when getImageAttr";
return false;
}
$info = getimagesize($tmp_file);
$sw = $info[0];
$sh = $info[1];
$image_type = strtolower(substr(image_type_to_extension($info[2]), 1));
$createFun = "imagecreatefrom" . $image_type;
$sImage = $createFun($tmp_file);
//设置位置
switch ($p) {
case SAE_TOP_LEFT:
$dst_x = $x;
$dst_y = -$y;
break;
case SAE_TOP_CENTER:
$dst_x = ($w - $sw) / 2 + $x;
$dst_y = -$y;
break;
case SAE_TOP_RIGHT:
$dst_x = $w - $sw + $x;
$dst_y = -$y;
break;
case SAE_CENTER_LEFT:
$dst_x = $x;
$dst_y = ($h - $sh) / 2 - $y;
break;
case SAE_CENTER_CENTER:
$dst_x = ($w - $sw) / 2 + $x;
$dst_y = ($h - $sh) / 2 - $y;
break;
case SAE_CENTER_RIGHT:
$dst_x = $w - $sw + $x;
$dst_y = ($h - $sh) / 2 - $y;
break;
case SAE_BOTTOM_LEFT:
$dst_x = $x;
$dst_y = $h - $sh - $y;
break;
case SAE_BOTTOM_CENTER:
$dst_x = ($w - $sw) / 2 + $x;
$dst_y = $h - $sh - $y;
break;
case SAE_BOTTOM_RIGHT:
$dst_x = $w - $sw + $x;
$dst_y = $h - $sh - $y;
break;
}
$this->imagecopymerge_alpha($_image, $sImage, $dst_x, $dst_y, 0, 0, $sw, $sh, $o);
unlink($tmp_file);
}
$this->_image = $_image;
unset($this->_options[0]);
} else {
if (is_null($this->_image))
$this->getImageAttr();
}
return true;
}
//修复合并时png透明问题
private function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
$w = imagesx($src_im);
$h = imagesy($src_im);
$cut = imagecreatetruecolor($src_w, $src_h);
imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
imagecopymerge($dst_im, $cut, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h,$pct);
}
//水平翻转
public function flipH() {
if ($this->imageNull())
return false;
array_push($this->_options, array('act' => 'flipH'));
return true;
}
//垂直翻转
public function flipV() {
if ($this->imageNull())
return false;
array_push($this->_options, array('act' => 'flipV'));
return true;
}
//获取图像属性
public function getImageAttr() {
if ($this->imageNull())
return false;
$fn = tempnam(SAE_TMP_PATH, "SAE_IMAGE");
if ($fn == false) {
$this->errmsg = "tempnam call failed when getImageAttr";
return false;
}
if (!file_put_contents($fn, $this->_img_data)) {
$this->errmsg = "file_put_contents to SAETMP_PATH failed when getImageAttr";
return false;
}
if (!($size = getimagesize($fn, $info))) {
$this->errmsg = "getimagesize failed when getImageAttr";
return false;
}
foreach ($info as $k => $v) {
$size[$k] = $v;
}
$this->_width = $size[0];
$this->_height = $size[1];
//建立图片资源
$image_type = strtolower(substr(image_type_to_extension($size[2]), 1));
$createFun = "imagecreatefrom" . $image_type;
$this->_image = $createFun($fn);
unlink($fn); //删除临时文件
return $size;
}
//去噪点,改善图片质量,通常用于exec之前
public function improve() {
if ($this->imageNull())
return false;
array_push($this->_options, array('act' => 'improve'));
return true;
}
//等比例缩放
public function resize($width=0, $height=0) {
$width = intval($width);
$height = intval($height);
if ($this->imageNull())
return false;
array_push($this->_options, array('act' => 'resize', "width" => $width, "height" => $height));
return true;
}
//按比例缩放
public function resizeRatio($ratio=0.5) {
$ratio = floatval($ratio);
if ($this->imageNull())
return false;
if ($this->_width == 0) {
$attr = $this->getImageAttr();
if (!$attr)
return false;
}
array_push($this->_options, array('act' => 'resize', "width" => $this->_width * $ratio, "height" => $this->_height * $ratio));
return true;
}
//顺时针旋转图片
public function rotate($degree=90) {
$degree = intval($degree);
if ($this->imageNull())
return false;
array_push($this->_options, array('act' => 'rotate', "degree" => $degree));
return true;
}
//设置数据
public function setData($img_data) {
if (is_array($img_data)) {
$_size = 0;
foreach ($img_data as $k => $i) {
if (count($i) < 1 || count($i) > 5) {
$this->errno = SAE_ErrParameter;
$this->errmsg = "image data array you supplied invalid";
return false;
}
if (is_null($i[1]) || $i[1] === false)
$img_data[$k][1] = 0;
if (is_null($i[2]) || $i[1] === false)
$img_data[$k][2] = 0;
if (is_null($i[3]) || $i[1] === false)
$img_data[$k][3] = 1;
if (is_null($i[4]) || $i[1] === false)
$img_data[$k][4] = SAE_TOP_LEFT;
$_size += strlen($i[0]);
}
if ($_size > self::image_limitsize) {
$this->errno = SAE_ErrParameter;
$this->errmsg = "image datas length more than 2M";
return false;
}
} else if (strlen($img_data) > self::image_limitsize) {
$this->errno = SAE_ErrParameter;
$this->errmsg = "image data length more than 2M";
return false;
}
$this->_img_data = $img_data;
return true;
}
//判断图片数据是否可用
private function imageNull() {
if (empty($this->_img_data)) {
$this->errno = SAE_ErrParameter;
$this->errmsg = "image data cannot be empty";
return true;
} else {
return false;
}
}
//将颜色转换为RGB格式
private function toRGB($color) {
$color = trim($color);
if (preg_match('/^rgb\((\d+),(\d+),(\d+)\)$/i', $color, $arr)) {
//支持rgb(r,g,b)格式
return array(
'r' => $arr[1],
'g' => $arr[2],
'b' => $arr[3]
);
}
$e_color = array(
//支持英文颜色名
'black' => '#000',
'red' => '#f00',
'blue'=>'#00f'
//TODU 增加其他
);
$hexColor = str_replace(array_keys($e_color), array_values($e_color), $color);
$color = str_replace('#', '', $hexColor);
if (strlen($color) > 3) {
$rgb = array(
'r' => hexdec(substr($color, 0, 2)),
'g' => hexdec(substr($color, 2, 2)),
'b' => hexdec(substr($color, 4, 2))
);
} else {
$color = str_replace('#', '', $hexColor);
$r = substr($color, 0, 1) . substr($color, 0, 1);
$g = substr($color, 1, 1) . substr($color, 1, 1);
$b = substr($color, 2, 1) . substr($color, 2, 1);
$rgb = array(
'r' => hexdec($r),
'g' => hexdec($g),
'b' => hexdec($b)
);
}
return $rgb;
}
/**
* 添加文字
* 参数格式
* array("txt" => $txt, "opacity" => $opacity,
"gravity" => $gravity, "font" => array("name" => $font['name'], "size" => $font["size"],
"weight" => $font["weight"], "color" => $font["color"]))
* @param array $args
*/
private function _annotate($args) {
$font = $args['font'];
$rgb = $this->toRGB($font['color']);
$color = imagecolorclosestalpha($this->_image, $rgb['r'], $rgb['g'], $rgb['b'], (1 - $args['opacity']) * 100);
//设置位置
$fontSize = imagettfbbox($font['size'], 0, $font['name'], $args['txt']);
$textWidth = $fontSize [4]; //取出宽
$textHeight = abs($fontSize[7]); //取出高
switch ($args['gravity']) {
case SAE_NorthWest:
$x=0;
$y=$textHeight;
break;
case SAE_North:
$x=($this->_width-$textWidth)/2;;
$y=$textHeight;
break;
case SAE_NorthEast:
$x=$this->_width-$textWidth;;
$y=$textHeight;
break;
case SAE_West:
$x=0;
$y=($this->_height-$textHeight)/2;
break;
case SAE_East:
$x=$this->_width-$textWidth;
$y=($this->_height-$textHeight)/2;
break;
case SAE_SouthWest:
$x=0;
$y=$this->_height-$textHeight;
break;
case SAE_South:
$x=($this->_width-$textWidth)/2;
$y=$this->_height-$textHeight;
break;
case SAE_SouthEast:
$x=$this->_width-$textWidth;
$y=$this->_height-$textHeight;
break;
case SAE_Static:
default :
$x=($this->_width-$textWidth)/2;
$y=($this->_height-$textHeight)/2;
break;
}
imagettftext($this->_image, $font['size'], 0, $x, $y, $color, $font['name'], $args['txt']);
}
/**
*截取图片
* 参数 array("lx" => $lx, "rx" => $rx, "by" => $by, "ty" => $ty)
* @param array $args
*/
private function _crop($args){
$width=($args['rx']-$args['lx'])*$this->_width;
$height=($args['ty']-$args['by'])*$this->_height;
$x=$args['lx']*$this->_width;
$y=$args['by']*$this->_height;
$_image=imagecreatetruecolor($width, $height);
imagecopyresampled($_image,$this->_image,0,0,$x,$y,
$width,$height,$width,$height);
$this->_image=$_image;
}
/**
*图片放缩
* 参数:array( "width" => $width, "height" => $height)
* @param array $args
*/
private function _resize($args){
if($args['width']==0 && $args['heigth']==0) return ;
if($args['width']==0){
//高度固定等比例放缩
$h=$args['heigth'];
$w=$h/$this->_height*$this->_width;
}elseif($args['heigth']==0){
//宽度固定等比例放缩
$w=$args['width'];
$h=$w/$this->_width*$this->_height;
}else{
$w=$args['width'];
$h=$args['height'];
}
$_image=imagecreatetruecolor($w, $h);
imagecopyresampled($_image, $this->_image, 0, 0, 0, 0, $w, $h, $this->_width, $this->_height);
$this->_image=$_image;
}
/**
*旋转角度
* @param array $args
*/
private function _rotate($args){
$this->_image=imagerotate($this->_image, 360-$args['degree'],0);
}
//水平翻转
private function _flipH($args) {
$_image=imagecreatetruecolor($this->_width, $this->_height);
for ($i = 0; $i < $this->_width; $i++) {
imagecopyresampled($_image, $this->_image, ($this->_width - $i), 0, $i, 0, 1, $this->_height, 1, $this->_height);
}
$this->_image=$_image;
}
//垂直翻转
private function _flipV($args) {
$this->_flipH(array());
$this->_rotate(array('degree'=>180));
}
//去除噪点
private function _improve($args){
//本地不做任何处理
}
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/SaeImage.class.php | PHP | asf20 | 18,057 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <www.3g4k.com>
// +----------------------------------------------------------------------
// $Id: SaeRank.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
class SaeRank extends SaeObject{
public function __construct(){
parent::__construct();
}
public function clear($namespace){
if($this->emptyName($namespace)) return false;
self::$db->runSql("delete from sae_rank where namespace='$namespace'");
self::$db->runSql("delete from sae_rank_list where namespace='$namespace'");
return true;
}
//创建
//expire过期时间的单位为分钟
public function create($namespace,$number,$expire=0){
//判断是否存在
if(!$this->emptyName($namespace)){
$this->errno=-10;
$this->errmsg=Imit_L("_SAE_THE_RANK_IS_EXISTED_");
return false;
}
$ret=self::$db->runSql("insert into sae_rank(namespace,num,expire,createtime) values('$namespace','$number','$expire','".time()."')");
if($ret===false){
$this->errno=-6;
$this->errmsg=Imit_L("_SAE_ERR_");
return false;
}else{
return true;
}
}
//减去
public function decrease($namespace,$key,$value,$renkReurn=false){
if($this->emptyName($namespace)) return false;
$this->check($namespace);
if(self::$db->getVar("select count(*) from sae_rank_list where namespace='$namespace' and k='$key'")==0){
//如果不存在
$this->errno=-3;
$this->errmsg=Imit_L("_SAE_NOT_IN_BILLBOARD_");
return false;
}else{
$ret=self::$db->runSql("update sae_rank_list set v=v-$value where namespace='$namespace' and k='$key'");
if($ret===false) return false;
if(rankReturn){
return $this->getRank($namespace,$key);
}
return true;
}
}
//删除键
public function delete($namespace,$key,$rankReturn=false){
if($this->emptyName($namespace)) return false;
if($rankReturn) $r=$this->getRank($namespace,$key);
$ret=self::$db->runSql("delete from sae_rank_list where namespace='$namespace' and k='$key'");
if($ret===false){
$this->errno=-6;
$this->errmsg=Imit_L("_SAE_ERR_");
return false;
}else{
if($rankReturn) return $r;
return true;
}
}
//获得排行榜
public function getList($namespace,$order=false,$offsetFrom=0,$offsetTo=PHP_INT_MAX){
//判断是否存在
if($this->emptyName($namespace)) return false;
$ord="v asc";
//获得列表
if($order) $ord="v desc";
//判断是否有长度限制
$num=self::$db->getVar("select num from sae_rank where namespace='$namespace'");
if($num!=0){
$ord="v desc";//todu,完善和sae数据一致。
if($offsetTo>$num) $offsetTo=$num;
}
$data=self::$db->getData("select * from sae_rank_list where namespace='$namespace' order by $ord limit $offsetFrom,$offsetTo");
$ret=array();
foreach($data as $r){
$ret[$r['k']]=$r['v'];
}
$this->check($namespace);//检查过期
if($data===false){
$this->errno=-6;
$this->errmsg=Imit_L("_SAE_ERR_");
return false;
}else{
return $ret;
}
}
//获得某个键的排名
//注意排名是从0开始的
public function getRank($namespace,$key){
if($this->emptyName($namespace)) return false;
$v=self::$db->getVar("select v from sae_rank_list where namespace='$namespace' and k='$key'");
$ret=self::$db->getVar("select count(*) from sae_rank_list where namespace='$namespace' and v>=$v");
if(!$ret){
$this->errno=-3;
$this->errmsg=Imit_L("_SAE_NOT_IN_BILLBOARD_");
return false;
}
return $ret-1;
}
//增加值
public function increase($namespace,$key,$value,$rankReturn=false){
if($this->emptyName($namespace)) return false;
$this->check($namespace);
if(self::$db->getVar("select count(*) from sae_rank_list where namespace='$namespace' and k='$key'")==0){
//如果不存在
$this->errno=-3;
$this->errmsg=Imit_L("_SAE_NOT_IN_BILLBOARD_");
return false;
}else{
$ret=self::$db->runSql("update sae_rank_list set v=v+$value where namespace='$namespace' and k='$key'");
if($ret===false) return false;
if(rankReturn){
return $this->getRank($namespace,$key);
}
return true;
}
}
//设置值
public function set($namespace,$key,$value,$rankReturn=false){
//判断是否存在
if($this->emptyName($namespace)) return false;
//检查是否过期
$this->check($namespace);
//设置值
//判断是否有此key
if(self::$db->getVar("select count(*) from sae_rank_list where namespace='$namespace' and k='$key'")==0){
$setarr=array(
'namespace'=>$namespace,
'k'=>$key,
'v'=>$value
);
$ret=self::$db->runSql("insert into sae_rank_list(namespace,k,v) values('$namespace','$key','$value')");
}else{
$ret=self::$db->runSql("update sae_rank_list set v='$value' where namespace='$namespace' and k='$key'");
}
if($ret===false) return false;
if($rankReturn){
//返回排名
return $this->getRank($namespace,$key);
}
return true;
}
//判断是否为空
private function emptyName($name){
$num=self::$db->getVar("select count(*) from sae_rank where namespace='$name'");
if($num==0){
return true;
}else{
$this->errno=-4;
$this->errmsg=Imit_L("_SAE_BILLBOARD_NOT_EXISTS_");
return false;
}
}
//检查是否过期
private function check($name){
$data=self::$db->getLine("select * from sae_rank where namespace='$name'");
if($data['expire'] && $data['createtime']+$data['expire']*60<=time()){
self::$db->runSql("delete from sae_rank_list where namespace='$name'");
//重新设置创建时间
self::$db->runSql("update sae_rank set createtime='".time()."' where namespace='$name'");
}
}
}
?> | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/SaeRank.class.php | PHP | asf20 | 6,491 |
<?php
/**
* SAE数据抓取服务
*
* @author zhiyong
* @version $Id: SaeFetchurl.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
* @package sae
*
*/
/**
* SAE数据抓取class
*
* SaeFetchurl用于抓取外部数据。支持的协议为http/https。<br />
* 该类已被废弃,请直接使用curl抓取外部资源
* @deprecated 该类已被废弃,请直接使用curl抓取外部资源
*
* 默认超时时间:
* - 连接超时: 5秒
* - 发送数据超时: 30秒
* - 接收数据超时: 40秒
*
* 抓取页面
* <code>
* $f = new SaeFetchurl();
* $content = $f->fetch('http://sina.cn');
* </code>
*
* 发起POST请求
* <code>
* $f = new SaeFetchurl();
* $f->setMethod('post');
* $f->setPostData( array('name'=> 'easychen' , 'email' => 'easychen@gmail.com' , 'file' => '文件的二进制内容') );
* $ret = $f->fetch('http://photo.sinaapp.com/save.php');
*
* //抓取失败时输出错误码和错误信息
* if ($ret === false)
* var_dump($f->errno(), $f->errmsg());
* </code>
*
* 错误码参考:
* - errno: 0 成功
* - errno: 600 fetchurl 服务内部错误
* - errno: 601 accesskey 不存在
* - errno: 602 认证错误,可能是secretkey错误
* - errno: 603 超出fetchurl的使用配额
* - errno: 604 REST 协议错误,相关的header不存在或其它错误,建议使用SAE提供的fetch_url函数
* - errno: 605 请求的URI格式不合法
* - errno: 606 请求的URI,服务器不可达。
*
* @author zhiyong
* @version $Id: SaeFetchurl.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
* @package sae
*
*/
class SaeFetchurl extends SaeObject
{
function __construct( $akey = NULL , $skey = NULL )
{
if( $akey === NULL )
$akey = SAE_ACCESSKEY;
if( $skey === NULL )
$skey = SAE_SECRETKEY;
$this->impl_ = new FetchUrl($akey, $skey);
$this->method_ = "get";
$this->cookies_ = array();
$this->opt_ = array();
$this->headers_ = array();
}
/**
* 设置acccesskey和secretkey
*
* 使用当前的应用的key时,不需要调用此方法
*
* @param string $akey
* @param string $skey
* @return void
* @author zhiyong
* @ignore
*/
public function setAuth( $akey , $skey )
{
$this->impl_->setAccesskey($akey);
$this->impl_->setSecretkey($skey);
}
/**
* @ignore
*/
public function setAccesskey( $akey )
{
$this->impl_->setAccesskey($akey);
}
/**
* @ignore
*/
public function setSecretkey( $skey )
{
$this->impl_->setSecretkey($skey);
}
/**
* 设置请求的方法(POST/GET/PUT... )
*
* @param string $method
* @return void
* @author zhiyong
*/
public function setMethod( $method )
{
$this->method_ = trim($method);
$this->opt_['method'] = trim($method);
}
/**
* 设置POST方法的数据
*
* @param array|string $post_data 当格式为array时,key为变量名称,value为变量值,使用multipart方式提交。当格式为string时,直接做为post的content提交。与curl_setopt($ch, CURLOPT_POSTFIELDS, $data)中$data的格式相同。
* @param bool $multipart value是否为二进制数据
* @return bool
* @author zhiyong
*/
public function setPostData( $post_data , $multipart = false )
{
$this->opt_["post"] = $post_data;
$this->opt_["multipart"] = $multipart;
return true;
}
/**
* 在发起的请求中,添加请求头
*
* 不可以使用此方法设定的头:
* - Content-Length
* - Host
* - Vary
* - Via
* - X-Forwarded-For
* - FetchUrl
* - AccessKey
* - TimeStamp
* - Signature
* - AllowTruncated //可使用setAllowTrunc方法来进行设定
* - ConnectTimeout //可使用setConnectTimeout方法来进行设定
* - SendTimeout //可使用setSendTimeout方法来进行设定
* - ReadTimeout //可使用setReadTimeout方法来进行设定
*
*
* @param string $name
* @param string $value
* @return bool
* @author zhiyong
*/
public function setHeader( $name , $value )
{
$name = trim($name);
if (!in_array(strtolower($name), FetchUrl::$disabledHeaders)) {
$this->headers_[$name] = $value;
return true;
} else {
trigger_error("Disabled FetchUrl Header:" . $name, E_USER_NOTICE);
return false;
}
}
/**
* 设置FetchUrl参数
*
* 参数列表:
* - truncated 布尔 是否截断
* - redirect 布尔 是否支持重定向
* - username 字符串 http认证用户名
* - password 字符串 http认证密码
* - useragent 字符串 自定义UA
*
* @param string $name
* @param string $value
* @return void
* @author Elmer Zhang
* @ignore
*/
public function setOpt( $name , $value )
{
$name = trim($name);
$this->opt_[$name] = $value;
}
/**
* 在发起的请求中,批量添加cookie数据
*
* @param array $cookies 要添加的Cookies,格式:array('key1' => 'value1', 'key2' => 'value2', ....)
* @return void
* @author zhiyong
*/
public function setCookies( $cookies = array() )
{
if ( is_array($cookies) and !empty($cookies) ) {
foreach ( $cookies as $k => $v ) {
$this->setCookie($k, $v);
}
}
}
/**
* 在发起的请求中,添加cookie数据,此函数可多次调用,添加多个cookie
*
* @param string $name
* @param string $value
* @return void
* @author zhiyong
*/
public function setCookie( $name , $value )
{
$name = trim($name);
array_push($this->cookies_, "$name=$value");
}
/**
* 是否允许截断,默认为不允许
*
* 如果设置为true,当发送数据超过允许大小时,自动截取符合大小的部分;<br />
* 如果设置为false,当发送数据超过允许大小时,直接返回false;
*
* @param bool $allow
* @return void
* @author zhiyong
*/
public function setAllowTrunc($allow) {
$this->opt_["truncated"] = $allow;
}
/**
* 设置连接超时时间,此时间必须小于SAE系统设置的时间,否则以SAE系统设置为准(默认为5秒)
*
* @param int $ms 毫秒
* @return void
* @author zhiyong
*/
public function setConnectTimeout($ms) {
$this->opt_["connecttimeout"] = $ms;
}
/**
* 设置发送超时时间,此时间必须小于SAE系统设置的时间,否则以SAE系统设置为准(默认为20秒)
*
* @param int $ms 毫秒
* @return void
* @author zhiyong
*/
public function setSendTimeout($ms) {
$this->opt_["sendtimeout"] = $ms;
}
/**
* 设置读取超时时间,此时间必须小于SAE系统设置的时间,否则以SAE系统设置为准(默认为60秒)
*
* @param int $ms 毫秒
* @return void
* @author zhiyong
*/
public function setReadTimeout($ms) {
$this->opt_["ReadTimeout"] = $ms;
}
/**
* 当请求页面是转向页时,是否允许跳转,SAE最大支持5次跳转(默认不跳转)
*
* @param bool $allow 是否允许跳转。true:允许,false:禁止,默认为true
* @return void
* @author zhiyong
*/
public function setAllowRedirect($allow = true) {
$this->opt_["redirect"] = $allow;
}
/**
* 设置HTTP认证用户名密码
*
* @param string $username HTTP认证用户名
* @param string $password HTTP认证密码
* @return void
* @author zhiyong
*/
public function setHttpAuth($username, $password) {
$this->opt_["username"] = $username;
$this->opt_["password"] = $password;
}
/**
* 发起请求
*
* <code>
* <?php
* echo "Use callback function\n";
*
* function demo($content) {
* echo strtoupper($content);
* }
*
* $furl = new SaeFetchurl();
* $furl->fetch($url, $opt, 'demo');
*
* echo "Use callback class\n";
*
* class Ctx {
* public function demo($content) {
* $this->c .= $content;
* }
* public $c;
* };
*
* $ctx = new Ctx;
* $furl = new SaeFetchurl();
* $furl->fetch($url, $opt, array($ctx, 'demo'));
* echo $ctx->c;
* ?>
* </code>
*
* @param string $url
* @param array $opt 请求参数,格式:array('key1'=>'value1', 'key2'=>'value2', ... )。参数列表:
* - truncated 布尔 是否截断
* - redirect 布尔 是否支持重定向
* - username 字符串 http认证用户名
* - password 字符串 http认证密码
* - useragent 字符串 自定义UA
* @param callback $callback 用来处理返回的数据的函数。可以为函数名或某个实例对象的方法。
* @return string 成功时读取到的内容,否则返回false
* @author zhiyong
*/
public function fetch( $url, $opt = NULL, $callback=NULL )
{
if (count($this->cookies_) != 0) {
$this->opt_["cookie"] = join("; ", $this->cookies_);
}
$opt = ($opt) ? array_merge($this->opt_, $opt) : $this->opt_;
return $this->impl_->fetch($url, $opt, $this->headers_, $callback);
}
/**
* 返回数据的header信息
*
* @param bool $parse 是否解析header,默认为true。
* @return array
* @author zhiyong
*/
public function responseHeaders($parse = true)
{
$items = explode("\r\n", $this->impl_->headerContent());
if (!$parse) {
return $items;
}
array_shift($items);
$headers = array();
foreach ($items as $_) {
$pos = strpos($_, ":");
$key = trim(substr($_, 0, $pos));
$value = trim(substr($_, $pos + 1));
if ($key == "Set-Cookie") {
if (array_key_exists($key, $headers)) {
array_push($headers[$key], trim($value));
} else {
$headers[$key] = array(trim($value));
}
} else {
$headers[$key] = trim($value);
}
}
return $headers;
}
/**
* 返回HTTP状态码
*
* @return int
* @author Elmer Zhang
*/
public function httpCode() {
return $this->impl_->httpCode();
}
/**
* 返回网页内容
* 常用于fetch()方法返回false时
*
* @return string
* @author Elmer Zhang
*/
public function body() {
return $this->impl_->body();
}
/**
* 返回头里边的cookie信息
*
* @param bool $all 是否返回完整Cookies信息。为true时,返回Cookie的name,value,path,max-age,为false时,只返回Cookies的name, value
* @return array
* @author zhiyong
*/
public function responseCookies($all = true)
{
$header = $this->impl_->headerContent();
$matchs = array();
$cookies = array();
$kvs = array();
if (preg_match_all('/Set-Cookie:\s([^\r\n]+)/i', $header, $matchs)) {
foreach ($matchs[1] as $match) {
$cookie = array();
$items = explode(";", $match);
foreach ($items as $_) {
$item = explode("=", trim($_));
$cookie[$item[0]]= $item[1];
}
array_push($cookies, $cookie);
$kvs = array_merge($kvs, $cookie);
}
}
if ($all) {
return $cookies;
} else {
unset($kvs['path']);
unset($kvs['max-age']);
return $kvs;
}
}
/**
* 返回错误码
*
* @return int
* @author zhiyong
*/
public function errno()
{
if ($this->impl_->errno() != 0) {
return $this->impl_->errno();
} else {
if ($this->impl_->httpCode() != 200) {
return $this->impl_->httpCode();
}
}
return 0;
}
/**
* 返回错误信息
*
* @return string
* @author zhiyong
*/
public function errmsg()
{
if ($this->impl_->errno() != 0) {
return $this->impl_->error();
} else {
if ($this->impl_->httpCode() != 200) {
return $this->impl_->httpDesc();
}
}
return "";
}
/**
* 将对象的数据重新初始化,用于多次重用一个SaeFetchurl对象
*
* @return void
* @author Elmer Zhang
*/
public function clean() {
$this->__construct();
}
/**
* 开启/关闭调试模式
*
* @param bool $on true:开启调试;false:关闭调试
* @return void
* @author Elmer Zhang
*/
public function debug($on) {
if ($on) {
$this->impl_->setDebugOn();
} else {
$this->impl_->setDebugOff();
}
}
private $impl_;
private $opt_;
private $headers_;
}
/**
* FetchUrl , the sub class of SaeFetchurl
*
*
* @package sae
* @subpackage fetchurl
* @author zhiyong
* @ignore
*/
class FetchUrl {
const end_ = "http://fetchurl.sae.sina.com.cn/" ;
const maxRedirect_ = 5;
public static $disabledHeaders = array(
'content-length',
'host',
'vary',
'via',
'x-forwarded-for',
'fetchurl',
'accesskey',
'timestamp',
'signature',
'allowtruncated',
'connecttimeout',
'sendtimeout',
'readtimeout',
);
public function __construct($accesskey, $secretkey) {
$accesskey = trim($accesskey);
$secretkey = trim($secretkey);
$this->accesskey_ = $accesskey;
$this->secretkey_ = $secretkey;
$this->errno_ = 0;
$this->error_ = null;
$this->debug_ = false;
}
public function __destruct() {
// do nothing
}
public function setAccesskey($accesskey) {
$accesskey = trim($accesskey);
$this->accesskey_ = $accesskey;
}
public function setSecretkey($secretkey) {
$secretkey = trim($secretkey);
$this->secretkey_ = $secretkey;
}
public function setDebugOn() {
$this->debug_ = true;
}
public function setDebugOff() {
$this->debug_ = false;
}
public function fetch($url, $opt = null, $headers = null, $callback = null) {
$url = trim($url);
if (substr($url, 0, 7) != 'http://' && substr($url, 0, 8) != 'https://') {
$url = 'http://' . $url;
}
$this->callback_ = $callback;
$maxRedirect = FetchUrl::maxRedirect_;
if (is_array($opt) && array_key_exists('redirect',$opt) && !$opt['redirect']) {
$maxRedirect = 1;
}
for ($i = 0; $i < $maxRedirect; ++$i) {
$this->dofetch($url, $opt, $headers);
if ($this->errno_ == 0) {
if ($this->httpCode_ == 301 || $this->httpCode_ == 302) {
$matchs = array();
if (preg_match('/Location:\s([^\r\n]+)/i', $this->header_, $matchs)) {
$newUrl = $matchs[1];
// if new domain
if (strncasecmp($newUrl, "http://", strlen("http://")) == 0) {
$url = $newUrl;
} else {
$url = preg_replace('/^((?:https?:\/\/)?[^\/]+)\/(.*)$/i', '$1', $url) . "/". $newUrl;
}
if ($this->debug_) {
echo "[debug] redirect to $url\n";
}
continue;
}
}
}
break;
}
if ($this->errno_ == 0 && $this->httpCode_ == 200) {
return $this->body_;
} else {
return false;
}
}
public function headerContent() {
return $this->header_;
}
public function errno() {
return $this->errno_;
}
public function error() {
return $this->error_;
}
public function httpCode() {
return $this->httpCode_;
}
public function body() {
return $this->body_;
}
public function httpDesc() {
return $this->httpDesc_;
}
private function signature($url, $timestamp) {
$content = "FetchUrl" . $url .
"TimeStamp" . $timestamp .
"AccessKey" . $this->accesskey_;
$signature = (base64_encode(hash_hmac('sha256',$content,$this->secretkey_,true)));
if ($this->debug_) {
echo "[debug] content: $content" . "\n";
echo "[debug] signature: $signature" . "\n";
}
return $signature;
}
// we have to set wirteBody & writeHeader public
// for we used them in curl_setopt()
public function writeBody($ch, $body) {
if ($this->callback_) {
call_user_func($this->callback_, $body);
} else {
$this->body_ .= $body;
}
if ($this->debug_) {
echo "[debug] body => $body";
}
return strlen($body);
}
public function writeHeader($ch, $header) {
$this->header_ .= $header;
if ($this->debug_) {
echo "[debug] header => $header";
}
return strlen($header);
}
private function dofetch($url, $opt, $headers_) {
$this->header_ = $this->body_ = null;
$headers = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false) ;
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,true) ;
curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this, 'writeBody'));
curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'writeHeader'));
if ($this->debug_) {
curl_setopt($ch, CURLOPT_VERBOSE, true);
}
if (is_array($opt) && !empty($opt)) {
foreach( $opt as $k => $v) {
switch(strtolower($k)) {
case 'username':
if (array_key_exists("password",$opt)) {
curl_setopt($ch, CURLOPT_USERPWD, $v . ":" . $opt["password"]);
}
break;
case 'password':
if (array_key_exists("username",$opt)) {
curl_setopt($ch, CURLOPT_USERPWD, $opt["username"] . ":" . $v);
}
break;
case 'useragent':
curl_setopt($ch, CURLOPT_USERAGENT, $v);
break;
case 'post':
curl_setopt($ch, CURLOPT_POSTFIELDS, $v);
break;
case 'cookie':
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIE, $v);
break;
case 'multipart':
if ($v) array_push($headers, "Content-Type: multipart/form-data");
break;
case 'truncated':
array_push($headers, "AllowTruncated:" . $v);
break;
case 'connecttimeout':
array_push($headers, "ConnectTimeout:" . intval($v));
break;
case 'sendtimeout':
array_push($headers, "SendTimeout:" . intval($v));
break;
case 'readtimeout':
array_push($headers, "ReadTimeout:" . intval($v));
break;
default:
break;
}
}
}
if (isset($opt['method'])) {
if (strtolower($opt['method']) == 'get') {
curl_setopt($ch, CURLOPT_HTTPGET, true);
}
}
if (is_array($headers_) && !empty($headers_)) {
foreach($headers_ as $k => $v) {
if (!in_array(strtolower($k), FetchUrl::$disabledHeaders)) {
array_push($headers, "{$k}:" . $v);
}
}
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
$info = curl_getinfo($ch);
if ($this->debug_) {
echo "[debug] curl_getinfo => " . print_r($info, true) . "\n";
}
$this->errno_ = curl_errno($ch);
$this->error_ = curl_error($ch);
if ($this->errno_ == 0) {
$matchs = array();
if (preg_match('/^(?:[^\s]+)\s([^\s]+)\s([^\r\n]+)/', $this->header_, $matchs)) {
$this->httpCode_ = $matchs[1];
$this->httpDesc_ = $matchs[2];
if ($this->debug_) {
echo "[debug] httpCode = " . $this->httpCode_ . " httpDesc = " . $this->httpDesc_ . "\n";
}
} else {
$this->errno_ = -1;
$this->error_ = "invalid response";
}
}
curl_close($ch);
}
private $accesskey_;
private $secretkey_;
private $errno_;
private $error_;
private $httpCode_;
private $httpDesc_;
private $header_;
private $body_;
private $debug_;
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/SaeFetchurl.class.php | PHP | asf20 | 18,374 |
<?php
// +----------------------------------------------------------------------
// | sae模拟器配置
// +----------------------------------------------------------------------
// | Author: luofei614<www.3g4k.com>
// +----------------------------------------------------------------------
// $Id: config.php 2793 2012-03-02 05:34:40Z liu21st $
$appConfig= include APP_PATH.'Conf/config.php';
return array(
'db_host'=>isset($appConfig['DB_HOST'])?$appConfig['DB_HOST']:'localhost',
'db_user'=>isset($appConfig['DB_USER'])?$appConfig['DB_USER']:'root',
'db_pass'=>isset($appConfig['DB_PWD'])?$appConfig['DB_PWD']:'',
'db_name'=>isset($appConfig['DB_NAME'])?$appConfig['DB_NAME']:'sae',
'db_charset'=>isset($appConfig['DB_CHARSET'])?$appConfig['DB_CHARSET']:'utf8',
'storage_url'=>trim(dirname($_SERVER['SCRIPT_NAME']),'/\\').'/',
'storage_dir'=>'./',
'debug_file'=>APP_PATH.'Runtime/Logs/sae_debug.log'
); | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/config.php | PHP | asf20 | 963 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <www.3g4k.com>
// +----------------------------------------------------------------------
// $Id: SaeCounter.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
/**
* SaeCounter模拟器
* 使用了数据库存储统计器信息,
* 相关数据表:think_sae_counter
*/
class SaeCounter extends SaeObject {
//创建统计器
public function create($name, $value=0) {
//判断是否存在
if ($this->exists($name))
return false;
return self::$db->runSql("insert into sae_counter(name,val) values('$name','$value')");
}
//减法
public function decr($name, $value=1) {
if (!$this->exists($name))
return false;
self::$db->runSql("update sae_counter set val=val-$value where name='$name'");
return self::$db->getVar("select val from sae_counter where name='$name'");
}
//是否存在
public function exists($name) {
$num = self::$db->getVar("select count(*) from sae_counter where name='$name'");
return $num != 0 ? true : false;
}
public function get($name) {
if (!$this->exists($name))
return false;
return self::$db->getVar("select val from sae_counter where name='$name'");
}
public function getall() {
$data = self::$db->getData("select * from sae_counter where name='$name'");
$ret = array();
foreach ($data as $r) {
$ret[$r['name']] = $r['val'];
}
return $ret;
}
//加法
public function incr($name, $value=1) {
if (!$this->exists($name))
return false;
self::$db->runSql("update sae_counter set val=val+$value where name='$name'");
return self::$db->getVar("select val from sae_counter where name='$name'");
}
public function length() {
return self::$db->getVar("select count(*) from sae_counter");
}
//获得多个统计器,names为数组
public function mget($names) {
array_walk($names, function(&$name) {
$name = "'$name'";
});
$where = implode(',', $names);
$data = self::$db->getData("select * from sae_counter where name in($where)");
$ret = array();
foreach ($data as $r) {
$ret[$r['name']] = $r['val'];
}
return $ret;
}
public function remove($name) {
if (!$this->exists($name))
return false;
return self::$db->runSql("delete from sae_counter where name='$name'");
}
//设置值
public function set($name, $value) {
return self::$db->runSql("update sae_counter set val='$value' where name='$name'");
}
}
?> | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/SaeCounter.class.php | PHP | asf20 | 3,296 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <www.3g4k.com>
// +----------------------------------------------------------------------
// $Id: Lang.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
Imit_L(array(
'_SAE_DATABASE_NOT_EXIST_'=>'数据库['.SAE_MYSQL_DB.']不存在',
'_SAE_NOT_IN_BILLBOARD_'=>'查找元素没有在排行榜中[not in billboard]',
'_SAE_BILLBOARD_NOT_EXISTS_'=>'排行榜不存在[billboard not exists]',
'_SAE_THE_RANK_IS_EXISTED_'=>'排行榜已存在[the rank is existed]',
'_SAE_ERR_'=>'SAE内部错误',
'_SAE_OK_'=>'操作成功[OK]',
'_SAE_ERRPARAMTER_'=>'参数错误[Unavailable tasks]',
'_SAE_TASKQUEUE_SERVICE_FAULT_'=>'服务内部错误[taskqueue service segment fault]',
'_SAE_TASKQUEUE_SERVICE_ERROR_'=>'服务内部错误[taskqueue service internal error]',
'_SAE_UNKNOWN_ERROR_'=>'未知错误[unknown error]',
'_SAE_STORAGE_PARAM_EMPTY_'=>'参数错误',
'_SAE_STORAGE_SERVER_ERR_'=>'存储服务器返回错误',
'_SAE_STORAGE_DELETE_ERR_'=>'删除失败[deleted failed!...]',
'_SAE_STORAGE_FILE_NOT_EXISTS_'=>'文件不存在',
'_SAE_MAIL_SIZE_lARGER_'=>'邮件内容过大[mail size cannot larger than 1048576 bytes]',
'_SAE_CONNECT_DB_ERR_'=>'数据库连接失败',
'_SAE_PLEASE_CONFIG_DB_'=>'请配置数据库'
)
);
?> | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/Lang.php | PHP | asf20 | 1,774 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <www.3g4k.com>
// +----------------------------------------------------------------------
// $Id: SaeKVClient.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
/**
*KVDB模拟器
*使用到数据库表think_sae_kv
*/
class SaeKvClient extends SaeObject{
public function delete($key){
$ret=self::$db->runSql("delete from sae_kv where k='$key'");
return $ret?true:false;
}
public function get($key){
$data=self::$db->getLine("select * from sae_kv where k='$key'");
$value=$this->output(array($data));
$ret=$value[$key];
return $ret?$ret:false;
}
public function get_info(){
//todu
}
public function init(){
return true;
}
public function mget($ary){
if(empty($ary)) return null;
array_walk($ary,function(&$r){
$r="'$r'";
});
$where=implode(',', $ary);
$data=self::$db->getData("select * from sae_kv where k in($where)");
return $this->output($data);
}
public function pkrget($prefix_key,$count,$start_key){
//todu
}
public function set($key,$value){
if(!is_string($value)){
//如果不是字符串序列化
$value=serialize($value);
$isobj=1;
}else{
$isobj=0;
}
//判断是否存在键
if(self::$db->getVar("select count(*) from sae_kv where k='$key'")>0){
$ret=self::$db->runSql("update sae_kv set v='$value',isobj='$isobj' where k='$key'");
}else{
$ret=self::$db->runSql("insert into sae_kv(k,v,isobj) values('$key','$value','$isobj')");
}
return $ret?true:false;
}
private function output($arr){
$ret=array();
foreach($arr as $k=>$ary){
$ret[$ary['k']]=$ary['isobj']?unserialize($ary['v']):$ary['v'];
}
return $ret;
}
}
?> | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/SaeKVClient.class.php | PHP | asf20 | 2,231 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <www.3g4k.com>
// +----------------------------------------------------------------------
// $Id: Memcache.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
/**
*memcache模拟器。
*当本地环境不支持memcache时被调用。
*当你本地环境支持memcache时,会使用原始的memcache,此类将不起作用。
*/
class Memcache extends Think{
private static $handler;
public function __construct(){
if(!is_object(self::$handler)){
self::$handler=new CacheFile();
}
}
public static function add($key, $var, $flag=null, $expire=-1){
if(self::$handler->get($key)!==false) return false;
return self::$handler->set($key,$var,$expire);
}
public static function addServer($host,$port=11211,$persistent=null,$weight=null,$timeout=null,$retry_interval=null,$status=null,$failure_back=null,$timeoutms=null){
return true;
}
public static function close(){
return true;
}
public static function connect($host,$port=11211,$timeout=null){
return true;
}
public static function decrement($key,$value=1){
return self::$handler->decrement($key,$value);
}
public static function increment($key,$value=1){
return self::$handler->increment($key,$value);
}
public static function delete($key,$timeout=0){
$v=S($key);
if($v===false) return false;
if($timeout!==0){
return self::$handler->set($key,$v,$timeout);
}else{
return self::$handler->rm($key);
}
}
public static function flush(){
return self::$handler->clear();
}
public static function get($key,$flag=null){
if(is_string($key)){
return self::$handler->get($key);
}else{
//返回数组形式 array('k1'=>'v1','k2'=>'v2')
$ret=array();
foreach($key as $k){
$ret[$k]=self::$handler->get($k);
}
return $ret;
}
}
public static function getExtendedStats($type=null,$slabid=null,$limit=100){
//pass
return true;
}
public static function getServerStatus($host,$port=11211){
return 1;
}
public static function getStats($type,$stabid=null,$limit=100){
//pass
return true;
}
public static function getVersion(){
//todu 待完善
return true;
}
public static function pconnect($host,$port=11211,$timeout=null){
//pass
return true;
}
public static function replace($key,$var,$flag=null,$expire=-1){
if(self::$handler->get($key)===false) return false;
return self::$handler->set($key,$var,$flag,$expire);
}
public static function set($key,$var,$flag=null,$expire=-1){
return self::$handler->set($key,$var,$expire);
}
public static function setCompressThreshold($threshold,$min_savings=null){
//pass
return true;
}
public static function setServerParams($host,$port=11211,$timeout=-1,$retry_interval=false,$status=null,$retry_interval=false){
return true;
}
//todu memcache_debug 函数
}
function memcache_add($m,$key, $var, $flag=null, $expire=-1){
return Memcache::add($key,$var,$flag,$expire);
}
function memcache_add_server($host,$port=11211,$persistent=null,$weight=null,$timeout=null,$retry_interval=null,$status=null,$failure_back=null,$timeoutms=null){
return true;
}
function memcache_close(){
return true;
}
function memcache_decrement($m,$key,$value=1){
return Memcache::decrement($m,$key,$value);
}
function memcache_increment($m,$key,$value=1){
return Memcache::increment($key,$value);
}
function memcache_delete($m,$key,$timeout=0){
return Memcache::delete($key,$timeout);
}
function memcache_flush($m){
return Memcache::flush();
}
function memcache_get_extended_stats($m,$type=null,$slabid=null,$limit=100){
return true;
}
function memcache_get_server_status($m,$host,$port=11211){
return 1;
}
function memcache_get_stats($m,$type,$stabid=null,$limit=100){
return true;
}
function memcache_get_version($m){
return true;
}
function memcache_pconnect($host,$port=11211,$timeout=null){
return true;
}
function memcache_replace($m,$key,$var,$flag=null,$expire){
return Memcache::replace($key,$var,$flag,$expire);
}
function memcache_set_compress_threshold($m,$threshold,$min_savings=null){
return true;
}
function memcache_set_server_params($host,$port=11211,$timeout=-1,$retry_interval=false,$status=null,$retry_interval=false){
return true;
}
function memcache_set($m,$key,$value){
return $mmc->set($key,$value);
}
function memcache_get($m,$key){
return $mmc->get($key);
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/Memcache.class.php | PHP | asf20 | 4,969 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <www.3g4k.com>
// +----------------------------------------------------------------------
// $Id: SaeMail.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
/**
*Mail模拟器
*todu, 支持ssl和附件上传。
*现在暂不支持ssl,建议不用使用gmail测试。
*/
class SaeMail extends SaeObject{
private $msp = array(
"sina.com" => array("smtp.sina.com",25,0),
"sina.cn" => array("smtp.sina.cn",25,0),
"163.com" => array("smtp.163.com",25,0),
"263.com" => array("smtp.263.com",25,0),
"gmail.com" => array("smtp.gmail.com",587,1),
"sohu.com" => array("smtp.sohu.com",25,0),
"qq.com" => array("smtp.qq.com",25,0),
"vip.qq.com" => array("smtp.qq.com",25,0),
"126.com" => array("smtp.126.com",25,0),
);
private $_post=array();
const mail_limitsize=1048576;
const subject_limitsize=256;
private $_count;
private $_attachSize;
private $_allowedAttachType = array("bmp","css","csv","gif","htm","html","jpeg","jpg","jpe","pdf","png","rss","text","txt","asc","diff","pot","tiff","tif","wbmp","ics","vcf");
public function __construct($options=array()){
$this->setOpt($options);
}
public function clean(){
$this->_post = array();
$this->_count = 0;
$this->_attachSize = 0;
return true;
}
public function quickSend($to,$subject,$msgbody,$smtp_user,$smtp_pass,$smtp_host='',$smtp_port=25,$smtp_tls=false){
$to = trim($to);
$subject = trim($subject);
$msgbody = trim($msgbody);
$smtp_user = trim($smtp_user);
$smtp_host = trim($smtp_host);
$smtp_port = intval($smtp_port);
$this->_count = strlen($msgbody) + $this->_attachSize;
if(strlen($subject) > self::subject_limitsize) {
$this->errno = SAE_ErrParameter;
$this->errmsg = "subject cannot larger than ".self::subject_limitsize." bytes";
return false;
}
if($this->_count > self::mail_limitsize) {
$this->errno = SAE_ErrParameter;
$this->errmsg = "mail size cannot larger than ".self::subject_limitsize." bytes";
return false;
}
if (filter_var($smtp_user, FILTER_VALIDATE_EMAIL)) {
preg_match('/([^@]+)@(.*)/', $smtp_user, $match);
$user = $match[1]; $host = $match[2];
if(empty($smtp_host)) {
//print_r($match);
if(isset($this->msp[$host])) { $smtp_host = $this->msp[$host][0]; }
else {
$this->errno = SAE_ErrParameter;
$this->errmsg = "you can set smtp_host explicitly or choose msp from sina,gmail,163,265,netease,qq,sohu,yahoo";
return false;
}
}
if($smtp_port == 25 and isset($this->msp[$host])) {
$smtp_port = $this->msp[$host][1];
}
if(!$smtp_tls and isset($this->msp[$host])) {
$smtp_tls = $this->msp[$host][2];
}
$smtp_tls = ($smtp_tls == true);
$username = $user;
} else {
$this->_errno = SAE_ErrParameter;
$this->_errmsg = "invalid email address";
return false;
}
$this->_post = array_merge($this->_post, array("from"=>$smtp_user, "smtp_username"=>$username, "smtp_password"=>$smtp_pass, "smtp_host"=>$smtp_host, "smtp_port"=>$smtp_port, 'to'=>$to,'subject'=>$subject,'content'=>$msgbody, 'tls'=>$smtp_tls));
return $this->send();
}
public function send(){
if ( empty($this->_post['from'])
|| empty($this->_post['to'])
|| empty($this->_post['smtp_host'])
|| empty($this->_post['smtp_username'])
|| empty($this->_post['smtp_password'])
|| empty($this->_post['subject']) ) {
$this->_errno = SAE_ErrParameter;
$this->_errmsg = "parameters from, to, subject, smtp_host, smtp_username, smtp_password can no be empty";
return false;
}
if($this->_count > self::mail_limitsize) {
$this->_errno = SAE_ErrForbidden;
$this->_errmsg = "mail size cannot larger than ".self::mail_limitsize." bytes";
return false;
}
//连接服务器
$fp = fsockopen ( $this->_post['smtp_host'], $this->_post['smtp_port'], $errno, $errstr, 60);
if (!$fp ) return "联接服务器失败".__LINE__;
stream_set_blocking($fp, true );
$lastmessage=fgets($fp,512);
if ( substr($lastmessage,0,3) != 220 ) return "error1:".$lastmessage.__LINE__;
//HELO
$yourname = "YOURNAME";
$lastact="EHLO ".$yourname."\r\n";
fputs($fp, $lastact);
$lastmessage == fgets($fp,512);
if (substr($lastmessage,0,3) != 220 ) return "error2:$lastmessage".__LINE__;
while (true) {
$lastmessage = fgets($fp,512);
if ( (substr($lastmessage,3,1) != "-") or (empty($lastmessage)) )
break;
}
//身份验证
//验证开始
$lastact="AUTH LOGIN"."\r\n";
fputs( $fp, $lastact);
$lastmessage = fgets ($fp,512);
if (substr($lastmessage,0,3) != 334) return "error3:$lastmessage".__LINE__;
//用户姓名
$lastact=base64_encode($this->_post['smtp_username'])."\r\n";
fputs( $fp, $lastact);
$lastmessage = fgets ($fp,512);
if (substr($lastmessage,0,3) != 334) return "error4:$lastmessage".__LINE__;
//用户密码
$lastact=base64_encode($this->_post['smtp_password'])."\r\n";
fputs( $fp, $lastact);
$lastmessage = fgets ($fp,512);
if (substr($lastmessage,0,3) != "235") return "error5:$lastmessage".__LINE__;
//FROM:
$lastact="MAIL FROM: ". $this->_post['from'] . "\r\n";
fputs( $fp, $lastact);
$lastmessage = fgets ($fp,512);
if (substr($lastmessage,0,3) != 250) return "error6:$lastmessage".__LINE__;
//TO:
$lastact="RCPT TO: ".$this->_post['to']. "\r\n";
fputs( $fp, $lastact);
$lastmessage = fgets ($fp,512);
if (substr($lastmessage,0,3) != 250) return "error7:$lastmessage".__LINE__;
//DATA
$lastact="DATA\r\n";
fputs($fp, $lastact);
$lastmessage = fgets ($fp,512);
if (substr($lastmessage,0,3) != 354) return "error8:$lastmessage".__LINE__;
//处理Subject头
$head="Subject: ".$this->_post['subject']."\r\n";
$message = $head."\r\n".$this->_post['content'];
//处理From头
$head="From: ".$this->_post['from']."\r\n";
$message = $head.$message;
//处理To头
$head="To: ".$this->_post['to']."\r\n";
$message = $head.$message;
//加上结束串
$message .= "\r\n.\r\n";
//发送信息
fputs($fp, $message);
$lastact="QUIT\r\n";
fputs($fp,$lastact);
fclose($fp);
}
public function setAttach($attach){
if(!is_array($attach)) {
$this->errmsg = "attach parameter must be an array!";
$this->errno = SAE_ErrParameter;
return false;
}
$this->_attachSize = 0;
foreach($attach as $fn=>$blob) {
$suffix = end(explode(".", $fn));
if(!in_array($suffix, $this->_allowedAttachType)) {
$this->errno = SAE_ErrParameter;
$this->errmsg = "Invalid attachment type";
return false;
}
$this->_attachSize += strlen($blob);
$this->_count = $this->_attachSize + strlen($this->_post['content']);
if($this->_count > self::mail_limitsize) {
$this->errno = SAE_ErrForbidden;
$this->errmsg = "mail size cannot larger than ".self::mail_limitsize." bytes";
return false;
}
//$this->_post = array_merge($this->_post, array("attach:$fn:B:".$this->_disposition[$suffix] => base64_encode($blob)));
}
return true;
}
public function setOpt($options){
if (isset($options['subject']) && strlen($options['subject']) > self::subject_limitsize) {
$this->errno = SAE_ErrParameter;
$this->errmsg = Imit_L("_SAE_MAIL_SIZE_lARGER_");
return false;
}
if(isset($options['content']))
$this->_count = $this->_attachSize + strlen($options['content']);
if($this->_count > self::mail_limitsize) {
$this->errno = SAE_ErrParameter;
$this->errmsg = Imit_L("_SAE_MAIL_SIZE_lARGER_");
return false;
}
$this->_post = array_merge($this->_post, $options);
return true;
}
}
| 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/SaeMail.class.php | PHP | asf20 | 8,282 |
<?php
//SAE系统常量,根据自己实际情况进行修改。
define( 'SAE_MYSQL_HOST_M', $sae_config['db_host'] );
define( 'SAE_MYSQL_HOST_S', $sae_config['db_host'] );
define( 'SAE_MYSQL_PORT', 3306 );
define( 'SAE_MYSQL_USER', $sae_config['db_user'] );
define( 'SAE_MYSQL_PASS', $sae_config['db_pass']);
define( 'SAE_MYSQL_DB', $sae_config['db_name']);
define('IMIT_CREATE_TABLE',true);//是否自动建立模拟器需要的数据表
// settings
define('SAE_FETCHURL_SERVICE_ADDRESS','http://fetchurl.sae.sina.com.cn');
// storage
define( 'SAE_STOREHOST', 'http://stor.sae.sina.com.cn/storageApi.php' );
define( 'SAE_S3HOST', 'http://s3.sae.sina.com.cn/s3Api.php' );
// saetmp constant
define( 'SAE_TMP_PATH' , '');
// define AccessKey and SecretKey
define( 'SAE_ACCESSKEY', '');
define( 'SAE_SECRETKEY', '');
//unset( $_SERVER['HTTP_ACCESSKEY'] );
//unset( $_SERVER['HTTP_SECRETKEY'] );
// gravity define
define('SAE_NorthWest', 1);
define('SAE_North', 2);
define('SAE_NorthEast',3);
define('SAE_East',6);
define('SAE_SouthEast',9);
define('SAE_South',8);
define('SAE_SouthWest',7);
define('SAE_West',4);
define('SAE_Static',10);
define('SAE_Center',5);
// font stretch
define('SAE_Undefined',0);
define('SAE_Normal',1);
define('SAE_UltraCondensed',2);
define('SAE_ExtraCondensed',3);
define('SAE_Condensed',4);
define('SAE_SemiCondensed',5);
define('SAE_SemiExpanded',6);
define('SAE_Expanded',7);
define('SAE_ExtraExpanded',8);
define('SAE_UltraExpanded',9);
// font style
define('SAE_Italic',2);
define('SAE_Oblique',3);
// font name
define('SAE_SimSun',1);
define('SAE_SimKai',2);
define('SAE_SimHei',3);
define('SAE_Arial',4);
define('SAE_MicroHei',5);
// anchor postion
define('SAE_TOP_LEFT','tl');
define('SAE_TOP_CENTER','tc');
define('SAE_TOP_RIGHT','tr');
define('SAE_CENTER_LEFT','cl');
define('SAE_CENTER_CENTER','cc');
define('SAE_CENTER_RIGHT','cr');
define('SAE_BOTTOM_LEFT','bl');
define('SAE_BOTTOM_CENTER','bc');
define('SAE_BOTTOM_RIGHT','br');
// errno define
define('SAE_Success', 0); // OK
define('SAE_ErrKey', 1); // invalid accesskey or secretkey
define('SAE_ErrForbidden', 2); // access fibidden for quota limit
define('SAE_ErrParameter', 3); // parameter not exist or invalid
define('SAE_ErrInternal', 500); // internal Error
define('SAE_ErrUnknown', 999); // unknown error
// fonts for gd
define('SAE_Font_Sun', '/usr/share/fonts/chinese/TrueType/uming.ttf');
define('SAE_Font_Kai', '/usr/share/fonts/chinese/TrueType/ukai.ttf');
define('SAE_Font_Hei', '/usr/share/fonts/chinese/TrueType/wqy-zenhei.ttc');
define('SAE_Font_MicroHei', '/usr/share/fonts/chinese/TrueType/wqy-microhei.ttc');
| 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/defines.php | PHP | asf20 | 2,720 |
<?php
//SAE系统函数
function sae_set_display_errors($show=true){
//在本地设置不显示错误, 只不显示sae_debug的文字信息, 但是会显示系统错误,方便我们开发。
global $sae_config;
$sae_config['display_error']=$show;
}
function sae_debug($log){
global $sae_config;
error_log(date('[c]').$log.PHP_EOL,3,$sae_config['debug_file']);
if($sae_config['display_error']!==false){
echo $log.PHP_EOL;
}
}
function memcache_init(){
static $handler;
if(is_object($handler)) return $handler;
$handler=new Memcache;
$handler->connect('127.0.0.1',11211);
return $handler;
}
function sae_xhprof_start()
{
//pass
}
function sae_xhprof_end()
{
return true;
}
//向下兼容函数
function sae_image_init( $ak='', $sk='', $image_bin = '' )
{
if( !isset( $GLOBALS['sae_image_instance'] ) )
{
$GLOBALS['sae_image_instance'] = new SaeImage($image_bin);
}
return $GLOBALS['sae_image_instance'];
}
function sae_storage_init( $accesskey , $secretkey , $ssl = false )
{
if( !isset( $GLOBALS['sae_storage_instance'] ) )
{
include_once( 'sae_storage.class.php' );
$GLOBALS['sae_storage_instance'] = new SaeStorage($accesskey,$secretkey);
}
return $GLOBALS['sae_storage_instance'];
}
function sae_mysql_init( $host , $port , $accesskey , $secretkey , $appname , $do_replication = true )
{
if( !isset( $GLOBALS['sae_mysql_instance'] ) )
{
include_once( 'sae_mysql.class.php' );
$GLOBALS['sae_mysql_instance'] = new SaeMysql();
}
return $GLOBALS['sae_mysql_instance'];
}
//TODU 完善 fetch url
//-------------------------------------------------------------------------------------------------
function _header_info($header)
{
$hinfo = array();
$header_lines = explode("\r",trim( $header));
$first = array_shift($header_lines);
// HTTP/1.1 301 Moved Permanently
$reg ="/HTTP\/(.+?)\s([0-9]+)\s(.+)/is";
if(preg_match($reg,trim($first),$out))
{
$hinfo['version'] = $out[1];
$hinfo['code'] = $out[2];
$hinfo['code_info'] = $out[3];
}
else
return false;
if(is_array($header_lines))
{
foreach($header_lines as $line)
{
$fs=explode( ":" , trim($line),2);
if(strlen(trim($fs[0])) > 0 )
{
if(isset( $hinfo[strtolower(trim($fs[0]))] ) )
$hinfo[strtolower(trim($fs[0]))] = array_merge( (array)$hinfo[strtolower(trim($fs[0]))] , (array)trim($fs[1]) );
else
$hinfo[strtolower(trim($fs[0]))] = trim($fs[1]);
}
}
}
return $hinfo;
}
//-------------------------------------------------------------------------------------------------
function _get_signature($accesskey,$securekey,&$header_array)
{
$content="FetchUrl";
$content.=$header_array["FetchUrl"];
$content.="TimeStamp";
$content.=$header_array['TimeStamp'];
$content.="AccessKey";
$content.=$header_array['AccessKey'];
return base64_encode(hash_hmac('sha256',$content,$securekey,true));
}
//-------------------------------------------------------------------------------------------------
function _read_header($ch,$string)
{
global $errno,$errmsg,$rheader;
$rheader.=$string;
$ret=explode(" ",$string);
if(count($ret)==3 && $ret[0]=='HTTP/1.1')
{
if($ret[1]==200)
$errno=0;
else
{
$errno=$ret[1];
$errmsg=$ret[2];
}
}
return strlen($string);
}
//-------------------------------------------------------------------------------------------------
function _read_data($ch,$string)
{
global $rdata;
$rdata.=$string;
return strlen($string);
}
//-------------------------------------------------------------------------------------------------
function _fetch_url($url,$accesskey,$securekey,&$header,&$error,$opt=NULL)
{
global $errno,$errmsg,$rheader,$rdata;
$rheader='';
$rdata='';
$errno=0;
$errmsg='';
$ch=curl_init();
curl_setopt($ch,CURLOPT_HEADERFUNCTION,'_read_header');
curl_setopt($ch,CURLOPT_WRITEFUNCTION,'_read_data');
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,3);
curl_setopt($ch,CURLOPT_TIMEOUT,10);
$header_array=array();
if($opt && is_array($opt))
{
if(array_key_exists('username',$opt) && array_key_exists('password',$opt))
curl_setopt($ch,CURLOPT_USERPWD,$opt['username'].':'.$opt['password']);
if(array_key_exists('useragent',$opt))
curl_setopt($ch,CURLOPT_USERAGENT,$opt['useragent']);
if(array_key_exists('post',$opt))
{
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$opt['post']);
}
if(array_key_exists('truncated',$opt))
$header_array['AllowTruncated']=$opt['truncated'];
// if(array_key_exists('connecttimeout',$opt))
// $header_array['ConnectTimeout']=$opt['connecttimeout'];
// if(array_key_exists('sendtimeout',$opt))
// $header_array['SendTimeout']=$opt['sendtimeout'];
// if(array_key_exists('readtimeout',$opt))
// $header_array['ReadTimeout']=$opt['readtimeout'];
if(array_key_exists('headers',$opt))
{
$headers=$opt['headers'];
if(is_array($headers))
{
foreach($headers as $k => $v)
$header_array[$k]=$v;
}
}
}//end if is_array
$header_array['FetchUrl']=$url;
$header_array['AccessKey']=$accesskey;
$header_array['TimeStamp']=date('Y-m-d H:i:s');
$header_array['Signature']=_get_signature($accesskey,$securekey,$header_array);
$header_array2=array();
foreach($header_array as $k => $v)
array_push($header_array2,$k.': '.$v);
curl_setopt($ch,CURLOPT_HTTPHEADER,$header_array2);
curl_setopt($ch,CURLOPT_URL,SAE_FETCHURL_SERVICE_ADDRESS);
curl_exec($ch);
curl_close($ch);
$header=$rheader;
if($errno==0)
return $rdata;
$error=$errno.': '.$errmsg;
return false;
}//end function fetchurl
//-------------------------------------------------------------------------------------------------
function fetch_url($url,$accesskey,$securekey,&$header,&$error,$opt=NULL)
{
if($opt && is_array($opt) && array_key_exists('redirect',$opt) && $opt['redirect']==true)
{
$times=0;
while(true)
{
$rt=_fetch_url($url,$accesskey,$securekey,$header,$error,$opt);
if($rt==false)
return $rt;
$info=_header_info($header);
$jump=false;
if(isset($info['location']) && ($info['code']==301|| $info['code']==302) && $times<5)
$jump=true;
if($jump==true)
{
$times++;
$url=$info['location'];
continue;
}
return $rt;
}//end while
}//end if
return _fetch_url($url,$accesskey,$securekey,$header,$error,$opt);
}
//-------------------------------------------------------------------------------------------------
//实现wrapper
if ( ! in_array("saemc", stream_get_wrappers()) )
stream_wrapper_register("saemc", "SaeMemcacheWrapper");
class SaeMemcacheWrapper // implements WrapperInterface
{
public $dir_mode = 16895 ; //040000 + 0222;
public $file_mode = 33279 ; //0100000 + 0777;
public function __construct()
{
$this->mc = memcache_init();
}
public function mc() {
if ( !isset( $this->mc ) ) $this->mc = new Memcache();
return $this->mc;
}
public function stream_open( $path , $mode , $options , &$opened_path)
{
$this->position = 0;
$this->mckey = trim(substr($path, 8));
$this->mode = $mode;
$this->options = $options;
if ( in_array( $this->mode, array( 'r', 'r+', 'rb' ) ) ) {
if ( $this->mccontent = memcache_get( $this->mc, $this->mckey ) ) {
$this->get_file_info( $this->mckey );
$this->stat['mode'] = $this->stat[2] = $this->file_mode;
} else {
trigger_error("fopen({$path}): failed to read from Memcached: No such key.", E_USER_WARNING);
return false;
}
} elseif ( in_array( $this->mode, array( 'a', 'a+', 'ab' ) ) ) {
if ( $this->mccontent = memcache_get( $this->mc , $this->mckey ) ) {
$this->get_file_info( $this->mckey );
$this->stat['mode'] = $this->stat[2] = $this->file_mode;
$this->position = strlen($this->mccontent);
} else {
$this->mccontent = '';
$this->stat['ctime'] = $this->stat[10] = time();
}
} elseif ( in_array( $this->mode, array( 'x', 'x+', 'xb' ) ) ) {
if ( !memcache_get( $this->mc , $this->mckey ) ) {
$this->mccontent = '';
$this->statinfo_init();
$this->stat['ctime'] = $this->stat[10] = time();
} else {
trigger_error("fopen({$path}): failed to create at Memcached: Key exists.", E_USER_WARNING);
return false;
}
} elseif ( in_array( $this->mode, array( 'w', 'w+', 'wb' ) ) ) {
$this->mccontent = '';
$this->statinfo_init();
$this->stat['ctime'] = $this->stat[10] = time();
} else {
$this->mccontent = memcache_get( $this->mc , $this->mckey );
}
return true;
}
public function stream_read($count)
{
if (in_array($this->mode, array('w', 'x', 'a', 'wb', 'xb', 'ab') ) ) {
return false;
}
$ret = substr( $this->mccontent , $this->position, $count);
$this->position += strlen($ret);
$this->stat['atime'] = $this->stat[8] = time();
$this->stat['uid'] = $this->stat[4] = 0;
$this->stat['gid'] = $this->stat[5] = 0;
return $ret;
}
public function stream_write($data)
{
if ( in_array( $this->mode, array( 'r', 'rb' ) ) ) {
return false;
}
$left = substr($this->mccontent, 0, $this->position);
$right = substr($this->mccontent, $this->position + strlen($data));
$this->mccontent = $left . $data . $right;
if ( memcache_set( $this->mc , $this->mckey , $this->mccontent ) ) {
$this->stat['mtime'] = $this->stat[9] = time();
$this->position += strlen($data);
return $this->stat['size'] = $this->stat[7] = strlen( $data );
}
else return false;
}
public function stream_close()
{
memcache_set( $this->mc , $this->mckey.'.meta' , serialize($this->stat) );
//memcache_close( $this->mc );
}
public function stream_eof()
{
return $this->position >= strlen( $this->mccontent );
}
public function stream_tell()
{
return $this->position;
}
public function stream_seek($offset , $whence = SEEK_SET)
{
switch ($whence) {
case SEEK_SET:
if ($offset < strlen( $this->mccontent ) && $offset >= 0) {
$this->position = $offset;
return true;
}
else
return false;
break;
case SEEK_CUR:
if ($offset >= 0) {
$this->position += $offset;
return true;
}
else
return false;
break;
case SEEK_END:
if (strlen( $this->mccontent ) + $offset >= 0) {
$this->position = strlen( $this->mccontent ) + $offset;
return true;
}
else
return false;
break;
default:
return false;
}
}
public function stream_stat()
{
return $this->stat;
}
// ============================================
public function mkdir($path , $mode , $options)
{
$path = trim(substr($path, 8));
//echo "回调mkdir\n";
$path = rtrim( $path , '/' );
$this->stat = $this->get_file_info( $path );
$this->stat['ctime'] = $this->stat[10] = time();
$this->stat['mode'] = $this->stat[2] = $this->dir_mode;
//echo "生成新的stat数据" . print_r( $this->stat , 1 );
memcache_set( $this->mc() , $path.'.meta' , serialize($this->stat) );
//echo "写入MC. key= " . $path.'.meta ' . memcache_get( $this->mc , $path.'.meta' );
memcache_close( $this->mc );
return true;
}
public function rename($path_from , $path_to)
{
$path_from = trim(substr($path_from, 8));
$path_to = trim(substr($path_to, 8));
memcache_set( $this->mc() , $path_to , memcache_get( $this->mc() , $path_from ) );
memcache_set( $this->mc() , $path_to . '.meta' , memcache_get( $this->mc() , $path_from . '.meta' ) );
memcache_delete( $this->mc() , $path_from );
memcache_delete( $this->mc() , $path_from.'.meta' );
clearstatcache( true );
return true;
}
public function rmdir($path , $options)
{
$path = trim(substr($path, 8));
$path = rtrim( $path , '/' );
memcache_delete( $this->mc() , $path .'.meta' );
clearstatcache( true );
return true;
}
public function unlink($path)
{
$path = trim(substr($path, 8));
$path = rtrim( $path , '/' );
memcache_delete( $this->mc() , $path );
memcache_delete( $this->mc() , $path . '.meta' );
clearstatcache( true );
return true;
}
public function url_stat($path , $flags)
{
$path = trim(substr($path, 8));
$path = rtrim( $path , '/' );
if ( !$this->is_file_info_exists( $path ) ) {
return false;
} else {
if ( $stat = memcache_get( $this->mc() , $path . '.meta' ) ) {
$this->stat = unserialize($stat);
if ( is_array($this->stat) ) {
if ( $this->stat['mode'] == $this->dir_mode || $c = memcache_get( $this->mc(), $path ) ) {
return $this->stat;
} else {
memcache_delete( $this->mc() , $path . '.meta' );
}
}
}
return false;
}
}
// ============================================
public function is_file_info_exists( $path )
{
//echo "获取MC数据 key= " . $path.'.meta' ;
$d = memcache_get( $this->mc() , $path . '.meta' );
//echo "\n返回数据为" . $d . "\n";
return $d;
}
public function get_file_info( $path )
{
if ( $stat = memcache_get( $this->mc() , $path . '.meta' ) )
return $this->stat = unserialize($stat);
else $this->statinfo_init();
}
public function statinfo_init( $is_file = true )
{
$this->stat['dev'] = $this->stat[0] = 0x8002;
$this->stat['ino'] = $this->stat[1] = mt_rand(10000, PHP_INT_MAX);
if( $is_file )
$this->stat['mode'] = $this->stat[2] = $this->file_mode;
else
$this->stat['mode'] = $this->stat[2] = $this->dir_mode;
$this->stat['nlink'] = $this->stat[3] = 0;
$this->stat['uid'] = $this->stat[4] = 0;
$this->stat['gid'] = $this->stat[5] = 0;
$this->stat['rdev'] = $this->stat[6] = 0;
$this->stat['size'] = $this->stat[7] = 0;
$this->stat['atime'] = $this->stat[8] = 0;
$this->stat['mtime'] = $this->stat[9] = 0;
$this->stat['ctime'] = $this->stat[10] = 0;
$this->stat['blksize'] = $this->stat[11] = 0;
$this->stat['blocks'] = $this->stat[12] = 0;
}
public function dir_closedir() {
return false;
}
public function dir_opendir($path, $options) {
return false;
}
public function dir_readdir() {
return false;
}
public function dir_rewinddir() {
return false;
}
public function stream_cast($cast_as) {
return false;
}
public function stream_flush() {
return false;
}
public function stream_lock($operation) {
return false;
}
public function stream_set_option($option, $arg1, $arg2) {
return false;
}
}
/* BEGIN ******************* Storage Wrapper By Elmer Zhang At 16/Mar/2010 14:47 ****************/
class SaeStorageWrapper // implements WrapperInterface
{
private $writen = true;
public function __construct()
{
$this->stor = new SaeStorage();
}
public function stor() {
if ( !isset( $this->stor ) ) $this->stor = new SaeStorage();
}
public function stream_open( $path , $mode , $options , &$opened_path)
{
$pathinfo = parse_url($path);
$this->domain = $pathinfo['host'];
$this->file = ltrim(strstr($path, $pathinfo['path']), '/\\');
$this->position = 0;
$this->mode = $mode;
$this->options = $options;
// print_r("OPEN\tpath:{$path}\tmode:{$mode}\toption:{$option}\topened_path:{$opened_path}\n");
if ( in_array( $this->mode, array( 'r', 'r+', 'rb' ) ) ) {
if ( $this->fcontent = $this->stor->read($this->domain, $this->file) ) {
} else {
trigger_error("fopen({$path}): failed to read from Storage: No such domain or file.", E_USER_WARNING);
return false;
}
} elseif ( in_array( $this->mode, array( 'a', 'a+', 'ab' ) ) ) {
trigger_error("fopen({$path}): Sorry, saestor does not support appending", E_USER_WARNING);
if ( $this->fcontent = $this->stor->read($this->domain, $this->file) ) {
} else {
trigger_error("fopen({$path}): failed to read from Storage: No such domain or file.", E_USER_WARNING);
return false;
}
} elseif ( in_array( $this->mode, array( 'x', 'x+', 'xb' ) ) ) {
if ( !$this->stor->getAttr($this->domain, $this->file) ) {
$this->fcontent = '';
} else {
trigger_error("fopen({$path}): failed to create at Storage: File exists.", E_USER_WARNING);
return false;
}
} elseif ( in_array( $this->mode, array( 'w', 'w+', 'wb' ) ) ) {
$this->fcontent = '';
} else {
$this->fcontent = $this->stor->read($this->domain, $this->file);
}
return true;
}
public function stream_read($count)
{
if (in_array($this->mode, array('w', 'x', 'a', 'wb', 'xb', 'ab') ) ) {
return false;
}
$ret = substr( $this->fcontent , $this->position, $count);
$this->position += strlen($ret);
return $ret;
}
public function stream_write($data)
{
if ( in_array( $this->mode, array( 'r', 'rb' ) ) ) {
return false;
}
// print_r("WRITE\tcontent:".strlen($this->fcontent)."\tposition:".$this->position."\tdata:".strlen($data)."\n");
$left = substr($this->fcontent, 0, $this->position);
$right = substr($this->fcontent, $this->position + strlen($data));
$this->fcontent = $left . $data . $right;
//if ( $this->stor->write( $this->domain, $this->file, $this->fcontent ) ) {
$this->position += strlen($data);
if ( strlen( $data ) > 0 )
$this->writen = false;
return strlen( $data );
//}
//else return false;
}
public function stream_close()
{
if (!$this->writen) {
$this->stor->write( $this->domain, $this->file, $this->fcontent );
$this->writen = true;
}
}
public function stream_eof()
{
return $this->position >= strlen( $this->fcontent );
}
public function stream_tell()
{
return $this->position;
}
public function stream_seek($offset , $whence = SEEK_SET)
{
switch ($whence) {
case SEEK_SET:
if ($offset < strlen( $this->fcontent ) && $offset >= 0) {
$this->position = $offset;
return true;
}
else
return false;
break;
case SEEK_CUR:
if ($offset >= 0) {
$this->position += $offset;
return true;
}
else
return false;
break;
case SEEK_END:
if (strlen( $this->fcontent ) + $offset >= 0) {
$this->position = strlen( $this->fcontent ) + $offset;
return true;
}
else
return false;
break;
default:
return false;
}
}
public function unlink($path)
{
self::stor();
$pathinfo = parse_url($path);
$this->domain = $pathinfo['host'];
$this->file = ltrim(strstr($path, $pathinfo['path']), '/\\');
clearstatcache( true );
return $this->stor->delete( $this->domain , $this->file );
}
public function stream_flush() {
if (!$this->writen) {
$this->stor->write( $this->domain, $this->file, $this->fcontent );
$this->writen = true;
}
return $this->writen;
}
public function stream_stat() {
return array();
}
public function url_stat($path, $flags) {
self::stor();
$pathinfo = parse_url($path);
$this->domain = $pathinfo['host'];
$this->file = ltrim(strstr($path, $pathinfo['path']), '/\\');
if ( $attr = $this->stor->getAttr( $this->domain , $this->file ) ) {
$stat = array();
$stat['dev'] = $stat[0] = 0x8001;
$stat['ino'] = $stat[1] = 0;;
$stat['mode'] = $stat[2] = 33279; //0100000 + 0777;
$stat['nlink'] = $stat[3] = 0;
$stat['uid'] = $stat[4] = 0;
$stat['gid'] = $stat[5] = 0;
$stat['rdev'] = $stat[6] = 0;
$stat['size'] = $stat[7] = $attr['length'];
$stat['atime'] = $stat[8] = 0;
$stat['mtime'] = $stat[9] = $attr['datetime'];
$stat['ctime'] = $stat[10] = $attr['datetime'];
$stat['blksize'] = $stat[11] = 0;
$stat['blocks'] = $stat[12] = 0;
return $stat;
} else {
return false;
}
}
public function dir_closedir() {
return false;
}
public function dir_opendir($path, $options) {
return false;
}
public function dir_readdir() {
return false;
}
public function dir_rewinddir() {
return false;
}
public function mkdir($path, $mode, $options) {
return false;
}
public function rename($path_from, $path_to) {
return false;
}
public function rmdir($path, $options) {
return false;
}
public function stream_cast($cast_as) {
return false;
}
public function stream_lock($operation) {
return false;
}
public function stream_set_option($option, $arg1, $arg2) {
return false;
}
}
if ( in_array( "saestor", stream_get_wrappers() ) ) {
stream_wrapper_unregister("saestor");
}
stream_wrapper_register( "saestor", "SaeStorageWrapper" )
or die( "Failed to register protocol" );
/* END ********************* Storage Wrapper By Elmer Zhang At 16/Mar/2010 14:47 ****************/
/* BEGIN ******************* KVDB Wrapper By Elmer Zhang At 12/Dec/2011 12:37 ****************/
class SaeKVWrapper // implements WrapperInterface
{
private $dir_mode = 16895 ; //040000 + 0222;
private $file_mode = 33279 ; //0100000 + 0777;
public function __construct() { }
private function kv() {
if ( !isset( $this->kv ) ) $this->kv = new SaeKV();
$this->kv->init();
return $this->kv;
}
private function open( $key ) {
$value = $this->kv()->get( $key );
if ( $value !== false && $this->unpack_stat(substr($value, 0, 20)) === true ) {
$this->kvcontent = substr($value, 20);
return true;
} else {
return false;
}
}
private function save( $key ) {
$this->stat['mtime'] = $this->stat[9] = time();
if ( isset($this->kvcontent) ) {
$this->stat['size'] = $this->stat[7] = strlen($this->kvcontent);
$value = $this->pack_stat() . $this->kvcontent;
} else {
$this->stat['size'] = $this->stat[7] = 0;
$value = $this->pack_stat();
}
return $this->kv()->set($key, $value);
}
private function unpack_stat( $str ) {
$arr = unpack("L5", $str);
// check if valid
if ( $arr[1] < 10000 ) return false;
if ( !in_array($arr[2], array( $this->dir_mode, $this->file_mode ) ) ) return false;
if ( $arr[4] > time() ) return false;
if ( $arr[5] > time() ) return false;
$this->stat['dev'] = $this->stat[0] = 0x8003;
$this->stat['ino'] = $this->stat[1] = $arr[1];
$this->stat['mode'] = $this->stat[2] = $arr[2];
$this->stat['nlink'] = $this->stat[3] = 0;
$this->stat['uid'] = $this->stat[4] = 0;
$this->stat['gid'] = $this->stat[5] = 0;
$this->stat['rdev'] = $this->stat[6] = 0;
$this->stat['size'] = $this->stat[7] = $arr[3];
$this->stat['atime'] = $this->stat[8] = 0;
$this->stat['mtime'] = $this->stat[9] = $arr[4];
$this->stat['ctime'] = $this->stat[10] = $arr[5];
$this->stat['blksize'] = $this->stat[11] = 0;
$this->stat['blocks'] = $this->stat[12] = 0;
return true;
}
private function pack_stat( ) {
$str = pack("LLLLL", $this->stat['ino'], $this->stat['mode'], $this->stat['size'], $this->stat['ctime'], $this->stat['mtime']);
return $str;
}
public function stream_open( $path , $mode , $options , &$opened_path)
{
$this->position = 0;
$this->kvkey = rtrim(trim(substr(trim($path), 8)), '/');
$this->mode = $mode;
$this->options = $options;
if ( in_array( $this->mode, array( 'r', 'r+', 'rb' ) ) ) {
if ( $this->open( $this->kvkey ) === false ) {
trigger_error("fopen({$path}): No such key in KVDB.", E_USER_WARNING);
return false;
}
} elseif ( in_array( $this->mode, array( 'a', 'a+', 'ab' ) ) ) {
if ( $this->open( $this->kvkey ) === true ) {
$this->position = strlen($this->kvcontent);
} else {
$this->kvcontent = '';
$this->statinfo_init();
}
} elseif ( in_array( $this->mode, array( 'x', 'x+', 'xb' ) ) ) {
if ( $this->open( $this->kvkey ) === false ) {
$this->kvcontent = '';
$this->statinfo_init();
} else {
trigger_error("fopen({$path}): Key exists in KVDB.", E_USER_WARNING);
return false;
}
} elseif ( in_array( $this->mode, array( 'w', 'w+', 'wb' ) ) ) {
$this->kvcontent = '';
$this->statinfo_init();
} else {
$this->open( $this->kvkey );
}
return true;
}
public function stream_read($count)
{
if (in_array($this->mode, array('w', 'x', 'a', 'wb', 'xb', 'ab') ) ) {
return false;
}
$ret = substr( $this->kvcontent , $this->position, $count);
$this->position += strlen($ret);
return $ret;
}
public function stream_write($data)
{
if ( in_array( $this->mode, array( 'r', 'rb' ) ) ) {
return false;
}
$left = substr($this->kvcontent, 0, $this->position);
$right = substr($this->kvcontent, $this->position + strlen($data));
$this->kvcontent = $left . $data . $right;
if ( $this->save( $this->kvkey ) === true ) {
$this->position += strlen($data);
return strlen( $data );
} else return false;
}
public function stream_close()
{
$this->save( $this->kvkey );
}
public function stream_eof()
{
return $this->position >= strlen( $this->kvcontent );
}
public function stream_tell()
{
return $this->position;
}
public function stream_seek($offset , $whence = SEEK_SET)
{
switch ($whence) {
case SEEK_SET:
if ($offset < strlen( $this->kvcontent ) && $offset >= 0) {
$this->position = $offset;
return true;
}
else
return false;
break;
case SEEK_CUR:
if ($offset >= 0) {
$this->position += $offset;
return true;
}
else
return false;
break;
case SEEK_END:
if (strlen( $this->kvcontent ) + $offset >= 0) {
$this->position = strlen( $this->kvcontent ) + $offset;
return true;
}
else
return false;
break;
default:
return false;
}
}
public function stream_stat()
{
return $this->stat;
}
// ============================================
public function mkdir($path , $mode , $options)
{
$path = rtrim(trim(substr(trim($path), 8)), '/');
if ( $this->open( $path ) === false ) {
$this->statinfo_init( false );
return $this->save( $path );
} else {
trigger_error("mkdir({$path}): Key exists in KVDB.", E_USER_WARNING);
return false;
}
}
public function rename($path_from , $path_to)
{
$path_from = rtrim(trim(substr(trim($path_from), 8)), '/');
$path_to = rtrim(trim(substr(trim($path_to), 8)), '/');
if ( $this->open( $path_from ) === true ) {
clearstatcache( true );
return $this->save( $path_to );
} else {
trigger_error("rename({$path_from}, {$path_to}): No such key in KVDB.", E_USER_WARNING);
return false;
}
}
public function rmdir($path , $options)
{
$path = rtrim(trim(substr(trim($path), 8)), '/');
clearstatcache( true );
return $this->kv()->delete($path);
}
public function unlink($path)
{
$path = rtrim(trim(substr(trim($path), 8)), '/');
clearstatcache( true );
return $this->kv()->delete($path);
}
public function url_stat($path , $flags)
{
$path = rtrim(trim(substr(trim($path), 8)), '/');
if ( $this->open( $path ) !== false ) {
return $this->stat;
} else {
return false;
}
}
// ============================================
private function statinfo_init( $is_file = true )
{
$this->stat['dev'] = $this->stat[0] = 0x8003;
$this->stat['ino'] = $this->stat[1] = crc32(SAE_APPNAME . '/' . $this->kvkey);
if( $is_file )
$this->stat['mode'] = $this->stat[2] = $this->file_mode;
else
$this->stat['mode'] = $this->stat[2] = $this->dir_mode;
$this->stat['nlink'] = $this->stat[3] = 0;
$this->stat['uid'] = $this->stat[4] = 0;
$this->stat['gid'] = $this->stat[5] = 0;
$this->stat['rdev'] = $this->stat[6] = 0;
$this->stat['size'] = $this->stat[7] = 0;
$this->stat['atime'] = $this->stat[8] = 0;
$this->stat['mtime'] = $this->stat[9] = time();
$this->stat['ctime'] = $this->stat[10] = 0;
$this->stat['blksize'] = $this->stat[11] = 0;
$this->stat['blocks'] = $this->stat[12] = 0;
}
public function dir_closedir() {
return false;
}
public function dir_opendir($path, $options) {
return false;
}
public function dir_readdir() {
return false;
}
public function dir_rewinddir() {
return false;
}
public function stream_cast($cast_as) {
return false;
}
public function stream_flush() {
return false;
}
public function stream_lock($operation) {
return false;
}
public function stream_set_option($option, $arg1, $arg2) {
return false;
}
}
if ( ! in_array("saekv", stream_get_wrappers()) )
stream_wrapper_register("saekv", "SaeKVWrapper");
/* END ********************* KVDB Wrapper By Elmer Zhang At 12/Dec/2011 12:37 ****************/
/* START ********************* Supported for AppCookie By Elmer Zhang At 13/Jun/2010 15:49 ****************/
$appSettings = array();
if (isset($_SERVER['HTTP_APPCOOKIE']) && $_SERVER['HTTP_APPCOOKIE']) {
$appCookie = trim($_SERVER['HTTP_APPCOOKIE']);
$tmpSettings = array_filter(explode(';', $appCookie));
if ($tmpSettings) {
foreach($tmpSettings as $setting) {
$tmp = explode('=', $setting);
$appSettings[$tmp[0]] = $tmp[1];
}
}
}
if (isset($appSettings['xhprof']) && in_array($_SERVER['HTTP_APPVERSION'], explode(',', $appSettings['xhprof']))) {
sae_xhprof_start();
register_shutdown_function("sae_xhprof_end");
}
if (isset($appSettings['debug']) && in_array($_SERVER['HTTP_APPVERSION'], explode(',', $appSettings['debug']))) {
sae_set_display_errors(true);
}
unset($appSettings);
unset($appCookie);
unset($tmpSettings);
unset($tmp);
| 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/sae_functions.php | PHP | asf20 | 34,744 |
<?php
//模拟器需要用的函数
function Imit_L($key){
static $msgs=array();
if(is_array($key)){
$msgs=array_merge($msgs,$key);
return ;
}
return $msgs[$key];
}
| 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/imit_functions.php | PHP | asf20 | 213 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <www.3g4k.com>
// +----------------------------------------------------------------------
// $Id: SaeObject.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
class SaeObject {
protected $errno = SAE_Success;
protected $errmsg;
static $db;
//实现自动建表
public function __construct() {
$this->errmsg = Imit_L("_SAE_OK_");
static $inited = false;
//只初始化一次
if ($inited)
return;
if (extension_loaded('sqlite3')) {
self::$db = new ImitSqlite();
} else {
self::$db = get_class($this) == "SaeMysql" ? $this : new SaeMysql();
$this->createTable();
}
$inited = true;
}
//获得错误代码
public function errno() {
return $this->errno;
}
//获得错误信息
public function errmsg() {
return $this->errmsg;
}
public function setAuth($accesskey, $secretkey) {
}
protected function createTable() {
$sql = file_get_contents(dirname(__FILE__).'/sae.sql');
$tablepre = C('DB_PREFIX');
$tablesuf = C('DB_SUFFIX');
$dbcharset = C('DB_CHARSET');
$sql = str_replace("\r", "\n",$sql);
$ret = array();
$num = 0;
foreach (explode(";\n", trim($sql)) as $query) {
$queries = explode("\n", trim($query));
foreach ($queries as $query) {
$ret[$num] .= $query[0] == '#' || $query[0] . $query[1] == '--' ? '' : $query;
}
$num++;
}
unset($sql);
foreach ($ret as $query) {
$query = trim($query);
if ($query) {
if (substr($query, 0, 12) == 'CREATE TABLE') {
$name = preg_replace("/CREATE TABLE ([a-z0-9_]+) .*/is", "\\1", $query);
$type = strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $query));
$type = in_array($type, array('MYISAM', 'HEAP')) ? $type : 'MYISAM';
$query = preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $query) .
(mysql_get_server_info() > '4.1' ? " ENGINE=$type DEFAULT CHARSET=$dbcharset" : " TYPE=$type");
}
self::$db->runSql($query);
}
}
}
}
?> | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/SaeObject.class.php | PHP | asf20 | 2,982 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <www.3g4k.com>
// +----------------------------------------------------------------------
// $Id: SaeStorage.class.php 2803 2012-03-06 14:57:17Z luofei614@gmail.com $
/**
* storage模拟器
* 在本地环境时,domain对应了Public文件夹下以domain名命名的的文件夹
*/
//本地默认的域在public中, 建立的文件夹名为域名。
class SaeStorage extends SaeObject {
private $domainDir; //域的根目录
private $filterPath;
private $url;
private $domainSize = array(); //记录域大小
private $domainSizeFlag = "";
//todu 增加api文档没有的函数
public function __construct($_accessKey='', $_secretKey='') {
global $sae_config;
$this->domainDir = $sae_config['storage_dir'];
$this->url = $sae_config['storage_url'];
parent::__construct();
}
public function delete($domain, $filename) {
$domain = trim($domain);
$filename = $this->formatFilename($filename);
if (Empty($domain) || Empty($filename)) {
$this->errMsg = Imit_L("_SAE_STORAGE_PARAM_EMPTY_") . '[the value of parameter (domain,filename) can not be empty!]';
$this->errNum = -101;
return false;
}
$filepath = $this->domainDir . $domain . "/" . $filename;
if (unlink($filepath)) {
return true;
} else {
$this->errno = -1;
$this->errmsg = Imit_L("_SAE_STORAGE_DELETE_ERR_");
return false;
}
}
public function deleteFolder($domain, $path) {
$domain = trim($domain);
$path = $this->formatFilename($path);
if (Empty($domain) || Empty($path)) {
$this->errmsg = Imit_L("_SAE_STORAGE_PARAM_EMPTY_") . '[the value of parameter (domain,path) can not be empty!]';
$this->errno = -101;
return false;
}
$folder = $this->domainDir . $domain . "/" . $path;
$this->delDir($folder);
return true;
}
private function delDir($directory) {
if (is_dir($directory) == false) {
exit("The Directory Is Not Exist!");
}
$handle = opendir($directory);
while (($file = readdir($handle)) !== false) {
if ($file != "." && $file != "..") {
is_dir("$directory/$file") ?
$this->delDir("$directory/$file") :
unlink("$directory/$file");
}
}
if (readdir($handle) == false) {
closedir($handle);
rmdir($directory);
}
}
public function fileExists($domain, $filename) {
$domain = trim($domain);
$filename = $this->formatFilename($filename);
if (Empty($domain) || Empty($filename)) {
$this->errmsg = Imit_L("_SAE_STORAGE_PARAM_EMPTY_") . '[the value of parameter (domain,filename) can not be empty!]';
$this->errno = -101;
return false;
}
$filepath = $this->domainDir . $domain . "/" . $filename;
return file_exists($filepath);
}
public function getAttr($domain, $filename, $attrKey=array()) {
$filepath = $this->domainDir . $domain . "/" . $filename;
if (!is_file($filepath)) {
$this->errno = -1;
$this->errmsg = Imit_L("_SAE_STORAGE_FILE_NOT_EXISTS_");
return false;
}
if (empty($attrKey))
$attrKey = array('fileName', 'length', 'datetime');
$ret = array();
foreach ($attrKey as $key) {
switch ($key) {
case "fileName":
$ret['fileName'] = $filename;
break;
case "length":
$ret['length'] = filesize($filepath);
break;
case "datetime":
$ret['datetime'] = filemtime($filepath); //todu 需要验证一下
break;
}
}
return $ret;
}
public function getDomainCapacity($domain) {
if (!isset($this->domainSize[$domain]))
$this->getList($domain);
return $this->domainSize[$domain];
}
public function getFilesNum($domain, $path=NULL) {
static $filesNum = array();
if (isset($filesNum[md5($domin . $path)]))
return $filesNum[md5($domin . $path)];
if ($path == NULL)
$path = "*";
$filesNum[md5($domin . $path)] = count($this->getList($domain, $path));
return $filesNum[md5($domin . $path)];
}
public function getList($domain, $prefix='*', $limit=10, $offset=0) {
$domain = trim($domain);
if (Empty($domain)) {
$this->errMsg = Imit_L("_SAE_STORAGE_PARAM_EMPTY_") . '[the value of parameter (domain) can not be empty!]';
$this->errNum = -101;
return false;
}
$path = $this->domainDir . $domain;
$this->filterPath = $path . "/";
//记录域的大小
if ($prefix == "*" && !isset($this->domainSize[$domain]))
$this->domainSizeFlag = $domain;
$files = $this->getAllList($path, $prefix);
$this->domainSizeFlag = "";
//偏移
return array_slice($files, $offset, $limit);
}
//获得所有文件
private function getAllList($path, $prefix, &$files=array()) {
$list = glob($path . "/" . $prefix);
//循环处理,创建数组
$dirs = array();
$_files = array();
foreach ($list as $i => $file) {
if (is_dir($file) && !$this->isEmpty($file)) {//如果不是空文件夹
$dirs[] = $file;
continue;
};
if (!empty($this->domainSizeFlag))
$this->domainSize[$this->domainSizeFlag]+=filesize($file); //统计大小
$_files[$i]['name'] = str_replace($this->filterPath, '', $file); //不含域的名称
$_files[$i]['isDir'] = is_dir($file);
}
//排序$_files
$cmp_func = create_function('$a,$b', '
$k="isDir";
if($a[$k] == $b[$k]) return 0;
return $a[$k]>$b[$k]?-1:1;
');
usort($_files, $cmp_func);
foreach ($_files as $file) {
//设置$files
$files[] = $file['isDir'] ? $file['name'] . "/__________sae-dir-tag" : $file['name'];
}
//循环数组,读取二级目录
foreach ($dirs as $dir) {
$this->getAllList($dir, "*", $files);
}
return $files;
}
//判断是否为空目录
private function isEmpty($directory) {
$handle = opendir($directory);
while (($file = readdir($handle)) !== false) {
if ($file != "." && $file != "..") {
closedir($handle);
return false;
}
}
closedir($handle);
return true;
}
public function getListByPath($domain, $path=NULL, $limit=100, $offset=0, $fold=true) {
$filepath = $this->domainDir . $domain . "/" . $path;
$list = scandir($filepath);
//读取非折叠数据
$files = array();
$dirnum = 0;
$filenum = 0;
foreach ($list as $file) {
//统计
if ($file == '.' || $file == '..')
continue;
$fullfile = $filepath . "/" . $file;
if (is_dir($fullfile)) {
$dirnum++;
$filename = $fullfile . "/__________sae-dir-tag";
} else {
$filenum++;
$filename = $fullfile;
}
$filename = str_replace($this->domainDir . $domain . "/", '', $filename);
$files[] = array(
'name' => basename($filename),
'fullName' => $filename,
'length' => filesize($fullfile),
'uploadTime' => filectime($fullfile)
);
}
//偏移
$files = array_slice($files, $offset, $limit);
if ($fold) {
//折叠处理
$rets = array(
'dirNum' => $dirnum,
'fileNum' => $filenum
);
foreach ($files as $file) {
if ($file['name'] == "__________sae-dir-tag") {
//文件夹
$rets['dirs'][] = array(
'name' => $file['name'],
'fullName' => $file['fullName']
);
} else {
$rets['files'][] = $file;
}
}
return $rets;
}
return $files;
}
public function getUrl($domain, $filename) {
$domain = trim($domain);
$filename = $this->formatFilename($filename);
return $this->url. $domain . "/" . $filename;
}
public function read($domain, $filename) {
$domain = trim($domain);
$filename = $this->formatFilename($filename);
if (Empty($domain) || Empty($filename)) {
$this->errmsg = Imit_L("_SAE_STORAGE_PARAM_EMPTY_") . '[the value of parameter (domain,filename) can not be empty!]';
$this->errno = -101;
return false;
}
$filepath = $this->domainDir . $domain . "/" . $filename;
return file_get_contents($filepath);
}
public function setDomainAttr($domain, $attr=array()) {
//pass
return true;
}
public function setFileAttr($domain, $filename, $attr=array()) {
//pass
return true;
}
public function upload($domain, $destFileName, $srcFileName, $attr=array()) {
$domain = trim($domain);
$destFileName = $this->formatFilename($destFileName);
if (Empty($domain) || Empty($destFileName) || Empty($srcFileName)) {
$this->errmsg = Imit_L("_SAE_STORAGE_PARAM_EMPTY_") . '[the value of parameter (domain,destFile,srcFileName) can not be empty!]';
$this->errno = -101;
return false;
}
return $this->write($domain,$destFileName,file_get_contents($srcFileName));
}
public function write($domain, $destFileName, $content, $size=-1, $attr=array(), $compress=false) {
if (Empty($domain) || Empty($destFileName)) {
$this->errmsg = Imit_L("_SAE_STORAGE_PARAM_EMPTY_") . "[the value of parameter (domain,destFileName,content) can not be empty!]";
$this->errno = -101;
return false;
}
//定义文件路径
$filepath = $this->domainDir . $domain . "/" . $destFileName;
$this->mkdir(dirname($filepath));
//设置长度
if ($size > -1)
$content = substr($content, 0, $size);
//写入文件
if (file_put_contents($filepath, $content)) {
return true;
} else {
$this->errmsg = Imit_L('_SAE_STORAGE_SERVER_ERR_');
$this->errno = -12;
return false;
}
}
//创建目录,无限层次。传递一个文件的
private function mkdir($dir) {
static $_dir; // 记录需要建立的目录
if (!is_dir($dir)) {
if (empty($_dir))
$_dir = $dir;
if (!is_dir(dirname($dir))) {
$this->mkdir(dirname($dir));
} else {
mkdir($dir);
if (!is_dir($_dir)) {
$this->mkdir($_dir);
} else {
$_dir = "";
}
}
}
}
private function formatFilename($filename) {
$filename = trim($filename);
$encodings = array('UTF-8', 'GBK', 'BIG5');
$charset = mb_detect_encoding($filename, $encodings);
if ($charset != 'UTF-8') {
$filename = mb_convert_encoding($filename, "UTF-8", $charset);
}
return $filename;
}
}
?> | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/SaeStorage.class.php | PHP | asf20 | 12,417 |
<?php
// +----------------------------------------------------------------------
// | 模拟器数据库采用sqlite3
// +----------------------------------------------------------------------
// | Author: luofei614<www.3g4k.com>
// +----------------------------------------------------------------------
// $Id: ImitSqlite.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
class ImitSqlite extends SQLite3{
function __construct()
{
$this->open(dirname(__FILE__).'/sae.db');
}
//获得数据,返回数组
public function getData($sql){
$this->last_sql = $sql;
$result=$this->query($sql);
if(!$result){
return false;
}
$data=array();
while($arr=$result->fetchArray(SQLITE3_ASSOC)){
$data[]=$arr;
}
return $data;
}
//返回第一条数据
public function getLine($sql) {
$data = $this->getData($sql);
if ($data) {
return @reset($data);
} else {
return false;
}
}
//返回第一条记录的第一个字段值
public function getVar($sql) {
$data = $this->getLine($sql);
if ($data) {
return $data[@reset(@array_keys($data))];
} else {
return false;
}
}
//运行sql语句
public function runSql($sql) {
return $this->exec($sql);
}
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/ImitSqlite.class.php | PHP | asf20 | 1,474 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <www.3g4k.com>
// +----------------------------------------------------------------------
// $Id: SaeTaskQueue.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
/**
*任务列队
*本地环境暂时需要支持curl才行。
*/
class SaeTaskQueue extends SaeObject{
public $queue=array();
//添加列队
public function addTask($tasks,$postdata=null,$prior=false,$options=array()){
if ( is_string($tasks) ) {
if ( !filter_var($tasks, FILTER_VALIDATE_URL) ) {
$this->errno = SAE_ErrParameter;
$this->errmsg = Imit_L("_SAE_ERRPARAMTER_");
return false;
}
//添加单条任务
$item = array();
$item['url'] = $tasks;
if ($postdata != NULL) $item['postdata'] = $postdata;
if ($prior) $item['prior'] = true;
$tasks=$item;
}
if ( empty($tasks) ) {
$this->errno = SAE_ErrParameter;
$this->errmsg = Imit_L("_SAE_ERRPARAMTER_");
return false;
}
//记录任务,处理优先
foreach($tasks as $k => $v) {
if (is_array($v) && isset($v['url'])) {
//当是二维数组时
if($v['prior']){
$this->queue=array_merge(array($v),$this->queue);
}else{
$this->queue[]=$v;
}
} elseif ( isset($tasks['url']) ) {
//当是一维数组时
if($tasks['prior']){
$this->queue=array_merge(array($tasks),$this->queue);
}else{
$this->queue[]=$tasks;
}
break;
} else {
$this->errno = SAE_ErrParameter;
$this->errmsg = Imit_L("_SAE_ERRPARAMTER_");
return false;
}
}
return true;
}
public function curLength(){
return true;
}
public function leftLength(){
return true;
}
public function push(){
//todu, 当用户环境不支持curl时用socket发送。
if(empty($this->queue)) return false;
$s = curl_init();
foreach($this->queue as $k=>$v){
curl_setopt($s,CURLOPT_URL,$v['url']);
//curl_setopt($s,CURLOPT_TIMEOUT,5);
curl_setopt($s,CURLOPT_RETURNTRANSFER,true);
curl_setopt($s,CURLOPT_HEADER, 1);
curl_setopt($s,CURLINFO_HEADER_OUT, true);
curl_setopt($s,CURLOPT_POST,true);
curl_setopt($s,CURLOPT_POSTFIELDS,$v['postdata']);
$ret = curl_exec($s);
$info = curl_getinfo($s);
// print_r($info);
if(empty($info['http_code'])) {
$this->errno = SAE_ErrInternal;
$this->errmsg = Imit_L("_SAE_TASKQUEUE_SERVICE_FAULT_");
return false;
} else if($info['http_code'] != 200) {
$this->errno = SAE_ErrInternal;
$this->errmsg = Imit_L("_SAE_TASKQUEUE_SERVICE_ERROR_");
return false;
} else {
//todu 这里好像有些问题
if($info['size_download'] == 0) { // get MailError header
$this->errno = SAE_ErrUnknown;
$this->errmsg = Imit_L("_SAE_UNKNOWN_ERROR_");
return false;
}
}
}
//循环结束
$this->queue=array();//清空列队
return true;
}
}
?> | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit/SaeTaskQueue.class.php | PHP | asf20 | 3,440 |
<?php
/**
* +---------------------------------------------------
* | SAE本地开发环境, 模拟sae服务
* +---------------------------------------------------
* @author luofei614<www.3g4k.com>
*/
@(ini_set('post_max_size', '10M')); // sae下最大上传文件为10M
@(ini_set('upload_max_filesize', '10M'));
$sae_config = include(SAE_PATH.'SaeImit/config.php');//读取配置文件
include_once SAE_PATH.'SaeImit/defines.php';
include_once SAE_PATH.'SaeImit/sae_functions.php';
include_once SAE_PATH.'SaeImit/imit_functions.php';
include_once SAE_PATH.'SaeImit/Lang.php';
spl_autoload_register('sae_auto_load');
function sae_auto_load($class){
$files=array(
'SaeObject'=>SAE_PATH.'SaeImit/SaeObject.class.php',
'SaeCounter'=> SAE_PATH.'SaeImit/SaeCounter.class.php',
'SaeRank'=>SAE_PATH.'SaeImit/SaeRank.class.php',
'SaeTaskQueue'=>SAE_PATH.'SaeImit/SaeTaskQueue.class.php',
'SaeStorage'=>SAE_PATH.'SaeImit/SaeStorage.class.php',
'SaeKVClient'=>SAE_PATH.'SaeImit/SaeKVClient.class.php',
'Memcache'=>SAE_PATH.'SaeImit/Memcache.class.php',
'CacheFile'=>THINK_PATH.'Lib/Driver/Cache/CacheFile.class.php',
'SaeMail'=>SAE_PATH.'SaeImit/SaeMail.class.php',
'SaeMysql'=>SAE_PATH.'SaeImit/SaeMysql.class.php',
'ImitSqlite'=>SAE_PATH.'SaeImit/ImitSqlite.class.php',
'SaeFetchurl'=>SAE_PATH.'SaeImit/SaeFetchurl.class.php',
'SaeImage'=>SAE_PATH.'SaeImit/SaeImage.class.php'
);
if(isset($files[$class]))
require $files[$class];
}
?>
| 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/SaeImit.php | PHP | asf20 | 1,544 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: alias.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
if (!defined('THINK_PATH')) exit();
// 系统别名定义文件
return array(
'Model' => CORE_PATH.'Core/Model.class.php',
'Db' => CORE_PATH.'Core/Db.class.php',
'Log' => SAE_PATH.'Lib/Core/Log.class.php',
'ThinkTemplate' => SAE_PATH.'Lib/Template/ThinkTemplate.class.php',
'TagLib' => CORE_PATH.'Template/TagLib.class.php',
'Cache' => CORE_PATH.'Core/Cache.class.php',
'Widget' => CORE_PATH.'Core/Widget.class.php',
'TagLibCx' => CORE_PATH.'Driver/TagLib/TagLibCx.class.php',
); | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Conf/alias.php | PHP | asf20 | 1,249 |
<?php
//sae下的固定配置,以下配置将会覆盖项目配置。
return array(
'DB_TYPE'=> 'mysql', // 数据库类型
'DB_HOST'=> SAE_MYSQL_HOST_M.','.SAE_MYSQL_HOST_S, // 服务器地址
'DB_NAME'=> SAE_MYSQL_DB, // 数据库名
'DB_USER'=> SAE_MYSQL_USER, // 用户名
'DB_PWD'=> SAE_MYSQL_PASS, // 密码
'DB_PORT'=> SAE_MYSQL_PORT, // 端口
'DB_RW_SEPARATE'=>true,
'DB_DEPLOY_TYPE'=> 1, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'SAE_SPECIALIZED_FILES'=>array(
//SAE系统专属文件。
'UploadFile.class.php'=>SAE_PATH.'Lib/Extend/Library/ORG/Net/UploadFile_sae.class.php',
'Image.class.php'=>SAE_PATH.'Lib/Extend/Library/ORG/Util/Image_sae.class.php'
)
);
| 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Conf/convention_sae.php | PHP | asf20 | 840 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: tags.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
// 系统默认的核心行为扩展列表文件
//[sae]定义别名,让在SAE下时,调试模式也加载对应文件。
alias_import(array(
'ParseTemplateBehavior'=>SAE_PATH.'Lib/Behavior/ParseTemplateBehavior.class.php',
'ReadHtmlCacheBehavior'=>SAE_PATH.'Lib/Behavior/ReadHtmlCacheBehavior.class.php',
'WriteHtmlCacheBehavior'=>SAE_PATH.'Lib/Behavior/WriteHtmlCacheBehavior.class.php'
));
return array(
'app_init'=>array(
),
'app_begin'=>array(
'ReadHtmlCache'=>SAE_PATH.'Lib/Behavior/ReadHtmlCacheBehavior.class.php', // 读取静态缓存
),
'route_check'=>array(
'CheckRoute', // 路由检测
),
'app_end'=>array(),
'path_info'=>array(),
'action_begin'=>array(),
'action_end'=>array(),
'view_begin'=>array(),
'view_template'=>array(
'LocationTemplate', // 自动定位模板文件
),
'view_parse'=>array(
'ParseTemplate'=>SAE_PATH.'Lib/Behavior/ParseTemplateBehavior.class.php', //[sae] 模板解析 支持PHP、内置模板引擎和第三方模板引擎
),
'view_filter'=>array(
'ContentReplace', // 模板输出替换
'TokenBuild', // 表单令牌
'WriteHtmlCache'=>SAE_PATH.'Lib/Behavior/WriteHtmlCacheBehavior.class.php', // 写入静态缓存
'ShowRuntime', // 运行时间显示
),
'view_end'=>array(
'ShowPageTrace', // 页面Trace显示
),
); | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Conf/tags.php | PHP | asf20 | 2,135 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: ThinkTemplate.class.php 2821 2012-03-16 06:17:49Z luofei614@gmail.com $
/**
+------------------------------------------------------------------------------
* ThinkPHP内置模板引擎类
* 支持XML标签和普通标签的模板解析
* 编译型模板引擎 支持动态缓存
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Template
* @author liu21st <liu21st@gmail.com>
* @version $Id: ThinkTemplate.class.php 2821 2012-03-16 06:17:49Z luofei614@gmail.com $
+------------------------------------------------------------------------------
*/
class ThinkTemplate {
// 模板页面中引入的标签库列表
protected $tagLib = array();
// 当前模板文件
protected $templateFile = '';
// 模板变量
public $tVar = array();
public $config = array();
private $literal = array();
/**
+----------------------------------------------------------
* 取得模板实例对象
* 静态方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return ThinkTemplate
+----------------------------------------------------------
*/
static public function getInstance() {
return get_instance_of(__CLASS__);
}
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $config 模板引擎配置数组
+----------------------------------------------------------
*/
public function __construct(){
//[sae] 不用此项 $this->config['cache_path'] = C('CACHE_PATH');
$this->config['template_suffix'] = C('TMPL_TEMPLATE_SUFFIX');
$this->config['cache_suffix'] = C('TMPL_CACHFILE_SUFFIX');
$this->config['tmpl_cache'] = C('TMPL_CACHE_ON');
$this->config['cache_time'] = C('TMPL_CACHE_TIME');
$this->config['taglib_begin'] = $this->stripPreg(C('TAGLIB_BEGIN'));
$this->config['taglib_end'] = $this->stripPreg(C('TAGLIB_END'));
$this->config['tmpl_begin'] = $this->stripPreg(C('TMPL_L_DELIM'));
$this->config['tmpl_end'] = $this->stripPreg(C('TMPL_R_DELIM'));
$this->config['default_tmpl'] = C('TEMPLATE_NAME');
$this->config['layout_item'] = C('TMPL_LAYOUT_ITEM');
}
private function stripPreg($str) {
return str_replace(array('{','}','(',')','|','[',']'),array('\{','\}','\(','\)','\|','\[','\]'),$str);
}
// 模板变量获取和设置
public function get($name) {
if(isset($this->tVar[$name]))
return $this->tVar[$name];
else
return false;
}
public function set($name,$value) {
$this->tVar[$name]= $value;
}
// 加载模板
public function fetch($templateFile,$templateVar) {
$this->tVar = $templateVar;
$templateCacheFile = $this->loadTemplate($templateFile);
//[sae]载入模版缓存文件
SaeMC::include_file($templateCacheFile,$templateVar);
}
/**
+----------------------------------------------------------
* 加载主模板并缓存
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $tmplTemplateFile 模板文件
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function loadTemplate ($tmplTemplateFile) {
$this->templateFile = $tmplTemplateFile;
//[sae] 根据模版文件名定位缓存文件
$tmplCacheFile = md5($tmplTemplateFile).$this->config['cache_suffix'];
// 读取模板文件内容
$tmplContent = file_get_contents($tmplTemplateFile);
// 判断是否启用布局
if(C('LAYOUT_ON')) {
if(false !== strpos($tmplContent,'{__NOLAYOUT__}')) { // 可以单独定义不使用布局
$tmplContent = str_replace('{__NOLAYOUT__}','',$tmplContent);
}else{ // 替换布局的主体内容
$layoutFile = THEME_PATH.C('LAYOUT_NAME').$this->config['template_suffix'];
$tmplContent = str_replace($this->config['layout_item'],$tmplContent,file_get_contents($layoutFile));
}
}
//编译模板内容
$tmplContent = $this->compiler($tmplContent);
//[sae]去掉检测分组目录
//[sae]重写Cache文件
SaeMC::set($tmplCacheFile, trim($tmplContent));
return $tmplCacheFile;
}
/**
+----------------------------------------------------------
* 编译模板文件内容
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $tmplContent 模板内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function compiler($tmplContent) {
//模板解析
$tmplContent = $this->parse($tmplContent);
// 还原被替换的Literal标签
$tmplContent = preg_replace('/<!--###literal(\d)###-->/eis',"\$this->restoreLiteral('\\1')",$tmplContent);
// 添加安全代码
$tmplContent = '<?php if (!defined(\'THINK_PATH\')) exit();?>'.$tmplContent;
if(C('TMPL_STRIP_SPACE')) {
/* 去除html空格与换行 */
$find = array("~>\s+<~","~>(\s+\n|\r)~");
$replace = array('><','>');
$tmplContent = preg_replace($find, $replace, $tmplContent);
}
// 优化生成的php代码
$tmplContent = str_replace('?><?php','',$tmplContent);
return strip_whitespace($tmplContent);
}
/**
+----------------------------------------------------------
* 模板解析入口
* 支持普通标签和TagLib解析 支持自定义标签库
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $content 要解析的模板内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parse($content) {
// 内容为空不解析
if(empty($content)) return '';
$begin = $this->config['taglib_begin'];
$end = $this->config['taglib_end'];
// 首先替换literal标签内容
$content = preg_replace('/'.$begin.'literal'.$end.'(.*?)'.$begin.'\/literal'.$end.'/eis',"\$this->parseLiteral('\\1')",$content);
// 检查include语法
$content = $this->parseInclude($content);
// 检查PHP语法
$content = $this->parsePhp($content);
// 获取需要引入的标签库列表
// 标签库只需要定义一次,允许引入多个一次
// 一般放在文件的最前面
// 格式:<taglib name="html,mytag..." />
// 当TAGLIB_LOAD配置为true时才会进行检测
if(C('TAGLIB_LOAD')) {
$this->getIncludeTagLib($content);
if(!empty($this->tagLib)) {
// 对导入的TagLib进行解析
foreach($this->tagLib as $tagLibName) {
$this->parseTagLib($tagLibName,$content);
}
}
}
// 预先加载的标签库 无需在每个模板中使用taglib标签加载 但必须使用标签库XML前缀
if(C('TAGLIB_PRE_LOAD')) {
$tagLibs = explode(',',C('TAGLIB_PRE_LOAD'));
foreach ($tagLibs as $tag){
$this->parseTagLib($tag,$content);
}
}
// 内置标签库 无需使用taglib标签导入就可以使用 并且不需使用标签库XML前缀
$tagLibs = explode(',',C('TAGLIB_BUILD_IN'));
foreach ($tagLibs as $tag){
$this->parseTagLib($tag,$content,true);
}
//解析普通模板标签 {tagName}
$content = preg_replace('/('.$this->config['tmpl_begin'].')(\S.+?)('.$this->config['tmpl_end'].')/eis',"\$this->parseTag('\\2')",$content);
return $content;
}
// 检查PHP语法
protected function parsePhp($content) {
// PHP语法检查
if(C('TMPL_DENY_PHP') && false !== strpos($content,'<?php')) {
throw_exception(L('_NOT_ALLOW_PHP_'));
}elseif(ini_get('short_open_tag')){
// 开启短标签的情况要将<?标签用echo方式输出 否则无法正常输出xml标识
$content = preg_replace('/(<\?(?!php|=|$))/i', '<?php echo \'\\1\'; ?>'."\n", $content );
}
return $content;
}
// 解析模板中的布局标签
protected function parseLayout($content) {
// 读取模板中的布局标签
$find = preg_match('/'.$this->config['taglib_begin'].'layout\s(.+?)\s*?\/'.$this->config['taglib_end'].'/is',$content,$matches);
if($find) {
//替换Layout标签
$content = str_replace($matches[0],'',$content);
//解析Layout标签
$layout = $matches[1];
$xml = '<tpl><tag '.$layout.' /></tpl>';
$xml = simplexml_load_string($xml);
if(!$xml)
throw_exception(L('_XML_TAG_ERROR_'));
$xml = (array)($xml->tag->attributes());
$array = array_change_key_case($xml['@attributes']);
if(!C('LAYOUT_ON') || C('LAYOUT_NAME') !=$array['name'] ) {
// 读取布局模板
$layoutFile = THEME_PATH.$array['name'].$this->config['template_suffix'];
$replace = isset($array['replace'])?$array['replace']:$this->config['layout_item'];
// 替换布局的主体内容
$content = str_replace($replace,$content,file_get_contents($layoutFile));
}
}
return $content;
}
// 解析模板中的include标签
protected function parseInclude($content) {
// 解析布局
$content = $this->parseLayout($content);
// 读取模板中的布局标签
$find = preg_match_all('/'.$this->config['taglib_begin'].'include\s(.+?)\s*?\/'.$this->config['taglib_end'].'/is',$content,$matches);
if($find) {
for($i=0;$i<$find;$i++) {
$include = $matches[1][$i];
$xml = '<tpl><tag '.$include.' /></tpl>';
$xml = simplexml_load_string($xml);
if(!$xml)
throw_exception(L('_XML_TAG_ERROR_'));
$xml = (array)($xml->tag->attributes());
$array = array_change_key_case($xml['@attributes']);
$file = $array['file'];
unset($array['file']);
$content = str_replace($matches[0][$i],$this->parseIncludeItem($file,$array),$content);
}
}
return $content;
}
/**
+----------------------------------------------------------
* 替换页面中的literal标签
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $content 模板内容
+----------------------------------------------------------
* @return string|false
+----------------------------------------------------------
*/
private function parseLiteral($content) {
if(trim($content)=='')
return '';
$content = stripslashes($content);
$i = count($this->literal);
$parseStr = "<!--###literal{$i}###-->";
$this->literal[$i] = $content;
return $parseStr;
}
/**
+----------------------------------------------------------
* 还原被替换的literal标签
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $tag literal标签序号
+----------------------------------------------------------
* @return string|false
+----------------------------------------------------------
*/
private function restoreLiteral($tag) {
// 还原literal标签
$parseStr = $this->literal[$tag];
// 销毁literal记录
unset($this->literal[$tag]);
return $parseStr;
}
/**
+----------------------------------------------------------
* 搜索模板页面中包含的TagLib库
* 并返回列表
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $content 模板内容
+----------------------------------------------------------
* @return string|false
+----------------------------------------------------------
*/
public function getIncludeTagLib(& $content) {
//搜索是否有TagLib标签
$find = preg_match('/'.$this->config['taglib_begin'].'taglib\s(.+?)(\s*?)\/'.$this->config['taglib_end'].'\W/is',$content,$matches);
if($find) {
//替换TagLib标签
$content = str_replace($matches[0],'',$content);
//解析TagLib标签
$tagLibs = $matches[1];
$xml = '<tpl><tag '.$tagLibs.' /></tpl>';
$xml = simplexml_load_string($xml);
if(!$xml)
throw_exception(L('_XML_TAG_ERROR_'));
$xml = (array)($xml->tag->attributes());
$array = array_change_key_case($xml['@attributes']);
$this->tagLib = explode(',',$array['name']);
}
return;
}
/**
+----------------------------------------------------------
* TagLib库解析
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $tagLib 要解析的标签库
* @param string $content 要解析的模板内容
* @param boolen $hide 是否隐藏标签库前缀
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseTagLib($tagLib,&$content,$hide=false) {
$begin = $this->config['taglib_begin'];
$end = $this->config['taglib_end'];
$className = 'TagLib'.ucwords($tagLib);
if(!import($className)) {
if(is_file(EXTEND_PATH.'Driver/TagLib/'.$className.'.class.php')) {
// 扩展标签库优先识别
$file = EXTEND_PATH.'Driver/TagLib/'.$className.'.class.php';
}else{
// 系统目录下面的标签库
$file = CORE_PATH.'Driver/TagLib/'.$className.'.class.php';
}
require_cache($file);
}
$tLib = Think::instance($className);
foreach ($tLib->getTags() as $name=>$val){
$tags = array($name);
if(isset($val['alias'])) {// 别名设置
$tags = explode(',',$val['alias']);
$tags[] = $name;
}
$level = isset($val['level'])?$val['level']:1;
$closeTag = isset($val['close'])?$val['close']:true;
foreach ($tags as $tag){
$parseTag = !$hide? $tagLib.':'.$tag: $tag;// 实际要解析的标签名称
if(!method_exists($tLib,'_'.$tag)) {
// 别名可以无需定义解析方法
$tag = $name;
}
$n1 = empty($val['attr'])?'(\s*?)':'\s(.*?)';
if (!$closeTag){
$patterns = '/'.$begin.$parseTag.$n1.'\/(\s*?)'.$end.'/eis';
$replacement = "\$this->parseXmlTag('$tagLib','$tag','$1','')";
$content = preg_replace($patterns, $replacement,$content);
}else{
$patterns = '/'.$begin.$parseTag.$n1.$end.'(.*?)'.$begin.'\/'.$parseTag.'(\s*?)'.$end.'/eis';
$replacement = "\$this->parseXmlTag('$tagLib','$tag','$1','$2')";
for($i=0;$i<$level;$i++) $content=preg_replace($patterns,$replacement,$content);
}
}
}
}
/**
+----------------------------------------------------------
* 解析标签库的标签
* 需要调用对应的标签库文件解析类
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $tagLib 标签库名称
* @param string $tag 标签名
* @param string $attr 标签属性
* @param string $content 标签内容
+----------------------------------------------------------
* @return string|false
+----------------------------------------------------------
*/
public function parseXmlTag($tagLib,$tag,$attr,$content) {
//if (MAGIC_QUOTES_GPC) {
$attr = stripslashes($attr);
$content = stripslashes($content);
//}
if(ini_get('magic_quotes_sybase'))
$attr = str_replace('\"','\'',$attr);
$tLib = Think::instance('TagLib'.ucwords(strtolower($tagLib)));
$parse = '_'.$tag;
$content = trim($content);
return $tLib->$parse($attr,$content);
}
/**
+----------------------------------------------------------
* 模板标签解析
* 格式: {TagName:args [|content] }
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $tagStr 标签内容
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseTag($tagStr){
//if (MAGIC_QUOTES_GPC) {
$tagStr = stripslashes($tagStr);
//}
//还原非模板标签
if(preg_match('/^[\s|\d]/is',$tagStr))
//过滤空格和数字打头的标签
return C('TMPL_L_DELIM') . $tagStr .C('TMPL_R_DELIM');
$flag = substr($tagStr,0,1);
$name = substr($tagStr,1);
if('$' == $flag){ //解析模板变量 格式 {$varName}
return $this->parseVar($name);
}elseif('-' == $flag || '+'== $flag){ // 输出计算
return '<?php echo '.$flag.$name.';?>';
}elseif(':' == $flag){ // 输出某个函数的结果
return '<?php echo '.$name.';?>';
}elseif('~' == $flag){ // 执行某个函数
return '<?php '.$name.';?>';
}elseif(substr($tagStr,0,2)=='//' || (substr($tagStr,0,2)=='/*' && substr($tagStr,-2)=='*/')){
//注释标签
return '';
}
// 未识别的标签直接返回
return C('TMPL_L_DELIM') . $tagStr .C('TMPL_R_DELIM');
}
/**
+----------------------------------------------------------
* 模板变量解析,支持使用函数
* 格式: {$varname|function1|function2=arg1,arg2}
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $varStr 变量数据
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseVar($varStr){
$varStr = trim($varStr);
static $_varParseList = array();
//如果已经解析过该变量字串,则直接返回变量值
if(isset($_varParseList[$varStr])) return $_varParseList[$varStr];
$parseStr ='';
$varExists = true;
if(!empty($varStr)){
$varArray = explode('|',$varStr);
//取得变量名称
$var = array_shift($varArray);
//非法变量过滤 不允许在变量里面使用 ->
//TODO:还需要继续完善
if(preg_match('/->/is',$var))
return '';
if('Think.' == substr($var,0,6)){
// 所有以Think.打头的以特殊变量对待 无需模板赋值就可以输出
$name = $this->parseThinkVar($var);
}elseif( false !== strpos($var,'.')) {
//支持 {$var.property}
$vars = explode('.',$var);
$var = array_shift($vars);
switch(strtolower(C('TMPL_VAR_IDENTIFY'))) {
case 'array': // 识别为数组
$name = '$'.$var;
foreach ($vars as $key=>$val)
$name .= '["'.$val.'"]';
break;
case 'obj': // 识别为对象
$name = '$'.$var;
foreach ($vars as $key=>$val)
$name .= '->'.$val;
break;
default: // 自动判断数组或对象 只支持二维
$name = 'is_array($'.$var.')?$'.$var.'["'.$vars[0].'"]:$'.$var.'->'.$vars[0];
}
}elseif(false !==strpos($var,':')){
//支持 {$var:property} 方式输出对象的属性
$vars = explode(':',$var);
$var = str_replace(':','->',$var);
$name = "$".$var;
$var = $vars[0];
}elseif(false !== strpos($var,'[')) {
//支持 {$var['key']} 方式输出数组
$name = "$".$var;
preg_match('/(.+?)\[(.+?)\]/is',$var,$match);
$var = $match[1];
}else {
$name = "$$var";
}
//对变量使用函数
if(count($varArray)>0)
$name = $this->parseVarFunction($name,$varArray);
$parseStr = '<?php echo ('.$name.'); ?>';
}
$_varParseList[$varStr] = $parseStr;
return $parseStr;
}
/**
+----------------------------------------------------------
* 对模板变量使用函数
* 格式 {$varname|function1|function2=arg1,arg2}
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 变量名
* @param array $varArray 函数列表
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseVarFunction($name,$varArray){
//对变量使用函数
$length = count($varArray);
//取得模板禁止使用函数列表
$template_deny_funs = explode(',',C('TMPL_DENY_FUNC_LIST'));
for($i=0;$i<$length ;$i++ ){
$args = explode('=',$varArray[$i],2);
//模板函数过滤
$fun = strtolower(trim($args[0]));
switch($fun) {
case 'default': // 特殊模板函数
$name = '('.$name.')?('.$name.'):'.$args[1];
break;
default: // 通用模板函数
if(!in_array($fun,$template_deny_funs)){
if(isset($args[1])){
if(strstr($args[1],'###')){
$args[1] = str_replace('###',$name,$args[1]);
$name = "$fun($args[1])";
}else{
$name = "$fun($name,$args[1])";
}
}else if(!empty($args[0])){
$name = "$fun($name)";
}
}
}
}
return $name;
}
/**
+----------------------------------------------------------
* 特殊模板变量解析
* 格式 以 $Think. 打头的变量属于特殊模板变量
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $varStr 变量字符串
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function parseThinkVar($varStr){
$vars = explode('.',$varStr);
$vars[1] = strtoupper(trim($vars[1]));
$parseStr = '';
if(count($vars)>=3){
$vars[2] = trim($vars[2]);
switch($vars[1]){
case 'SERVER':
$parseStr = '$_SERVER[\''.strtoupper($vars[2]).'\']';break;
case 'GET':
$parseStr = '$_GET[\''.$vars[2].'\']';break;
case 'POST':
$parseStr = '$_POST[\''.$vars[2].'\']';break;
case 'COOKIE':
if(isset($vars[3])) {
$parseStr = '$_COOKIE[\''.$vars[2].'\'][\''.$vars[3].'\']';
}else{
$parseStr = '$_COOKIE[\''.$vars[2].'\']';
}break;
case 'SESSION':
if(isset($vars[3])) {
$parseStr = '$_SESSION[\''.$vars[2].'\'][\''.$vars[3].'\']';
}else{
$parseStr = '$_SESSION[\''.$vars[2].'\']';
}
break;
case 'ENV':
$parseStr = '$_ENV[\''.strtoupper($vars[2]).'\']';break;
case 'REQUEST':
$parseStr = '$_REQUEST[\''.$vars[2].'\']';break;
case 'CONST':
$parseStr = strtoupper($vars[2]);break;
case 'LANG':
$parseStr = 'L("'.$vars[2].'")';break;
case 'CONFIG':
if(isset($vars[3])) {
$vars[2] .= '.'.$vars[3];
}
$parseStr = 'C("'.$vars[2].'")';break;
default:break;
}
}else if(count($vars)==2){
switch($vars[1]){
case 'NOW':
$parseStr = "date('Y-m-d g:i a',time())";
break;
case 'VERSION':
$parseStr = 'THINK_VERSION';
break;
case 'TEMPLATE':
$parseStr = "'".$this->templateFile."'";//'C("TEMPLATE_NAME")';
break;
case 'LDELIM':
$parseStr = 'C("TMPL_L_DELIM")';
break;
case 'RDELIM':
$parseStr = 'C("TMPL_R_DELIM")';
break;
default:
if(defined($vars[1]))
$parseStr = $vars[1];
}
}
return $parseStr;
}
/**
+----------------------------------------------------------
* 加载公共模板并缓存 和当前模板在同一路径,否则使用相对路径
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $tmplPublicName 公共模板文件名
* @param array $vars 要传递的变量列表
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function parseIncludeItem($tmplPublicName,$vars=array()){
if(substr($tmplPublicName,0,1)=='$')
//支持加载变量文件名
$tmplPublicName = $this->get(substr($tmplPublicName,1));
if(false === strpos($tmplPublicName,$this->config['template_suffix'])) {
// 解析规则为 模板主题:模块:操作 不支持 跨项目和跨分组调用
$path = explode(':',$tmplPublicName);
$action = array_pop($path);
$module = !empty($path)?array_pop($path):MODULE_NAME;
if(!empty($path)) {// 设置模板主题
$path = dirname(THEME_PATH).'/'.array_pop($path).'/';
}else{
$path = THEME_PATH;
}
$depr = defined('GROUP_NAME')?C('TMPL_FILE_DEPR'):'/';
$tmplPublicName = $path.$module.$depr.$action.$this->config['template_suffix'];
}
// 获取模板文件内容
$parseStr = file_get_contents($tmplPublicName);
foreach ($vars as $key=>$val) {
$parseStr = str_replace('['.$key.']',$val,$parseStr);
}
//再次对包含文件进行模板分析
return $this->parseInclude($parseStr);
}
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Lib/Template/ThinkTemplate.class.php | PHP | asf20 | 30,903 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: WriteHtmlCacheBehavior.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
/**
+------------------------------------------------------------------------------
* 系统行为扩展 静态缓存写入
* 增加配置参数如下:
+------------------------------------------------------------------------------
*/
class WriteHtmlCacheBehavior extends Behavior {
// 行为扩展的执行入口必须是run
public function run(&$content){
if(C('HTML_CACHE_ON') && defined('HTML_FILE_NAME')) {
//静态文件写入
// 如果开启HTML功能 检查并重写HTML文件
// 没有模版的操作不生成静态文件
//[sae] 生成静态缓存
$kv = Think::instance('SaeKVClient');
if (!$kv->init())
halt('您没有初始化KVDB,请在SAE平台进行初始化');
trace('[SAE]静态缓存',HTML_FILE_NAME);
$kv->set(HTML_FILE_NAME,time().$content);
}
}
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Lib/Behavior/WriteHtmlCacheBehavior.class.php | PHP | asf20 | 1,639 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: ReadHtmlCacheBehavior.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
/**
+------------------------------------------------------------------------------
* 系统行为扩展 静态缓存读取
+------------------------------------------------------------------------------
*/
class ReadHtmlCacheBehavior extends Behavior {
protected $options = array(
'HTML_CACHE_ON'=>false,
'HTML_CACHE_TIME'=>60,
'HTML_CACHE_RULES'=>array(),
'HTML_FILE_SUFFIX'=>'.html',
);
static protected $html_content='';//[sae] 存储html内容
// 行为扩展的执行入口必须是run
public function run(&$params){
// 开启静态缓存
if(C('HTML_CACHE_ON')) {
if(($cacheTime = $this->requireHtmlCache()) && $this->checkHTMLCache(HTML_FILE_NAME,$cacheTime)) { //静态页面有效
//[sae] 读取静态页面输出
exit(self::$html_content);
}
}
}
// 判断是否需要静态缓存
static private function requireHtmlCache() {
// 分析当前的静态规则
$htmls = C('HTML_CACHE_RULES'); // 读取静态规则
if(!empty($htmls)) {
// 静态规则文件定义格式 actionName=>array(‘静态规则’,’缓存时间’,’附加规则')
// 'read'=>array('{id},{name}',60,'md5') 必须保证静态规则的唯一性 和 可判断性
// 检测静态规则
$moduleName = strtolower(MODULE_NAME);
if(isset($htmls[$moduleName.':'.ACTION_NAME])) {
$html = $htmls[$moduleName.':'.ACTION_NAME]; // 某个模块的操作的静态规则
}elseif(isset($htmls[$moduleName.':'])){// 某个模块的静态规则
$html = $htmls[$moduleName.':'];
}elseif(isset($htmls[ACTION_NAME])){
$html = $htmls[ACTION_NAME]; // 所有操作的静态规则
}elseif(isset($htmls['*'])){
$html = $htmls['*']; // 全局静态规则
}elseif(isset($htmls['empty:index']) && !class_exists(MODULE_NAME.'Action')){
$html = $htmls['empty:index']; // 空模块静态规则
}elseif(isset($htmls[$moduleName.':_empty']) && $this->isEmptyAction(MODULE_NAME,ACTION_NAME)){
$html = $htmls[$moduleName.':_empty']; // 空操作静态规则
}
if(!empty($html)) {
// 解读静态规则
$rule = $html[0];
// 以$_开头的系统变量
$rule = preg_replace('/{\$(_\w+)\.(\w+)\|(\w+)}/e',"\\3(\$\\1['\\2'])",$rule);
$rule = preg_replace('/{\$(_\w+)\.(\w+)}/e',"\$\\1['\\2']",$rule);
// {ID|FUN} GET变量的简写
$rule = preg_replace('/{(\w+)\|(\w+)}/e',"\\2(\$_GET['\\1'])",$rule);
$rule = preg_replace('/{(\w+)}/e',"\$_GET['\\1']",$rule);
// 特殊系统变量
$rule = str_ireplace(
array('{:app}','{:module}','{:action}','{:group}'),
array(APP_NAME,MODULE_NAME,ACTION_NAME,defined('GROUP_NAME')?GROUP_NAME:''),
$rule);
// {|FUN} 单独使用函数
$rule = preg_replace('/{|(\w+)}/e',"\\1()",$rule);
if(!empty($html[2])) $rule = $html[2]($rule); // 应用附加函数
$cacheTime = isset($html[1])?$html[1]:C('HTML_CACHE_TIME'); // 缓存有效期
// 当前缓存文件
define('HTML_FILE_NAME',HTML_PATH . $rule.C('HTML_FILE_SUFFIX'));
return $cacheTime;
}
}
// 无需缓存
return false;
}
/**
+----------------------------------------------------------
* 检查静态HTML文件是否有效
* 如果无效需要重新更新
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $cacheFile 静态文件名
* @param integer $cacheTime 缓存有效期
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
//[sae] 检查静态缓存
static public function checkHTMLCache($cacheFile='',$cacheTime='') {
$kv=Think::instance('SaeKVClient');
if(!$kv->init()) halt('您没有初始化KVDB,请在SAE平台进行初始化');
$content=$kv->get($cacheFile);
if(!$content)
return false;
$mtime= substr($content,0,10);
self::$html_content=substr($content,10);
if (filemtime(C('TEMPLATE_NAME')) > $mtime) {
// 模板文件如果更新静态文件需要更新
return false;
}elseif(!is_numeric($cacheTime) && function_exists($cacheTime)){
return $cacheTime($cacheFile);
}elseif ($cacheTime != 0 && time() > $mtime+$cacheTime) {
// 文件是否在有效期
return false;
}
//静态文件有效
return true;
}
//检测是否是空操作
static private function isEmptyAction($module,$action) {
$className = $module.'Action';
$class=new $className;
return !method_exists($class,$action);
}
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Lib/Behavior/ReadHtmlCacheBehavior.class.php | PHP | asf20 | 6,182 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: ParseTemplateBehavior.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
/**
+------------------------------------------------------------------------------
* 系统行为扩展 模板解析
+------------------------------------------------------------------------------
*/
class ParseTemplateBehavior extends Behavior {
// 行为参数定义(默认值) 可在项目配置中覆盖
protected $options = array(
// 布局设置
'TMPL_ENGINE_TYPE' => 'Think', // 默认模板引擎 以下设置仅对使用Think模板引擎有效
'TMPL_CACHFILE_SUFFIX' => '.php', // 默认模板缓存后缀
'TMPL_DENY_FUNC_LIST' => 'echo,exit', // 模板引擎禁用函数
'TMPL_DENY_PHP' =>false, // 默认模板引擎是否禁用PHP原生代码
'TMPL_L_DELIM' => '{', // 模板引擎普通标签开始标记
'TMPL_R_DELIM' => '}', // 模板引擎普通标签结束标记
'TMPL_VAR_IDENTIFY' => 'array', // 模板变量识别。留空自动判断,参数为'obj'则表示对象
'TMPL_STRIP_SPACE' => true, // 是否去除模板文件里面的html空格与换行
'TMPL_CACHE_ON' => true, // 是否开启模板编译缓存,设为false则每次都会重新编译
'TMPL_CACHE_TIME' => 0, // 模板缓存有效期 0 为永久,(以数字为值,单位:秒)
'TMPL_LAYOUT_ITEM' => '{__CONTENT__}', // 布局模板的内容替换标识
'LAYOUT_ON' => false, // 是否启用布局
'LAYOUT_NAME' => 'layout', // 当前布局名称 默认为layout
// Think模板引擎标签库相关设定
'TAGLIB_BEGIN' => '<', // 标签库标签开始标记
'TAGLIB_END' => '>', // 标签库标签结束标记
'TAGLIB_LOAD' => true, // 是否使用内置标签库之外的其它标签库,默认自动检测
'TAGLIB_BUILD_IN' => 'cx', // 内置标签库名称(标签使用不必指定标签库名称),以逗号分隔 注意解析顺序
'TAGLIB_PRE_LOAD' => '', // 需要额外加载的标签库(须指定标签库名称),多个以逗号分隔
);
// 行为扩展的执行入口必须是run
public function run(&$_data){
$engine = strtolower(C('TMPL_ENGINE_TYPE'));
if('think'==$engine){ //[sae] 采用Think模板引擎
if($this->checkCache($_data['file'])) { // 缓存有效
SaeMC::include_file(md5($_data['file']).C('TMPL_CACHFILE_SUFFIX'),$_data['var']);
}else{
$tpl = Think::instance('ThinkTemplate');
// 编译并加载模板文件
$tpl->fetch($_data['file'],$_data['var']);
}
}else{
// 调用第三方模板引擎解析和输出
$class = 'Template'.ucwords($engine);
if(is_file(CORE_PATH.'Driver/Template/'.$class.'.class.php')) {
// 内置驱动
$path = CORE_PATH;
}else{ // 扩展驱动
$path = EXTEND_PATH;
}
if(require_cache($path.'Driver/Template/'.$class.'.class.php')) {
$tpl = new $class;
$tpl->fetch($_data['file'],$_data['var']);
}else { // 类没有定义
throw_exception(L('_NOT_SUPPERT_').': ' . $class);
}
}
//[sae] 添加trace信息。
trace(array(
'[SAE]核心缓存'=>$_SERVER['HTTP_APPVERSION'].'/'.RUNTIME_FILE,
'[SAE]模板缓存'=>$_SERVER['HTTP_APPVERSION'].'/'.md5($_data['file']).C('TMPL_CACHFILE_SUFFIX')
));
}
/**
+----------------------------------------------------------
* 检查缓存文件是否有效
* 如果无效则需要重新编译
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $tmplTemplateFile 模板文件名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
//[sae] 检查模版
protected function checkCache($tmplTemplateFile) {
if (!C('TMPL_CACHE_ON')) // 优先对配置设定检测
return false;
//[sae] 不加模版目录,简化模版名称
$tmplCacheFile = md5($tmplTemplateFile).C('TMPL_CACHFILE_SUFFIX');
if(!SaeMC::file_exists($tmplCacheFile)){
return false;
//}elseif (filemtime($tmplTemplateFile) > filemtime($tmplCacheFile)) {
}elseif (filemtime($tmplTemplateFile) > SaeMC::filemtime($tmplCacheFile)) {
// 模板文件如果有更新则缓存需要更新
return false;
}elseif (C('TMPL_CACHE_TIME') != 0 && time() > SaeMC::filemtime($tmplCacheFile)+C('TMPL_CACHE_TIME')) {
// 缓存是否在有效期
return false;
}
// 开启布局模板
if(C('LAYOUT_ON')) {
$layoutFile = THEME_PATH.C('LAYOUT_NAME').C('TMPL_TEMPLATE_SUFFIX');
if(filemtime($layoutFile) > SaeMC::filemtime($tmplCacheFile)) {
return false;
}
}
// 缓存有效
return true;
}
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Lib/Behavior/ParseTemplateBehavior.class.php | PHP | asf20 | 6,113 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Log.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
/**
+------------------------------------------------------------------------------
* 日志处理类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: Log.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
+------------------------------------------------------------------------------
*/
class Log {
// 日志级别 从上到下,由低到高
const EMERG = 'EMERG'; // 严重错误: 导致系统崩溃无法使用
const ALERT = 'ALERT'; // 警戒性错误: 必须被立即修改的错误
const CRIT = 'CRIT'; // 临界值错误: 超过临界值的错误,例如一天24小时,而输入的是25小时这样
const ERR = 'ERR'; // 一般错误: 一般性错误
const WARN = 'WARN'; // 警告性错误: 需要发出警告的错误
const NOTICE = 'NOTIC'; // 通知: 程序可以运行但是还不够完美的错误
const INFO = 'INFO'; // 信息: 程序输出信息
const DEBUG = 'DEBUG'; // 调试: 调试信息
const SQL = 'SQL'; // SQL:SQL语句 注意只在调试模式开启时有效
// 日志记录方式
const SYSTEM = 0;
const MAIL = 1;
const FILE = 3;
const SAPI = 4;
// 日志信息
static $log = array();
// 日期格式
static $format = '[ c ]';
/**
+----------------------------------------------------------
* 记录日志 并且会过滤未经设置的级别
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $message 日志信息
* @param string $level 日志级别
* @param boolean $record 是否强制记录
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function record($message,$level=self::ERR,$record=false) {
if($record || strpos(C('LOG_LEVEL'),$level)) {
//[sae] 下不记录时间 sae_debug会记录
self::$log[] = '###'.$_SERVER['REQUEST_URI'] . " | {$level}: {$message}###";
}
}
/**
+----------------------------------------------------------
* 日志保存
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param integer $type 日志记录方式
* @param string $destination 写入目标
* @param string $extra 额外参数
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
//[sae]保存日志
static function save($type='',$destination='',$extra='') {
self::sae_set_display_errors(false);
foreach (self::$log as $log)
sae_debug($log);
// 保存后清空日志缓存
self::$log = array();
self::sae_set_display_errors(true);
//clearstatcache();
}
/**
+----------------------------------------------------------
* 日志直接写入
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $message 日志信息
* @param string $level 日志级别
* @param integer $type 日志记录方式
* @param string $destination 写入目标
* @param string $extra 额外参数
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
//[sae]下写入日志。
static function write($message,$level=self::ERR,$type='',$destination='',$extra='') {
self::sae_set_display_errors(false);
sae_debug('###'.$_SERVER['REQUEST_URI'] . " | {$level}: {$message}###");
self::sae_set_display_errors(true);
//clearstatcache();
}
//[sae] 增加错误信息显示控制,弥补SAE平台字段的sae_set_display_errors的不足。
static function sae_set_display_errors($bool){
static $is_debug=null;
if (is_null($is_debug)) {
preg_replace('@(\w+)\=([^;]*)@e', '$appSettings[\'\\1\']="\\2";', $_SERVER['HTTP_APPCOOKIE']);
$is_debug = in_array($_SERVER['HTTP_APPVERSION'], explode(',', $appSettings['debug'])) ? true : false;
}
if($is_debug)
sae_set_display_errors ($bool);
}
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Lib/Core/Log.class.php | PHP | asf20 | 5,535 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Think.class.php 2793 2012-03-02 05:34:40Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP Portal类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: Think.class.php 2793 2012-03-02 05:34:40Z liu21st $
+------------------------------------------------------------------------------
*/
class Think {
private static $_instance = array();
/**
+----------------------------------------------------------
* 应用程序初始化
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function Start() {
// 设定错误和异常处理
set_error_handler(array('Think','appError'));
set_exception_handler(array('Think','appException'));
// 注册AUTOLOAD方法
spl_autoload_register(array('Think', 'autoload'));
//[RUNTIME]
Think::buildApp(); // 预编译项目
//[/RUNTIME]
// 运行应用
App::run();
return ;
}
//[RUNTIME]
/**
+----------------------------------------------------------
* 读取配置信息 编译项目
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static private function buildApp() {
// 加载底层惯例配置文件
C(include THINK_PATH.'Conf/convention.php');
// 读取运行模式
if(defined('MODE_NAME')) { // 模式的设置并入核心模式
$mode = include MODE_PATH.strtolower(MODE_NAME).'.php';
}else{
$mode = array();
}
// 加载模式配置文件
if(isset($mode['config'])) {
C( is_array($mode['config'])?$mode['config']:include $mode['config'] );
}
// 加载项目配置文件
if(is_file(CONF_PATH.'config.php'))
C(include CONF_PATH.'config.php');
//[sae]惯例配置
C(include SAE_PATH.'Conf/convention_sae.php');
//[sae]专有配置
if (is_file(CONF_PATH . 'config_sae.php'))
C(include CONF_PATH . 'config_sae.php');
// 加载框架底层语言包
L(include THINK_PATH.'Lang/'.strtolower(C('DEFAULT_LANG')).'.php');
// 加载模式系统行为定义
if(C('APP_TAGS_ON')) {
if(isset($mode['extends'])) {
C('extends',is_array($mode['extends'])?$mode['extends']:include $mode['extends']);
}else{ //[sae] 默认加载系统行为扩展定义
C('extends', include SAE_PATH.'Conf/tags.php');
}
}
// 加载应用行为定义
if(isset($mode['tags'])) {
C('tags', is_array($mode['tags'])?$mode['tags']:include $mode['tags']);
}elseif(is_file(CONF_PATH.'tags.php')){
// 默认加载项目配置目录的tags文件定义
C('tags', include CONF_PATH.'tags.php');
}
$compile = '';
// 读取核心编译文件列表
if(isset($mode['core'])) {
$list = $mode['core'];
}else{
$list = array(
SAE_PATH.'Common/functions.php', //[sae] 标准模式函数库
SAE_PATH.'Common/sae_functions.php',//[sae]新增sae专用函数
SAE_PATH.'Lib/Core/Log.class.php', // 日志处理类
CORE_PATH.'Core/Dispatcher.class.php', // URL调度类
CORE_PATH.'Core/App.class.php', // 应用程序类
SAE_PATH.'Lib/Core/Action.class.php', //[sae] 控制器类
CORE_PATH.'Core/View.class.php', // 视图类
);
}
// 项目追加核心编译列表文件
if(is_file(CONF_PATH.'core.php')) {
$list = array_merge($list,include CONF_PATH.'core.php');
}
foreach ($list as $file){
if(is_file($file)) {
require_cache($file);
if(!APP_DEBUG) $compile .= compile($file);
}
}
// 加载项目公共文件
if(is_file(COMMON_PATH.'common.php')) {
include COMMON_PATH.'common.php';
// 编译文件
if(!APP_DEBUG) $compile .= compile(COMMON_PATH.'common.php');
}
// 加载模式别名定义
if(isset($mode['alias'])) {
$alias = is_array($mode['alias'])?$mode['alias']:include $mode['alias'];
alias_import($alias);
if(!APP_DEBUG) $compile .= 'alias_import('.var_export($alias,true).');';
}
// 加载项目别名定义
if(is_file(CONF_PATH.'alias.php')){
$alias = include CONF_PATH.'alias.php';
alias_import($alias);
if(!APP_DEBUG) $compile .= 'alias_import('.var_export($alias,true).');';
}
if(APP_DEBUG) {
// 调试模式加载系统默认的配置文件
C(include THINK_PATH.'Conf/debug.php');
// 读取调试模式的应用状态
$status = C('APP_STATUS');
// 加载对应的项目配置文件
if(is_file(CONF_PATH.$status.'.php'))
// 允许项目增加开发模式配置定义
C(include CONF_PATH.$status.'.php');
}else{
// 部署模式下面生成编译文件
build_runtime_cache($compile);
}
return ;
}
//[/RUNTIME]
/**
+----------------------------------------------------------
* 系统自动加载ThinkPHP类库
* 并且支持配置自动加载路径
+----------------------------------------------------------
* @param string $class 对象类名
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public static function autoload($class) {
// 检查是否存在别名定义
if(alias_import($class)) return ;
if(substr($class,-8)=='Behavior') { // 加载行为
if(require_cache(CORE_PATH.'Behavior/'.$class.'.class.php')
|| require_cache(EXTEND_PATH.'Behavior/'.$class.'.class.php')
|| require_cache(LIB_PATH.'Behavior/'.$class.'.class.php')
|| (defined('MODE_NAME') && require_cache(MODE_PATH.ucwords(MODE_NAME).'/Behavior/'.$class.'.class.php'))) {
return ;
}
}elseif(substr($class,-5)=='Model'){ // 加载模型
if(require_cache(LIB_PATH.'Model/'.$class.'.class.php')
|| require_cache(EXTEND_PATH.'Model/'.$class.'.class.php') ) {
return ;
}
}elseif(substr($class,-6)=='Action'){ // 加载控制器
if((defined('GROUP_NAME') && require_cache(LIB_PATH.'Action/'.GROUP_NAME.'/'.$class.'.class.php'))
|| require_cache(LIB_PATH.'Action/'.$class.'.class.php')
|| require_cache(EXTEND_PATH.'Action/'.$class.'.class.php') ) {
return ;
}
}
// 根据自动加载路径设置进行尝试搜索
$paths = explode(',',C('APP_AUTOLOAD_PATH'));
foreach ($paths as $path){
if(import($path.'.'.$class))
// 如果加载类成功则返回
return ;
}
}
/**
+----------------------------------------------------------
* 取得对象实例 支持调用类的静态方法
+----------------------------------------------------------
* @param string $class 对象类名
* @param string $method 类的静态方法名
+----------------------------------------------------------
* @return object
+----------------------------------------------------------
*/
static public function instance($class,$method='') {
$identify = $class.$method;
if(!isset(self::$_instance[$identify])) {
if(class_exists($class)){
$o = new $class();
if(!empty($method) && method_exists($o,$method))
self::$_instance[$identify] = call_user_func_array(array(&$o, $method));
else
self::$_instance[$identify] = $o;
}
else
halt(L('_CLASS_NOT_EXIST_').':'.$class);
}
return self::$_instance[$identify];
}
/**
+----------------------------------------------------------
* 自定义异常处理
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $e 异常对象
+----------------------------------------------------------
*/
static public function appException($e) {
halt($e->__toString());
}
/**
+----------------------------------------------------------
* 自定义错误处理
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param int $errno 错误类型
* @param string $errstr 错误信息
* @param string $errfile 错误文件
* @param int $errline 错误行数
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function appError($errno, $errstr, $errfile, $errline) {
switch ($errno) {
case E_ERROR:
case E_USER_ERROR:
$errorStr = "[$errno] $errstr ".basename($errfile)." 第 $errline 行.";
if(C('LOG_RECORD')) Log::write($errorStr,Log::ERR);
halt($errorStr);
break;
case E_STRICT:
case E_USER_WARNING:
case E_USER_NOTICE:
default:
$errorStr = "[$errno] $errstr ".basename($errfile)." 第 $errline 行.";
Log::record($errorStr,Log::NOTICE);
break;
}
}
/**
+----------------------------------------------------------
* 自动变量设置
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param $name 属性名称
* @param $value 属性值
+----------------------------------------------------------
*/
public function __set($name ,$value) {
if(property_exists($this,$name))
$this->$name = $value;
}
/**
+----------------------------------------------------------
* 自动变量获取
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param $name 属性名称
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __get($name) {
return isset($this->$name)?$this->$name:null;
}
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Lib/Core/Think.class.php | PHP | asf20 | 12,476 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Action.class.php 2793 2012-03-02 05:34:40Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP Action控制器基类 抽象类
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: Action.class.php 2793 2012-03-02 05:34:40Z liu21st $
+------------------------------------------------------------------------------
*/
abstract class Action {
// 视图实例对象
protected $view = null;
// 当前Action名称
private $name = '';
/**
+----------------------------------------------------------
* 架构函数 取得模板对象实例
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct() {
tag('action_begin');
//实例化视图类
$this->view = Think::instance('View');
//控制器初始化
if(method_exists($this,'_initialize'))
$this->_initialize();
}
/**
+----------------------------------------------------------
* 获取当前Action名称
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
*/
protected function getActionName() {
if(empty($this->name)) {
// 获取Action名称
$this->name = substr(get_class($this),0,-6);
}
return $this->name;
}
/**
+----------------------------------------------------------
* 是否AJAX请求
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return bool
+----------------------------------------------------------
*/
protected function isAjax() {
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) ) {
if('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH']))
return true;
}
if(!empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')]))
// 判断Ajax方式提交
return true;
return false;
}
/**
+----------------------------------------------------------
* 模板显示
* 调用内置的模板引擎显示方法,
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $templateFile 指定要调用的模板文件
* 默认为空 由系统自动定位模板文件
* @param string $charset 输出编码
* @param string $contentType 输出类型
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function display($templateFile='',$charset='',$contentType='') {
$this->view->display($templateFile,$charset,$contentType);
}
/**
+----------------------------------------------------------
* 获取输出页面内容
* 调用内置的模板引擎fetch方法,
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $templateFile 指定要调用的模板文件
* 默认为空 由系统自动定位模板文件
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function fetch($templateFile='') {
return $this->view->fetch($templateFile);
}
/**
+----------------------------------------------------------
* 创建静态页面
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @htmlfile 生成的静态文件名称
* @htmlpath 生成的静态文件路径
* @param string $templateFile 指定要调用的模板文件
* 默认为空 由系统自动定位模板文件
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
//[sae] 生成静态文件
protected function buildHtml($htmlfile='',$htmlpath='',$templateFile='') {
$content = $this->fetch($templateFile);
$kv=Think::instance('SaeKVClient');
if(!$kv->init()) halt('您没有初始化KVDB,请在SAE平台进行初始化');
$htmlpath = !empty($htmlpath)?$htmlpath:HTML_PATH;
$htmlfile = $htmlpath.$htmlfile.C('HTML_FILE_SUFFIX');
trace('[SAE]静态缓存',$htmlfile);
$kv->set($htmlfile,$content);//[sae] 注意buildHtml生成的静态数据没有记录生成时间
return $content;
}
/**
+----------------------------------------------------------
* 模板变量赋值
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $name 要显示的模板变量
* @param mixed $value 变量的值
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function assign($name,$value='') {
$this->view->assign($name,$value);
}
public function __set($name,$value) {
$this->view->assign($name,$value);
}
/**
+----------------------------------------------------------
* 取得模板显示变量的值
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $name 模板显示变量
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __get($name) {
return $this->view->get($name);
}
/**
+----------------------------------------------------------
* 魔术方法 有不存在的操作的时候执行
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名
* @param array $args 参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$args) {
if( 0 === strcasecmp($method,ACTION_NAME)) {
if(method_exists($this,'_empty')) {
// 如果定义了_empty操作 则调用
$this->_empty($method,$args);
}elseif(file_exists_case(C('TEMPLATE_NAME'))){
// 检查是否存在默认模版 如果有直接输出模版
$this->display();
}elseif(function_exists('__hack_action')) {
// hack 方式定义扩展操作
__hack_action();
}elseif(APP_DEBUG) {
// 抛出异常
throw_exception(L('_ERROR_ACTION_').ACTION_NAME);
}else{
if(C('LOG_EXCEPTION_RECORD')) Log::write(L('_ERROR_ACTION_').ACTION_NAME);
send_http_status(404);
exit;
}
}else{
switch(strtolower($method)) {
// 判断提交方式
case 'ispost':
case 'isget':
case 'ishead':
case 'isdelete':
case 'isput':
return strtolower($_SERVER['REQUEST_METHOD']) == strtolower(substr($method,2));
// 获取变量 支持过滤和默认值 调用方式 $this->_post($key,$filter,$default);
case '_get': $input =& $_GET;break;
case '_post':$input =& $_POST;break;
case '_put': parse_str(file_get_contents('php://input'), $input);break;
case '_request': $input =& $_REQUEST;break;
case '_session': $input =& $_SESSION;break;
case '_cookie': $input =& $_COOKIE;break;
case '_server': $input =& $_SERVER;break;
case '_globals': $input =& $GLOBALS;break;
default:
throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
}
if(isset($input[$args[0]])) { // 取值操作
$data = $input[$args[0]];
$fun = $args[1]?$args[1]:C('DEFAULT_FILTER');
$data = $fun($data); // 参数过滤
}else{ // 变量默认值
$data = isset($args[2])?$args[2]:NULL;
}
return $data;
}
}
/**
+----------------------------------------------------------
* 操作错误跳转的快捷方法
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $message 错误信息
* @param string $jumpUrl 页面跳转地址
* @param Boolean $ajax 是否为Ajax方式
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function error($message,$jumpUrl='',$ajax=false) {
$this->dispatchJump($message,0,$jumpUrl,$ajax);
}
/**
+----------------------------------------------------------
* 操作成功跳转的快捷方法
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $message 提示信息
* @param string $jumpUrl 页面跳转地址
* @param Boolean $ajax 是否为Ajax方式
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function success($message,$jumpUrl='',$ajax=false) {
$this->dispatchJump($message,1,$jumpUrl,$ajax);
}
/**
+----------------------------------------------------------
* Ajax方式返回数据到客户端
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 要返回的数据
* @param String $info 提示信息
* @param boolean $status 返回状态
* @param String $status ajax返回类型 JSON XML
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function ajaxReturn($data,$info='',$status=1,$type='') {
$result = array();
$result['status'] = $status;
$result['info'] = $info;
$result['data'] = $data;
//扩展ajax返回数据, 在Action中定义function ajaxAssign(&$result){} 方法 扩展ajax返回数据。
if(method_exists($this,'ajaxAssign'))
$this->ajaxAssign($result);
if(empty($type)) $type = C('DEFAULT_AJAX_RETURN');
if(strtoupper($type)=='JSON') {
// 返回JSON数据格式到客户端 包含状态信息
header('Content-Type:text/html; charset=utf-8');
exit(json_encode($result));
}elseif(strtoupper($type)=='XML'){
// 返回xml格式数据
header('Content-Type:text/xml; charset=utf-8');
exit(xml_encode($result));
}elseif(strtoupper($type)=='EVAL'){
// 返回可执行的js脚本
header('Content-Type:text/html; charset=utf-8');
exit($data);
}else{
// TODO 增加其它格式
}
}
/**
+----------------------------------------------------------
* Action跳转(URL重定向) 支持指定模块和延时跳转
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $url 跳转的URL表达式
* @param array $params 其它URL参数
* @param integer $delay 延时跳转的时间 单位为秒
* @param string $msg 跳转提示信息
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function redirect($url,$params=array(),$delay=0,$msg='') {
$url = U($url,$params);
redirect($url,$delay,$msg);
}
/**
+----------------------------------------------------------
* 默认跳转操作 支持错误导向和正确跳转
* 调用模板显示 默认为public目录下面的success页面
* 提示页面为可配置 支持模板标签
+----------------------------------------------------------
* @param string $message 提示信息
* @param Boolean $status 状态
* @param string $jumpUrl 页面跳转地址
* @param Boolean $ajax 是否为Ajax方式
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
private function dispatchJump($message,$status=1,$jumpUrl='',$ajax=false) {
// 判断是否为AJAX返回
if($ajax || $this->isAjax()) $this->ajaxReturn($ajax,$message,$status);
if(!empty($jumpUrl)) $this->assign('jumpUrl',$jumpUrl);
// 提示标题
$this->assign('msgTitle',$status? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_'));
//如果设置了关闭窗口,则提示完毕后自动关闭窗口
if($this->view->get('closeWin')) $this->assign('jumpUrl','javascript:window.close();');
$this->assign('status',$status); // 状态
//保证输出不受静态缓存影响
C('HTML_CACHE_ON',false);
if($status) { //发送成功信息
$this->assign('message',$message);// 提示信息
// 成功操作后默认停留1秒
if(!$this->view->get('waitSecond')) $this->assign('waitSecond','1');
// 默认操作成功自动返回操作前页面
if(!$this->view->get('jumpUrl')) $this->assign('jumpUrl',$_SERVER['HTTP_REFERER']);
$this->display(C('TMPL_ACTION_SUCCESS'));
}else{
$this->assign('error',$message);// 提示信息
//发生错误时候默认停留3秒
if(!$this->view->get('waitSecond')) $this->assign('waitSecond','3');
// 默认发生错误的话自动返回上页
if(!$this->view->get('jumpUrl')) $this->assign('jumpUrl','javascript:history.back(-1);');
$this->display(C('TMPL_ACTION_ERROR'));
// 中止执行 避免出错后继续执行
exit ;
}
}
/**
+----------------------------------------------------------
* 析构方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __destruct() {
// 保存日志
if(C('LOG_RECORD')) Log::save();
// 执行后续操作
tag('action_end');
}
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Lib/Core/Action.class.php | PHP | asf20 | 16,959 |
<?php
/**
* +---------------------------------------------------
* | 对Memcache操作的封装,用于文件缓存
* +---------------------------------------------------
* @author luofei614<www.3g4k.com>
*/
if (!class_exists('SaeMC')) {
//[sae]对Memcache操作的封装,编译缓存,模版缓存存入Memcache中(非wrappers的形式)
class SaeMC {
static public $handler;
static private $current_include_file = null;
static private $contents = array();
static private $filemtimes = array();
//设置文件内容
static public function set($filename, $content) {
$time=time();
self::$handler->set($_SERVER['HTTP_APPVERSION'] . '/' . $filename, $time . $content, MEMCACHE_COMPRESSED, 0);
self::$contents[$filename]=$content;
self::$filemtimes[$filename]=$time;
}
//载入文件
static public function include_file($_filename,$_vars=null) {
self::$current_include_file = 'saemc://' . $_SERVER['HTTP_APPVERSION'] . '/' . $_filename;
$_content = isset(self::$contents[$_filename]) ? self::$contents[$_filename] : self::getValue($_filename, 'content');
if(!is_null($_vars))
extract($_vars, EXTR_OVERWRITE);
if (!$_content)
exit('<br /><b>SAE_Parse_error</b>: failed to open stream: No such file ' . self::$current_include_file);
if (@(eval(' ?>' . $_content)) === false)
self::error();
self::$current_include_file = null;
unset(self::$contents[$_filename]); //释放内存
}
static private function getValue($filename, $type='mtime') {
$content = self::$handler->get($_SERVER['HTTP_APPVERSION'] . '/' . $filename);
if (!$content)
return false;
$ret = array(
'mtime' => substr($content, 0, 10),
'content' => substr($content, 10)
);
self::$contents[$filename] = $ret['content'];
self::$filemtimes[$filename] = $ret['mtime'];
return $ret[$type];
}
//获得文件修改时间
static public function filemtime($filename) {
if (!isset(self::$filemtimes[$filename]))
return self::getValue($filename, 'mtime');
return self::$filemtimes[$filename];
}
//删除文件
static public function unlink($filename) {
if (isset(self::$contents[$filename]))
unset(self::$contents[$filename]);
if (isset(self::$filemtimes[$filename]))
unset(self::$filemtimes[$filename]);
return self::$handler->delete($_SERVER['HTTP_APPVERSION'] . '/' . $filename);
}
static public function file_exists($filename) {
return self::filemtime($filename) === false ? false : true;
}
static function error() {
$error = error_get_last();
if (!is_null($error)) {
$file = strpos($error['file'], 'eval()') !== false ? self::$current_include_file : $error['file'];
exit("<br /><b>SAE_error</b>: {$error['message']} in <b>" . $file . "</b> on line <b>{$error['line']}</b><br />");
}
}
}
register_shutdown_function(array('SaeMC', 'error'));
//[sae] 初始化memcache
if (!(SaeMC::$handler = @(memcache_init()))) {
header('Content-Type:text/html; charset=utf-8');
exit('<div style=\'font-weight:bold;float:left;width:430px;text-align:center;border:1px solid silver;background:#E8EFFF;padding:8px;color:red;font-size:14px;font-family:Tahoma\'>您的Memcache还没有初始化,请登录SAE平台进行初始化~</div>');
}
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Lib/Core/SaeMC.class.php | PHP | asf20 | 3,818 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: UploadFile_sae.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
/**
+------------------------------------------------------------------------------
* 文件上传类
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Net
* @author liu21st <liu21st@gmail.com>
* @version $Id: UploadFile_sae.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
+------------------------------------------------------------------------------
*/
class UploadFile {//类定义开始
// 上传文件的最大值
public $maxSize = -1;
// 是否支持多文件上传
public $supportMulti = true;
// 允许上传的文件后缀
// 留空不作后缀检查
public $allowExts = array();
// 允许上传的文件类型
// 留空不做检查
public $allowTypes = array();
// 使用对上传图片进行缩略图处理
public $thumb = false;
// 图库类包路径
public $imageClassPath = 'ORG.Util.Image';
// 缩略图最大宽度
public $thumbMaxWidth;
// 缩略图最大高度
public $thumbMaxHeight;
// 缩略图前缀
public $thumbPrefix = 'thumb_';
public $thumbSuffix = '';
// 缩略图保存路径
public $thumbPath = '';
// 缩略图文件名
public $thumbFile = '';
// 是否移除原图
public $thumbRemoveOrigin = false;
// 压缩图片文件上传
public $zipImages = false;
// 启用子目录保存文件
public $autoSub = false;
// 子目录创建方式 可以使用hash date
public $subType = 'hash';
public $dateFormat = 'Ymd';
public $hashLevel = 1; // hash的目录层次
// 上传文件保存路径
public $savePath = '';
public $autoCheck = true; // 是否自动检查附件
// 存在同名是否覆盖
public $uploadReplace = false;
// 上传文件命名规则
// 例如可以是 time uniqid com_create_guid 等
// 必须是一个无需任何参数的函数名 可以使用自定义函数
public $saveRule = '';
// 上传文件Hash规则函数名
// 例如可以是 md5_file sha1_file 等
public $hashType = 'md5_file';
// 错误信息
private $error = '';
// 上传成功的文件信息
private $uploadFileInfo;
//[sae] domain
private $domain;
private $thumbDomain;
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($maxSize='', $allowExts='', $allowTypes='', $savePath='', $saveRule='') {
if (!empty($maxSize) && is_numeric($maxSize)) {
$this->maxSize = $maxSize;
}
if (!empty($allowExts)) {
if (is_array($allowExts)) {
$this->allowExts = array_map('strtolower', $allowExts);
} else {
$this->allowExts = explode(',', strtolower($allowExts));
}
}
if (!empty($allowTypes)) {
if (is_array($allowTypes)) {
$this->allowTypes = array_map('strtolower', $allowTypes);
} else {
$this->allowTypes = explode(',', strtolower($allowTypes));
}
}
if (!empty($saveRule)) {
$this->saveRule = $saveRule;
} else {
$this->saveRule = C('UPLOAD_FILE_RULE');
}
$this->savePath = $savePath;
}
/**
+----------------------------------------------------------
* 上传一个文件
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $name 数据
* @param string $value 数据表名
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
private function save($file) {
$filename = $file['savepath'] . $file['savename'];
$s = Think::instance('SaeStorage');
if (!$this->uploadReplace && $s->fileExists($this->domain, $filename)) {
// 不覆盖同名文件
$this->error = '文件已经存在!' . $filename;
return false;
}
// 如果是图像文件 检测文件格式
if (in_array(strtolower($file['extension']), array('gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf')) && false === getimagesize($file['tmp_name'])) {
$this->error = '非法图像文件';
return false;
}
//if(!move_uploaded_file($file['tmp_name'], $this->autoCharset($filename,'utf-8','gbk'))) {
if (!$this->thumbRemoveOrigin && !$s->upload($this->domain, $filename, $file['tmp_name']) ) {
$this->error = $s->errno() == -7 ? 'domain [ ' . $this->domain . ' ] 不存在!请在SAE控制台的Storage服务中添加一个domain' : '文件上传保存错误!';
return false;
}
if ($this->thumb && in_array(strtolower($file['extension']), array('gif', 'jpg', 'jpeg', 'bmp', 'png'))) {
$image = getimagesize($file['tmp_name']);
if (false !== $image) {
//是图像文件生成缩略图
$thumbWidth = explode(',', $this->thumbMaxWidth);
$thumbHeight = explode(',', $this->thumbMaxHeight);
$thumbPrefix = explode(',', $this->thumbPrefix);
$thumbSuffix = explode(',', $this->thumbSuffix);
$thumbFile = explode(',', $this->thumbFile);
$thumbPath = $this->thumbPath ? $this->thumbPath : $file['savepath'];
//[sae] 定义缩略图目录时,判断doamin
$domain = $this->thumbPath ? $this->thumbDomain : $this->domain;
//[sae] 用自带image类生成缩略图
$realFilename = $this->autoSub ? basename($file['savename']) : $file['savename'];
$srcWidth = $image[0];
$srcHeight = $image[1];
$img = Think::instance('SaeImage');
for ($i = 0, $len = count($thumbWidth); $i < $len; $i++) {
$scale = min($thumbWidth[$i] / $srcWidth, $thumbHeight[$i] / $srcHeight); // 计算缩放比例
if ($scale >= 1) {
// 超过原图大小不再缩略
$width = $srcWidth;
$height = $srcHeight;
} else {
// 缩略图尺寸
$width = (int) ($srcWidth * $scale);
$height = (int) ($srcHeight * $scale);
}
$thumbname = $thumbPrefix[$i] . substr($realFilename, 0, strrpos($realFilename, '.')) . $thumbSuffix[$i] . '.' . $file['extension'];
$img->setData(file_get_contents($file['tmp_name']));
$img->resize($width, $height);
$new_data = $img->exec();
if (!$s->write($domain, $thumbPath . $thumbname, $new_data)) {
$this->error = $s->errno() == -7 ? 'domain [ ' . $this->domain . ' ] 不存在!请在SAE控制台的Storage服务中添加一个domain' : '生成缩略图失败!';
return false;
}
}
}
}
if ($this->zipImags) {
// TODO 对图片压缩包在线解压
}
return true;
}
//[sae]获得domain,改变path
private function getDomain($filePath) {
$arr = explode('/', ltrim($filePath, './'));
$domain = array_shift($arr);
$filePath = implode('/', $arr);
return array($domain, $filePath);
}
/**
+----------------------------------------------------------
* 上传所有文件
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $savePath 上传文件保存路径
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function upload($savePath ='') {
//如果不指定保存文件名,则由系统默认
if (empty($savePath))
$savePath = $this->savePath;
//[sae] 去掉检查上传目录
$fileInfo = array();
$isUpload = false;
//[sae] 分析出domain,第一个目录为domain
list($this->domain, $savePath) = $this->getDomain($savePath);
//[sae] 分析缩略图保存地址
if ($this->thumb && $this->thumbPath)
list($this->thumbDomain, $this->thumbPath) = $this->getDomain($this->thumbPath);
// 获取上传的文件信息
// 对$_FILES数组信息处理
$files = $this->dealFiles($_FILES);
foreach ($files as $key => $file) {
//过滤无效的上传
if (!empty($file['name'])) {
//登记上传文件的扩展信息
$file['key'] = $key;
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file);
// 自动检查附件
if ($this->autoCheck) {
if (!$this->check($file))
return false;
}
//保存上传文件
if (!$this->save($file))
return false;
if (function_exists($this->hashType)) {
$fun = $this->hashType;
$file['hash'] = $fun($this->autoCharset($file['savepath'] . $file['savename'], 'utf-8', 'gbk'));
}
//上传成功后保存文件信息,供其他地方调用
unset($file['tmp_name'], $file['error']);
$fileInfo[] = $file;
$isUpload = true;
}
}
if ($isUpload) {
$this->uploadFileInfo = $fileInfo;
return true;
} else {
$this->error = '没有选择上传文件';
return false;
}
}
/**
+----------------------------------------------------------
* 上传单个上传字段中的文件 支持多附件
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $file 上传文件信息
* @param string $savePath 上传文件保存路径
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function uploadOne($file, $savePath='') {
//如果不指定保存文件名,则由系统默认
if (empty($savePath))
$savePath = $this->savePath;
//[sae] 不检查上传目录
//[sae] 分析出domain,第一个目录为domain
list($this->domain, $savePath) = $this->getDomain($savePath);
//[sae] 分析缩略图保存地址
if ($this->thumb && $this->thumbPath)
list($this->thumbDomain, $this->thumbPath) = $this->getDomain($this->thumbPath);
//过滤无效的上传
if (!empty($file['name'])) {
$fileArray = array();
if (is_array($file['name'])) {
$keys = array_keys($file);
$count = count($file['name']);
for ($i = 0; $i < $count; $i++) {
foreach ($keys as $key)
$fileArray[$i][$key] = $file[$key][$i];
}
} else {
$fileArray[] = $file;
}
$info = array();
foreach ($fileArray as $key => $file) {
//登记上传文件的扩展信息
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file);
// 自动检查附件
if ($this->autoCheck) {
if (!$this->check($file))
return false;
}
//保存上传文件
if (!$this->save($file))
return false;
if (function_exists($this->hashType)) {
$fun = $this->hashType;
$file['hash'] = $fun($this->autoCharset($file['savepath'] . $file['savename'], 'utf-8', 'gbk'));
}
unset($file['tmp_name'], $file['error']);
$info[] = $file;
}
// 返回上传的文件信息
return $info;
} else {
$this->error = '没有选择上传文件';
return false;
}
}
/**
+----------------------------------------------------------
* 转换上传文件数组变量为正确的方式
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $files 上传的文件变量
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
private function dealFiles($files) {
$fileArray = array();
$n = 0;
foreach ($files as $file) {
if (is_array($file['name'])) {
$keys = array_keys($file);
$count = count($file['name']);
for ($i = 0; $i < $count; $i++) {
foreach ($keys as $key)
$fileArray[$n][$key] = $file[$key][$i];
$n++;
}
} else {
$fileArray[$n] = $file;
$n++;
}
}
return $fileArray;
}
/**
+----------------------------------------------------------
* 获取错误代码信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $errorNo 错误号码
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
protected function error($errorNo) {
switch ($errorNo) {
case 1:
$this->error = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
break;
case 2:
$this->error = '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
break;
case 3:
$this->error = '文件只有部分被上传';
break;
case 4:
$this->error = '没有文件被上传';
break;
case 6:
$this->error = '找不到临时文件夹';
break;
case 7:
$this->error = '文件写入失败';
break;
default:
$this->error = '未知上传错误!';
}
return;
}
/**
+----------------------------------------------------------
* 根据上传文件命名规则取得保存文件名
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 数据
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function getSaveName($filename) {
$rule = $this->saveRule;
if (empty($rule)) {//没有定义命名规则,则保持文件名不变
$saveName = $filename['name'];
} else {
if (function_exists($rule)) {
//使用函数生成一个唯一文件标识号
$saveName = $rule() . "." . $filename['extension'];
} else {
//使用给定的文件名作为标识号
$saveName = $rule . "." . $filename['extension'];
}
}
if ($this->autoSub) {
// 使用子目录保存文件
$filename['savename'] = $saveName;
$saveName = $this->getSubName($filename) . '/' . $saveName;
}
return $saveName;
}
/**
+----------------------------------------------------------
* 获取子目录的名称
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $file 上传的文件信息
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function getSubName($file) {
switch ($this->subType) {
case 'date':
$dir = date($this->dateFormat, time());
break;
case 'hash':
default:
$name = md5($file['savename']);
$dir = '';
for ($i = 0; $i < $this->hashLevel; $i++) {
$dir .= $name{$i} . '/';
}
break;
}
if (!is_dir($file['savepath'] . $dir)) {
mk_dir($file['savepath'] . $dir);
}
return $dir;
}
/**
+----------------------------------------------------------
* 检查上传的文件
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $file 文件信息
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function check($file) {
if ($file['error'] !== 0) {
//文件上传失败
//捕获错误代码
$this->error($file['error']);
return false;
}
//文件上传成功,进行自定义规则检查
//检查文件大小
if (!$this->checkSize($file['size'])) {
$this->error = '上传文件大小不符!';
return false;
}
//检查文件Mime类型
if (!$this->checkType($file['type'])) {
$this->error = '上传文件MIME类型不允许!';
return false;
}
//检查文件类型
if (!$this->checkExt($file['extension'])) {
$this->error = '上传文件类型不允许';
return false;
}
//检查是否合法上传
if (!$this->checkUpload($file['tmp_name'])) {
$this->error = '非法上传文件!';
return false;
}
return true;
}
// 自动转换字符集 支持数组转换
private function autoCharset($fContents, $from='gbk', $to='utf-8') {
$from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
$to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
//如果编码相同或者非字符串标量则不转换
return $fContents;
}
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($fContents, $to, $from);
} elseif (function_exists('iconv')) {
return iconv($from, $to, $fContents);
} else {
return $fContents;
}
}
/**
+----------------------------------------------------------
* 检查上传的文件类型是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $type 数据
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkType($type) {
if (!empty($this->allowTypes))
return in_array(strtolower($type), $this->allowTypes);
return true;
}
/**
+----------------------------------------------------------
* 检查上传的文件后缀是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $ext 后缀名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkExt($ext) {
if (!empty($this->allowExts))
return in_array(strtolower($ext), $this->allowExts, true);
return true;
}
/**
+----------------------------------------------------------
* 检查文件大小是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param integer $size 数据
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkSize($size) {
return!($size > $this->maxSize) || (-1 == $this->maxSize);
}
/**
+----------------------------------------------------------
* 检查文件是否非法提交
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 文件名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkUpload($filename) {
return is_uploaded_file($filename);
}
/**
+----------------------------------------------------------
* 取得上传文件的后缀
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 文件名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function getExt($filename) {
$pathinfo = pathinfo($filename);
return $pathinfo['extension'];
}
/**
+----------------------------------------------------------
* 取得上传文件的信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getUploadFileInfo() {
return $this->uploadFileInfo;
}
/**
+----------------------------------------------------------
* 取得最后一次错误信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getErrorMsg() {
return $this->error;
}
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Lib/Extend/Library/ORG/Net/UploadFile_sae.class.php | PHP | asf20 | 25,721 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Image_sae.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
/**
+------------------------------------------------------------------------------
* 图像操作类库
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id: Image_sae.class.php 2766 2012-02-20 15:58:21Z luofei614@gmail.com $
+------------------------------------------------------------------------------
*/
class Image {
/**
+----------------------------------------------------------
* 取得图像信息
*
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $image 图像文件名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
static function getImageInfo($img) {
$imageInfo = getimagesize($img);
if ($imageInfo !== false) {
$imageType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
$imageSize = filesize($img);
$info = array(
"width" => $imageInfo[0],
"height" => $imageInfo[1],
"type" => $imageType,
"size" => $imageSize,
"mime" => $imageInfo['mime']
);
return $info;
} else {
return false;
}
}
/**
+----------------------------------------------------------
* 为图片添加水印
+----------------------------------------------------------
* @static public
+----------------------------------------------------------
* @param string $source 原文件名
* @param string $water 水印图片
* @param string $$savename 添加水印后的图片名
* @param string $alpha 水印的透明度
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
//[sae] 水印,使用saeimage实现
static public function water($source, $water, $savename=null, $alpha=80) {
//检查文件是否存在
$arr = explode('/', ltrim($source, './'));
$domain = array_shift($arr);
$source = implode('/', $arr);
$s = Think::instance('SaeStorage');
if (!$s->fileExists($domain, $source) || !file_exists($water))
return false;
$source_url = $s->getUrl($domain, $source);
$img = Think::instance('SaeImage');
$source_data = file_get_contents($source_url);
$water_data = file_get_contents($water);
$img->setData($source_data);
$size = $img->getImageAttr();
//获得后缀
$ext = array(
1 => 'gif',
2 => 'jpg',
3 => 'png'
);
$type = isset($ext[$size[2]]) ? $ext[$size[2]] : 'jpg';
$img->clean();
$alpha = $alpha * 0.01;
$img->setData(array(
array($source_data, 0, 0, 1, SAE_TOP_LEFT),
array($water_data, 0, 0, $alpha, SAE_BOTTOM_RIGHT)
));
$img->composite($size[0], $size[1]);
$data = $img->exec($type);
if (!$savename) {
$savename = $source;
} else {
$arr = explode('/', ltrim($savename, './'));
$domain = array_shift($arr);
$savename = implode('/', $arr);
}
$s->write($domain, $savename, $data);
}
function showImg($imgFile, $text='', $x='10', $y='10', $alpha='50') {
//获取图像文件信息
//2007/6/26 增加图片水印输出,$text为图片的完整路径即可
$info = Image::getImageInfo($imgFile);
if ($info !== false) {
$createFun = str_replace('/', 'createfrom', $info['mime']);
$im = $createFun($imgFile);
if ($im) {
$ImageFun = str_replace('/', '', $info['mime']);
//水印开始
if (!empty($text)) {
$tc = imagecolorallocate($im, 0, 0, 0);
if (is_file($text) && file_exists($text)) {//判断$text是否是图片路径
// 取得水印信息
$textInfo = Image::getImageInfo($text);
$createFun2 = str_replace('/', 'createfrom', $textInfo['mime']);
$waterMark = $createFun2($text);
//$waterMark=imagecolorallocatealpha($text,255,255,0,50);
$imgW = $info["width"];
$imgH = $info["width"] * $textInfo["height"] / $textInfo["width"];
//$y = ($info["height"]-$textInfo["height"])/2;
//设置水印的显示位置和透明度支持各种图片格式
imagecopymerge($im, $waterMark, $x, $y, 0, 0, $textInfo['width'], $textInfo['height'], $alpha);
} else {
imagestring($im, 80, $x, $y, $text, $tc);
}
//ImageDestroy($tc);
}
//水印结束
if ($info['type'] == 'png' || $info['type'] == 'gif') {
imagealphablending($im, FALSE); //取消默认的混色模式
imagesavealpha($im, TRUE); //设定保存完整的 alpha 通道信息
}
Header("Content-type: " . $info['mime']);
$ImageFun($im);
@ImageDestroy($im);
return;
}
//保存图像
$ImageFun($sImage, $savename);
imagedestroy($sImage);
//获取或者创建图像文件失败则生成空白PNG图片
$im = imagecreatetruecolor(80, 30);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
imagestring($im, 4, 5, 5, "no pic", $tc);
Image::output($im);
return;
}
}
/**
+----------------------------------------------------------
* 生成缩略图
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $image 原图
* @param string $type 图像格式
* @param string $thumbname 缩略图文件名
* @param string $maxWidth 宽度
* @param string $maxHeight 高度
* @param string $position 缩略图保存目录
* @param boolean $interlace 启用隔行扫描
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function thumb($image, $thumbname, $type='', $maxWidth=200, $maxHeight=50, $interlace=true) {
// 获取原图信息
$info = Image::getImageInfo($image);
if ($info !== false) {
$srcWidth = $info['width'];
$srcHeight = $info['height'];
$type = empty($type) ? $info['type'] : $type;
$type = strtolower($type);
$interlace = $interlace ? 1 : 0;
unset($info);
$scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight); // 计算缩放比例
if ($scale >= 1) {
// 超过原图大小不再缩略
$width = $srcWidth;
$height = $srcHeight;
} else {
// 缩略图尺寸
$width = (int) ($srcWidth * $scale);
$height = (int) ($srcHeight * $scale);
}
// 载入原图
$createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
$srcImg = $createFun($image);
//创建缩略图
if ($type != 'gif' && function_exists('imagecreatetruecolor'))
$thumbImg = imagecreatetruecolor($width, $height);
else
$thumbImg = imagecreate($width, $height);
// 复制图片
if (function_exists("ImageCopyResampled"))
imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
else
imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
if ('gif' == $type || 'png' == $type) {
//imagealphablending($thumbImg, false);//取消默认的混色模式
//imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息
$background_color = imagecolorallocate($thumbImg, 0, 255, 0); // 指派一个绿色
imagecolortransparent($thumbImg, $background_color); // 设置为透明色,若注释掉该行则输出绿色的图
}
// 对jpeg图形设置隔行扫描
if ('jpg' == $type || 'jpeg' == $type)
imageinterlace($thumbImg, $interlace);
//$gray=ImageColorAllocate($thumbImg,255,0,0);
//ImageString($thumbImg,2,5,5,"ThinkPHP",$gray);
// 生成图片
$imageFun = 'image' . ($type == 'jpg' ? 'jpeg' : $type);
$imageFun($thumbImg, $thumbname);
imagedestroy($thumbImg);
imagedestroy($srcImg);
return $thumbname;
}
return false;
}
/**
+----------------------------------------------------------
* 根据给定的字符串生成图像
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $string 字符串
* @param string $size 图像大小 width,height 或者 array(width,height)
* @param string $font 字体信息 fontface,fontsize 或者 array(fontface,fontsize)
* @param string $type 图像格式 默认PNG
* @param integer $disturb 是否干扰 1 点干扰 2 线干扰 3 复合干扰 0 无干扰
* @param bool $border 是否加边框 array(color)
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function buildString($string, $rgb=array(), $filename='', $type='png', $disturb=1, $border=true) {
if (is_string($size))
$size = explode(',', $size);
$width = $size[0];
$height = $size[1];
if (is_string($font))
$font = explode(',', $font);
$fontface = $font[0];
$fontsize = $font[1];
$length = strlen($string);
$width = ($length * 9 + 10) > $width ? $length * 9 + 10 : $width;
$height = 22;
if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
$im = @imagecreatetruecolor($width, $height);
} else {
$im = @imagecreate($width, $height);
}
if (empty($rgb)) {
$color = imagecolorallocate($im, 102, 104, 104);
} else {
$color = imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]);
}
$backColor = imagecolorallocate($im, 255, 255, 255); //背景色(随机)
$borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
$pointColor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); //点颜色
@imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
@imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
@imagestring($im, 5, 5, 3, $string, $color);
if (!empty($disturb)) {
// 添加干扰
if ($disturb = 1 || $disturb = 3) {
for ($i = 0; $i < 25; $i++) {
imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $pointColor);
}
} elseif ($disturb = 2 || $disturb = 3) {
for ($i = 0; $i < 10; $i++) {
imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $pointColor);
}
}
}
Image::output($im, $type, $filename);
}
/**
+----------------------------------------------------------
* 生成图像验证码
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $length 位数
* @param string $mode 类型
* @param string $type 图像格式
* @param string $width 宽度
* @param string $height 高度
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
//[sae]使用saevcode实现
static function buildImageVerify($length=4, $mode=1, $type='png', $width=48, $height=22, $verifyName='verify') {
$vcode = Think::instance('SaeVcode');
$_SESSION[$verifyName] = md5($vcode->answer());
$question = $vcode->question();
header('Location:' . $question['img_url']);
}
// 中文验证码
static function GBVerify($length=4, $type='png', $width=180, $height=50, $fontface='simhei.ttf', $verifyName='verify') {
import('ORG.Util.String');
$code = String::randString($length, 4);
$width = ($length * 45) > $width ? $length * 45 : $width;
$_SESSION[$verifyName] = md5($code);
$im = imagecreatetruecolor($width, $height);
$borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
$bkcolor = imagecolorallocate($im, 250, 250, 250);
imagefill($im, 0, 0, $bkcolor);
@imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
// 干扰
for ($i = 0; $i < 15; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $fontcolor);
}
for ($i = 0; $i < 255; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $fontcolor);
}
if (!is_file($fontface)) {
$fontface = dirname(__FILE__) . "/" . $fontface;
}
for ($i = 0; $i < $length; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120)); //这样保证随机出来的颜色较深。
$codex = String::msubstr($code, $i, 1);
imagettftext($im, mt_rand(16, 20), mt_rand(-60, 60), 40 * $i + 20, mt_rand(30, 35), $fontcolor, $fontface, $codex);
}
Image::output($im, $type);
}
/**
+----------------------------------------------------------
* 把图像转换成字符显示
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $image 要显示的图像
* @param string $type 图像类型,默认自动获取
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function showASCIIImg($image, $string='', $type='') {
$info = Image::getImageInfo($image);
if ($info !== false) {
$type = empty($type) ? $info['type'] : $type;
unset($info);
// 载入原图
$createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
$im = $createFun($image);
$dx = imagesx($im);
$dy = imagesy($im);
$i = 0;
$out = '<span style="padding:0px;margin:0;line-height:100%;font-size:1px;">';
set_time_limit(0);
for ($y = 0; $y < $dy; $y++) {
for ($x = 0; $x < $dx; $x++) {
$col = imagecolorat($im, $x, $y);
$rgb = imagecolorsforindex($im, $col);
$str = empty($string) ? '*' : $string[$i++];
$out .= sprintf('<span style="margin:0px;color:#%02x%02x%02x">' . $str . '</span>', $rgb['red'], $rgb['green'], $rgb['blue']);
}
$out .= "<br>\n";
}
$out .= '</span>';
imagedestroy($im);
return $out;
}
return false;
}
/**
+----------------------------------------------------------
* 生成UPC-A条形码
+----------------------------------------------------------
* @static
+----------------------------------------------------------
* @param string $type 图像格式
* @param string $type 图像格式
* @param string $lw 单元宽度
* @param string $hi 条码高度
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function UPCA($code, $type='png', $lw=2, $hi=100) {
static $Lencode = array('0001101', '0011001', '0010011', '0111101', '0100011',
'0110001', '0101111', '0111011', '0110111', '0001011');
static $Rencode = array('1110010', '1100110', '1101100', '1000010', '1011100',
'1001110', '1010000', '1000100', '1001000', '1110100');
$ends = '101';
$center = '01010';
/* UPC-A Must be 11 digits, we compute the checksum. */
if (strlen($code) != 11) {
die("UPC-A Must be 11 digits.");
}
/* Compute the EAN-13 Checksum digit */
$ncode = '0' . $code;
$even = 0;
$odd = 0;
for ($x = 0; $x < 12; $x++) {
if ($x % 2) {
$odd += $ncode[$x];
} else {
$even += $ncode[$x];
}
}
$code.= ( 10 - (($odd * 3 + $even) % 10)) % 10;
/* Create the bar encoding using a binary string */
$bars = $ends;
$bars.=$Lencode[$code[0]];
for ($x = 1; $x < 6; $x++) {
$bars.=$Lencode[$code[$x]];
}
$bars.=$center;
for ($x = 6; $x < 12; $x++) {
$bars.=$Rencode[$code[$x]];
}
$bars.=$ends;
/* Generate the Barcode Image */
if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
$im = imagecreatetruecolor($lw * 95 + 30, $hi + 30);
} else {
$im = imagecreate($lw * 95 + 30, $hi + 30);
}
$fg = ImageColorAllocate($im, 0, 0, 0);
$bg = ImageColorAllocate($im, 255, 255, 255);
ImageFilledRectangle($im, 0, 0, $lw * 95 + 30, $hi + 30, $bg);
$shift = 10;
for ($x = 0; $x < strlen($bars); $x++) {
if (($x < 10) || ($x >= 45 && $x < 50) || ($x >= 85)) {
$sh = 10;
} else {
$sh = 0;
}
if ($bars[$x] == '1') {
$color = $fg;
} else {
$color = $bg;
}
ImageFilledRectangle($im, ($x * $lw) + 15, 5, ($x + 1) * $lw + 14, $hi + 5 + $sh, $color);
}
/* Add the Human Readable Label */
ImageString($im, 4, 5, $hi - 5, $code[0], $fg);
for ($x = 0; $x < 5; $x++) {
ImageString($im, 5, $lw * (13 + $x * 6) + 15, $hi + 5, $code[$x + 1], $fg);
ImageString($im, 5, $lw * (53 + $x * 6) + 15, $hi + 5, $code[$x + 6], $fg);
}
ImageString($im, 4, $lw * 95 + 17, $hi - 5, $code[11], $fg);
/* Output the Header and Content. */
Image::output($im, $type);
}
static function output($im, $type='png', $filename='') {
header("Content-type: image/" . $type);
$ImageFun = 'image' . $type;
if (empty($filename)) {
$ImageFun($im);
} else {
$ImageFun($im, $filename);
}
imagedestroy($im);
}
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Lib/Extend/Library/ORG/Util/Image_sae.class.php | PHP | asf20 | 21,676 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: functions.php 2821 2012-03-16 06:17:49Z luofei614@gmail.com $
/**
+------------------------------------------------------------------------------
* Think 标准模式公共函数库
+------------------------------------------------------------------------------
* @category Think
* @package Common
* @author liu21st <liu21st@gmail.com>
* @version $Id: functions.php 2821 2012-03-16 06:17:49Z luofei614@gmail.com $
+------------------------------------------------------------------------------
*/
// 错误输出
function halt($error) {
$e = array();
if (APP_DEBUG) {
//调试模式下输出错误信息
if (!is_array($error)) {
$trace = debug_backtrace();
$e['message'] = $error;
$e['file'] = $trace[0]['file'];
$e['class'] = $trace[0]['class'];
$e['function'] = $trace[0]['function'];
$e['line'] = $trace[0]['line'];
$traceInfo = '';
$time = date('y-m-d H:i:m');
foreach ($trace as $t) {
$traceInfo .= '[' . $time . '] ' . $t['file'] . ' (' . $t['line'] . ') ';
$traceInfo .= $t['class'] . $t['type'] . $t['function'] . '(';
$traceInfo .= implode(', ', $t['args']);
$traceInfo .=')<br/>';
}
$e['trace'] = $traceInfo;
} else {
$e = $error;
}
// 包含异常页面模板
include C('TMPL_EXCEPTION_FILE');
} else {
//否则定向到错误页面
$error_page = C('ERROR_PAGE');
if (!empty($error_page)) {
redirect($error_page);
} else {
if (C('SHOW_ERROR_MSG'))
$e['message'] = is_array($error) ? $error['message'] : $error;
else
$e['message'] = C('ERROR_MESSAGE');
// 包含异常页面模板
include C('TMPL_EXCEPTION_FILE');
}
}
exit;
}
// 自定义异常处理
function throw_exception($msg, $type='ThinkException', $code=0) {
if (class_exists($type, false))
throw new $type($msg, $code, true);
else
halt($msg); // 异常类型不存在则输出错误信息字串
}
// 浏览器友好的变量输出
function dump($var, $echo=true, $label=null, $strict=true) {
$label = ($label === null) ? '' : rtrim($label) . ' ';
if (!$strict) {
if (ini_get('html_errors')) {
$output = print_r($var, true);
$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
} else {
$output = $label . print_r($var, true);
}
} else {
ob_start();
var_dump($var);
$output = ob_get_clean();
if (!extension_loaded('xdebug')) {
$output = preg_replace("/\]\=\>\n(\s+)/m", '] => ', $output);
$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
}
}
if ($echo) {
echo($output);
return null;
}else
return $output;
}
// 区间调试开始
function debug_start($label='') {
$GLOBALS[$label]['_beginTime'] = microtime(TRUE);
if (MEMORY_LIMIT_ON)
$GLOBALS[$label]['_beginMem'] = memory_get_usage();
}
// 区间调试结束,显示指定标记到当前位置的调试
function debug_end($label='') {
$GLOBALS[$label]['_endTime'] = microtime(TRUE);
echo '<div style="text-align:center;width:100%">Process ' . $label . ': Times ' . number_format($GLOBALS[$label]['_endTime'] - $GLOBALS[$label]['_beginTime'], 6) . 's ';
if (MEMORY_LIMIT_ON) {
$GLOBALS[$label]['_endMem'] = memory_get_usage();
echo ' Memories ' . number_format(($GLOBALS[$label]['_endMem'] - $GLOBALS[$label]['_beginMem']) / 1024) . ' k';
}
echo '</div>';
}
// 添加和获取页面Trace记录
function trace($title='',$value='') {
if(!C('SHOW_PAGE_TRACE')) return;
static $_trace = array();
if(is_array($title)) { // 批量赋值
$_trace = array_merge($_trace,$title);
}elseif('' !== $value){ // 赋值
$_trace[$title] = $value;
}elseif('' !== $title){ // 取值
return $_trace[$title];
}else{ // 获取全部Trace数据
return $_trace;
}
}
// 设置当前页面的布局
function layout($layout) {
if(false !== $layout) {
// 开启布局
C('LAYOUT_ON',true);
if(is_string($layout)) {
C('LAYOUT_NAME',$layout);
}
}
}
// URL组装 支持不同模式
// 格式:U('[分组/模块/操作]?参数','参数','伪静态后缀','是否跳转','显示域名')
function U($url,$vars='',$suffix=true,$redirect=false,$domain=false) {
// 解析URL
$info = parse_url($url);
$url = !empty($info['path'])?$info['path']:ACTION_NAME;
// 解析子域名
if($domain===true){
$domain = $_SERVER['HTTP_HOST'];
if(C('APP_SUB_DOMAIN_DEPLOY') ) { // 开启子域名部署
$domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.');
// '子域名'=>array('项目[/分组]');
foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) {
if(false === strpos($key,'*') && 0=== strpos($url,$rule[0])) {
$domain = $key.strstr($domain,'.'); // 生成对应子域名
$url = substr_replace($url,'',0,strlen($rule[0]));
break;
}
}
}
}
// 解析参数
if(is_string($vars)) { // aaa=1&bbb=2 转换成数组
parse_str($vars,$vars);
}elseif(!is_array($vars)){
$vars = array();
}
if(isset($info['query'])) { // 解析地址里面参数 合并到vars
parse_str($info['query'],$params);
$vars = array_merge($params,$vars);
}
// URL组装
$depr = C('URL_PATHINFO_DEPR');
if($url) {
if(0=== strpos($url,'/')) {// 定义路由
$route = true;
$url = substr($url,1);
if('/' != $depr) {
$url = str_replace('/',$depr,$url);
}
}else{
if('/' != $depr) { // 安全替换
$url = str_replace('/',$depr,$url);
}
// 解析分组、模块和操作
$url = trim($url,$depr);
$path = explode($depr,$url);
$var = array();
$var[C('VAR_ACTION')] = !empty($path)?array_pop($path):ACTION_NAME;
$var[C('VAR_MODULE')] = !empty($path)?array_pop($path):MODULE_NAME;
if(C('URL_CASE_INSENSITIVE')) {
$var[C('VAR_MODULE')] = parse_name($var[C('VAR_MODULE')]);
}
if(C('APP_GROUP_LIST')) {
if(!empty($path)) {
$group = array_pop($path);
$var[C('VAR_GROUP')] = $group;
}else{
if(GROUP_NAME != C('DEFAULT_GROUP')) {
$var[C('VAR_GROUP')] = GROUP_NAME;
}
}
}
}
}
if(C('URL_MODEL') == 0) { // 普通模式URL转换
$url = __APP__.'?'.http_build_query($var);
if(!empty($vars)) {
$vars = http_build_query($vars);
$url .= '&'.$vars;
}
}else{ // PATHINFO模式或者兼容URL模式
if(isset($route)) {
$url = __APP__.'/'.$url;
}else{
$url = __APP__.'/'.implode($depr,array_reverse($var));
}
if(!empty($vars)) { // 添加参数
$vars = http_build_query($vars);
$url .= $depr.str_replace(array('=','&'),$depr,$vars);
}
if($suffix) {
$suffix = $suffix===true?C('URL_HTML_SUFFIX'):$suffix;
if($suffix) {
$url .= '.'.ltrim($suffix,'.');
}
}
}
if($domain) {
$url = 'http://'.$domain.$url;
}
if($redirect) // 直接跳转URL
redirect($url);
else
return $url;
}
// URL重定向
function redirect($url, $time=0, $msg='') {
//多行URL地址支持
$url = str_replace(array("\n", "\r"), '', $url);
if (empty($msg))
$msg = "系统将在{$time}秒之后自动跳转到{$url}!";
if (!headers_sent()) {
// redirect
if (0 === $time) {
header('Location: ' . $url);
} else {
header("refresh:{$time};url={$url}");
echo($msg);
}
exit();
} else {
$str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
if ($time != 0)
$str .= $msg;
exit($str);
}
}
// 全局缓存设置和读取
//[sae] 在sae下S缓存固定用memcache实现。
function S($name, $value='', $expire=0, $type='', $options=null) {
static $_cache = array();
static $mc;
//取得缓存对象实例
if (!is_object($mc)) {
$mc = memcache_init();
}
if ('' !== $value) {
if (is_null($value)) {
// 删除缓存
$result = $mc->delete($_SERVER['HTTP_APPVERSION'] . '/' . $name);
if ($result)
unset($_cache[$name]);
return $result;
}else {
// 缓存数据
$mc->set($_SERVER['HTTP_APPVERSION'] . '/' . $name, $value, MEMCACHE_COMPRESSED, $expire);
$_cache[$name] = $value;
//[sae] 实现列队
if (!is_null($options['length']) && $options['length'] > 0) {
$queue = F('think_queue');
if (!$queue) {
$queue = array();
}
array_push($queue, $name);
if (count($queue) > $options['length']) {
$key = array_shift($queue);
$mc->delete($key);
//[sae] 在调试模式下,统计出队次数
if (APP_DEBUG) {
$counter = Think::instance('SaeCounter');
if ($counter->exists('think_queue_out_times'))
$counter->incr('think_queue_out_times');
else
$counter->create('think_queue_out_times', 1);
}
}
F('think_queue', $queue);
}
}
return;
}
if (isset($_cache[$name]))
return $_cache[$name];
// 获取缓存数据
$value = $mc->get($_SERVER['HTTP_APPVERSION'] . '/' . $name);
$_cache[$name] = $value;
return $value;
}
// 快速文件数据读取和保存 针对简单类型数据 字符串、数组
//[sae] 在sae下F缓存使用KVDB实现
function F($name, $value='', $path=DATA_PATH) {
//sae使用KVDB实现F缓存
static $_cache = array();
static $kv;
if (!is_object($kv)) {
$kv = Think::instance('SaeKVClient');
if(!$kv->init()) halt('您没有初始化KVDB,请在SAE平台进行初始化');
}
if ('' !== $value) {
if (is_null($value)) {
// 删除缓存
return $kv->delete($_SERVER['HTTP_APPVERSION'] . '/' . $name);
} else {
return $kv->set($_SERVER['HTTP_APPVERSION'] . '/' . $name, $value);
}
}
if (isset($_cache[$name]))
return $_cache[$name];
// 获取缓存数据
$value = $kv->get($_SERVER['HTTP_APPVERSION'] . '/' . $name);
return $value;
}
// 取得对象实例 支持调用类的静态方法
function get_instance_of($name, $method='', $args=array()) {
static $_instance = array();
$identify = empty($args) ? $name . $method : $name . $method . to_guid_string($args);
if (!isset($_instance[$identify])) {
if (class_exists($name)) {
$o = new $name();
if (method_exists($o, $method)) {
if (!empty($args)) {
$_instance[$identify] = call_user_func_array(array(&$o, $method), $args);
} else {
$_instance[$identify] = $o->$method();
}
}
else
$_instance[$identify] = $o;
}
else
halt(L('_CLASS_NOT_EXIST_') . ':' . $name);
}
return $_instance[$identify];
}
// 根据PHP各种类型变量生成唯一标识号
function to_guid_string($mix) {
if (is_object($mix) && function_exists('spl_object_hash')) {
return spl_object_hash($mix);
} elseif (is_resource($mix)) {
$mix = get_resource_type($mix) . strval($mix);
} else {
$mix = serialize($mix);
}
return md5($mix);
}
// xml编码
function xml_encode($data, $encoding='utf-8', $root='think') {
$xml = '<?xml version="1.0" encoding="' . $encoding . '"?>';
$xml.= '<' . $root . '>';
$xml.= data_to_xml($data);
$xml.= '</' . $root . '>';
return $xml;
}
function data_to_xml($data) {
$xml = '';
foreach ($data as $key => $val) {
is_numeric($key) && $key = "item id=\"$key\"";
$xml.="<$key>";
$xml.= ( is_array($val) || is_object($val)) ? data_to_xml($val) : $val;
list($key, ) = explode(' ', $key);
$xml.="</$key>";
}
return $xml;
}
// session管理函数
function session($name,$value='') {
$prefix = C('SESSION_PREFIX');
if(is_array($name)) { // session初始化 在session_start 之前调用
if(isset($name['prefix'])) C('SESSION_PREFIX',$name['prefix']);
if(isset($_REQUEST[C('VAR_SESSION_ID')])){
session_id($_REQUEST[C('VAR_SESSION_ID')]);
}elseif(isset($name['id'])) {
session_id($name['id']);
}
//ini_set('session.auto_start', 0);//[sae] 在sae平台不用设置
if(isset($name['name'])) session_name($name['name']);
if(isset($name['path'])) session_save_path($name['path']);
if(isset($name['domain'])) ini_set('session.cookie_domain', $name['domain']);
if(isset($name['expire'])) ini_set('session.gc_maxlifetime', $name['expire']);
if(isset($name['use_trans_sid'])) ini_set('session.use_trans_sid', $name['use_trans_sid']?1:0);
if(isset($name['use_cookies'])) ini_set('session.use_cookies', $name['use_cookies']?1:0);
if(isset($name['type'])) C('SESSION_TYPE',$name['type']);
if(C('SESSION_TYPE')) { // 读取session驱动
$class = 'Session'. ucwords(strtolower(C('SESSION_TYPE')));
// 检查驱动类
if(require_cache(EXTEND_PATH.'Driver/Session/'.$class.'.class.php')) {
$hander = new $class();
$hander->execute();
}else {
// 类没有定义
throw_exception(L('_CLASS_NOT_EXIST_').': ' . $class);
}
}
// 启动session
if(C('SESSION_AUTO_START')) session_start();
}elseif('' === $value){
if(0===strpos($name,'[')) { // session 操作
if('[pause]'==$name){ // 暂停session
session_write_close();
}elseif('[start]'==$name){ // 启动session
session_start();
}elseif('[destroy]'==$name){ // 销毁session
$_SESSION = array();
session_unset();
session_destroy();
}elseif('[regenerate]'==$name){ // 重新生成id
session_regenerate_id();
}
}elseif(0===strpos($name,'?')){ // 检查session
$name = substr($name,1);
if($prefix) {
return isset($_SESSION[$prefix][$name]);
}else{
return isset($_SESSION[$name]);
}
}elseif(is_null($name)){ // 清空session
if($prefix) {
unset($_SESSION[$prefix]);
}else{
$_SESSION = array();
}
}elseif($prefix){ // 获取session
return $_SESSION[$prefix][$name];
}else{
return $_SESSION[$name];
}
}elseif(is_null($value)){ // 删除session
if($prefix){
unset($_SESSION[$prefix][$name]);
}else{
unset($_SESSION[$name]);
}
}else{ // 设置session
if($prefix){
if (!is_array($_SESSION[$prefix])) {
$_SESSION[$prefix] = array();
}
$_SESSION[$prefix][$name] = $value;
}else{
$_SESSION[$name] = $value;
}
}
}
// Cookie 设置、获取、删除
function cookie($name, $value='', $option=null) {
// 默认设置
$config = array(
'prefix' => C('COOKIE_PREFIX'), // cookie 名称前缀
'expire' => C('COOKIE_EXPIRE'), // cookie 保存时间
'path' => C('COOKIE_PATH'), // cookie 保存路径
'domain' => C('COOKIE_DOMAIN'), // cookie 有效域名
);
// 参数设置(会覆盖黙认设置)
if (!empty($option)) {
if (is_numeric($option))
$option = array('expire' => $option);
elseif (is_string($option))
parse_str($option, $option);
$config = array_merge($config, array_change_key_case($option));
}
// 清除指定前缀的所有cookie
if (is_null($name)) {
if (empty($_COOKIE))
return;
// 要删除的cookie前缀,不指定则删除config设置的指定前缀
$prefix = empty($value) ? $config['prefix'] : $value;
if (!empty($prefix)) {// 如果前缀为空字符串将不作处理直接返回
foreach ($_COOKIE as $key => $val) {
if (0 === stripos($key, $prefix)) {
setcookie($key, '', time() - 3600, $config['path'], $config['domain']);
unset($_COOKIE[$key]);
}
}
}
return;
}
$name = $config['prefix'] . $name;
if ('' === $value) {
return isset($_COOKIE[$name]) ? $_COOKIE[$name] : null; // 获取指定Cookie
} else {
if (is_null($value)) {
setcookie($name, '', time() - 3600, $config['path'], $config['domain']);
unset($_COOKIE[$name]); // 删除指定cookie
} else {
// 设置cookie
$expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0;
setcookie($name, $value, $expire, $config['path'], $config['domain']);
$_COOKIE[$name] = $value;
}
}
}
// 加载扩展配置文件
function load_ext_file() {
// 加载自定义外部文件
if(C('LOAD_EXT_FILE')) {
$files = explode(',',C('LOAD_EXT_FILE'));
foreach ($files as $file){
$file = COMMON_PATH.$file.'.php';
if(is_file($file)) include $file;
}
}
// 加载自定义的动态配置文件
if(C('LOAD_EXT_CONFIG')) {
$configs = C('LOAD_EXT_CONFIG');
if(is_string($configs)) $configs = explode(',',$configs);
foreach ($configs as $key=>$config){
$file = CONF_PATH.$config.'.php';
if(is_file($file)) {
is_numeric($key)?C(include $file):C($key,include $file);
}
}
}
}
// 获取客户端IP地址
function get_client_ip() {
static $ip = NULL;
if ($ip !== NULL) return $ip;
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown',$arr);
if(false !== $pos) unset($arr[$pos]);
$ip = trim($arr[0]);
}elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
// IP地址合法验证
$ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0';
return $ip;
}
function send_http_status($code) {
static $_status = array(
// Success 2xx
200 => 'OK',
// Redirection 3xx
301 => 'Moved Permanently',
302 => 'Moved Temporarily ', // 1.1
// Client Error 4xx
400 => 'Bad Request',
403 => 'Forbidden',
404 => 'Not Found',
// Server Error 5xx
500 => 'Internal Server Error',
503 => 'Service Unavailable',
);
if(isset($_status[$code])) {
header('HTTP/1.1 '.$code.' '.$_status[$code]);
// 确保FastCGI模式下正常
header('Status:'.$code.' '.$_status[$code]);
}
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Common/functions.php | PHP | asf20 | 21,598 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: runtime.php 2821 2012-03-16 06:17:49Z luofei614@gmail.com $
/**
+------------------------------------------------------------------------------
* ThinkPHP 运行时文件 编译后不再加载
+------------------------------------------------------------------------------
*/
if (!defined('THINK_PATH')) exit();
if (version_compare(PHP_VERSION, '5.2.0', '<')) die('require PHP > 5.2.0 !');
// 版本信息
define('THINK_VERSION', '3.0');
define('THINK_RELEASE', '20120313');
// 系统信息
if(version_compare(PHP_VERSION,'5.4.0','<') ) {
//[sae]下不支持这个函数
//@set_magic_quotes_runtime (0);
define('MAGIC_QUOTES_GPC',get_magic_quotes_gpc()?True:False);
}
define('IS_CGI',substr(PHP_SAPI, 0,3)=='cgi' ? 1 : 0 );
define('IS_WIN',strstr(PHP_OS, 'WIN') ? 1 : 0 );
define('IS_CLI',PHP_SAPI=='cli'? 1 : 0);
// 项目名称
defined('APP_NAME') or define('APP_NAME', basename(dirname($_SERVER['SCRIPT_FILENAME'])));
if(!IS_CLI) {
// 当前文件名
if(!defined('_PHP_FILE_')) {
if(IS_CGI) {
//CGI/FASTCGI模式下
$_temp = explode('.php',$_SERVER['PHP_SELF']);
define('_PHP_FILE_', rtrim(str_replace($_SERVER['HTTP_HOST'],'',$_temp[0].'.php'),'/'));
}else {
define('_PHP_FILE_', rtrim($_SERVER['SCRIPT_NAME'],'/'));
}
}
if(!defined('__ROOT__')) {
// 网站URL根目录
if( strtoupper(APP_NAME) == strtoupper(basename(dirname(_PHP_FILE_))) ) {
$_root = dirname(dirname(_PHP_FILE_));
}else {
$_root = dirname(_PHP_FILE_);
}
define('__ROOT__', (($_root=='/' || $_root=='\\')?'':$_root));
}
//支持的URL模式
define('URL_COMMON', 0); //普通模式
define('URL_PATHINFO', 1); //PATHINFO模式
define('URL_REWRITE', 2); //REWRITE模式
define('URL_COMPAT', 3); // 兼容模式
}
// 路径设置 可在入口文件中重新定义 所有路径常量都必须以/ 结尾
defined('CORE_PATH') or define('CORE_PATH',THINK_PATH.'Lib/'); // 系统核心类库目录
defined('EXTEND_PATH') or define('EXTEND_PATH',THINK_PATH.'Extend/'); // 系统扩展目录
defined('MODE_PATH') or define('MODE_PATH',EXTEND_PATH.'Mode/'); // 模式扩展目录
defined('ENGINE_PATH') or define('ENGINE_PATH',EXTEND_PATH.'Engine/'); // 引擎扩展目录// 系统模式目录
defined('VENDOR_PATH') or define('VENDOR_PATH',EXTEND_PATH.'Vendor/'); // 第三方类库目录
defined('LIBRARY_PATH') or define('LIBRARY_PATH',EXTEND_PATH.'Library/'); // 扩展类库目录
defined('COMMON_PATH') or define('COMMON_PATH', APP_PATH.'Common/'); // 项目公共目录
defined('LIB_PATH') or define('LIB_PATH', APP_PATH.'Lib/'); // 项目类库目录
defined('CONF_PATH') or define('CONF_PATH', APP_PATH.'Conf/'); // 项目配置目录
defined('LANG_PATH') or define('LANG_PATH', APP_PATH.'Lang/'); // 项目语言包目录
defined('TMPL_PATH') or define('TMPL_PATH',APP_PATH.'Tpl/'); // 项目模板目录
defined('HTML_PATH') or define('HTML_PATH',$_SERVER['HTTP_APPVERSION'].'/html/'); //[sae] 项目静态目录,静态文件会存到KVDB
defined('LOG_PATH') or define('LOG_PATH', RUNTIME_PATH.'Logs/'); // 项目日志目录
defined('TEMP_PATH') or define('TEMP_PATH', RUNTIME_PATH.'Temp/'); // 项目缓存目录
defined('DATA_PATH') or define('DATA_PATH', RUNTIME_PATH.'Data/'); // 项目数据目录
defined('CACHE_PATH') or define('CACHE_PATH', RUNTIME_PATH.'Cache/'); // 项目模板缓存目录
// 为了方便导入第三方类库 设置Vendor目录到include_path
set_include_path(get_include_path() . PATH_SEPARATOR . VENDOR_PATH);
// 加载运行时所需要的文件 并负责自动目录生成
function load_runtime_file() {
//[sae] 加载系统基础函数库
require SAE_PATH.'Common/common.php';
//[sae] 读取核心编译文件列表
$list = array(
SAE_PATH.'Lib/Core/Think.class.php',
CORE_PATH.'Core/ThinkException.class.php', // 异常处理类
CORE_PATH.'Core/Behavior.class.php',
);
// 加载模式文件列表
foreach ($list as $key=>$file){
if(is_file($file)) require_cache($file);
}
//[sae] 加载系统类库别名定义
alias_import(include SAE_PATH.'Conf/alias.php');
//[sae]在sae下不对目录结构进行检查
if(APP_DEBUG){
//[sae] 调试模式切换删除编译缓存
if(SaeMC::file_exists(RUNTIME_FILE)) SaeMC::unlink(RUNTIME_FILE) ;
}
}
//[sae]下,不需要生成检查runtime目录函数
// 创建编译缓存
function build_runtime_cache($append='') {
// 生成编译文件
$defs = get_defined_constants(TRUE);
$content = '$GLOBALS[\'_beginTime\'] = microtime(TRUE);';
//[sae]编译SaeMC核心
$content.=compile(SAE_PATH.'Lib/Core/SaeMC.class.php');
if(defined('RUNTIME_DEF_FILE')) { //[sae] 编译后的常量文件外部引入
SaeMC::set(RUNTIME_DEF_FILE, '<?php '.array_define($defs['user']));
$content .= 'SaeMC::include_file(\''.RUNTIME_DEF_FILE.'\');';
}else{
$content .= array_define($defs['user']);
}
$content .= 'set_include_path(get_include_path() . PATH_SEPARATOR . VENDOR_PATH);';
//[sae] 读取核心编译文件列表
$list = array(
SAE_PATH.'Common/common.php',
SAE_PATH.'Lib/Core/Think.class.php',
CORE_PATH.'Core/ThinkException.class.php',
CORE_PATH.'Core/Behavior.class.php',
);
foreach ($list as $file){
$content .= compile($file);
}
// 系统行为扩展文件统一编译
if(C('APP_TAGS_ON')) {
$content .= build_tags_cache();
}
//[sae] 编译SAE的alias
$alias = include SAE_PATH.'Conf/alias.php';
$content .= 'alias_import('.var_export($alias,true).');';
// 编译框架默认语言包和配置参数
$content .= $append."\nL(".var_export(L(),true).");C(".var_export(C(),true).');G(\'loadTime\');Think::Start();';
//[sae] 生成编译缓存文件
SaeMC::set(RUNTIME_FILE, strip_whitespace('<?php '.$content));
}
// 编译系统行为扩展类库
function build_tags_cache() {
$tags = C('extends');
$content = '';
foreach ($tags as $tag=>$item){
foreach ($item as $key=>$name) {
$content .= is_int($key)?compile(CORE_PATH.'Behavior/'.$name.'Behavior.class.php'):compile($name);
}
}
return $content;
}
//[sae]下,不需要生成目录结构函数
// 加载运行时所需文件
load_runtime_file();
// 记录加载文件时间
G('loadTime');
// 执行入口
Think::Start(); | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Common/runtime.php | PHP | asf20 | 7,359 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: common.php 2821 2012-03-16 06:17:49Z luofei614@gmail.com $
/**
+------------------------------------------------------------------------------
* Think 基础函数库
+------------------------------------------------------------------------------
* @category Think
* @package Common
* @author liu21st <liu21st@gmail.com>
* @version $Id: common.php 2821 2012-03-16 06:17:49Z luofei614@gmail.com $
+------------------------------------------------------------------------------
*/
// 记录和统计时间(微秒)
function G($start,$end='',$dec=4) {
static $_info = array();
if(is_float($end)) { // 记录时间
$_info[$start] = $end;
}elseif(!empty($end)){ // 统计时间
if(!isset($_info[$end])) $_info[$end] = microtime(TRUE);
return number_format(($_info[$end]-$_info[$start]),$dec);
}else{ // 记录时间
$_info[$start] = microtime(TRUE);
}
}
// 设置和获取统计数据
function N($key, $step=0) {
static $_num = array();
if (!isset($_num[$key])) {
$_num[$key] = 0;
}
if (empty($step))
return $_num[$key];
else
$_num[$key] = $_num[$key] + (int) $step;
}
/**
+----------------------------------------------------------
* 字符串命名风格转换
* type
* =0 将Java风格转换为C的风格
* =1 将C风格转换为Java的风格
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $name 字符串
* @param integer $type 转换类型
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
function parse_name($name, $type=0) {
if ($type) {
return ucfirst(preg_replace("/_([a-zA-Z])/e", "strtoupper('\\1')", $name));
} else {
return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
}
}
// 优化的require_once
//[sae], 在sae下可以导入sae专用文件
function require_cache($filename) {
static $_importFiles = array();
if (!isset($_importFiles[$filename])) {
//sae专属文件的文件名为 name_sae.class.php 或 name_sae.php
$sae_filename = strpos($filename, 'class.php') ? str_replace('.class.php', '_sae.class.php', $filename) : str_replace('.php', '_sae.php', $filename);
$sae_files=C('SAE_SPECIALIZED_FILES');//[sae]读取系统专属文件列表
if (is_file($sae_filename)) {
require $sae_filename;
$_importFiles[$filename] = true;
}elseif(isset($sae_files[basename($filename)])){
require $sae_files[basename($filename)];
$_importFiles[$filename] = true;
}elseif (file_exists_case($filename)) {
require $filename;
$_importFiles[$filename] = true;
} else {
$_importFiles[$filename] = false;
}
}
return $_importFiles[$filename];
}
// 区分大小写的文件存在判断
function file_exists_case($filename) {
if (is_file($filename)) {
if (IS_WIN && C('APP_FILE_CASE')) {
if (basename(realpath($filename)) != basename($filename))
return false;
}
return true;
}
return false;
}
/**
+----------------------------------------------------------
* 导入所需的类库 同java的Import
* 本函数有缓存功能
+----------------------------------------------------------
* @param string $class 类库命名空间字符串
* @param string $baseUrl 起始路径
* @param string $ext 导入的文件扩展名
+----------------------------------------------------------
* @return boolen
+----------------------------------------------------------
*/
function import($class, $baseUrl = '', $ext='.class.php') {
static $_file = array();
$class = str_replace(array('.', '#'), array('/', '.'), $class);
if ('' === $baseUrl && false === strpos($class, '/')) {
// 检查别名导入
return alias_import($class);
}
if (isset($_file[$class . $baseUrl]))
return true;
else
$_file[$class . $baseUrl] = true;
$class_strut = explode('/', $class);
if (empty($baseUrl)) {
if ('@' == $class_strut[0] || APP_NAME == $class_strut[0]) {
//加载当前项目应用类库
$baseUrl = dirname(LIB_PATH);
$class = substr_replace($class, basename(LIB_PATH).'/', 0, strlen($class_strut[0]) + 1);
}elseif ('think' == strtolower($class_strut[0])){ // think 官方基类库
$baseUrl = CORE_PATH;
$class = substr($class,6);
}elseif (in_array(strtolower($class_strut[0]), array('org', 'com'))) {
// org 第三方公共类库 com 企业公共类库
$baseUrl = LIBRARY_PATH;
}else { // 加载其他项目应用类库
$class = substr_replace($class, '', 0, strlen($class_strut[0]) + 1);
$baseUrl = APP_PATH . '../' . $class_strut[0] . '/'.basename(LIB_PATH).'/';
}
}
if (substr($baseUrl, -1) != '/')
$baseUrl .= '/';
$classfile = $baseUrl . $class . $ext;
if (!class_exists(basename($class),false)) {
// 如果类不存在 则导入类库文件
return require_cache($classfile);
}
}
/**
+----------------------------------------------------------
* 基于命名空间方式导入函数库
* load('@.Util.Array')
+----------------------------------------------------------
* @param string $name 函数库命名空间字符串
* @param string $baseUrl 起始路径
* @param string $ext 导入的文件扩展名
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
function load($name, $baseUrl='', $ext='.php') {
$name = str_replace(array('.', '#'), array('/', '.'), $name);
if (empty($baseUrl)) {
if (0 === strpos($name, '@/')) {
//加载当前项目函数库
$baseUrl = COMMON_PATH;
$name = substr($name, 2);
} else {
//加载ThinkPHP 系统函数库
$baseUrl = EXTEND_PATH . 'Function/';
}
}
if (substr($baseUrl, -1) != '/')
$baseUrl .= '/';
require_cache($baseUrl . $name . $ext);
}
// 快速导入第三方框架类库
// 所有第三方框架的类库文件统一放到 系统的Vendor目录下面
// 并且默认都是以.php后缀导入
function vendor($class, $baseUrl = '', $ext='.php') {
if (empty($baseUrl))
$baseUrl = VENDOR_PATH;
return import($class, $baseUrl, $ext);
}
// 快速定义和导入别名
function alias_import($alias, $classfile='') {
static $_alias = array();
if (is_string($alias)) {
if(isset($_alias[$alias])) {
return require_cache($_alias[$alias]);
}elseif ('' !== $classfile) {
// 定义别名导入
$_alias[$alias] = $classfile;
return;
}
}elseif (is_array($alias)) {
$_alias = array_merge($_alias,$alias);
return;
}
return false;
}
/**
+----------------------------------------------------------
* D函数用于实例化Model 格式 项目://分组/模块
+----------------------------------------------------------
* @param string name Model资源地址
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
function D($name='') {
if(empty($name)) return new Model;
static $_model = array();
if(isset($_model[$name]))
return $_model[$name];
if(strpos($name,'://')) {// 指定项目
$name = str_replace('://','/Model/',$name);
}else{
$name = C('DEFAULT_APP').'/Model/'.$name;
}
import($name.'Model');
$class = basename($name.'Model');
if(class_exists($class)) {
$model = new $class();
}else {
$model = new Model(basename($name));
}
$_model[$name] = $model;
return $model;
}
/**
+----------------------------------------------------------
* M函数用于实例化一个没有模型文件的Model
+----------------------------------------------------------
* @param string name Model名称 支持指定基础模型 例如 MongoModel:User
* @param string tablePrefix 表前缀
* @param mixed $connection 数据库连接信息
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
function M($name='', $tablePrefix='',$connection='') {
static $_model = array();
if(strpos($name,':')) {
list($class,$name) = explode(':',$name);
}else{
$class = 'Model';
}
if (!isset($_model[$name . '_' . $class]))
$_model[$name . '_' . $class] = new $class($name,$tablePrefix,$connection);
return $_model[$name . '_' . $class];
}
/**
+----------------------------------------------------------
* A函数用于实例化Action 格式:[项目://][分组/]模块
+----------------------------------------------------------
* @param string name Action资源地址
+----------------------------------------------------------
* @return Action
+----------------------------------------------------------
*/
function A($name) {
static $_action = array();
if(isset($_action[$name]))
return $_action[$name];
if(strpos($name,'://')) {// 指定项目
$name = str_replace('://','/Action/',$name);
}else{
$name = '@/Action/'.$name;
}
import($name.'Action');
$class = basename($name.'Action');
if(class_exists($class,false)) {
$action = new $class();
$_action[$name] = $action;
return $action;
}else {
return false;
}
}
// 远程调用模块的操作方法
// URL 参数格式 [项目://][分组/]模块/操作
function R($url,$vars=array()) {
$info = pathinfo($url);
$action = $info['basename'];
$module = $info['dirname'];
$class = A($module);
if($class)
return call_user_func_array(array(&$class,$action),$vars);
else
return false;
}
// 获取和设置语言定义(不区分大小写)
function L($name=null, $value=null) {
static $_lang = array();
// 空参数返回所有定义
if (empty($name))
return $_lang;
// 判断语言获取(或设置)
// 若不存在,直接返回全大写$name
if (is_string($name)) {
$name = strtoupper($name);
if (is_null($value))
return isset($_lang[$name]) ? $_lang[$name] : $name;
$_lang[$name] = $value; // 语言定义
return;
}
// 批量定义
if (is_array($name))
$_lang = array_merge($_lang, array_change_key_case($name, CASE_UPPER));
return;
}
// 获取配置值
function C($name=null, $value=null) {
static $_config = array();
// 无参数时获取所有
if (empty($name))
return $_config;
// 优先执行设置获取或赋值
if (is_string($name)) {
if (!strpos($name, '.')) {
$name = strtolower($name);
if (is_null($value))
return isset($_config[$name]) ? $_config[$name] : null;
$_config[$name] = is_array($value)?array_change_key_case($value):$value;
return;
}
// 二维数组设置和获取支持
$name = explode('.', $name);
$name[0] = strtolower($name[0]);
if (is_null($value))
return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null;
$_config[$name[0]][$name[1]] = $value;
return;
}
// 批量设置
if (is_array($name)){
return $_config = array_merge($_config, array_change_key_case($name));
}
return null; // 避免非法参数
}
// 处理标签扩展
function tag($tag, &$params=NULL) {
// 系统标签扩展
$extends = C('extends.' . $tag);
// 应用标签扩展
$tags = C('tags.' . $tag);
if (!empty($tags)) {
if(empty($tags['_overlay']) && !empty($extends)) { // 合并扩展
$tags = array_unique(array_merge($extends,$tags));
}elseif(isset($tags['_overlay'])){ // 通过设置 '_overlay'=>1 覆盖系统标签
unset($tags['_overlay']);
}
}elseif(!empty($extends)) {
$tags = $extends;
}
if($tags) {
if(APP_DEBUG) {
G($tag.'Start');
Log::record('Tag[ '.$tag.' ] --START--',Log::INFO);
}
// 执行扩展
foreach ($tags as $key=>$name) {
if(!is_int($key)) { // 指定行为类的完整路径 用于模式扩展
$name = $key;
}
B($name, $params);
}
if(APP_DEBUG) { // 记录行为的执行日志
Log::record('Tag[ '.$tag.' ] --END-- [ RunTime:'.G($tag.'Start',$tag.'End',6).'s ]',Log::INFO);
}
}else{ // 未执行任何行为 返回false
return false;
}
}
// 动态添加行为扩展到某个标签
function add_tag_behavior($tag,$behavior,$path='') {
$array = C('tags.'.$tag);
if(!$array) {
$array = array();
}
if($path) {
$array[$behavior] = $path;
}else{
$array[] = $behavior;
}
C('tags.'.$tag,$array);
}
// 过滤器方法
function filter($name, &$content) {
$class = $name . 'Filter';
require_cache(LIB_PATH . 'Filter/' . $class . '.class.php');
$filter = new $class();
$content = $filter->run($content);
}
// 执行行为
function B($name, &$params=NULL) {
$class = $name.'Behavior';
G('behaviorStart');
$behavior = new $class();
$behavior->run($params);
if(APP_DEBUG) { // 记录行为的执行日志
G('behaviorEnd');
Log::record('Run '.$name.' Behavior [ RunTime:'.G('behaviorStart','behaviorEnd',6).'s ]',Log::INFO);
}
}
// 渲染输出Widget
function W($name, $data=array(), $return=false) {
$class = $name . 'Widget';
require_cache(LIB_PATH . 'Widget/' . $class . '.class.php');
if (!class_exists($class))
throw_exception(L('_CLASS_NOT_EXIST_') . ':' . $class);
$widget = Think::instance($class);
$content = $widget->render($data);
if ($return)
return $content;
else
echo $content;
}
// 去除代码中的空白和注释
function strip_whitespace($content) {
$stripStr = '';
//分析php源码
$tokens = token_get_all($content);
$last_space = false;
for ($i = 0, $j = count($tokens); $i < $j; $i++) {
if (is_string($tokens[$i])) {
$last_space = false;
$stripStr .= $tokens[$i];
} else {
switch ($tokens[$i][0]) {
//过滤各种PHP注释
case T_COMMENT:
case T_DOC_COMMENT:
break;
//过滤空格
case T_WHITESPACE:
if (!$last_space) {
$stripStr .= ' ';
$last_space = true;
}
break;
case T_START_HEREDOC:
$stripStr .= "<<<THINK\n";
break;
case T_END_HEREDOC:
$stripStr .= "THINK;\n";
for($k = $i+1; $k < $j; $k++) {
if(is_string($tokens[$k]) && $tokens[$k] == ';') {
$i = $k;
break;
} else if($tokens[$k][0] == T_CLOSE_TAG) {
break;
}
}
break;
default:
$last_space = false;
$stripStr .= $tokens[$i][1];
}
}
}
return $stripStr;
}
// 循环创建目录
function mk_dir($dir, $mode = 0777) {
if (is_dir($dir) || @mkdir($dir, $mode))
return true;
if (!mk_dir(dirname($dir), $mode))
return false;
return @mkdir($dir, $mode);
}
//[RUNTIME]
//[sae] 在sae下能编译sae专用文件
function compile($filename) {
$sae_filename = strpos($filename, 'class.php') ? str_replace('.class.php', '_sae.class.php', $filename) : str_replace('.php', '_sae.php', $filename);
$content = is_file($sae_filename) ? file_get_contents($sae_filename) : file_get_contents($filename);
// 替换预编译指令
$content = preg_replace('/\/\/\[RUNTIME\](.*?)\/\/\[\/RUNTIME\]/s', '', $content);
$content = substr(trim($content), 5);
if ('?>' == substr($content, -2))
$content = substr($content, 0, -2);
return $content;
}
// 根据数组生成常量定义
function array_define($array,$check=true) {
$content = "\n";
foreach ($array as $key => $val) {
$key = strtoupper($key);
if($check) $content .= 'defined(\'' . $key . '\') or ';
if (is_int($val) || is_float($val)) {
$content .= "define('" . $key . "'," . $val . ');';
} elseif (is_bool($val)) {
$val = ($val) ? 'true' : 'false';
$content .= "define('" . $key . "'," . $val . ');';
} elseif (is_string($val)) {
$content .= "define('" . $key . "','" . addslashes($val) . "');";
}
$content .= "\n";
}
return $content;
}
//[/RUNTIME] | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Common/common.php | PHP | asf20 | 18,590 |
<?php
//平滑函数,sae和本地都可以用,增加系统平滑性
function sae_unlink($filePath) {
if (IS_SAE) {
$arr = explode('/', ltrim($filePath, './'));
$domain = array_shift($arr);
$filePath = implode('/', $arr);
$s = Think::instance('SaeStorage');
return $s->delete($domain, $filePath);
} else {
return unlink($filePath);
}
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae/Common/sae_functions.php | PHP | asf20 | 398 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Sae.php 2793 2012-03-02 05:34:40Z liu21st $
// Sae版ThinkPHP 入口文件
//[sae]定义SAE_PATH
defined('ENGINE_PATH') or define('ENGINE_PATH',dirname(__FILE__).'/');
define('SAE_PATH', ENGINE_PATH.'Sae/');
//[sae]判断是否运行在SAE上。
if (!isset($_SERVER['HTTP_APPCOOKIE'])) {
define('IS_SAE', FALSE);
defined('THINK_PATH') or define('THINK_PATH', dirname(dirname(dirname(__FILE__))) . '/');
defined('APP_PATH') or define('APP_PATH', dirname($_SERVER['SCRIPT_FILENAME']) . '/');
//加载平滑函数
require SAE_PATH.'Common/sae_functions.php';
//加载模拟器
if (!defined('SAE_APPNAME'))
require SAE_PATH.'SaeImit.php';
require THINK_PATH . 'ThinkPHP.php';
exit();
}
define('IS_SAE', TRUE);
require SAE_PATH.'Lib/Core/SaeMC.class.php';
//记录开始运行时间
$GLOBALS['_beginTime'] = microtime(TRUE);
// 记录内存初始使用
define('MEMORY_LIMIT_ON', function_exists('memory_get_usage'));
if (MEMORY_LIMIT_ON) $GLOBALS['_startUseMems'] = memory_get_usage();
defined('APP_PATH') or define('APP_PATH', dirname($_SERVER['SCRIPT_FILENAME']) . '/');
//[sae] 判断是否手动建立项目目录
if (!is_dir(APP_PATH . '/Lib/')) {
header('Content-Type:text/html; charset=utf-8');
exit('<div style=\'font-weight:bold;float:left;width:430px;text-align:center;border:1px solid silver;background:#E8EFFF;padding:8px;color:red;font-size:14px;font-family:Tahoma\'>sae环境下请手动生成项目目录~</div>');
}
defined('RUNTIME_PATH') or define('RUNTIME_PATH', APP_PATH . 'Runtime/');
defined('APP_DEBUG') or define('APP_DEBUG', false); // 是否调试模式
$runtime = defined('MODE_NAME') ? '~' . strtolower(MODE_NAME) . '_runtime.php' : '~runtime.php';
defined('RUNTIME_FILE') or define('RUNTIME_FILE', RUNTIME_PATH . $runtime);
//[sae] 载入核心编译缓存
if (!APP_DEBUG && SaeMC::file_exists(RUNTIME_FILE)) {
// 部署模式直接载入allinone缓存
SaeMC::include_file(RUNTIME_FILE);
} else {
// ThinkPHP系统目录定义
defined('THINK_PATH') or define('THINK_PATH', dirname(dirname(dirname(__FILE__))) . '/');
//[sae] 加载运行时文件
require SAE_PATH.'Common/runtime.php';
} | 10npsite | trunk/DThinkPHP/Extend/Engine/Sae.php | PHP | asf20 | 2,849 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: RelationModel.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP 关联模型类扩展
+------------------------------------------------------------------------------
*/
define('HAS_ONE',1);
define('BELONGS_TO',2);
define('HAS_MANY',3);
define('MANY_TO_MANY',4);
class RelationModel extends Model {
// 关联定义
protected $_link = array();
/**
+----------------------------------------------------------
* 动态方法实现
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名称
* @param array $args 调用参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$args) {
if(strtolower(substr($method,0,8))=='relation'){
$type = strtoupper(substr($method,8));
if(in_array($type,array('ADD','SAVE','DEL'),true)) {
array_unshift($args,$type);
return call_user_func_array(array(&$this, 'opRelation'), $args);
}
}else{
return parent::__call($method,$args);
}
}
/**
+----------------------------------------------------------
* 得到关联的数据表名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getRelationTableName($relation) {
$relationTable = !empty($this->tablePrefix) ? $this->tablePrefix : '';
$relationTable .= $this->tableName?$this->tableName:$this->name;
$relationTable .= '_'.$relation->getModelName();
return strtolower($relationTable);
}
// 查询成功后的回调方法
protected function _after_find(&$result,$options) {
// 获取关联数据 并附加到结果中
if(!empty($options['link']))
$this->getRelation($result,$options['link']);
}
// 查询数据集成功后的回调方法
protected function _after_select(&$result,$options) {
// 获取关联数据 并附加到结果中
if(!empty($options['link']))
$this->getRelations($result,$options['link']);
}
// 写入成功后的回调方法
protected function _after_insert($data,$options) {
// 关联写入
if(!empty($options['link']))
$this->opRelation('ADD',$data,$options['link']);
}
// 更新成功后的回调方法
protected function _after_update($data,$options) {
// 关联更新
if(!empty($options['link']))
$this->opRelation('SAVE',$data,$options['link']);
}
// 删除成功后的回调方法
protected function _after_delete($data,$options) {
// 关联删除
if(!empty($options['link']))
$this->opRelation('DEL',$data,$options['link']);
}
/**
+----------------------------------------------------------
* 对保存到数据库的数据进行处理
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 要操作的数据
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
protected function _facade($data) {
$this->_before_write($data);
return $data;
}
/**
+----------------------------------------------------------
* 获取返回数据集的关联记录
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $resultSet 返回数据
* @param string|array $name 关联名称
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function getRelations(&$resultSet,$name='') {
// 获取记录集的主键列表
foreach($resultSet as $key=>$val) {
$val = $this->getRelation($val,$name);
$resultSet[$key] = $val;
}
return $resultSet;
}
/**
+----------------------------------------------------------
* 获取返回数据的关联记录
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $result 返回数据
* @param string|array $name 关联名称
* @param boolean $return 是否返回关联数据本身
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function getRelation(&$result,$name='',$return=false) {
if(!empty($this->_link)) {
foreach($this->_link as $key=>$val) {
$mappingName = !empty($val['mapping_name'])?$val['mapping_name']:$key; // 映射名称
if(empty($name) || true === $name || $mappingName == $name || (is_array($name) && in_array($mappingName,$name))) {
$mappingType = !empty($val['mapping_type'])?$val['mapping_type']:$val; // 关联类型
$mappingClass = !empty($val['class_name'])?$val['class_name']:$key; // 关联类名
$mappingFields = !empty($val['mapping_fields'])?$val['mapping_fields']:'*'; // 映射字段
$mappingCondition = !empty($val['condition'])?$val['condition']:'1=1'; // 关联条件
if(strtoupper($mappingClass)==strtoupper($this->name)) {
// 自引用关联 获取父键名
$mappingFk = !empty($val['parent_key'])? $val['parent_key'] : 'parent_id';
}else{
$mappingFk = !empty($val['foreign_key'])?$val['foreign_key']:strtolower($this->name).'_id'; // 关联外键
}
// 获取关联模型对象
$model = D($mappingClass);
switch($mappingType) {
case HAS_ONE:
$pk = $result[$this->getPk()];
$mappingCondition .= " AND {$mappingFk}='{$pk}'";
$relationData = $model->where($mappingCondition)->field($mappingFields)->find();
break;
case BELONGS_TO:
if(strtoupper($mappingClass)==strtoupper($this->name)) {
// 自引用关联 获取父键名
$mappingFk = !empty($val['parent_key'])? $val['parent_key'] : 'parent_id';
}else{
$mappingFk = !empty($val['foreign_key'])?$val['foreign_key']:strtolower($model->getModelName()).'_id'; // 关联外键
}
$fk = $result[$mappingFk];
$mappingCondition .= " AND {$model->getPk()}='{$fk}'";
$relationData = $model->where($mappingCondition)->field($mappingFields)->find();
break;
case HAS_MANY:
$pk = $result[$this->getPk()];
$mappingCondition .= " AND {$mappingFk}='{$pk}'";
$mappingOrder = !empty($val['mapping_order'])?$val['mapping_order']:'';
$mappingLimit = !empty($val['mapping_limit'])?$val['mapping_limit']:'';
// 延时获取关联记录
$relationData = $model->where($mappingCondition)->field($mappingFields)->order($mappingOrder)->limit($mappingLimit)->select();
break;
case MANY_TO_MANY:
$pk = $result[$this->getPk()];
$mappingCondition = " {$mappingFk}='{$pk}'";
$mappingOrder = $val['mapping_order'];
$mappingLimit = $val['mapping_limit'];
$mappingRelationFk = $val['relation_foreign_key']?$val['relation_foreign_key']:$model->getModelName().'_id';
$mappingRelationTable = $val['relation_table']?$val['relation_table']:$this->getRelationTableName($model);
$sql = "SELECT b.{$mappingFields} FROM {$mappingRelationTable} AS a, ".$model->getTableName()." AS b WHERE a.{$mappingRelationFk} = b.{$model->getPk()} AND a.{$mappingCondition}";
if(!empty($val['condition'])) {
$sql .= ' AND '.$val['condition'];
}
if(!empty($mappingOrder)) {
$sql .= ' ORDER BY '.$mappingOrder;
}
if(!empty($mappingLimit)) {
$sql .= ' LIMIT '.$mappingLimit;
}
$relationData = $this->query($sql);
break;
}
if(!$return){
if(isset($val['as_fields']) && in_array($mappingType,array(HAS_ONE,BELONGS_TO)) ) {
// 支持直接把关联的字段值映射成数据对象中的某个字段
// 仅仅支持HAS_ONE BELONGS_TO
$fields = explode(',',$val['as_fields']);
foreach ($fields as $field){
if(strpos($field,':')) {
list($name,$nick) = explode(':',$field);
$result[$nick] = $relationData[$name];
}else{
$result[$field] = $relationData[$field];
}
}
}else{
$result[$mappingName] = $relationData;
}
unset($relationData);
}else{
return $relationData;
}
}
}
}
return $result;
}
/**
+----------------------------------------------------------
* 操作关联数据
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $opType 操作方式 ADD SAVE DEL
* @param mixed $data 数据对象
* @param string $name 关联名称
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
protected function opRelation($opType,$data='',$name='') {
$result = false;
if(empty($data) && !empty($this->data)){
$data = $this->data;
}elseif(!is_array($data)){
// 数据无效返回
return false;
}
if(!empty($this->_link)) {
// 遍历关联定义
foreach($this->_link as $key=>$val) {
// 操作制定关联类型
$mappingName = $val['mapping_name']?$val['mapping_name']:$key; // 映射名称
if(empty($name) || true === $name || $mappingName == $name || (is_array($name) && in_array($mappingName,$name)) ) {
// 操作制定的关联
$mappingType = !empty($val['mapping_type'])?$val['mapping_type']:$val; // 关联类型
$mappingClass = !empty($val['class_name'])?$val['class_name']:$key; // 关联类名
// 当前数据对象主键值
$pk = $data[$this->getPk()];
if(strtoupper($mappingClass)==strtoupper($this->name)) {
// 自引用关联 获取父键名
$mappingFk = !empty($val['parent_key'])? $val['parent_key'] : 'parent_id';
}else{
$mappingFk = !empty($val['foreign_key'])?$val['foreign_key']:strtolower($this->name).'_id'; // 关联外键
}
$mappingCondition = !empty($val['condition'])? $val['condition'] : "{$mappingFk}='{$pk}'";
// 获取关联model对象
$model = D($mappingClass);
$mappingData = isset($data[$mappingName])?$data[$mappingName]:false;
if(!empty($mappingData) || $opType == 'DEL') {
switch($mappingType) {
case HAS_ONE:
switch (strtoupper($opType)){
case 'ADD': // 增加关联数据
$mappingData[$mappingFk] = $pk;
$result = $model->add($mappingData);
break;
case 'SAVE': // 更新关联数据
$result = $model->where($mappingCondition)->save($mappingData);
break;
case 'DEL': // 根据外键删除关联数据
$result = $model->where($mappingCondition)->delete();
break;
}
break;
case BELONGS_TO:
break;
case HAS_MANY:
switch (strtoupper($opType)){
case 'ADD' : // 增加关联数据
$model->startTrans();
foreach ($mappingData as $val){
$val[$mappingFk] = $pk;
$result = $model->add($val);
}
$model->commit();
break;
case 'SAVE' : // 更新关联数据
$model->startTrans();
$pk = $model->getPk();
foreach ($mappingData as $vo){
if(isset($vo[$pk])) {// 更新数据
$mappingCondition = "$pk ={$vo[$pk]}";
$result = $model->where($mappingCondition)->save($vo);
}else{ // 新增数据
$vo[$mappingFk] = $data[$this->getPk()];
$result = $model->add($vo);
}
}
$model->commit();
break;
case 'DEL' : // 删除关联数据
$result = $model->where($mappingCondition)->delete();
break;
}
break;
case MANY_TO_MANY:
$mappingRelationFk = $val['relation_foreign_key']?$val['relation_foreign_key']:$model->getModelName().'_id';// 关联
$mappingRelationTable = $val['relation_table']?$val['relation_table']:$this->getRelationTableName($model);
if(is_array($mappingData)) {
$ids = array();
foreach ($mappingData as $vo)
$ids[] = $vo[$model->getPk()];
$relationId = implode(',',$ids);
}
switch (strtoupper($opType)){
case 'ADD': // 增加关联数据
case 'SAVE': // 更新关联数据
if(isset($relationId)) {
$this->startTrans();
// 删除关联表数据
$this->table($mappingRelationTable)->where($mappingCondition)->delete();
// 插入关联表数据
$sql = 'INSERT INTO '.$mappingRelationTable.' ('.$mappingFk.','.$mappingRelationFk.') SELECT a.'.$this->getPk().',b.'.$model->getPk().' FROM '.$this->getTableName().' AS a ,'.$model->getTableName()." AS b where a.".$this->getPk().' ='. $pk.' AND b.'.$model->getPk().' IN ('.$relationId.") ";
$result = $model->execute($sql);
if(false !== $result)
// 提交事务
$this->commit();
else
// 事务回滚
$this->rollback();
}
break;
case 'DEL': // 根据外键删除中间表关联数据
$result = $this->table($mappingRelationTable)->where($mappingCondition)->delete();
break;
}
break;
}
}
}
}
}
return $result;
}
/**
+----------------------------------------------------------
* 进行关联查询
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $name 关联名称
+----------------------------------------------------------
* @return Model
+----------------------------------------------------------
*/
public function relation($name) {
$this->options['link'] = $name;
return $this;
}
/**
+----------------------------------------------------------
* 关联数据获取 仅用于查询后
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $name 关联名称
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function relationGet($name) {
if(empty($this->data))
return false;
return $this->getRelation($this->data,$name,true);
}
} | 10npsite | trunk/DThinkPHP/Extend/Model/RelationModel.class.php | PHP | asf20 | 21,601 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: AdvModel.class.php 2702 2012-02-02 12:35:01Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP 高级模型类扩展
+------------------------------------------------------------------------------
*/
class AdvModel extends Model {
protected $optimLock = 'lock_version';
protected $returnType = 'array';
protected $blobFields = array();
protected $blobValues = null;
protected $serializeField = array();
protected $readonlyField = array();
protected $_filter = array();
public function __construct($name='',$tablePrefix='',$connection='') {
if('' !== $name || is_subclass_of($this,'AdvModel') ){
// 如果是AdvModel子类或者有传入模型名称则获取字段缓存
}else{
// 空的模型 关闭字段缓存
$this->autoCheckFields = false;
}
parent::__construct($name,$tablePrefix,$connection);
}
/**
+----------------------------------------------------------
* 利用__call方法重载 实现一些特殊的Model方法 (魔术方法)
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名称
* @param mixed $args 调用参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$args) {
if(strtolower(substr($method,0,3))=='top'){
// 获取前N条记录
$count = substr($method,3);
array_unshift($args,$count);
return call_user_func_array(array(&$this, 'topN'), $args);
}else{
return parent::__call($method,$args);
}
}
/**
+----------------------------------------------------------
* 对保存到数据库的数据进行处理
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 要操作的数据
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
protected function _facade($data) {
// 检查序列化字段
$data = $this->serializeField($data);
return parent::_facade($data);
}
// 查询成功后的回调方法
protected function _after_find(&$result,$options='') {
// 检查序列化字段
$this->checkSerializeField($result);
// 获取文本字段
$this->getBlobFields($result);
// 检查字段过滤
$result = $this->getFilterFields($result);
// 缓存乐观锁
$this->cacheLockVersion($result);
}
// 查询数据集成功后的回调方法
protected function _after_select(&$resultSet,$options='') {
// 检查序列化字段
$resultSet = $this->checkListSerializeField($resultSet);
// 获取文本字段
$resultSet = $this->getListBlobFields($resultSet);
// 检查列表字段过滤
$resultSet = $this->getFilterListFields($resultSet);
}
// 写入前的回调方法
protected function _before_insert(&$data,$options='') {
// 记录乐观锁
$data = $this->recordLockVersion($data);
// 检查文本字段
$data = $this->checkBlobFields($data);
// 检查字段过滤
$data = $this->setFilterFields($data);
}
protected function _after_insert($data,$options) {
// 保存文本字段
$this->saveBlobFields($data);
}
// 更新前的回调方法
protected function _before_update(&$data,$options='') {
// 检查乐观锁
if(!$this->checkLockVersion($data,$options)) {
return false;
}
// 检查文本字段
$data = $this->checkBlobFields($data);
// 检查只读字段
$data = $this->checkReadonlyField($data);
// 检查字段过滤
$data = $this->setFilterFields($data);
}
protected function _after_update($data,$options) {
// 保存文本字段
$this->saveBlobFields($data);
}
protected function _after_delete($data,$options) {
// 删除Blob数据
$this->delBlobFields($data);
}
/**
+----------------------------------------------------------
* 记录乐观锁
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data 数据对象
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function recordLockVersion($data) {
// 记录乐观锁
if($this->optimLock && !isset($data[$this->optimLock]) ) {
if(in_array($this->optimLock,$this->fields,true)) {
$data[$this->optimLock] = 0;
}
}
return $data;
}
/**
+----------------------------------------------------------
* 缓存乐观锁
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data 数据对象
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function cacheLockVersion($data) {
if($this->optimLock) {
if(isset($data[$this->optimLock]) && isset($data[$this->getPk()])) {
// 只有当存在乐观锁字段和主键有值的时候才记录乐观锁
$_SESSION[$this->name.'_'.$data[$this->getPk()].'_lock_version'] = $data[$this->optimLock];
}
}
}
/**
+----------------------------------------------------------
* 检查乐观锁
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data 当前数据
* @param array $options 查询表达式
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
protected function checkLockVersion(&$data,$options) {
$id = $data[$this->getPk()];
// 检查乐观锁
$identify = $this->name.'_'.$id.'_lock_version';
if($this->optimLock && isset($_SESSION[$identify])) {
$lock_version = $_SESSION[$identify];
$vo = $this->field($this->optimLock)->find($id);
$_SESSION[$identify] = $lock_version;
$curr_version = $vo[$this->optimLock];
if(isset($curr_version)) {
if($curr_version>0 && $lock_version != $curr_version) {
// 记录已经更新
$this->error = L('_RECORD_HAS_UPDATE_');
return false;
}else{
// 更新乐观锁
$save_version = $data[$this->optimLock];
if($save_version != $lock_version+1) {
$data[$this->optimLock] = $lock_version+1;
}
$_SESSION[$identify] = $lock_version+1;
}
}
}
return true;
}
/**
+----------------------------------------------------------
* 查找前N个记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param integer $count 记录个数
* @param array $options 查询表达式
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function topN($count,$options=array()) {
$options['limit'] = $count;
return $this->select($options);
}
/**
+----------------------------------------------------------
* 查询符合条件的第N条记录
* 0 表示第一条记录 -1 表示最后一条记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param integer $position 记录位置
* @param array $options 查询表达式
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function getN($position=0,$options=array()) {
if($position>=0) { // 正向查找
$options['limit'] = $position.',1';
$list = $this->select($options);
return $list?$list[0]:false;
}else{ // 逆序查找
$list = $this->select($options);
return $list?$list[count($list)-abs($position)]:false;
}
}
/**
+----------------------------------------------------------
* 获取满足条件的第一条记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 查询表达式
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function first($options=array()) {
return $this->getN(0,$options);
}
/**
+----------------------------------------------------------
* 获取满足条件的最后一条记录
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $options 查询表达式
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function last($options=array()) {
return $this->getN(-1,$options);
}
/**
+----------------------------------------------------------
* 返回数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $data 数据
* @param string $type 返回类型 默认为数组
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function returnResult($data,$type='') {
if('' === $type)
$type = $this->returnType;
switch($type) {
case 'array' : return $data;
case 'object': return (object)$data;
default:// 允许用户自定义返回类型
if(class_exists($type))
return new $type($data);
else
throw_exception(L('_CLASS_NOT_EXIST_').':'.$type);
}
}
/**
+----------------------------------------------------------
* 获取数据的时候过滤数据字段
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $result 查询的数据
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function getFilterFields(&$result) {
if(!empty($this->_filter)) {
foreach ($this->_filter as $field=>$filter){
if(isset($result[$field])) {
$fun = $filter[1];
if(!empty($fun)) {
if(isset($filter[2]) && $filter[2]){
// 传递整个数据对象作为参数
$result[$field] = call_user_func($fun,$result);
}else{
// 传递字段的值作为参数
$result[$field] = call_user_func($fun,$result[$field]);
}
}
}
}
}
return $result;
}
protected function getFilterListFields(&$resultSet) {
if(!empty($this->_filter)) {
foreach ($resultSet as $key=>$result)
$resultSet[$key] = $this->getFilterFields($result);
}
return $resultSet;
}
/**
+----------------------------------------------------------
* 写入数据的时候过滤数据字段
+----------------------------------------------------------
* @access pubic
+----------------------------------------------------------
* @param mixed $result 查询的数据
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function setFilterFields($data) {
if(!empty($this->_filter)) {
foreach ($this->_filter as $field=>$filter){
if(isset($data[$field])) {
$fun = $filter[0];
if(!empty($fun)) {
if(isset($filter[2]) && $filter[2]) {
// 传递整个数据对象作为参数
$data[$field] = call_user_func($fun,$data);
}else{
// 传递字段的值作为参数
$data[$field] = call_user_func($fun,$data[$field]);
}
}
}
}
}
return $data;
}
/**
+----------------------------------------------------------
* 返回数据列表
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $resultSet 数据
* @param string $type 返回类型 默认为数组
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function returnResultSet(&$resultSet,$type='') {
foreach ($resultSet as $key=>$data)
$resultSet[$key] = $this->returnResult($data,$type);
return $resultSet;
}
protected function checkBlobFields(&$data) {
// 检查Blob文件保存字段
if(!empty($this->blobFields)) {
foreach ($this->blobFields as $field){
if(isset($data[$field])) {
if(isset($data[$this->getPk()]))
$this->blobValues[$this->name.'/'.$data[$this->getPk()].'_'.$field] = $data[$field];
else
$this->blobValues[$this->name.'/@?id@_'.$field] = $data[$field];
unset($data[$field]);
}
}
}
return $data;
}
/**
+----------------------------------------------------------
* 获取数据集的文本字段
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $resultSet 查询的数据
* @param string $field 查询的字段
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function getListBlobFields(&$resultSet,$field='') {
if(!empty($this->blobFields)) {
foreach ($resultSet as $key=>$result){
$result = $this->getBlobFields($result,$field);
$resultSet[$key] = $result;
}
}
return $resultSet;
}
/**
+----------------------------------------------------------
* 获取数据的文本字段
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 查询的数据
* @param string $field 查询的字段
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function getBlobFields(&$data,$field='') {
if(!empty($this->blobFields)) {
$pk = $this->getPk();
$id = $data[$pk];
if(empty($field)) {
foreach ($this->blobFields as $field){
$identify = $this->name.'/'.$id.'_'.$field;
$data[$field] = F($identify);
}
return $data;
}else{
$identify = $this->name.'/'.$id.'_'.$field;
return F($identify);
}
}
}
/**
+----------------------------------------------------------
* 保存File方式的字段
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 保存的数据
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function saveBlobFields(&$data) {
if(!empty($this->blobFields)) {
foreach ($this->blobValues as $key=>$val){
if(strpos($key,'@?id@'))
$key = str_replace('@?id@',$data[$this->getPk()],$key);
F($key,$val);
}
}
}
/**
+----------------------------------------------------------
* 删除File方式的字段
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 保存的数据
* @param string $field 查询的字段
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function delBlobFields(&$data,$field='') {
if(!empty($this->blobFields)) {
$pk = $this->getPk();
$id = $data[$pk];
if(empty($field)) {
foreach ($this->blobFields as $field){
$identify = $this->name.'/'.$id.'_'.$field;
F($identify,null);
}
}else{
$identify = $this->name.'/'.$id.'_'.$field;
F($identify,null);
}
}
}
/**
+----------------------------------------------------------
* 字段值延迟增长
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $field 字段名
* @param integer $step 增长值
* @param integer $lazyTime 延时时间(s)
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function setLazyInc($field,$step=1,$lazyTime=0) {
$condition = $this->options['where'];
if(empty($condition)) { // 没有条件不做任何更新
return false;
}
if($lazyTime>0) {// 延迟写入
$guid = md5($this->name.'_'.$field.'_'.serialize($condition));
$step = $this->lazyWrite($guid,$step,$lazyTime);
if(false === $step ) return true; // 等待下次写入
}
return $this->setField($field,array('exp',$field.'+'.$step));
}
/**
+----------------------------------------------------------
* 字段值延迟减少
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $field 字段名
* @param integer $step 减少值
* @param integer $lazyTime 延时时间(s)
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function setLazyDec($field,$step=1,$lazyTime=0) {
$condition = $this->options['where'];
if(empty($condition)) { // 没有条件不做任何更新
return false;
}
if($lazyTime>0) {// 延迟写入
$guid = md5($this->name.'_'.$field.'_'.serialize($condition));
$step = $this->lazyWrite($guid,$step,$lazyTime);
if(false === $step ) return true; // 等待下次写入
}
return $this->setField($field,array('exp',$field.'-'.$step));
}
/**
+----------------------------------------------------------
* 延时更新检查 返回false表示需要延时
* 否则返回实际写入的数值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $guid 写入标识
* @param integer $step 写入步进值
* @param integer $lazyTime 延时时间(s)
+----------------------------------------------------------
* @return false|integer
+----------------------------------------------------------
*/
protected function lazyWrite($guid,$step,$lazyTime) {
if(false !== ($value = F($guid))) { // 存在缓存写入数据
if(time()>F($guid.'_time')+$lazyTime) {
// 延时更新时间到了,删除缓存数据 并实际写入数据库
F($guid,NULL);
F($guid.'_time',NULL);
return $value+$step;
}else{
// 追加数据到缓存
F($guid,$value+$step);
return false;
}
}else{ // 没有缓存数据
F($guid,$step);
// 计时开始
F($guid.'_time',time());
return false;
}
}
/**
+----------------------------------------------------------
* 检查序列化数据字段
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data 数据
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function serializeField(&$data) {
// 检查序列化字段
if(!empty($this->serializeField)) {
// 定义方式 $this->serializeField = array('ser'=>array('name','email'));
foreach ($this->serializeField as $key=>$val){
if(empty($data[$key])) {
$serialize = array();
foreach ($val as $name){
if(isset($data[$name])) {
$serialize[$name] = $data[$name];
unset($data[$name]);
}
}
if(!empty($serialize)) {
$data[$key] = serialize($serialize);
}
}
}
}
return $data;
}
// 检查返回数据的序列化字段
protected function checkSerializeField(&$result) {
// 检查序列化字段
if(!empty($this->serializeField)) {
foreach ($this->serializeField as $key=>$val){
if(isset($result[$key])) {
$serialize = unserialize($result[$key]);
foreach ($serialize as $name=>$value)
$result[$name] = $value;
unset($serialize,$result[$key]);
}
}
}
return $result;
}
// 检查数据集的序列化字段
protected function checkListSerializeField(&$resultSet) {
// 检查序列化字段
if(!empty($this->serializeField)) {
foreach ($this->serializeField as $key=>$val){
foreach ($resultSet as $k=>$result){
if(isset($result[$key])) {
$serialize = unserialize($result[$key]);
foreach ($serialize as $name=>$value)
$result[$name] = $value;
unset($serialize,$result[$key]);
$resultSet[$k] = $result;
}
}
}
}
return $resultSet;
}
/**
+----------------------------------------------------------
* 检查只读字段
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $data 数据
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function checkReadonlyField(&$data) {
if(!empty($this->readonlyField)) {
foreach ($this->readonlyField as $key=>$field){
if(isset($data[$field]))
unset($data[$field]);
}
}
return $data;
}
/**
+----------------------------------------------------------
* 批处理执行SQL语句
* 批处理的指令都认为是execute操作
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $sql SQL批处理指令
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function patchQuery($sql=array()) {
if(!is_array($sql)) return false;
// 自动启动事务支持
$this->startTrans();
try{
foreach ($sql as $_sql){
$result = $this->execute($_sql);
if(false === $result) {
// 发生错误自动回滚事务
$this->rollback();
return false;
}
}
// 提交事务
$this->commit();
} catch (ThinkException $e) {
$this->rollback();
}
return true;
}
/**
+----------------------------------------------------------
* 得到分表的的数据表名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $data 操作的数据
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getPartitionTableName($data=array()) {
// 对数据表进行分区
if(isset($data[$this->partition['field']])) {
$field = $data[$this->partition['field']];
switch($this->partition['type']) {
case 'id':
// 按照id范围分表
$step = $this->partition['expr'];
$seq = floor($field / $step)+1;
break;
case 'year':
// 按照年份分表
if(!is_numeric($field)) {
$field = strtotime($field);
}
$seq = date('Y',$field)-$this->partition['expr']+1;
break;
case 'mod':
// 按照id的模数分表
$seq = ($field % $this->partition['num'])+1;
break;
case 'md5':
// 按照md5的序列分表
$seq = (ord(substr(md5($field),0,1)) % $this->partition['num'])+1;
break;
default :
if(function_exists($this->partition['type'])) {
// 支持指定函数哈希
$fun = $this->partition['type'];
$seq = (ord(substr($fun($field),0,1)) % $this->partition['num'])+1;
}else{
// 按照字段的首字母的值分表
$seq = (ord($field{0}) % $this->partition['num'])+1;
}
}
return $this->getTableName().'_'.$seq;
}else{
// 当设置的分表字段不在查询条件或者数据中
// 进行联合查询,必须设定 partition['num']
$tableName = array();
for($i=0;$i<$this->partition['num'];$i++)
$tableName[] = 'SELECT * FROM '.$this->getTableName().'_'.($i+1);
$tableName = '( '.implode(" UNION ",$tableName).') AS '.$this->name;
return $tableName;
}
}
} | 10npsite | trunk/DThinkPHP/Extend/Model/AdvModel.class.php | PHP | asf20 | 31,282 |
<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: MongoModel.class.php 2576 2012-01-12 15:09:01Z liu21st $
/**
+------------------------------------------------------------------------------
* TOPThink MongoModel模型类
* 实现了ODM和ActiveRecords模式
+------------------------------------------------------------------------------
* @category Think
* @package Think
* @subpackage Core
* @author liu21st <liu21st@gmail.com>
* @version $Id: MongoModel.class.php 2576 2012-01-12 15:09:01Z liu21st $
+------------------------------------------------------------------------------
*/
class MongoModel extends Model{
// 主键类型
const TYPE_OBJECT = 1;
const TYPE_INT = 2;
const TYPE_STRING = 3;
// 主键名称
protected $pk = '_id';
// _id 类型 1 Object 采用MongoId对象 2 Int 整形 支持自动增长 3 String 字符串Hash
protected $_idType = self::TYPE_OBJECT;
// 主键是否自动增长 支持Int型主键
protected $_autoInc = false;
// Mongo默认关闭字段检测 可以动态追加字段
protected $autoCheckFields = false;
/**
+----------------------------------------------------------
* 利用__call方法实现一些特殊的Model方法
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method 方法名称
* @param array $args 调用参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$args) {
if(in_array(strtolower($method),array('table','where','order','limit','page'),true)) {
// 连贯操作的实现
$this->options[strtolower($method)] = $args[0];
return $this;
}elseif(strtolower(substr($method,0,5))=='getby') {
// 根据某个字段获取记录
$field = parse_name(substr($method,5));
$where[$field] =$args[0];
return $this->where($where)->find();
}elseif(strtolower(substr($method,0,10))=='getfieldby') {
// 根据某个字段获取记录的某个值
$name = parse_name(substr($method,10));
$where[$name] =$args[0];
return $this->where($where)->getField($args[1]);
}else{
throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
return;
}
}
/**
+----------------------------------------------------------
* 获取字段信息并缓存 主键和自增信息直接配置
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function flush() {
// 缓存不存在则查询数据表信息
$fields = $this->db->getFields();
if(!$fields) { // 暂时没有数据无法获取字段信息 下次查询
return false;
}
$this->fields = array_keys($fields);
$this->fields['_pk'] = $this->pk;
$this->fields['_autoinc'] = $this->_autoInc;
foreach ($fields as $key=>$val){
// 记录字段类型
$type[$key] = $val['type'];
}
// 记录字段类型信息
if(C('DB_FIELDTYPE_CHECK')) $this->fields['_type'] = $type;
// 2008-3-7 增加缓存开关控制
if(C('DB_FIELDS_CACHE')){
// 永久缓存数据表信息
$db = $this->dbName?$this->dbName:C('DB_NAME');
F('_fields/'.$db.'.'.$this->name,$this->fields);
}
}
// 写入数据前的回调方法 包括新增和更新
protected function _before_write(&$data) {
$pk = $this->getPk();
// 根据主键类型处理主键数据
if(isset($data[$pk]) && $this->_idType == self::TYPE_OBJECT) {
$data[$pk] = new MongoId($data[$pk]);
}
}
/**
+----------------------------------------------------------
* count统计 配合where连贯操作
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
public function count(){
// 分析表达式
$options = $this->_parseOptions();
return $this->db->count($options);
}
/**
+----------------------------------------------------------
* 获取下一ID 用于自动增长型
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $pk 字段名 默认为主键
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function getMongoNextId($pk=''){
if(empty($pk)) {
$pk = $this->getPk();
}
return $this->db->mongo_next_id($pk);
}
// 插入数据前的回调方法
protected function _before_insert(&$data,$options) {
// 写入数据到数据库
if($this->_autoInc && $this->_idType== self::TYPE_INT) { // 主键自动增长
$pk = $this->getPk();
if(!isset($data[$pk])) {
$data[$pk] = $this->db->mongo_next_id($pk);
}
}
}
public function clear(){
return $this->db->clear();
}
// 查询成功后的回调方法
protected function _after_select(&$resultSet,$options) {
array_walk($resultSet,array($this,'checkMongoId'));
}
/**
+----------------------------------------------------------
* 获取MongoId
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param array $result 返回数据
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function checkMongoId(&$result){
if(is_object($result['_id'])) {
$result['_id'] = $result['_id']->__toString();
}
return $result;
}
// 表达式过滤回调方法
protected function _options_filter(&$options) {
$id = $this->getPk();
if(isset($options['where'][$id]) && $this->_idType== self::TYPE_OBJECT) {
$options['where'][$id] = new MongoId($options['where'][$id]);
}
}
/**
+----------------------------------------------------------
* 查询数据
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $options 表达式参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function find($options=array()) {
if( is_numeric($options) || is_string($options)) {
$id = $this->getPk();
$where[$id] = $options;
$options = array();
$options['where'] = $where;
}
// 分析表达式
$options = $this->_parseOptions($options);
$result = $this->db->find($options);
if(false === $result) {
return false;
}
if(empty($result)) {// 查询结果为空
return null;
}else{
$this->checkMongoId($result);
}
$this->data = $result;
$this->_after_find($this->data,$options);
return $this->data;
}
/**
+----------------------------------------------------------
* 字段值增长
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $field 字段名
* @param integer $step 增长值
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function setInc($field,$step=1) {
return $this->setField($field,array('inc',$step));
}
/**
+----------------------------------------------------------
* 字段值减少
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $field 字段名
* @param integer $step 减少值
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
public function setDec($field,$step=1) {
return $this->setField($field,array('inc','-'.$step));
}
/**
+----------------------------------------------------------
* 获取一条记录的某个字段值
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $field 字段名
* @param string $spea 字段数据间隔符号
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function getField($field,$sepa=null) {
$options['field'] = $field;
$options = $this->_parseOptions($options);
if(strpos($field,',')) { // 多字段
$resultSet = $this->db->select($options);
if(!empty($resultSet)) {
$_field = explode(',', $field);
$field = array_keys($resultSet[0]);
$move = $_field[0]==$_field[1]?false:true;
$key = array_shift($field);
$key2 = array_shift($field);
$cols = array();
$count = count($_field);
foreach ($resultSet as $result){
$name = $result[$key];
if($move) { // 删除键值记录
unset($result[$key]);
}
if(2==$count) {
$cols[$name] = $result[$key2];
}else{
$cols[$name] = is_null($sepa)?$result:implode($sepa,$result);
}
}
return $cols;
}
}else{ // 查找一条记录
$result = $this->db->find($options);
if(!empty($result)) {
return $result[$field];
}
}
return null;
}
/**
+----------------------------------------------------------
* 执行Mongo指令
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $command 指令
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function command($command) {
return $this->db->command($command);
}
/**
+----------------------------------------------------------
* 执行MongoCode
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $code MongoCode
* @param array $args 参数
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function mongoCode($code,$args=array()) {
return $this->db->execute($code,$args);
}
// 数据库切换后回调方法
protected function _after_db() {
// 切换Collection
$this->db->switchCollection($this->getTableName(),$this->dbName?$this->dbName:C('db_name'));
}
/**
+----------------------------------------------------------
* 得到完整的数据表名 Mongo表名不带dbName
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getTableName() {
if(empty($this->trueTableName)) {
$tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
if(!empty($this->tableName)) {
$tableName .= $this->tableName;
}else{
$tableName .= parse_name($this->name);
}
$this->trueTableName = strtolower($tableName);
}
return $this->trueTableName;
}
} | 10npsite | trunk/DThinkPHP/Extend/Model/MongoModel.class.php | PHP | asf20 | 14,197 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: ViewModel.class.php 2795 2012-03-02 15:34:18Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP 视图模型类扩展
+------------------------------------------------------------------------------
*/
class ViewModel extends Model {
protected $viewFields = array();
/**
+----------------------------------------------------------
* 自动检测数据表信息
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function _checkTableInfo() {}
/**
+----------------------------------------------------------
* 得到完整的数据表名
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getTableName() {
if(empty($this->trueTableName)) {
$tableName = '';
foreach ($this->viewFields as $key=>$view){
// 获取数据表名称
if(isset($view['_table'])) { // 2011/10/17 添加实际表名定义支持 可以实现同一个表的视图
$tableName .= $view['_table'];
}else{
$class = $key.'Model';
$Model = class_exists($class)?new $class():M($key);
$tableName .= $Model->getTableName();
}
// 表别名定义
$tableName .= !empty($view['_as'])?' '.$view['_as']:' '.$key;
// 支持ON 条件定义
$tableName .= !empty($view['_on'])?' ON '.$view['_on']:'';
// 指定JOIN类型 例如 RIGHT INNER LEFT 下一个表有效
$type = !empty($view['_type'])?$view['_type']:'';
$tableName .= ' '.strtoupper($type).' JOIN ';
$len = strlen($type.'_JOIN ');
}
$tableName = substr($tableName,0,-$len);
$this->trueTableName = $tableName;
}
return $this->trueTableName;
}
/**
+----------------------------------------------------------
* 表达式过滤方法
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $options 表达式
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function _options_filter(&$options) {
if(isset($options['field']))
$options['field'] = $this->checkFields($options['field']);
else
$options['field'] = $this->checkFields();
if(isset($options['group']))
$options['group'] = $this->checkGroup($options['group']);
if(isset($options['where']))
$options['where'] = $this->checkCondition($options['where']);
if(isset($options['order']))
$options['order'] = $this->checkOrder($options['order']);
}
/**
+----------------------------------------------------------
* 检查是否定义了所有字段
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $name 模型名称
* @param array $fields 字段数组
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
private function _checkFields($name,$fields) {
if(false !== $pos = array_search('*',$fields)) {// 定义所有字段
$fields = array_merge($fields,M($name)->getDbFields());
unset($fields[$pos]);
}
return $fields;
}
/**
+----------------------------------------------------------
* 检查条件中的视图字段
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data 条件表达式
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
protected function checkCondition($where) {
if(is_array($where)) {
$view = array();
// 检查视图字段
foreach ($this->viewFields as $key=>$val){
$k = isset($val['_as'])?$val['_as']:$key;
$val = $this->_checkFields($key,$val);
foreach ($where as $name=>$value){
if(false !== $field = array_search($name,$val,true)) {
// 存在视图字段
$_key = is_numeric($field)? $k.'.'.$name : $k.'.'.$field;
$view[$_key] = $value;
unset($where[$name]);
}
}
}
$where = array_merge($where,$view);
}
return $where;
}
/**
+----------------------------------------------------------
* 检查Order表达式中的视图字段
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $order 字段
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function checkOrder($order='') {
if(is_string($order) && !empty($order)) {
$orders = explode(',',$order);
$_order = array();
foreach ($orders as $order){
$array = explode(' ',$order);
$field = $array[0];
$sort = isset($array[1])?$array[1]:'ASC';
// 解析成视图字段
foreach ($this->viewFields as $name=>$val){
$k = isset($val['_as'])?$val['_as']:$name;
$val = $this->_checkFields($name,$val);
if(false !== $_field = array_search($field,$val,true)) {
// 存在视图字段
$field = is_numeric($_field)?$k.'.'.$field:$k.'.'.$_field;
break;
}
}
$_order[] = $field.' '.$sort;
}
$order = implode(',',$_order);
}
return $order;
}
/**
+----------------------------------------------------------
* 检查Group表达式中的视图字段
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $group 字段
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function checkGroup($group='') {
if(!empty($group)) {
$groups = explode(',',$group);
$_group = array();
foreach ($groups as $field){
// 解析成视图字段
foreach ($this->viewFields as $name=>$val){
$k = isset($val['_as'])?$val['_as']:$name;
$val = $this->_checkFields($name,$val);
if(false !== $_field = array_search($field,$val,true)) {
// 存在视图字段
$field = is_numeric($_field)?$k.'.'.$field:$k.'.'.$_field;
break;
}
}
$_group[] = $field;
}
$group = implode(',',$_group);
}
return $group;
}
/**
+----------------------------------------------------------
* 检查fields表达式中的视图字段
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $fields 字段
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function checkFields($fields='') {
if(empty($fields) || '*'==$fields ) {
// 获取全部视图字段
$fields = array();
foreach ($this->viewFields as $name=>$val){
$k = isset($val['_as'])?$val['_as']:$name;
$val = $this->_checkFields($name,$val);
foreach ($val as $key=>$field){
if(is_numeric($key)) {
$fields[] = $k.'.'.$field.' AS '.$field;
}elseif('_' != substr($key,0,1)) {
// 以_开头的为特殊定义
if( false !== strpos($key,'*') || false !== strpos($key,'(') || false !== strpos($key,'.')) {
//如果包含* 或者 使用了sql方法 则不再添加前面的表名
$fields[] = $key.' AS '.$field;
}else{
$fields[] = $k.'.'.$key.' AS '.$field;
}
}
}
}
$fields = implode(',',$fields);
}else{
if(!is_array($fields))
$fields = explode(',',$fields);
// 解析成视图字段
$array = array();
foreach ($fields as $key=>$field){
if(strpos($field,'(') || strpos(strtolower($field),' as ')){
// 使用了函数或者别名
$array[] = $field;
unset($fields[$key]);
}
}
foreach ($this->viewFields as $name=>$val){
$k = isset($val['_as'])?$val['_as']:$name;
$val = $this->_checkFields($name,$val);
foreach ($fields as $key=>$field){
if(false !== $_field = array_search($field,$val,true)) {
// 存在视图字段
if(is_numeric($_field)) {
$array[] = $k.'.'.$field.' AS '.$field;
}elseif('_' != substr($_field,0,1)){
if( false !== strpos($_field,'*') || false !== strpos($_field,'(') || false !== strpos($_field,'.'))
//如果包含* 或者 使用了sql方法 则不再添加前面的表名
$array[] = $_field.' AS '.$field;
else
$array[] = $k.'.'.$_field.' AS '.$field;
}
}
}
}
$fields = implode(',',$array);
}
return $fields;
}
} | 10npsite | trunk/DThinkPHP/Extend/Model/ViewModel.class.php | PHP | asf20 | 12,282 |
<?php
//帐号和密码必须是字母或数字或中横线或下横线组成,长度在三位及以上
/**
访问范围:
帐号 三位以上20位以下
tours 所有的线路xml可访问
c1_5 可访问一级类别的id为5的所以线路
c1_5_c2_6 可访问一级类别的id为5并且二级类别id为6的线路 若有c2必须有c1
每分钟连接数
unlimited 为不限制 若为数字时表示一分钟内查接的次数
*/
$apiuser=array(
//帐号 密码 访问范围 每分钟连接数
"dreamstravel"=>array("sz123","tours","unlimited"),//key为帐号和密码 $v为访问的范围
);
/**
* 检查连接的用户的权限
*
* @param $arr 连接参数
* $arr["uname"] 用户名
* $arr["pass"] 密码
* $arr["rule] 访问权限
* $arr["rnumber"] 每分种访问次数
* @return 通过返回true 失败返回false
*/
function checkuser($arr)
{
global $apiuser;
foreach($apiuser as $k=>$v)
{
if($k==$arr["uname"] and $v[0]==$arr["pass"])
{
if($v[1]=="tours")
{
return true;
}
elseif ($v[1]=="unlimited")
{
return true;
}
}
}
return false;
}
?> | 10npsite | trunk/inc/apicount.php | PHP | asf20 | 1,220 |
<? require_once "../global.php";
require_once RootDir."/"."inc/Function.Libary.php";
require_once RootDir."/"."inc/Uifunction.php";
require_once "Up_file_suonue.php";
if($_SESSION["Login"][1]=="" or $_SESSION["Login"][1]==Null ) die("你没有权限上传");
?>
<style type="text/css">
<!--
.pt11 {
font-size: 11pt;
color: #333333;
}
body,td,th {
font-size: 12px;
}
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
}
-->
</style>
<?php
//需要引用/global.php 文件
//使用方法
//<iframe src="Up_file.php?formId=up1&getelementId=pic2" width="400" marginwidth="0" height="25" marginheight="0" scrolling="No" frameborder="0" vspale="0"></iframe>
//上传参数区
$getelementId=$_REQUEST["getelementId"];
$formId=$_REQUEST["formId"];//父目录表单名
$mulvupic="/".date("Y")."/".date("m")."/".date("d");//上传文件存放目录规则
mkdirs($SystemConest[0].$SystemConest[4] .$mulvupic);
$save_path=$SystemConest[0].$SystemConest[4] .$mulvupic;
$FILE_POSTFIX=$SystemConest[5] ;
$agree_size=$SystemConest[3];//允许许文件上传的大小
function reFileName($file_name)
{//涵数功能 获取文件名称
$extend =explode("." , $file_name);
$va=count($extend)-1;
return ".".strtolower($extend[$va]);
}
if($_POST["Submit"]=="上传")
{
$agree=$_REQUEST["AgreeFile_size"];//充许文件上传的大小
$file_name = $_FILES["file"]["name"];
$file_type= reFileName($file_name);
$file_size = $_FILES["file"]["size"];
$flag=0;
foreach($FILE_POSTFIX as $V)
{
if($V==$file_type)
{
$flag=1;
break;
}
}
if ($flag==0)
{
die("系统不充许上传这种类型 <a href='javascript:history.go(-1);'>返回</a>");
}
if( $file_size>$agree_size)
{
die("请上传".number_format($agree_size/1024,2,".","")."K以内的文件 <a href='javascript:history.go(-1);'>返回</a>");
}
$file_tn = time().$file_name;
$messg = "<p>上传文件发生以外:</p><a href='javascript:history.go(-1);'>返回</a>";
$messg_sr =$messg;
if($messg != $messg_sr){
echo $messg;
}
else
{
if(move_uploaded_file($_FILES["file"]["tmp_name"],$save_path."/".$file_tn))
{
//生成缩略图
$pics=new CreatMiniature();
$temppath=$SystemConest[0].$SystemConest[4].$mulvupic;
$pics->srcFile=$temppath."/".$file_tn;
$pics->echoType="file";
$pics->SetVar($pics->srcFile,$pics->echoType);
$pics->Prorate(
$temppath.replaceKuohaostr($file_tn,"_m.","/(\.)[^\.]+$/"),
$SystemConest["sys_suoluetu"]["w"],$SystemConest["sys_suoluetu"]["h"]);
//上传成功处理
echo "<script>parent.".$formId.".".$getelementId.".value='".$SystemConest[4].$mulvupic."/".$file_tn."'</script>";
}
else
{
echo $messg;
}
}
}
else
{
?>
<table border="0" cellspacing="0" align="left">
<form id="form1" name="form1" method="post" enctype="multipart/form-data" action="">
<tr>
<td align="center" bgcolor="#F1F1F1">
<input name="file" type="file" id="file" size="22" />
<input type="submit" name="Submit" value="上传" /> </td>
</tr></form>
</table>
<?php
}
?>
| 10npsite | trunk/inc/Up_file.php | PHP | asf20 | 3,501 |
<style>
.menu_iframe{position:absolute; visibility:inherit; top:0px; left:0px; width:170px; z-index:-1; filter: Alpha(Opacity=0);}
.cal_table{ border:#333333 solid 1px; border-collapse:collapse; background:#ffffff; font-size:12px}
.cal_drawdate{ background:#E3EBF6;border-collapse:collapse; width:100%}
.cal_drawdate td{ border:1px #ffffff solid; }
.cal_drawtime{ border:0px #ffffff solid; font-size:12px}
.cal_drawdate td{ border:0px #ffffff solid; }
.m_fieldset {
padding: 0,10,5,10;
text-align: center;
width: 150px;
}
.m_legend {
font-family: Tahoma;
font-size: 11px;
padding-bottom: 5px;
}
.m_frameborder {
border-left: 1px inset #D4D0C8;
border-top: 1px inset #D4D0C8;
border-right: 1px inset #D4D0C8;
border-bottom: 1px inset #D4D0C8;
width: 35px;
height: 19px;
background-color: #FFFFFF;
overflow: hidden;
text-align: right;
font-family: "Tahoma";
font-size: 10px;
}
.m_arrow {
width: 16px;
height: 8px;
background:#cccccc;
font-family: "Webdings";
font-size: 7px;
line-height: 2px;
padding-left: 2px;
cursor: default;
}
.m_input {
width: 12px;
height: 14px;
border: 0px solid black;
font-family: "Tahoma";
font-size: 9px;
text-align: right;
}
.c_fieldset {
padding: 0,10,5,10;
text-align: center;
width: 180px;
}
.c_legend {
font-family: Tahoma;
font-size: 11px;
padding-bottom: 5px;
}
.c_frameborder {
border-left: 1px #D4D0C8;
border-top: 1px #D4D0C8;
border-right: 1px #FFFFFF;
border-bottom: 1px #FFFFFF;
background-color: #FFFFFF;
overflow: hidden;
font-family: "Tahoma";
font-size: 10px;
width:100%;
height:120px;
}
.c_frameborder td {
width: 23px;
height: 16px;
font-family: "Tahoma";
font-size: 11px;
text-align: center;
cursor: default;
}
.c_frameborder .selected {
background-color:#0A246A;
width:12px;
height:12px;
color:white;
display:block;
}
.c_frameborder span {
width:12px;
height:12px;
}
.c_arrow {
width: 16px;
height: 8px;
background:#cccccc;
font-family: "Webdings";
font-size: 7px;
line-height: 2px;
padding-left: 2px;
cursor: default;
}
.c_year {
font-family: "Tahoma";
font-size: 11px;
cursor: default;
width:55px;
height:20px;
border:#99B2D3 solid 1px;
}
.c_month {
width:75px;
height:20px;
font:11px "Tahoma";
border:#99B2D3 solid 1px;
}
.c_dateHead {
background-color:#99B2D3;
color:#ffffff;
border-collapse:collapse;
}
.c_dateHead td{ border:0px #ffffff solid; }
.rightmenu{
float:left; /* 菜单总体水平位置 */
list-style:none;
line-height:19px; /* 一级菜单高 */
background:#1371A0 ; /* 所有菜单移出色 */
font-weight: bold;
padding:0px;
margin:0px;
border: 1px #000000 solid;
}
.rightmenu li{
float:left; /* 菜单总体水平位置 */
list-style:none;
line-height:19px; /* 一级菜单高 */
background:#1371A0 ; /* 所有菜单移出色 */
font-weight: bold;
color:#FFFFFF;
padding:0px;
margin:0px;
border: 1px #FFFFFF solid;
}
.rightmenu li a{
float:left; /* 菜单总体水平位置 */
list-style:none;
line-height:19px; /* 一级菜单高 */
background:#1371A0 ; /* 所有菜单移出色 */
font-weight: bold;
color:#FFFFFF !important;
padding:0px;
margin:0px;
border-right: 0px;
display:block;
width:80px;
}
.rightmenu li a:hover{
float:left; /* 菜单总体水平位置 */
list-style:none;
line-height:19px; /* 一级菜单高 */
background:#B2CFDF ; /* 所有菜单移出色 */
font-weight: bold;
color:#000000 !important;
padding:0px;
margin:0px;
border-right: 0px;
width:80px;
text-decoration:none;
}
</style>
<script>
function CalendarMinute(name,fName)
{
this.name = name;
this.fName = fName || "m_input";
this.timer = null;
this.fObj = null;
this.toString = function()
{
var objDate = new Date();
var sMinute_Common = "class=\"m_input\" maxlength=\"2\" name=\""+this.fName+"\" onfocus=\""+this.name+".setFocusObj(this)\" onblur=\""+this.name+".setTime(this)\" onkeyup=\""+this.name+".prevent(this)\" onkeypress=\"if (!/[0-9]/.test(String.fromCharCode(event.keyCode)))event.keyCode=0\" onpaste=\"return false\" ondragenter=\"return false\"";
var sButton_Common = "class=\"m_arrow\" onfocus=\"this.blur()\" onmouseup=\""+this.name+".controlTime()\" disabled"
var str = "";
str += "<table class=\"cal_drawtime\" cellspacing=\"0\" cellpadding=\"0\" border=>"
str += "<tr>"
str += "<td>"
str += "请选择时间:"
str += "</td>"
str += "<td>"
str += "<div class=\"m_frameborder\">"
str += "<input radix=\"24\" value=\""+this.formatTime(objDate.getHours())+"\" "+sMinute_Common+">:"
str += "<input radix=\"60\" value=\""+this.formatTime(objDate.getMinutes())+"\" "+sMinute_Common+">"
//str += "<input radix=\"60\" value=\""+this.formatTime(objDate.getSeconds())+"\" "+sMinute_Common+">"
str += "</div>"
str += "</td>"
str += "<td>"
str += "<table class=\"cal_drawtime\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"
str += "<tr><td><button id=\""+this.fName+"_up\" "+sButton_Common+">5</button></td></tr>"
str += "<tr><td><button id=\""+this.fName+"_down\" "+sButton_Common+">6</button></td></tr>"
str += "</table>"
str += "</td>"
str += "</tr>"
str += "</table>"
return str;
}
this.play = function()
{
this.timer = setInterval(this.name+".playback()",1000);
}
this.formatTime = function(sTime)
{
sTime = ("0"+sTime);
return sTime.substr(sTime.length-2);
}
this.playback = function()
{
var objDate = new Date();
var arrDate = [objDate.getHours(),objDate.getMinutes(),objDate.getSeconds()];
var objMinute = document.getElementsByName(this.fName);
for (var i=0;i<objMinute.length;i++)
{
objMinute[i].value = this.formatTime(arrDate[i])
}
}
this.prevent = function(obj)
{
clearInterval(this.timer);
this.setFocusObj(obj);
var value = parseInt(obj.value,10);
var radix = parseInt(obj.radix,10)-1;
if (obj.value>radix||obj.value<0)
{
obj.value = obj.value.substr(0,1);
}
}
this.controlTime = function(cmd)
{
event.cancelBubble = true;
if (!this.fObj) return;
clearInterval(this.timer);
var cmd = event.srcElement.innerText=="5"?true:false;
var i = parseInt(this.fObj.value,10);
var radix = parseInt(this.fObj.radix,10)-1;
if (i==radix&&cmd)
{
i = 0;
}
else if (i==0&&!cmd)
{
i = radix;
}
else
{
cmd?i++:i--;
}
this.fObj.value = this.formatTime(i);
this.fObj.select();
getDateTime();
}
this.setTime = function(obj)
{
obj.value = this.formatTime(obj.value);
}
this.setFocusObj = function(obj)
{
eval(this.fName+"_up").disabled = eval(this.fName+"_down").disabled = false;
this.fObj = obj;
}
this.getTime = function()
{
var arrTime = new Array(2);
for (var i=0;i<document.getElementsByName(this.fName).length;i++)
{
arrTime[i] = document.getElementsByName(this.fName)[i].value;
//alert(arrTime[i]);
}
return arrTime.join(":");
}
}
// Written by cloudchen, 2004/03/16
function CalendarCalendar(name,fName)
{
this.name = name;
this.fName = fName || "calendar";
this.year = new Date().getFullYear();
this.month = new Date().getMonth();
this.date = new Date().getDate();
//alert(this.month);
//private
this.toString = function()
{
var str = "";
str += "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" onselectstart=\"return false\">";
str += "<tr>";
str += "<td>";
str += this.drawMonth();
str += "</td>";
str += "<td align=\"right\">";
str += this.drawYear();
str += "</td>";
str += "</tr>";
str += "<tr>";
str += "<td colspan=\"2\">";
str += "<div class=\"c_frameborder\">";
str += "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"c_dateHead\">";
str += "<tr>";
str += "<td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td>";
str += "</tr>";
str += "</table>";
str += this.drawDate();
str += "</div>";
str += "</td>";
str += "</tr>";
str += "</table>";
return str;
}
//private
this.drawYear = function()
{
var str = "";
str += "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
str += "<tr>";
str += "<td>";
str += "<input class=\"c_year\" maxlength=\"4\" value=\""+this.year+"\" name=\""+this.fName+"\" id=\""+this.fName+"_year\" readonly>";
//DateField
str += "<input type=\"hidden\" name=\""+this.fName+"\" value=\""+this.date+"\" id=\""+this.fName+"_date\">";
str += "</td>";
str += "<td>";
str += "<table cellspacing=\"2\" cellpadding=\"0\" border=\"0\">";
str += "<tr>";
str += "<td><button class=\"c_arrow\" onfocus=\"this.blur()\" onclick=\"event.cancelBubble=true;document.getElementById('"+this.fName+"_year').value++;"+this.name+".redrawDate()\">5</button></td>";
str += "</tr>";
str += "<tr>";
str += "<td><button class=\"c_arrow\" onfocus=\"this.blur()\" onclick=\"event.cancelBubble=true;document.getElementById('"+this.fName+"_year').value--;"+this.name+".redrawDate()\">6</button></td>";
str += "</tr>";
str += "</table>";
str += "</td>";
str += "</tr>";
str += "</table>";
return str;
}
//priavate
this.drawMonth = function()
{ //alert(this.fName);
var aMonthName = ["一","二","三","四","五","六","七","八","九","十","十一","十二"];
var str = "";
str += "<select class=\"c_month\" name=\""+this.fName+"\" id=\""+this.fName+"_month\" onchange=\""+this.name+".redrawDate()\">";
for (var i=0;i<aMonthName.length;i++) {
str += "<option value=\""+(i+1)+"\" "+(i==this.month?"selected":"")+">"+aMonthName[i]+"月</option>";
}
str += "</select>";
return str;
}
//private
this.drawDate = function()
{
var str = "";
var fDay = new Date(this.year,this.month,1).getDay();
var fDate = 1-fDay;
var lDay = new Date(this.year,this.month+1,0).getDay();
var lDate = new Date(this.year,this.month+1,0).getDate();
str += "<table class=\"cal_drawdate\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" id=\""+this.fName+"_dateTable"+"\">";
for (var i=1,j=fDate;i<7;i++)
{
str += "<tr>";
for (var k=0;k<7;k++)
{
str += "<td><span"+(j==this.date?" class=\"selected\"":"")+" onclick=\""+this.name+".redrawDate(this.innerText)\">"+(isDate(j++))+"</span></td>";
}
str += "</tr>";
}
str += "</table>";
return str;
function isDate(n)
{
return (n>=1&&n<=lDate)?n:"";
}
}
//public
this.redrawDate = function(d)
{
this.year = document.getElementById(this.fName+"_year").value;
this.month = document.getElementById(this.fName+"_month").value-1;
//alert(this.date)
this.date = d || this.date;
//alert(this.date)
document.getElementById(this.fName+"_year").value = this.year;
document.getElementById(this.fName+"_month").selectedIndex = this.month;
document.getElementById(this.fName+"_date").value = this.date;
if (this.date>new Date(this.year,this.month+1,0).getDate()) this.date = new Date(this.year,this.month+1,0).getDate();
document.getElementById(this.fName+"_dateTable").outerHTML = this.drawDate();
//alert(this.year);
//alert(this.month);
//alert(this.date);
getDateTime();
}
//public
this.getDate = function(delimiter)
{
var s_month,s_date;
s_month=this.month+1;
s_date=this.date;
s_month = ("0"+s_month);
s_month=s_month.substr(s_month.length-2);
s_date = ("0"+s_date);
s_date=s_date.substr(s_date.length-2);
if (!delimiter) delimiter = "-";
var aValue = [this.year,s_month,s_date];
return aValue.join(delimiter);
}
}
function getDateTime(){
//alert(c.getDate()+' '+m.getTime());
gdCtrl.value = c.getDate()+' '+m.getTime();
}
var gdCtrl = new Object();
function showCal(popCtrl){
gdCtrl = popCtrl;
event.cancelBubble=true;
//alert(popCtrl);
var point = fGetXY(popCtrl);
//alert(point.x);
//var point = new Point(100,100);
//alert(gdCtrl.value);
var gdValue=gdCtrl.value;
var i_year,i_month,i_day,i_hour,i_minute;
if(gdCtrl.value!="" && validateDate1(gdCtrl.value,'yyyy-MM-dd HH:mm')){
i_year=gdValue.substr(0,4);
if(gdValue.substr(5,1)=="0"){
i_month=parseInt(gdValue.substr(6,1));
}else{
i_month=parseInt(gdValue.substr(5,2));
}
if(gdValue.substr(8,1)=="0"){
i_day=parseInt(gdValue.substr(9,1));
}else{
i_day=parseInt(gdValue.substr(8,2));
}
i_hour1=gdValue.substr(11,2);
i_minute=gdValue.substr(14,2);
//alert(i_hour1+"aaa");
//alert(i_minute);
document.getElementById(c.fName+"_year").value = i_year;
document.getElementById(c.fName+"_month").value= i_month;
//document.getElementById(c.fName+"_date").value = i_day;
c.date=i_day;
document.getElementsByName(m.fName)[0].value=i_hour1;
document.getElementsByName(m.fName)[1].value=i_minute;
c.redrawDate();
}
//c.month=
with (dateTime.style) {
left = point.x;
top = point.y+popCtrl.offsetHeight+1;
width = dateTime.offsetWidth;
height = dateTime.offsetHeight;
//fToggleTags(point);
visibility = 'visible';
}
dateTime.focus();
}
function Point(iX, iY){
this.x = iX;
this.y = iY;
}
function validateDate1(date,format){
var time=date;
if(time=="") return;
var reg=format;
var reg=reg.replace(/yyyy/,"[0-9]{4}");
var reg=reg.replace(/yy/,"[0-9]{2}");
var reg=reg.replace(/MM/,"((0[1-9])|1[0-2])");
var reg=reg.replace(/M/,"(([1-9])|1[0-2])");
var reg=reg.replace(/dd/,"((0[1-9])|([1-2][0-9])|30|31)");
var reg=reg.replace(/d/,"([1-9]|[1-2][0-9]|30|31))");
var reg=reg.replace(/HH/,"(([0-1][0-9])|20|21|22|23)");
var reg=reg.replace(/H/,"([0-9]|1[0-9]|20|21|22|23)");
var reg=reg.replace(/mm/,"([0-5][0-9])");
var reg=reg.replace(/m/,"([0-9]|([1-5][0-9]))");
var reg=reg.replace(/ss/,"([0-5][0-9])");
var reg=reg.replace(/s/,"([0-9]|([1-5][0-9]))");
reg=new RegExp("^"+reg+"$");
if(reg.test(time)==false){//验证格式是否合法
//alert(alt);
//date.focus();
return false;
}
return true;
}
function fGetXY(aTag){
var oTmp=aTag;
var pt = new Point(0,0);
do {
pt.x += oTmp.offsetLeft;
pt.y += oTmp.offsetTop;
oTmp = oTmp.offsetParent;
} while(oTmp.tagName!="BODY");
return pt;
}
function hideCalendar(){
dateTime.style.visibility = "hidden";
}
</script>
<div id='dateTime' onclick='event.cancelBubble=true' style='position:absolute;visibility:hidden;width:200px;height:100px;left=0px;top=0px;z-index:100;)'>
<table class="cal_table" border='0'><tr><td>
<script> var c = new CalendarCalendar('c');document.write(c);
</script>
</td></tr><tr><td valign='top' align='center'>
<script> var m = new CalendarMinute('m');document.write(m);
</script>
</td></tr></table><iframe src="javascript:false" style="height:200px;" class="menu_iframe"></iframe>
</div>
<SCRIPT event=onclick() for=document>hideCalendar()</SCRIPT>
<!--使用方法<input class="input" type="text" name="bgntime" style="width:120" value="" id="bgntime" onClick="showCal(this);"> -->
| 10npsite | trunk/inc/Calendarguoqi.php | PHP | asf20 | 17,179 |
<?
/*************************
说明:
判断传递的变量中是否含有非法字符
使用方法:1.在需要的地方包含本文件 调用函数FunPostGetFilter() 参数默认为1不显示非法的字符
如$_POST、$_GET
功能:
防注入
**************************/
function turnxinqi($str)
{//转入星期的数字,转换成中文字
switch($str)
{
case 0:
return "日";
case 1:
return "一";
case 2:
return "二";
case 3:
return "三";
case 4:
return "四";
case 5:
return "五";
case 6:
return "六";
}
return "";
}
//检查并返回是否是多床间的标识变量
function isDuoChuang($flag)
{
if(strlen($flag)>3)
{
return 1;
}
else
{
return 0;
}
}
//四舍五入两位小数
function myround($num)
{
if(is_numeric($num))
{
return round($num,2);
}
return 0.00;
}
//是否存在数组中的值
function FunStringExist($StrFiltrate,$ArrFiltrate)
{
foreach ($ArrFiltrate as $key=>$value)
{
if(strstr($StrFiltrate."",$value))
{
return $value;
}
}
return "";
}
//替换前台输入的信息 比如过滤非法字符为"*"
function HtmlReplace($str="")
{
//==========================================
//第一次过滤
global $SystemConest;
$flnum=0;//非法字符串长度
$YMstr="";
$FeFa_array=explode(",",$SystemConest[8]);
foreach($FeFa_array as $valudes)
{
$flnum=mb_strlen($valudes,'gb2312');
for($i=0;$i<$flnum;$i++)
{
$YMstr=$YMstr."*";
}
if(strstr($str,$valudes))
{
$str=str_replace($valudes,$YMstr,$str);
}
$YMstr="";
}
//==========================================
//第二次过滤
return $str;
}
function FunPostGetFilter($ShowType=1)
{
//要过滤的非法字符
global $SystemConest;
$SysFilteringStr=$SystemConest[8];
$ArrFiltrate=explode(",",$SysFilteringStr);
//合并$_POST 和 $_GET
if(function_exists(array_merge))
{
$ArrPostAndGet=array_merge($_GET,$_POST);
}
else
{
foreach($_POST as $key=>$value)
{
$ArrPostAndGet[]=$value;
}
foreach($_GET as $key=>$value)
{
$ArrPostAndGet[]=$value;
}
}
//验证开始
foreach($ArrPostAndGet as $key=>$value)
{
$v1="";
$v1=FunStringExist($value,$ArrFiltrate);
if ($v1!="")
{
if($ShowType==1)
{
echo "<script language='javascript'>alert('信息中不得包含非法字符');</script>";
}
else
{
echo "<script language='javascript'>alert('信息中不得包含非法字符:".$v1."');</script>";
}
echo "<script language='javascript'>history.go(-1);</script>";
exit;
}
}
}
/***************结束防止PHP注入*****************/
//计算两时间的差_传入的值必须时数字
function difftime_i($endtime,$starttime,$type="1")
{
//返回两时间的相差天数
return round(($endtime-$starttime)/3600/24);
}
//计算两时间的差
function difftime($endtime,$starttime,$type="1")
{
if($type=="1")
{//返回两时间的相差天数
return round((strtotime($endtime)-strtotime($starttime))/3600/24);
}
if($type=="4")
{//返回两时间的相差天数
return (strtotime($endtime)-strtotime($starttime))/3600/24;
}
if($type=="3")
{//返回两时间的相差秒数
return strtotime($endtime)-strtotime($starttime);
}
if($type=="2")
{//返回两时间的相差天数 如21天12小时 21分
$past = strtotime($starttime); // Some timestamp in the past
$now = strtotime($endtime); // Current timestamp
$time = $now - $past;
$year = floor($time / 60 / 60 / 24 / 365);
$time -= $year * 60 * 60 * 24 * 365;
$month = floor($time / 60 / 60 / 24 / 30);
$time -= $month * 60 * 60 * 24 * 30;
$week = floor($time / 60 / 60 / 24 / 7);
$time -= $week * 60 * 60 * 24 * 7;
$day = floor($time / 60 / 60 / 24);
$time -= $day * 60 * 60 * 24;
$hour = floor($time / 60 / 60);
$time -= $hour * 60 * 60;
$minute = floor($time / 60);
$time -= $minute * 60;
$second = $time;
$elapse = "";
$unitArr = array('年' =>'year', '个月'=>'month', '周'=>'week', '天'=>'day',
'小时'=>'hour', '分钟'=>'minute', '秒'=>'second'
);
foreach ( $unitArr as $cn => $u )
{
if($$u>0)
{
$elapse=$elapse. $$u . $cn;
}
}
return $elapse;
}
return 0;
}
function gbk2utf8($str)
{
return iconv("gbk","UTF-8",$str);
}
function utf82gbk($str)
{
return iconv("UTF-8","gbk",$str);
}
//把数字格式的字符串转换成数字,若字符串为空或不是数字型的则返回0
function strtoint($str)
{
if($str!="" and is_numeric($str))
{
return (int)$str;
}
else
{
return 0;
}
}
//检查传入的字符串是否是数字字符串,是的话返回true,反之反回false 当为空时返回flase
function CheckisNumber($str)
{
if($str=="" or $str==null ) return false;
if(is_numeric($str))return true;
return false;
}
/**
* 人民币和美元互换,默认是人民币转换成美元,
* @param $num 互换的金额
* @param $type 默认是r 表示是将美元转换成美元,当值是d时,表示是将美元换成人民币.
* @return 失败将返回false
*/
function RmbToDols($numi,$type="r")
{
global $Exchangerate;
$hl=$Exchangerate["dol"];
if($type=="r")
{
return round($numi,2);
}
if($type=="d")
{
return round(($hl * $numi),2);
}
}
/**
获取美元转人民币的汇率
*/
function RmbToDolsHuilv()
{
global $Exchangerate;
return $Exchangerate["dol"];
}
/**
显示信息
* @param $num 金额
* @param $type 显示的币种
*/
function showmoney($num,$type)
{
if($type=="rmb")
{
return "¥".RmbToDols($num,"d");;
}
if($type=="dol")
{
return "$".$num;
}
}
/**
* 根据周期的不同,显示不同的价格形式
* @param $zhouqi 周期值
* @param $indate 时间有效范围
* @param $anydate 任意时间
*/
function formatpriceshow($zhouqi,$indate,$anydate,$jutidate)
{
if($zhouqi=="每周")
{
//return $indate;
return preg_replace("/,周/",",",$jutidate);;
}
if($zhouqi=="任意")
{
$arr=explode(",", $anydate);
sort($arr);
return implode("<br>", $arr);
//return $anydate;
}
if($zhouqi=="每天")
{
return $indate;
}
}
/**
* 防止页面刷新
*/
function notreflash()
{
$allow_sep = "99999999";
if (isset($_SESSION["post_sep"]))
{
if (time() - $_SESSION["post_sep"] < $allow_sep)
{
exit("请不要反复刷新");
}
else
{
$_SESSION["post_sep"] = time();
}
}
else
{
$_SESSION["post_sep"] = time();
}
}
/**
* 获取一个评论类别的值 或相似格式的字
* @param $str 源字符串 如"预定|2|客服|1"
* @param $str1 目录值名 如"预定"
*/
function formpl($str,$str1)
{
preg_match("/".$str1."\|[0-9]{1}/",$str,$a1);
return str_replace($str1."|", "", $a1[0]);
}
/**
* 根据评论的选择值生成单选按纽
*/
function createplradio($spanname,$v)
{
if($v==2) $t1="checked";
if($v==1) $t2="checked";
if($v==0) $t3="checked";
$pjarrstr=" <input name='".$spanname."' value='2' type='radio' $t1 />满意 ";
$pjarrstr=$pjarrstr." <input name='".$spanname."' value='1' type='radio' $t2 />一般 ";
$pjarrstr=$pjarrstr." <input name='".$spanname."' value='0' type='radio' $t3 />不满意";
return $pjarrstr;
}
/**
* 循环建立文件夹
* @param $dir 路径要求传入物理路径
* @param $mode 权限模板,默认具有读写权限
*/
function mkdirs($dir, $mode = 0777){
if (is_dir($dir) || @mkdir($dir, $mode))
return true;
if (!mkdirs(dirname($dir), $mode))
return false;
return @mkdir($dir, $mode);
}
?>
| 10npsite | trunk/inc/Function.Libary.php | PHP | asf20 | 8,067 |
<?php require "../global.php";
require_once RootDir."/"."inc/config.php";
require_once RootDir."/"."inc/Uifunction.php";
require_once RootDir."/"."inc/Function.Libary.php";
require_once RootDir."/".$SystemConest[1]."/system/Config.php";
require_once RootDir."/".$SystemConest[1]."/UIFunction/adminClass.php";
require_once RootDir."/".$SystemConest[1]."/system/menusys/function.php";
require_once RootDir."/".$SystemConest[1]."/system/classsys/function.php";
?>
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="/Public/jsLibrary/Jslibary.js"></script>
<style>
body,td{font-size:12px;}
.spanplace{display:none;}
.xztdbgc{background-color:#FFDD99;}
</style>
<?php
$tid=$_REQUEST["tid"];//记录id
$hid=$_REQUEST["hid"];//客栈id
$fieldid=$_REQUEST["fieldid"];//存的值的字段id
$action=$_REQUEST["action"];//保存操作当是
if(!is_numeric($tid) or !is_numeric($fieldid)) die("传入参数不对");
$mydb=new YYBDB();
$TableName=$mydb->getTableName($MenuId);
$thismonth=$_REQUEST["thismonth"];//本月值
//规定值格式
/*
存放后值如下:
时间值(2012-09-04)|市场价|梦之旅|房差价|库存量,时间值2(2012-09-05)|市场价2|梦之旅2|房差价2|库存量2,............
*/
//获取这个月的日期值
$sql="select ".$TableName.$fieldid." from ".DQ.$TableName." where ".$TableName."0=".$tid."";
$rsc=$mydb->db_query($sql);
$rs=$mydb->db_fetch_array($rsc);
$valv="";
if($rs) $valv=$rs[0];
$datecontent=$valv;
//==================================================保存修后的值
if($action=="saved"){
$checkeddatev=$_REQUEST["checkeddatev"];//要更改的日期值
$market_price=$_REQUEST["market_price"];//市场价
$mzl_price=$_REQUEST["mzl_price"];//本站价
$fangcha=$_REQUEST["fangcha"];//房差
$kucun=$_REQUEST["kucun"];//库存
if(strlen($checkeddatev)<3) die("没有选择日期");
//格式化要存入的数据格式
$checkeddatev=preg_replace("/([\d]{4}\-[\d]{1,2}\-[\d]{1,2})/","$1|".$market_price."|".$mzl_price."|".$fangcha."|".$kucun,$checkeddatev);
//合并以前的数据
preg_match_all("/[\d]{4}\-[\d]{1,2}\-[\d]{1,2}\|[\d]+\|[\d]+\|[\d]+\|[\d]+/",$datecontent,$tarr);
foreach($tarr[0] as $v){
$temp=preg_replace("/\|[\|\d]+/","",$v);
if(!strstr($checkeddatev,$temp)) $checkeddatev.=",".$v;
}
$sql="update ".DQ.$TableName." set ".$TableName.$fieldid."='".$checkeddatev."' where ".$TableName."0=".$tid."";
$rsc2=$mydb->db_query($sql);
$tnum=$mydb->db_affected_rows();
$turl="?MenuId=".$MenuId."&fieldid=".$fieldid."&tid=".$tid."&thismonth=".$thismonth."&hid=".$_REQUEST["hid"]."&PMID=".$_REQUEST["PMID"];
if($tnum>0){
file_get_contents($SYS_config["siteurl"]."/guanli/u.php/hotelroom/updateurlpricemin/hid/".$hid);
alert($turl,2,"更改成功!");
}else{
alert($turl,2,"更改失败!");
}
die;
}
if($thismonth=="") $thismonth=date("Y-m");
$thefirstdayofweek=date('w',strtotime($thismonth."-01"));//本月第一天是星期几
//如果这个月的第一天不是星期一,那么,它的前面就以上一个月的补齐
//获取前上一个月的日期,以这个月的第一天为基准
function getqiandate($datestr,$num){
return date("Y-m-d",strtotime($datestr)-$num*3600*24);
}
//获取前一个月的日期,返回值是2012-09
function getqimonth($thismonth){
$yearn=preg_replace("/\-[\d]{1,2}$/","",$thismonth);
$month=preg_replace("/^[\d]{4}\-[0]*/","",$thismonth);
$nowmonth=($month==1)?12:$month-1;
if($month==1){
$nowmonth=12;
$yearn=$yearn-1;
}
else{
$nowmonth=$month-1;
}
return $yearn."-".substr("0".$nowmonth,-2);
}
//获取后一个月的日期
function getnextmonth($thismonth){
$yearn=preg_replace("/\-[\d]{1,2}$/","",$thismonth);
$month=preg_replace("/^[\d]{4}\-[0]*/","",$thismonth);
if($month==12){
$month=1;
$yearn+=1;
}
else{
$month+=1;
}
return $yearn."-".substr("0".$month,-2);
}
$qianbunum=$thefirstdayofweek==0?6:$thefirstdayofweek-1;//前面要补的天数
$monthmaxnum=date("t",strtotime($thismonth."-01"));//这个月有多少天
$lastbunum=7-($monthmaxnum+$qianbunum) % 7;
$lastbunum=$lastbunum==7?0:$lastbunum;//获取后面需要被的天数
//计算这次要循环的次数
$maxfornum=$qianbunum+$lastbunum+$monthmaxnum;
//获取本次的开始天数
$stardate= getqiandate($thismonth,$qianbunum);
?>
<a href="/guanli/u.php/hotelroom/listroom/MenuId/<?php echo $_REQUEST["MenuId"]?>/hid/<? echo $hid;?>/PMID/<? echo $hid;?>">返回房形管理</a>
<br>
批量设置<input type="checkbox" id="piliang">
<div>
<div style="float:left; width:510px;">
<table width="480" border="1" cellspacing="0" cellpadding="0" bordercolor="#ccc" style="border-collapse:collapse">
<tr>
<td height="37" colspan="7" align="center"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="37%" height="27"><a href="?MenuId=<? echo $MenuId;?>&fieldid=<? echo $fieldid;?>&hid=<? echo $hid;?>&tid=<? echo $tid;?>&thismonth=<?php $pmonth= getqimonth($thismonth);echo $pmonth; ?>"><?php echo preg_replace("/^[\d]{4}\-[0]*/","",$pmonth);?>月</a></td>
<td width="27%"><strong><?php echo str_replace("-","年",$thismonth)."月";?></strong><span class="spanplace" id="placeall">全选<input type="checkbox" id="cpall"></span></td>
<td width="36%" align="right"><a href="?MenuId=<? echo $MenuId;?>&fieldid=<? echo $fieldid;?>&hid=<? echo $hid;?>&tid=<? echo $tid;?>&thismonth=<?php $nmonth= getnextmonth($thismonth);echo $nmonth;?>"><?php echo preg_replace("/^[\d]{4}\-[0]*/","",$nmonth);?>月</a></td>
</tr>
</table></td>
</tr>
<tr>
<td width="11%" height="37" align="center">一<span class="spanplace" id="place1"><input type="checkbox" id="cpz1"></span></td>
<td width="14%" align="center">二<span class="spanplace" id="place2"><input type="checkbox" id="cpz2"></span></td>
<td width="13%" align="center">三<span class="spanplace" id="place3"><input type="checkbox" id="cpz3"></span></td>
<td width="13%" align="center">四<span class="spanplace" id="place4"><input type="checkbox" id="cpz4"></span></td>
<td width="15%" align="center">五<span class="spanplace" id="place5"><input type="checkbox" id="cpz5"></span></td>
<td width="15%" align="center">六<span class="spanplace" id="place6"><input type="checkbox" id="cpz6"></span></td>
<td width="19%" align="center">日<span class="spanplace" id="place0"><input type="checkbox" id="cpz0"></span></td>
</tr>
<?php
$zcthismonth=turntostrtozc($thismonth);
preg_match_all("/".$zcthismonth."\-[\d]{1,2}\|[\d\.]+\|[\d\.]+\|[\d]*\|[\d]+/",$datecontent,$datecontentarr);//只获取本月的日期值
$dcontentarr=array();//存放本月分解的数值
foreach($datecontentarr[0] as $k=>$v){
$varr=explode("|",$v);
$dcontentarr[$varr[0]][1]=$varr[1];
$dcontentarr[$varr[0]][2]=$varr[2];
$dcontentarr[$varr[0]][3]=$varr[3];
$dcontentarr[$varr[0]][4]=$varr[4];
}
for($i=1;$i<=$maxfornum;$i++){
$thisv=date("Y-m-d",strtotime($stardate)+($i-1)*3600*24);
if($i %7 ==1){
?> <tr><?php }?>
<td width="11%" align="left" valign="top" height="50"
<?php if(strstr($thisv,$thismonth)=="" or date("Y-m")>$thismonth){
echo "style='background-color:#E6DFDF'";}
else{
echo "data='".$thisv."|".$dcontentarr[$thisv][1]."|".$dcontentarr[$thisv][2]."|".$dcontentarr[$thisv][3]."|".$dcontentarr[$thisv][4]."' week='".date("w",strtotime($thisv))."'";
}
?>
class="">
<div style="width:100%;height:20px;">
<div style="float:left;"><span style="margin-top:15px; margin-left:5px; color: #396; font-size:14px;"><?php echo preg_replace("/^[\d]{4}\-[\d]{1,2}\-[0]*/","",$thisv);?></span>
</div>
<?php if($dcontentarr[$thisv]){?>
<div style="float:right;"><span style="color:333; margin-right:5px;">0/<?php echo $dcontentarr[$thisv][4];?></span></div>
<?php }?>
</div>
<?php if($dcontentarr[$thisv]){?>
<div style="width:100%;">
<span style="color:#999">市:¥<?php echo $dcontentarr[$thisv][1];?></span><br>
<span>梦:¥<?php echo $dcontentarr[$thisv][2];?></span>
</div>
<?php }?>
</td>
<?php if($i % 7==0){?> </tr><?php }?>
<?php
}
?>
</table>
</div>
<div style="float:left; width:200px; overflow:hidden;">
<table width="94%" border="1" cellspacing="0" cellpadding="0" bordercolor="#ccc" style="border-collapse:collapse">
<form action="?action=saved&thismonth=<? echo $thismonth;?>" method="post" name="formsubmit">
<input type="hidden" id="checkeddatev" name="checkeddatev" value="">
<input type="hidden" id="MenuId" name="MenuId" value="<?php echo $MenuId;?>">
<input type="hidden" id="tid" name="tid" value="<?php echo $tid;?>">
<input type="hidden" id="hid" name="hid" value="<?php echo $hid;?>">
<input type="hidden" id="PMID" name="PMID" value="<?php echo $hid;?>">
<input type="hidden" id="fieldid" name="fieldid" value="<?php echo $fieldid;?>">
<tr>
<td height="28" colspan="2" align="center">价格/库存设置</td>
</tr>
<tr>
<td height="29" align="right" >市 场 价:</td>
<td >
<input type="text" name="market_price" id="market_price" size="12"/>
<span style="color:#F00">*</span></td>
</tr>
<tr>
<td height="34" align="right" >本 站 价:</td>
<td ><input type="text" name="mzl_price" id="mzl_price" size="12"/>
<span style="color:#F00">*</span></td>
</tr>
<tr>
<td height="27" align="right" >房 差:</td>
<td ><input type="text" name="fangcha" id="fangcha" size="12"/></td>
</tr>
<tr>
<td height="32" align="right" >可预定房间:</td>
<td ><input type="text" name="kucun" id="kucun" size="12"/>
<span style="color:#F00">*</span></td>
</tr>
<tr>
<td height="30" > </td>
<td ><input type="submit" name="mysubmit" id="mysubmit" value="设 置" /> <input type="button" name="mysreset" id="mysreset" value="重 置" /></td>
</tr>
<tr>
</tr>
</form>
</table>
</div>
</div>
<script language="javascript">
$(document).ready(function(){
//绑定批量设置的事件
$("#piliang").bind("click", function(){
if($("#piliang").attr("checked")=="checked"){
$("span[id^='place']").show();
}else{
$("span[id^='place']").hide();
}
});
//绑定全选事件的功能
$("#cpall").bind("click",function(){
if($("#cpall").attr("checked")=="checked"){
$("input[id^='cpz']").attr("checked","checked");
$("td[week]").addClass("xztdbgc");
}else{
$("input[id^='cpz']").removeAttr("checked");
$("td[week]").removeClass();
}
});
//给选定每周的一天绑定事件
$("input[id^='cpz']").bind("click", function(){
id=$(this).attr("id");
id=id.replace("cpz","");
if($(this).attr("checked")=="checked"){
$("td[week^='"+id+"']").addClass("xztdbgc");
$("td[week^='"+id+"']").each(function(){
adddatetoseleed(this);
});
}
else{
$("td[week^='"+id+"']").removeClass();
$("td[week^='"+id+"']").each(function(){
deleteofseleed(this);
});
}
});
//给每一天绑定事件
$("td[data]").bind("click",function(){
classname=$(this).attr("class");
if(classname=="xztdbgc"){
$(this).removeClass();
deleteofseleed(this);
}
else{
$(this).addClass("xztdbgc");
adddatetoseleed(this);
}
//如果本月选定的只有一天时,在填写价格处写上这一天的价格
chooesv=$("#checkeddatev").val();
if(chooesv.match(/^,[\d]{4}\-[\d]{1,2}\-[\d]{1,2}$/)){
chooesv=chooesv.replace(",","");
$("td[data^='"+chooesv+"']").each(function(){
data=$(this).attr("data");
if(data!=""){
dataarr=data.split("|");
if(dataarr.length==5){
$("#market_price").val(dataarr[1]);
$("#mzl_price").val(dataarr[2]);
$("#fangcha").val(dataarr[3]);
$("#kucun").val(dataarr[4]);
}
}
});
}
else{
$("#market_price").val("");
$("#mzl_price").val("");
$("#fangcha").val("");
$("#kucun").val("");
}
});
//绑定设置价格按钮功能
$("#mysubmit").bind("click",function(){
if(!nzeletype("market_price","请输入市场价","float")) return false;
if(!nzeletype("mzl_price","请输入梦之旅价","float")) return false;
if($("#mzl_price").val()>$("#market_price").val()){
//alert("梦之旅价不能大于市场价");
//$("#mzl_price").val("");
//$("#mzl_price").focus();
//return false;
}
if(!nzeletype("kucun","请输入库存数量","int")) return false;
});
//=============================================提交验证
$("#mysubmit").bind("click",function(){
checkeddatev=$("#checkeddatev").val();
if(checkeddatev.length<2){
alert("你至少要选择一天");
return false;
}
market_price=$("#market_price").val();
if(!market_price.match(/^[\d\.]+$/) || market_price=="."){
alert("请填写正确的市场价");
$("#market_price").focus();
return false;
}
mzl_price=$("#mzl_price").val();
if(!mzl_price.match(/^[\d\.]+$/) || mzl_price=="."){
alert("请填写正确的本站价");
$("#mzl_price").focus();
return false;
}
if(parseInt(mzl_price)>parseInt(market_price)){
//alert("本站价不能高于市场价");
//$("#mzl_price").focus();
//return false;
}
fangcha=$("#fangcha").val();
if(!fangcha.match(/^[\d\.]+$/) || fangcha=="."){
alert("请填写正确的房差价");
$("#fangcha").focus();
return false;
}
kucun=$("#kucun").val();
if(!kucun.match(/^[\d]+$/) ){
alert("请填写正确的可预定房间数");
$("#kucun").focus();
return false;
}
return true;
});
});
//给当前值加入到已经选择到的值里
function adddatetoseleed(strdate){
data=$(strdate).attr("data");
data=data.match(/^[\d]{4}\-[\d]{1,2}\-[\d]{1,2}/);
tv=$("#checkeddatev").val();
if(tv.indexOf(data)<1) $("#checkeddatev").val(tv+","+data);
}
//给当前值从已经选择到的值里删除
function deleteofseleed(strdate){
data=$(strdate).attr("data");
data=data.match(/^[\d]{4}\-[\d]{1,2}\-[\d]{1,2}/);
tv=$("#checkeddatev").val();
tv=tv.replace(","+data,"")
$("#checkeddatev").val(tv);
}
</script> | 10npsite | trunk/inc/calendarprice.php | PHP | asf20 | 14,748 |
<style>
.menu_iframe{position:absolute; visibility:inherit; top:0px; left:0px; width:170px; z-index:-1; filter: Alpha(Opacity=0);}
.cal_table{ border:#333333 solid 1px; border-collapse:collapse; background:#ffffff; font-size:12px}
.cal_drawdate{ background:#E3EBF6;border-collapse:collapse; width:100%}
.cal_drawdate td{ border:1px #ffffff solid; }
.cal_drawtime{ border:0px #ffffff solid; font-size:12px}
.cal_drawdate td{ border:0px #ffffff solid; }
.m_fieldset {
padding: 0,10,5,10;
text-align: center;
width: 150px;
}
.m_legend {
font-family: Tahoma;
font-size: 11px;
padding-bottom: 5px;
}
.m_frameborder {
border-left: 1px inset #D4D0C8;
border-top: 1px inset #D4D0C8;
border-right: 1px inset #D4D0C8;
border-bottom: 1px inset #D4D0C8;
width: 35px;
height: 19px;
background-color: #FFFFFF;
overflow: hidden;
text-align: right;
font-family: "Tahoma";
font-size: 10px;
}
.m_arrow {
width: 16px;
height: 8px;
background:#cccccc;
font-family: "Webdings";
font-size: 7px;
line-height: 2px;
padding-left: 2px;
cursor: default;
}
.m_input {
width: 12px;
height: 14px;
border: 0px solid black;
font-family: "Tahoma";
font-size: 9px;
text-align: right;
}
.c_fieldset {
padding: 0,10,5,10;
text-align: center;
width: 180px;
}
.c_legend {
font-family: Tahoma;
font-size: 11px;
padding-bottom: 5px;
}
.c_frameborder {
border-left: 1px #D4D0C8;
border-top: 1px #D4D0C8;
border-right: 1px #FFFFFF;
border-bottom: 1px #FFFFFF;
background-color: #FFFFFF;
overflow: hidden;
font-family: "Tahoma";
font-size: 10px;
width:100%;
height:120px;
}
.c_frameborder td {
width: 23px;
height: 16px;
font-family: "Tahoma";
font-size: 11px;
text-align: center;
cursor: default;
}
.c_frameborder .selected {
background-color:#0A246A;
width:12px;
height:12px;
color:white;
display:block;
}
.c_frameborder span {
width:12px;
height:12px;
}
.c_arrow {
width: 16px;
height: 8px;
background:#cccccc;
font-family: "Webdings";
font-size: 7px;
line-height: 2px;
padding-left: 2px;
cursor: default;
}
.c_year {
font-family: "Tahoma";
font-size: 11px;
cursor: default;
width:55px;
height:20px;
border:#99B2D3 solid 1px;
}
.c_month {
width:75px;
height:20px;
font:11px "Tahoma";
border:#99B2D3 solid 1px;
}
.c_dateHead {
background-color:#99B2D3;
color:#ffffff;
border-collapse:collapse;
}
.c_dateHead td{ border:0px #ffffff solid; }
.rightmenu{
float:left; /* 菜单总体水平位置 */
list-style:none;
line-height:19px; /* 一级菜单高 */
background:#1371A0 ; /* 所有菜单移出色 */
font-weight: bold;
padding:0px;
margin:0px;
border: 1px #000000 solid;
}
.rightmenu li{
float:left; /* 菜单总体水平位置 */
list-style:none;
line-height:19px; /* 一级菜单高 */
background:#1371A0 ; /* 所有菜单移出色 */
font-weight: bold;
color:#FFFFFF;
padding:0px;
margin:0px;
border: 1px #FFFFFF solid;
}
.rightmenu li a{
float:left; /* 菜单总体水平位置 */
list-style:none;
line-height:19px; /* 一级菜单高 */
background:#1371A0 ; /* 所有菜单移出色 */
font-weight: bold;
color:#FFFFFF !important;
padding:0px;
margin:0px;
border-right: 0px;
display:block;
width:80px;
}
.rightmenu li a:hover{
float:left; /* 菜单总体水平位置 */
list-style:none;
line-height:19px; /* 一级菜单高 */
background:#B2CFDF ; /* 所有菜单移出色 */
font-weight: bold;
color:#000000 !important;
padding:0px;
margin:0px;
border-right: 0px;
width:80px;
text-decoration:none;
}
</style>
<script>
function CalendarMinute(name,fName)
{
this.name = name;
this.fName = fName || "m_input";
this.timer = null;
this.fObj = null;
this.toString = function()
{
var objDate = new Date();
var sMinute_Common = "class=\"m_input\" maxlength=\"2\" name=\""+this.fName+"\" onfocus=\""+this.name+".setFocusObj(this)\" onblur=\""+this.name+".setTime(this)\" onkeyup=\""+this.name+".prevent(this)\" onkeypress=\"if (!/[0-9]/.test(String.fromCharCode(event.keyCode)))event.keyCode=0\" onpaste=\"return false\" ondragenter=\"return false\"";
var sButton_Common = "class=\"m_arrow\" onfocus=\"this.blur()\" onmouseup=\""+this.name+".controlTime()\" disabled"
var str = "";
str += "<table class=\"cal_drawtime\" cellspacing=\"0\" cellpadding=\"0\" border=>"
str += "<tr>"
str += "<td>"
str += "请选择时间:"
str += "</td>"
str += "<td>"
str += "<div class=\"m_frameborder\">"
str += "<input radix=\"24\" value=\""+this.formatTime(objDate.getHours())+"\" "+sMinute_Common+">:"
str += "<input radix=\"60\" value=\""+this.formatTime(objDate.getMinutes())+"\" "+sMinute_Common+">"
//str += "<input radix=\"60\" value=\""+this.formatTime(objDate.getSeconds())+"\" "+sMinute_Common+">"
str += "</div>"
str += "</td>"
str += "<td>"
str += "<table class=\"cal_drawtime\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"
str += "<tr><td><button id=\""+this.fName+"_up\" "+sButton_Common+">5</button></td></tr>"
str += "<tr><td><button id=\""+this.fName+"_down\" "+sButton_Common+">6</button></td></tr>"
str += "</table>"
str += "</td>"
str += "</tr>"
str += "</table>"
return str;
}
this.play = function()
{
this.timer = setInterval(this.name+".playback()",1000);
}
this.formatTime = function(sTime)
{
sTime = ("0"+sTime);
return sTime.substr(sTime.length-2);
}
this.playback = function()
{
var objDate = new Date();
var arrDate = [objDate.getHours(),objDate.getMinutes(),objDate.getSeconds()];
var objMinute = document.getElementsByName(this.fName);
for (var i=0;i<objMinute.length;i++)
{
objMinute[i].value = this.formatTime(arrDate[i])
}
}
this.prevent = function(obj)
{
clearInterval(this.timer);
this.setFocusObj(obj);
var value = parseInt(obj.value,10);
var radix = parseInt(obj.radix,10)-1;
if (obj.value>radix||obj.value<0)
{
obj.value = obj.value.substr(0,1);
}
}
this.controlTime = function(cmd)
{
event.cancelBubble = true;
if (!this.fObj) return;
clearInterval(this.timer);
var cmd = event.srcElement.innerText=="5"?true:false;
var i = parseInt(this.fObj.value,10);
var radix = parseInt(this.fObj.radix,10)-1;
if (i==radix&&cmd)
{
i = 0;
}
else if (i==0&&!cmd)
{
i = radix;
}
else
{
cmd?i++:i--;
}
this.fObj.value = this.formatTime(i);
this.fObj.select();
getDateTime();
}
this.setTime = function(obj)
{
obj.value = this.formatTime(obj.value);
}
this.setFocusObj = function(obj)
{
eval(this.fName+"_up").disabled = eval(this.fName+"_down").disabled = false;
this.fObj = obj;
}
this.getTime = function()
{
var arrTime = new Array(2);
for (var i=0;i<document.getElementsByName(this.fName).length;i++)
{
arrTime[i] = document.getElementsByName(this.fName)[i].value;
//alert(arrTime[i]);
}
return arrTime.join(":");
}
}
// Written by cloudchen, 2004/03/16
function CalendarCalendar(name,fName)
{
this.name = name;
this.fName = fName || "calendar";
this.year = new Date().getFullYear();
this.month = new Date().getMonth();
this.date = new Date().getDate();
//alert(this.month);
//private
this.toString = function()
{
var str = "";
str += "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" onselectstart=\"return false\">";
str += "<tr>";
str += "<td>";
str += this.drawMonth();
str += "</td>";
str += "<td align=\"right\">";
str += this.drawYear();
str += "</td>";
str += "</tr>";
str += "<tr>";
str += "<td colspan=\"2\">";
str += "<div class=\"c_frameborder\">";
str += "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"c_dateHead\">";
str += "<tr>";
str += "<td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td>";
str += "</tr>";
str += "</table>";
str += this.drawDate();
str += "</div>";
str += "</td>";
str += "</tr>";
str += "</table>";
return str;
}
//private
this.drawYear = function()
{
var str = "";
str += "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
str += "<tr>";
str += "<td>";
str += "<input class=\"c_year\" maxlength=\"4\" value=\""+this.year+"\" name=\""+this.fName+"\" id=\""+this.fName+"_year\" readonly>";
//DateField
str += "<input type=\"hidden\" name=\""+this.fName+"\" value=\""+this.date+"\" id=\""+this.fName+"_date\">";
str += "</td>";
str += "<td>";
str += "<table cellspacing=\"2\" cellpadding=\"0\" border=\"0\">";
str += "<tr>";
str += "<td><button class=\"c_arrow\" onfocus=\"this.blur()\" onclick=\"event.cancelBubble=true;document.getElementById('"+this.fName+"_year').value++;"+this.name+".redrawDate()\">5</button></td>";
str += "</tr>";
str += "<tr>";
str += "<td><button class=\"c_arrow\" onfocus=\"this.blur()\" onclick=\"event.cancelBubble=true;document.getElementById('"+this.fName+"_year').value--;"+this.name+".redrawDate()\">6</button></td>";
str += "</tr>";
str += "</table>";
str += "</td>";
str += "</tr>";
str += "</table>";
return str;
}
//priavate
this.drawMonth = function()
{ //alert(this.fName);
var aMonthName = ["一","二","三","四","五","六","七","八","九","十","十一","十二"];
var str = "";
str += "<select class=\"c_month\" name=\""+this.fName+"\" id=\""+this.fName+"_month\" onchange=\""+this.name+".redrawDate()\">";
for (var i=0;i<aMonthName.length;i++) {
str += "<option value=\""+(i+1)+"\" "+(i==this.month?"selected":"")+">"+aMonthName[i]+"月</option>";
}
str += "</select>";
return str;
}
//private
this.drawDate = function()
{
var str = "";
var fDay = new Date(this.year,this.month,1).getDay();
var fDate = 1-fDay;
var lDay = new Date(this.year,this.month+1,0).getDay();
var lDate = new Date(this.year,this.month+1,0).getDate();
str += "<table class=\"cal_drawdate\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" id=\""+this.fName+"_dateTable"+"\">";
for (var i=1,j=fDate;i<7;i++)
{
str += "<tr>";
for (var k=0;k<7;k++)
{
str += "<td><span"+(j==this.date?" class=\"selected\"":"")+" onclick=\""+this.name+".redrawDate(this.innerText)\">"+(isDate(j++))+"</span></td>";
}
str += "</tr>";
}
str += "</table>";
return str;
function isDate(n)
{
return (n>=1&&n<=lDate)?n:"";
}
}
//public
this.redrawDate = function(d)
{
this.year = document.getElementById(this.fName+"_year").value;
this.month = document.getElementById(this.fName+"_month").value-1;
//alert(this.date)
this.date = d || this.date;
//alert(this.date)
document.getElementById(this.fName+"_year").value = this.year;
document.getElementById(this.fName+"_month").selectedIndex = this.month;
document.getElementById(this.fName+"_date").value = this.date;
if (this.date>new Date(this.year,this.month+1,0).getDate()) this.date = new Date(this.year,this.month+1,0).getDate();
document.getElementById(this.fName+"_dateTable").outerHTML = this.drawDate();
//alert(this.year);
//alert(this.month);
//alert(this.date);
getDateTime();
}
//public
this.getDate = function(delimiter)
{
var s_month,s_date;
s_month=this.month+1;
s_date=this.date;
s_month = ("0"+s_month);
s_month=s_month.substr(s_month.length-2);
s_date = ("0"+s_date);
s_date=s_date.substr(s_date.length-2);
if (!delimiter) delimiter = "-";
var aValue = [this.year,s_month,s_date];
return aValue.join(delimiter);
}
}
function getDateTime(){
//alert(c.getDate()+' '+m.getTime());
gdCtrl.value = c.getDate()+' '+m.getTime();
}
var gdCtrl = new Object();
function showCal(popCtrl){
gdCtrl = popCtrl;
event.cancelBubble=true;
//alert(popCtrl);
var point = fGetXY(popCtrl);
//alert(point.x);
//var point = new Point(100,100);
//alert(gdCtrl.value);
var gdValue=gdCtrl.value;
var i_year,i_month,i_day,i_hour,i_minute;
if(gdCtrl.value!="" && validateDate1(gdCtrl.value,'yyyy-MM-dd HH:mm')){
i_year=gdValue.substr(0,4);
if(gdValue.substr(5,1)=="0"){
i_month=parseInt(gdValue.substr(6,1));
}else{
i_month=parseInt(gdValue.substr(5,2));
}
if(gdValue.substr(8,1)=="0"){
i_day=parseInt(gdValue.substr(9,1));
}else{
i_day=parseInt(gdValue.substr(8,2));
}
i_hour1=gdValue.substr(11,2);
i_minute=gdValue.substr(14,2);
//alert(i_hour1+"aaa");
//alert(i_minute);
document.getElementById(c.fName+"_year").value = i_year;
document.getElementById(c.fName+"_month").value= i_month;
//document.getElementById(c.fName+"_date").value = i_day;
c.date=i_day;
document.getElementsByName(m.fName)[0].value=i_hour1;
document.getElementsByName(m.fName)[1].value=i_minute;
c.redrawDate();
}
//c.month=
with (dateTime.style) {
left = point.x;
top = point.y+popCtrl.offsetHeight+1;
width = dateTime.offsetWidth;
height = dateTime.offsetHeight;
//fToggleTags(point);
visibility = 'visible';
}
dateTime.focus();
}
function Point(iX, iY){
this.x = iX;
this.y = iY;
}
function validateDate1(date,format){
var time=date;
if(time=="") return;
var reg=format;
var reg=reg.replace(/yyyy/,"[0-9]{4}");
var reg=reg.replace(/yy/,"[0-9]{2}");
var reg=reg.replace(/MM/,"((0[1-9])|1[0-2])");
var reg=reg.replace(/M/,"(([1-9])|1[0-2])");
var reg=reg.replace(/dd/,"((0[1-9])|([1-2][0-9])|30|31)");
var reg=reg.replace(/d/,"([1-9]|[1-2][0-9]|30|31))");
var reg=reg.replace(/HH/,"(([0-1][0-9])|20|21|22|23)");
var reg=reg.replace(/H/,"([0-9]|1[0-9]|20|21|22|23)");
var reg=reg.replace(/mm/,"([0-5][0-9])");
var reg=reg.replace(/m/,"([0-9]|([1-5][0-9]))");
var reg=reg.replace(/ss/,"([0-5][0-9])");
var reg=reg.replace(/s/,"([0-9]|([1-5][0-9]))");
reg=new RegExp("^"+reg+"$");
if(reg.test(time)==false){//验证格式是否合法
//alert(alt);
//date.focus();
return false;
}
return true;
}
function fGetXY(aTag){
var oTmp=aTag;
var pt = new Point(0,0);
do {
pt.x += oTmp.offsetLeft;
pt.y += oTmp.offsetTop;
oTmp = oTmp.offsetParent;
} while(oTmp.tagName!="BODY");
return pt;
}
function hideCalendar(){
dateTime.style.visibility = "hidden";
}
</script>
<div id='dateTime' onclick='event.cancelBubble=true' style='position:absolute;visibility:hidden;width:100px;height:100px;left=0px;top=0px;z-index:100;)'>
<table class="cal_table" border='0'><tr><td>
<script> var c = new CalendarCalendar('c');document.write(c);
</script>
</td></tr><tr><td valign='top' align='center'>
<script> var m = new CalendarMinute('m');document.write(m);
</script>
</td></tr></table><iframe src="javascript:false" style="height:200px;" class="menu_iframe"></iframe>
</div>
<SCRIPT event=onclick() for=document>hideCalendar()</SCRIPT>
<!--使用方法<input class="input" type="text" name="bgntime" style="width:120" value="" id="bgntime" onClick="showCal(this);"> -->
| 10npsite | trunk/inc/Calendar.php | PHP | asf20 | 17,179 |
<?php
class CURL
{
var $cookie_file; // 设置Cookie文件保存路径及文件名
var $loginurl;//登陆地地址
var $actionstr;//登陆参数
function __construct()
{
$this->cookie_file=tempnam("./TEMP","COOKIEdsdsdsdsdsdwerwdszx454.txt");
}
function vlogin()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$this->loginurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//是否显示数据 0为显示 1为不显示
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->actionstr);
curl_setopt($ch,CURLOPT_COOKIEJAR,$this->cookie_file);
$data = curl_exec($ch);
curl_close($ch);
}
function gethtml($url)
{
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($curl, CURLOPT_HTTPGET, 1); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookie_file); // 读取上面所储存的Cookie信息
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
$tmpInfo = curl_exec($curl); // 执行操作
if (curl_errno($curl)) {
echo 'Errno'.curl_error($curl);
}
curl_close($curl); // 关闭CURL会话
return $tmpInfo; // 返回数据
}
}
$host="https://passport.baidu.com/";
$mycurl=new CURL();
$mycurl->actionstr="isphone=tpl&mem_pass=on&password=yyb513941&psp_tt=0&return_method=post&safeflg=0&tpl=mn&u=http://www.baidu.com/&username=yybjroam1205";
$mycurl->loginurl=$host."?login";
$mycurl->vlogin();//登陆
$htmlcontent=$mycurl->gethtml("http://passport.baidu.com/center");//获取这个页面的内容
echo $htmlcontent;//显示这个页面的内容
?> | 10npsite | trunk/inc/Curl.class.php | PHP | asf20 | 2,480 |
<?php
//定义网站参数
//$databese=1 为mysql数据库 2为mssql数据库
$databese=1;
if($databese==1)
{
require_once RootDir."/inc/dabase_mysql.php";
}
else
{
require_once RootDir."/inc/dabase_mssql.php";
}
?>
| 10npsite | trunk/inc/config.php | PHP | asf20 | 235 |
//interval :D表示查询精确到天数的之差
//interval :H表示查询精确到小时之差
//interval :M表示查询精确到分钟之差
//interval :S表示查询精确到秒之差
//interval :T表示查询精确到毫秒之差
//使用方法:
//alert(dateDiff('D', '2007-4-1', '2007/04/19'));
//时间差的计算方法
function dateDiff(interval, date1, date2)
{
var objInterval = {'D':1000 * 60 * 60 * 24,'H':1000 * 60 * 60,'M':1000 * 60,'S':1000,'T':1};
interval = interval.toUpperCase();
var dt1 = new Date(Date.parse(date1.replace(/-/g, '/')));
var dt2 = new Date(Date.parse(date2.replace(/-/g, '/')));
try
{
return (Math.round(dt2- dt1) / (1000 * 60 * 60 * 24));
}
catch (e)
{
return e.message;
}
}
| 10npsite | trunk/inc/UiFunction.js | JavaScript | asf20 | 804 |
<?php
/**
* 功能:生成缩略图
* 作者:phpox
* 日期:Thu May 17 09:57:05 CST 2007
*/
class CreatMiniature
{
//公共变量
var $srcFile=""; //原图
var $echoType; //输出图片类型,link--不保存为文件;file--保存为文件
var $im=""; //临时变量
var $srcW=""; //原图宽
var $srcH=""; //原图高
//设置变量及初始化
function SetVar($srcFile,$echoType)
{
if(!file_exists($srcFile)){
echo '源图片文件不存在!';
exit();
}
$this->srcFile=$srcFile;
$this->echoType=$echoType;
$info ="";
$data =GetImageSize($this->srcFile,$info);
switch($data[2])
{
case 1:
if(!function_exists("imagecreatefromgif")){
echo "你的GD库不能使用GIF格式的图片,请使用Jpeg或PNG格式!<ahref='javascript:go(-1);'>返回</a>";
exit();
}
$this->im =ImageCreateFromGIF($this->srcFile);
break;
case 2:
if(!function_exists("imagecreatefromjpeg")){
echo"你的GD库不能使用jpeg格式的图片,请使用其它格式的图片!<ahref='javascript:go(-1);'>返回</a>";
exit();
}
$this->im=ImageCreateFromJpeg($this->srcFile);
break;
case 3:
$this->im=ImageCreateFromPNG($this->srcFile);
break;
}
$this->srcW=ImageSX($this->im);
$this->srcH=ImageSY($this->im);
}
//生成扭曲型缩图
function Distortion($toFile,$toW,$toH)
{
$cImg=$this->CreatImage($this->im,$toW,$toH,0,0,0,0,$this->srcW,$this->srcH);
return $this->EchoImage($cImg,$toFile);
ImageDestroy($cImg);
}
//生成按比例缩放的缩图
function Prorate($toFile,$toW,$toH)
{
$toWH=$toW/$toH;
$srcWH=$this->srcW/$this->srcH;
if($toWH<=$srcWH)
{
$ftoW=$toW;
$ftoH=$ftoW*($this->srcH/$this->srcW);
}
else
{
$ftoH=$toH;
$ftoW=$ftoH*($this->srcW/$this->srcH);
}
if($this->srcW>$toW||$this->srcH>$toH)
{
$cImg=$this->CreatImage($this->im,$ftoW,$ftoH,0,0,0,0,$this->srcW,$this->srcH);
return $this->EchoImage($cImg,$toFile);
ImageDestroy($cImg);
}
else
{
$cImg=$this->CreatImage($this->im,$this->srcW,$this->srcH,0,0,0,0,$this->srcW,$this->srcH);
return $this->EchoImage($cImg,$toFile);
ImageDestroy($cImg);
}
}
//生成最小裁剪后的缩图
function Cut($toFile,$toW,$toH)
{
$toWH=$toW/$toH;
$srcWH=$this->srcW/$this->srcH;
if($toWH<=$srcWH)
{
$ctoH=$toH;
$ctoW=$ctoH*($this->srcW/$this->srcH);
}
else
{
$ctoW=$toW;
$ctoH=$ctoW*($this->srcH/$this->srcW);
}
$allImg=$this->CreatImage($this->im,$ctoW,$ctoH,0,0,0,0,$this->srcW,$this->srcH);
$cImg=$this->CreatImage($allImg,$toW,$toH,0,0,($ctoW-$toW)/2,($ctoH-$toH)/2,$toW,$toH);
return $this->EchoImage($cImg,$toFile);
ImageDestroy($cImg);
ImageDestroy($allImg);
}
//生成背景填充的缩图
function BackFill($toFile,$toW,$toH,$bk1=255,$bk2=255,$bk3=255)
{
$toWH=$toW/$toH;
$srcWH=$this->srcW/$this->srcH;
if($toWH<=$srcWH)
{
$ftoW=$toW;
$ftoH=$ftoW*($this->srcH/$this->srcW);
}
else
{
$ftoH=$toH;
$ftoW=$ftoH*($this->srcW/$this->srcH);
}
if(function_exists("imagecreatetruecolor"))
{
@$cImg=ImageCreateTrueColor($toW,$toH);
if(!$cImg)
{
$cImg=ImageCreate($toW,$toH);
}
}
else
{
$cImg=ImageCreate($toW,$toH);
}
$backcolor =imagecolorallocate($cImg, $bk1, $bk2,$bk3); //填充的背景颜色
ImageFilledRectangle($cImg,0,0,$toW,$toH,$backcolor);
if($this->srcW>$toW||$this->srcH>$toH)
{
$proImg=$this->CreatImage($this->im,$ftoW,$ftoH,0,0,0,0,$this->srcW,$this->srcH);
if($ftoW<$toW)
{
ImageCopy($cImg,$proImg,($toW-$ftoW)/2,0,0,0,$ftoW,$ftoH);
}
else if($ftoH<$toH)
{
ImageCopy($cImg,$proImg,0,($toH-$ftoH)/2,0,0,$ftoW,$ftoH);
}
else
{
ImageCopy($cImg,$proImg,0,0,0,0,$ftoW,$ftoH);
}
}
else
{
ImageCopyMerge($cImg,$this->im,($toW-$ftoW)/2,($toH-$ftoH)/2,0,0,$ftoW,$ftoH,100);
}
return $this->EchoImage($cImg,$toFile);
ImageDestroy($cImg);
}
function CreatImage($img,$creatW,$creatH,$dstX,$dstY,$srcX,$srcY,$srcImgW,$srcImgH)
{
if(function_exists("imagecreatetruecolor"))
{
@$creatImg =ImageCreateTrueColor($creatW,$creatH);
if($creatImg)
{
ImageCopyResampled($creatImg,$img,$dstX,$dstY,$srcX,$srcY,$creatW,$creatH,$srcImgW,$srcImgH);
}
else
{
$creatImg=ImageCreate($creatW,$creatH);
ImageCopyResized($creatImg,$img,$dstX,$dstY,$srcX,$srcY,$creatW,$creatH,$srcImgW,$srcImgH);
}
}
else
{
$creatImg=ImageCreate($creatW,$creatH);
ImageCopyResized($creatImg,$img,$dstX,$dstY,$srcX,$srcY,$creatW,$creatH,$srcImgW,$srcImgH);
}
return $creatImg;
}
//输出图片,link---只输出,不保存文件。file--保存为文件
function EchoImage($img,$to_File)
{
switch($this->echoType)
{
case "link":
if(function_exists('imagejpeg')) imagejpeg($img);
else return imagejpeg($img);
break;
case "file":
if(function_exists('imagejpeg')) imagejpeg($img,$to_File);
else return imagejpeg($img,$to_File);
break;
}
}
}
/*
$pics=new CreatMiniature();
$pics->srcFile=$SystemConest[0]."/upfiles/201204/1637619_1.jpg";
$pics->echoType="file";
$pics->SetVar($pics->srcFile,$pics->echoType);
$pics->Prorate($SystemConest[0]."/upfiles/201204/1637619_1_m.jpg",$SystemConest["sys_suoluetu"]["w"],$SystemConest["sys_suoluetu"]["h"]);
*/
?> | 10npsite | trunk/inc/Up_file_suonue.php | PHP | asf20 | 7,365 |
<?
$SYSTEM_FILE_POSTFIX=array('.zip','.rar','.jpg','.png','.gif','.wma','.rm','.wmv','.doc','.mpeg','.mp3','.avi');//充许文件上传类型
$SYSTEM_agree_size=1*1024*1024;//充许文件上传的大小
$SYSTEM_save_path=$dirname."/upfiles/";//上传文件存放的路径
?> | 10npsite | trunk/inc/BaseConst.php | PHP | asf20 | 278 |
<?php require "../global.php";?>
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="/Public/jsLibrary/Jslibary.js"></script>
<style>
body,td{font-size:12px;}
.spanplace{display:none;}
.xztdbgc{background-color:#FFDD99;}
</style>
<?php
require "Uifunction.php";
$thismonth=$_REQUEST["thismonth"];//本月值
//规定值格式
/*
存放后值如下:
时间值(2012-09-04)|市场价|梦之旅|房差价|库存量,时间值2(2012-09-05)|市场价2|梦之旅2|房差价2|库存量2,............
*/
$datecontent="2012-09-11|500|400|200|10,2012-09-17|520|410|230|20";
if($thismonth=="") $thismonth=date("Y-m");
$thefirstdayofweek=date('w',strtotime($thismonth."-01"));//本月第一天是星期几
//如果这个月的第一天不是星期一,那么,它的前面就以上一个月的补齐
//获取前上一个月的日期,以这个月的第一天为基准
function getqiandate($datestr,$num){
return date("Y-m-d",strtotime($datestr)-$num*3600*24);
}
//获取前一个月的日期,返回值是2012-09
function getqimonth($thismonth){
$yearn=preg_replace("/\-[\d]{1,2}$/","",$thismonth);
$month=preg_replace("/^[\d]{4}\-[0]*/","",$thismonth);
$nowmonth=($month==1)?12:$month-1;
if($month==1){
$nowmonth=12;
$yearn=$yearn-1;
}
else{
$nowmonth=$month-1;
}
return $yearn."-".substr("0".$nowmonth,-2);
}
//获取后一个月的日期
function getnextmonth($thismonth){
$yearn=preg_replace("/\-[\d]{1,2}$/","",$thismonth);
$month=preg_replace("/^[\d]{4}\-[0]*/","",$thismonth);
if($month==12){
$month=1;
$yearn+=1;
}
else{
$month+=1;
}
return $yearn."-".substr("0".$month,-2);
}
$qianbunum=$thefirstdayofweek==0?6:$thefirstdayofweek-1;//前面要补的天数
$monthmaxnum=date("t",strtotime($thismonth."-01"));//这个月有多少天
$lastbunum=7-($monthmaxnum+$qianbunum) % 7;
$lastbunum=$lastbunum==7?0:$lastbunum;//获取后面需要被的天数
//计算这次要循环的次数
$maxfornum=$qianbunum+$lastbunum+$monthmaxnum;
//获取本次的开始天数
$stardate= getqiandate($thismonth,$qianbunum);
?>
批量设置<input type="checkbox" id="piliang">
<div>
<div style="float:left; width:510px;">
<table width="500" border="1" cellspacing="0" cellpadding="0" bordercolor="#ccc" style="border-collapse:collapse">
<tr>
<td height="37" colspan="7" align="center"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="37%" height="27"><a href="?thismonth=<?php $pmonth= getqimonth($thismonth);echo $pmonth; ?>"><?php echo preg_replace("/^[\d]{4}\-[0]*/","",$pmonth);?>月</a></td>
<td width="27%"><strong><?php echo str_replace("-","年",$thismonth)."月";?></strong><span class="spanplace" id="placeall">全选<input type="checkbox" id="cpall"></span></td>
<td width="36%" align="right"><a href="?thismonth=<?php $nmonth= getnextmonth($thismonth);echo $nmonth;?>"><?php echo preg_replace("/^[\d]{4}\-[0]*/","",$nmonth);?>月</a></td>
</tr>
</table></td>
</tr>
<tr>
<td width="11%" height="37" align="center">一<span class="spanplace" id="place1"><input type="checkbox" id="cpz1"></span></td>
<td width="14%" align="center">二<span class="spanplace" id="place2"><input type="checkbox" id="cpz2"></span></td>
<td width="13%" align="center">三<span class="spanplace" id="place3"><input type="checkbox" id="cpz3"></span></td>
<td width="13%" align="center">四<span class="spanplace" id="place4"><input type="checkbox" id="cpz4"></span></td>
<td width="15%" align="center">五<span class="spanplace" id="place5"><input type="checkbox" id="cpz5"></span></td>
<td width="15%" align="center">六<span class="spanplace" id="place6"><input type="checkbox" id="cpz6"></span></td>
<td width="19%" align="center">日<span class="spanplace" id="place0"><input type="checkbox" id="cpz0"></span></td>
</tr>
<?php
$zcthismonth=turntostrtozc($thismonth);
preg_match_all("/".$zcthismonth."\-[\d]{1,2}\|[\d\.]+\|[\d\.]+\|[\d]*\|[\d]+/",$datecontent,$datecontentarr);//只获取本月的日期值
$dcontentarr=array();//存放本月分解的数值
foreach($datecontentarr[0] as $k=>$v){
$varr=explode("|",$v);
$dcontentarr[$varr[0]][1]=$varr[1];
$dcontentarr[$varr[0]][2]=$varr[2];
$dcontentarr[$varr[0]][3]=$varr[3];
$dcontentarr[$varr[0]][4]=$varr[4];
}
for($i=1;$i<=$maxfornum;$i++){
$thisv=date("Y-m-d",strtotime($stardate)+($i-1)*3600*24);
if($i %7 ==1){
?> <tr><?php }?>
<td width="11%" align="left" valign="top" height="50"
<?php if(strstr($thisv,$thismonth)=="" or date("Y-m")>$thismonth){
echo "style='background-color:#E6DFDF'";}
else{
echo "data='".$thisv."|".$dcontentarr[$thisv][1]."|".$dcontentarr[$thisv][2]."|".$dcontentarr[$thisv][3]."|".$dcontentarr[$thisv][4]."' week='".date("w",strtotime($thisv))."'";
}
?>
class="">
<div style="width:100%;height:20px;">
<div style="float:left;"><span style="margin-top:15px; margin-left:5px; color: #396; font-size:14px;"><?php echo preg_replace("/^[\d]{4}\-[\d]{1,2}\-[0]*/","",$thisv);?></span>
</div>
<?php if($dcontentarr[$thisv]){?>
<div style="float:right;"><span style="color:333; margin-right:5px;">0/<?php echo $dcontentarr[$thisv][4];?></span></div>
<?php }?>
</div>
<?php if($dcontentarr[$thisv]){?>
<div style="width:100%;">
<span style="color:#999">市:¥<?php echo $dcontentarr[$thisv][1];?></span><br>
<span>梦:¥<?php echo $dcontentarr[$thisv][2];?></span>
</div>
<?php }?>
</td>
<?php if($i % 7==0){?> </tr><?php }?>
<?php
}
?>
</table>
</div>
<div style="float:left; width:200px; overflow:hidden;">
<table width="94%" border="1" cellspacing="0" cellpadding="0" bordercolor="#ccc" style="border-collapse:collapse">
<form action="?" method="post" name="formsubmit">
<input type="hidden" id="checkeddatev" name="checkeddatev">
<tr>
<td height="28" colspan="2" align="center">价格/库存设置</td>
</tr>
<tr>
<td height="29" align="right" >市 场 价:</td>
<td >
<input type="text" name="market_price" id="market_price" size="12"/>
<span style="color:#F00">*</span></td>
</tr>
<tr>
<td height="34" align="right" >梦之旅价:</td>
<td ><input type="text" name="mzl_price" id="mzl_price" size="12"/>
<span style="color:#F00">*</span></td>
</tr>
<tr>
<td height="27" align="right" >房 差:</td>
<td ><input type="text" name="fangcha" id="fangcha" size="12"/></td>
</tr>
<tr>
<td height="32" align="right" >库 存:</td>
<td ><input type="text" name="kucun" id="kucun" size="12"/>
<span style="color:#F00">*</span></td>
</tr>
<tr>
<td height="30" > </td>
<td ><input type="button" name="mysubmit" id="mysubmit" value="设 置" /> <input type="button" name="mysreset" id="mysreset" value="重 置" /></td>
</tr>
<tr>
</tr>
</form>
</table>
</div>
</div>
<script language="javascript">
$(document).ready(function(){
//绑定批量设置的事件
$("#piliang").bind("click", function(){
if($("#piliang").attr("checked")=="checked"){
$("span[id^='place']").show();
}else{
$("span[id^='place']").hide();
}
});
//绑定全选事件的功能
$("#cpall").bind("click",function(){
if($("#cpall").attr("checked")=="checked"){
$("input[id^='cpz']").attr("checked","checked");
$("td[week]").addClass("xztdbgc");
}else{
$("input[id^='cpz']").removeAttr("checked");
$("td[week]").removeClass();
}
});
//给选定每周的一天绑定事件
$("input[id^='cpz']").bind("click", function(){
id=$(this).attr("id");
id=id.replace("cpz","");
if($(this).attr("checked")=="checked"){
$("td[week^='"+id+"']").addClass("xztdbgc");
$("td[week^='"+id+"']").each(function(){
adddatetoseleed(this);
});
}
else{
$("td[week^='"+id+"']").removeClass();
$("td[week^='"+id+"']").each(function(){
deleteofseleed(this);
});
}
});
//给每一天绑定事件
$("td[data]").bind("click",function(){
classname=$(this).attr("class");
if(classname=="xztdbgc"){
$(this).removeClass();
deleteofseleed(this);
}
else{
$(this).addClass("xztdbgc");
adddatetoseleed(this);
}
//如果本月选定的只有一天时,在填写价格处写上这一天的价格
chooesv=$("#checkeddatev").val();
if(chooesv.match(/^,[\d]{4}\-[\d]{1,2}\-[\d]{1,2}$/)){
chooesv=chooesv.replace(",","");
$("td[data^='"+chooesv+"']").each(function(){
data=$(this).attr("data");
if(data!=""){
dataarr=data.split("|");
if(dataarr.length==5){
$("#market_price").val(dataarr[1]);
$("#mzl_price").val(dataarr[2]);
$("#fangcha").val(dataarr[3]);
$("#kucun").val(dataarr[4]);
}
}
});
}
else{
$("#market_price").val("");
$("#mzl_price").val("");
$("#fangcha").val("");
$("#kucun").val("");
}
});
//绑定设置价格按钮功能
$("#mysubmit").bind("click",function(){
if(!nzeletype("market_price","请输入市场价","float")) return false;
if(!nzeletype("mzl_price","请输入梦之旅价","float")) return false;
if($("#mzl_price").val()>$("#market_price").val()){
alert("梦之旅价不能大于市场价");
$("#mzl_price").val("");
$("#mzl_price").focus();
return false;
}
if(!nzeletype("kucun","请输入库存数量","int")) return false;
});
});
//给当前值加入到已经选择到的值里
function adddatetoseleed(strdate){
data=$(strdate).attr("data");
data=data.match(/^[\d]{4}\-[\d]{1,2}\-[\d]{1,2}/);
tv=$("#checkeddatev").val();
if(tv.indexOf(data)<1) $("#checkeddatev").val(tv+","+data);
}
//给当前值从已经选择到的值里删除
function deleteofseleed(strdate){
data=$(strdate).attr("data");
data=data.match(/^[\d]{4}\-[\d]{1,2}\-[\d]{1,2}/);
tv=$("#checkeddatev").val();
tv=tv.replace(","+data,"")
$("#checkeddatev").val(tv);
}
</script> | 10npsite | trunk/inc/hotelcalendar.php | PHP | asf20 | 10,443 |
// 获取宽度
function getWidth()
{
var strWidth,clientWidth,bodyWidth;
clientWidth = document.documentElement.clientWidth;
bodyWidth = document.body.clientWidth;
if(bodyWidth > clientWidth){
strWidth = bodyWidth + 20;
} else {
strWidth = clientWidth;
}
return strWidth;
}
//获取高度
function getHeight()
{
var strHeight,clientHeight,bodyHeight;
clientHeight = document.documentElement.clientHeight;
bodyHeight = document.body.clientHeight;
if(bodyHeight > clientHeight){
strHeight = bodyHeight + 30;
} else {
strHeight = clientHeight;
}
return strHeight+1000;
}
// 锁屏
function showScreen(div1,div2,clientWidth)
{
var div1=div1;
var div2=div2;
var Msg = document.getElementById(div1);
var Bg = document.getElementById(div2);
Bg.style.width = getWidth()+'px';
Bg.style.height = getHeight()+'px';
document.getElementById(div1).style.left=clientWidth+"px"; //document.body.clientWidth / 2 表示居中
document.getElementById(div1).style.top=screen.height/2-300+"px";
Msg.style.display = 'block';
Bg.style.display = 'block';
}
//解屏
function hideScreen(div1,div2)
{
var div1=div1;
var div2=div2;
var Msg = document.getElementById(div1);
var Bg = document.getElementById(div2);
Msg.style.display = 'none';
Bg.style.display = 'none';
}
/*dfdfads
使用方法
此功能一共需要使用三个文件 1本js文件 2 lockscreen.css文件 3所以html调用的页面
调用:
showScreen(div1,div2) div1和div2是两个层的div名 注意css文件里的样式名要和div的名称对应
例如:
<div id="Message" style="border:#00BFFF solid 1px; background:#FFFFFF; width:400px; height:100px"><span style="cursor:pointer;" onclick="javascript:hideScreen('Message','Screen',距屏幕左边的像素);">关闭</span>
<div id="Screen"></div>
<p><span style="cursor:pointer;" onclick="javascript:showScreen('Message','Screen');">锁屏</span></p>
dsdsd*/ | 10npsite | trunk/inc/lockscreen_xieyi.js | JavaScript | asf20 | 2,071 |
<?php
?>
<script language='javascript'>var UEDITOR_HOME_URL= '/guanli/system/ueditor/';</script>
<script type='text/javascript' src='/guanli/system/ueditor/editor_config.js'></script>
<script type='text/javascript' src='/guanli/system/ueditor/editor_all.js'></script>
<link rel='stylesheet' href='/guanli/system/ueditor/themes/default/ueditor.css'>
| 10npsite | trunk/inc/editorfilespath.php | PHP | asf20 | 360 |
<?php
function Menu_JS($MenuNum)
{
?>
<script language="javascript" type="text/javascript">
<!--
NS4 = (document.layers) ? 1 : 0;
IE4 = (document.all) ? 1 : 0;
ver4 = (NS4 || IE4) ? 1 : 0;
function expandIt(index){//-----------------------------------------
var menuitem=new Array()
<?php
for($i=1;$i<=$MenuNum;$i++)
{
?>
menuitem[<?php echo $i;?>]=System_Child_<?php echo $i;?>;
<?php
}
?>
if (menuitem[index].style.display=="block"){
displayall()
}
else {
displayall()
menuitem[index].style.display="block"
}
}
function displayall(){//-----------------------------------------------------------
<?php
for($i=1;$i<=$MenuNum;$i++)
{
?>
System_Child_<?php echo $i;?>.style .display ="none"
<?php
}
?>
}
function arrange() {
nextY = document.layers[firstInd].pageY +document.layers[firstInd].document.height;
for (i=firstInd+1; i<document.layers.length; i++) {
whichEl = document.layers[i];
if (whichEl.visibility != "hide") {
whichEl.pageY = nextY;
nextY += whichEl.document.height;
}
}
}
function initIt(){
if (!ver4) return;
if (NS4) {
for (i=0; i<document.layers.length; i++) {
whichEl = document.layers[i];
if (whichEl.id.indexOf("Child") != -1) whichEl.visibility = "hide";
}
arrange();
}
else {
divColl = document.all.tags("DIV");
for (i=0; i<divColl.length; i++) {
whichEl = divColl(i);
if (whichEl.className == "child") whichEl.style.display = "none";
}
}
}
onload = initIt;
//-->
</script>
<?php
}
?> | 10npsite | trunk/inc/Menu_js.php | PHP | asf20 | 1,660 |
<?php
class Page
{
private $totalpage;
private $stride;
private $currentpage;
//配置总页数
function setTotalpage($objpage=0){
$this->totalpage=$objpage;
}
//配置当前页
function setCurrentpage($objpage=1){
$this->currentpage=$objpage;
}
//配置跨度
function setStride($objStride=1){
$this->stride=$objStride;
}
//获得总页数
function getTotalpage(){
return $this->totalpage;
}
//获得跨读
function getStride($objStride=1){
return $this->stride;
}
//获取当前页
function getCurrentpage($objpage=1){
return $this->currentpage;
}
//打印分页
function Pageprint(){
for($Tmpa=0;$Tmpa<$this->totalpage;$Tmpa++){
if($Tmpa+$this->stride<$this->currentpage){//加了跨度还小于当前页的不显示
continue;
}
if($Tmpa+$this->stride==$this->currentpage){//刚好够跨度的页数
$p=$this->currentpage-$this->stride-1;
$willprint.="<a href="$_SERVER[PHP_SELF]."?page=1><strong><<</strong></a><a href="$_SERVER[PHP_SELF]?page=$p"><strong><</strong></a>";
}
if($Tmpa>$this->currentpage+$this->stride){//大于当前页+跨度的页面
break;
}
$willprint.="<a href="$_SERVER[PHP_SELF]?page=$Tmpa"><strong>$Tmpa</strong></a>";
if($Tmpa==$this->currentpage+$this->stride){//刚好够跨度的页数
$p=$this->currentpage+$this->stride+1;
$willprint.="<a href=".$_SERVER[PHP_SELF].".?page=$p><strong>></strong></a><a href=".$_SERVER[PHP_SELF]".?page=".$this->totalpage."><strong>>></strong></a>";
}
}
echo $willprint;
}}if(isset($_GET[page])){
$page=$_GET[page];}else{
$page=1;}$CC=new Page();$CC->setTotalpage(1000);$CC->setCurrentpage($page);$CC->setStride(5);$CC->Pageprint();
?>
| 10npsite | trunk/inc/fanyeClass.php | PHP | asf20 | 2,050 |
function MinClassBox(strMinValue,SpanID,SelectName,FieldValue)
{
if(strMinValue=="")
{
SpanID.innerHTML="";
return;
}
var ArrMinClass,MinClass,strSelect,strSelected;
strSelected="";
strSelect="";
if(strMinValue.indexOf(",")>0)
{
ArrMinClass=strMinValue.split(",");
}
else
{
var ArrMinClass=new Array(1);
ArrMinClass[0]=strMinValue;
}
for(i=0;i<ArrMinClass.length;i++)
{
FieldValue_arr= ArrMinClass[i].split("|");
if(FieldValue==FieldValue_arr[0])
{
strSelected="selected='selected'";
}
else
{
strSelected="";
}
strSelect=strSelect + "<option " + strSelected + " value='" + FieldValue_arr[0]+ "'>" + FieldValue_arr[1] + "</option>";
}
SpanID.innerHTML=" <select name='"+SelectName +"' >" +strSelect + "</select>";
}
| 10npsite | trunk/inc/BaseFunction.js | JavaScript | asf20 | 833 |
<?php
/**
* 判断字符串是否是email
* @param str $str
* @return 是email返回true,不是返回false
*/
function ismail($str)
{
preg_match("/[\w\-\.]+@[\w\-\.]+\.[\w]+/", $str,$t);
return ($t[0])?true:false;
}
/**
* 判断字符串是否只由字母,数字,下划线或中划线或.组成
* @param str $str
* @param 成功返回true 失败返回false
*/
function isstri($str)
{
preg_match("/[\w\-\.]+/", $str,$t);
return ($t[0])?true:false;
}
/**
* 根据传过来的产品id,返回一定格式的产品编号
* Enter description here ...
* @param unknown_type $tid
*/
function gettourbianhao($tid)
{
if(!is_numeric($tid)) return $tid;
return substr("10000000", 0,-strlen($tid)).$tid;
}
/**
* 根据产品编号,返回线路的id
* @param int $tid
*/
function formtourbianhao($tid)
{
if(!is_numeric($tid)) return $tid;
return preg_replace("/^10{0,}/", "", $tid);
}
/**
* 转化正则表达式,解决在tp的模板里,反斜杠,会被自动去掉的问题
* 模板里的反斜杠用##代替
* @param $str
*/
function foramtzhengc($str){
return str_replace("##", "\\", $str);
}
/**
* 传递一个数组进来,返回其中的一个单元
* Enter description here ...
* @param unknown_type $arr
*/
function getRandArray($arr)
{
return $arr[array_rand($arr)];
}
/**
* 解析合并后的内容,每个项按一定的格式存放
* @param $str 数据库里存放的内容 存放格式{@客内:这是内容}{@客名:这是客服人员的名称} 等
* @param $flag 表示要获取哪一个值
*/
function getformcontent($str,$flag)
{
if($str=="") return "";
return getkuohaostr($str,"/\{@".$flag."\:([\s\S]*?)@\}/");
}
/**
* 字符串截取,支持中文和其他混合字符
* 对开始位置和截取长度可能会根据实际情况后移一个单位,以保证补全至一个完整字符
* @param string $str 被截取的源字符串
* @param string $start 开始位置,以半角字符为单位,如:英文/数字占一个单位,汉字占2个单位
* @param string $length 截取长度,以半角字符为单位,如:英文/数字占一个单位,汉字占2个单位
* @param string $charset 源字符串的编码格式(可能与本程序文件的编码有关)
* @param string $suffix 截取出的字符串附加后缀
* @return string
*/
function mstrcut($str, $length, $start=0, $charset="utf-8", $suffix=true) {
// 参数检查
if(
empty($str)
|| empty($length)
|| !is_numeric($length)
|| $length<=0
|| !in_array($charset,array('utf-8','gb2312','gbk','big5'))
) return "";
// 首先根据指定编码将字符串拆解为单个字符
$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
preg_match_all($re[$charset], $str, $match);
// 计算源字符串的字符数
$count = count($match[0]);
// 计算截取的起始位置
$i = 0;
$begin = 0;
while($start > 0) {
// 如果当前游标位置已经超过源字符数,却还未到达截取的起始位置,则立即返回空
if($i >= $count) return "";
$start -= (strlen($match[0][$i]) > 1 ? 2 : 1);
$i++;
}
$start = $i;//此处的$start已经变化为数组的游标
// 计算截取的终止位置,即$i的最终值
while($length > 0) {
// 如果当前游标位置已经超过源字符数,却还未到达预定的终止位置,则停止
if($i >= $count) break;
$length -= (strlen($match[0][$i]) > 1 ? 2 : 1);
$i++;
}
$slice = join("",array_slice($match[0], $start, $i-$start));
// 智能附加省略号
return ($suffix && ($i < $count)) ? $slice.'...' : $slice;
}
//返回正则获取后的第一个值
function getsubstr($str,$zc)
{
preg_match($zc, $str."",$temp);
return (isset($temp))?$temp[0]:"";
}
//转换日期形式的字符串为正则格式,以便用于传合成正则
function turntostrtozc($str){
return($str=="")?"":str_replace("-","\-",$str);
}
/**
* 正则中第一个匹配项中的第一个括号中的值
* @param 源字符串
* @param 正则表达式
* @return 返回正则中第一个匹配项中的第一个括号中的值
*/
function getkuohaostr($str,$zc)
{
preg_match($zc, $str."",$temp);
return (isset($temp))?$temp[1]:"";
}
/**
*
* 替换正则中的第一个括号里的内容
* @param $str 源字符串
* @param $replacem 替换后的内容
* @param $zc 正则
*/
function replaceKuohaostr($str,$replacem,$zc)
{
preg_match($zc, $str."",$temp);
$temp=(isset($temp))?$temp[1]:"";
return str_replace($temp, $replacem, $str);
}
/**
* 返回正则获取后的第一个值,用于格式化日期
* Enter description here ...
* @param unknown_type $str
* @param unknown_type $zc
*/
function getdatestr($str,$zc)
{
preg_match($zc, $str."",$temp);
if(isset($temp))
{
return preg_replace("/^20[\d]{2,2}-/", "", $temp[0]);
}
return "";
}
function gourl($url,$type)
{
//自动跳转页 $url跳转的地址 $type跳转的类型
if($type==1)
{
echo "<meta http-equiv=\"refresh\" content=\"0; url=".$url."\">";
die;
}
}
//弹出对话框并跳转目标网址
function alert($url,$type,$string)
{
if($type==0)
{
echo "<script language=\"JavaScript\">alert(\"".$string."\");</script>";
}
elseif($type==1)
{
echo "<script language=\"JavaScript\">\r\n";
echo " alert(\"".$string."\");\r\n";
echo " history.back();\r\n";
echo "</script>";
die;
exit;
}
elseif($type==2)
{
echo "<script language=\"JavaScript\">\r\n";
echo " alert(\"".$string."\");\r\n";
echo " location.replace(\"".$url."\");\r\n"; // 前往目标网址
echo "</script>";
exit;
}
elseif($type==3)
{
echo "<script language=\"JavaScript\">\r\n";
echo " alert(\"".$string."\");\r\n";
echo "window.close()";
echo "</script>";
exit;
}
elseif($type==4)
{
echo "<script language=\"JavaScript\">\r\n";
echo " location.replace(\"".$url."\");\r\n"; // 前往目标网址
echo "</script>";
exit;
}
}
/**
* 计算出评论的分数
* @param $str 格式 如:预定|2|客服|1|住宿|1|交通|1|导游|1|行程|1
* @return int 返回总的评论得分数
*/
function formstPinglunToNum($str)
{
preg_match_all("/[0-9]/",$str,$tem);
$t=0;
$t=array_sum($tem[0]);
/*
foreach($tem[0] as $k=>$v)
{
$t=$t+$v;
}
*/
$t=number_format($t/12,2)*100;
return $t;
}
/**
* 分类页
* @param 记录集 $mr
* @param 字符串 $sqlwhere 查询的条件
* @param 数字 $pagecount 每页显示条数
* @param 字符串 $otherurl 链接的其它参数
* @param 数字 $type 查询类型 默认为1,当是1时,表示用模型方式查,如果是2表示用原生态sql语句查
* @param 返回一个数组$rs,它包含两个项一个是$rs["rs"],查询到的记录集,另一个$rs["show"]是翻页的导航html代码
*/
function fanye($mr,$sqlwhere,$pagecount,$type="1",$otherurl="")
{
$p=($_GET["p"])?$_GET["p"]:1;//默认第一页
//根据查询方式不同建立不同的模型.
import("ORG.Util.Page");//导入分页库
if($type=="1"){
$list = $mr->where($sqlwhere)->page($p.','.$pagecount)->select();//模型查询
$count = $mr->where($sqlwhere)->count(); // 查询满足要求的总记录数
}
if($type=="2"){
$startn=($p==1)?0:($p-1)*$pagecount;
$tsql=$sqlwhere." limit ".$startn.",".$pagecount;
$list = $mr->query($tsql);//原生态sql语句查询
preg_match("/^[\s]*select[\s]+\*[\s]*,/i",$sqlwhere,$flagarr);
$tempfffy=(!$flagarr[0])?" , ":"";
$csql=preg_replace("/^[\s]*select[\s]+[\*]{0,1}/i", "select count(*) as sys_countnumv".$tempfffy, $sqlwhere);
$csql=preg_replace("/,[\s]*from/"," from",$csql);
$temprs=$mr->query($csql); // 查询满足要求的总记录数
$count=($temprs)?$temprs[0]["sys_countnumv"]:0;
}
$Page = new Page($count,$pagecount); // 实例化分页类 传入总记录数和每页显示的记录数
//分页跳转的时候保证查询条件
$Page->parameter=$otherurl;
$show= $Page->show(); // 分页显示输出
$rs=array();
$rs["rs"]=$list;
$rs["show"]=$show;
return $rs;
}
/**
* 把审核字段的值转化成中文 其值表示通过时为1 其它值时表示不通过
* @param int $str
* @return string 返回"已审核"或"未审核"
*/
function turnshenghe($str)
{
$tem=($str==1)?"已审核":"未审核";
return $tem;
}
/**
* 在php文件以js文件运行时,转换文件里的引号问题
* @param str $str 源字符串
*/
function jstowrite($str)
{
return str_replace("'","\'",$str);
}
/**
* 格式化时间,转换成数字存入数据库
* @param timestr $str 日期型字符串
*/
function formattime($str)
{
return ($str!="")? strtotime($str):0;
}
/**
* 当值为空时返回现在的时间值
* @param $str 字符串时间形式
*/
function getmorentime($str)
{
return ($str=="")? time():$str;
}
/**
* 当复选框不点时,要模型里修正其值
* @param $str
*/
function getis0orit($str)
{
return ($str=="")?0:$str;
}
/**
* 获取评论的满意度,例如:预定|2 其中2为一般,1为满意 3为不满意 返回"一般"
* @param $str 字符串,若传有汉字,也只提取数字
*/
function getPinglunCnameValue($str)
{
$temp=preg_replace("/[^0-9]*/","",$str);
if(strlen($temp)>0)
{
if($temp=="2") return "满意";
if($temp=="1") return "一般";
if($temp=="0") return "不满意";
}
else
{
return "";
}
}
//返回格式后的化评论 初始值应为:预定|2|客服|1|住宿|1|交通|1|导游|1|行程|1 1为满意 2为一般 3为不满意 目前是六个选项
/**
* 返回格式化后的评论
* @param string $str
*/
function formatPinglun($str)
{
//$str=iconv("gb2312","UTF-8",$str);
preg_match("/预定\|[0-9]{1}/",$str,$yuding);
preg_match("/客服\|[0-9]{1}/",$str,$kefu);
preg_match("/住宿\|[0-9]{1}/",$str,$zhusu);
preg_match("/交通\|[0-9]{1}/",$str,$jiaotong);
preg_match("/导游\|[0-9]{1}/",$str,$daoyou);
preg_match("/行程\|[0-9]{1}/",$str,$xingchen);
//die($yuding[0]);
$Temp="<b>预定</b>:".getPinglunCnameValue($yuding[0])." ";
$Temp=$Temp."<b>客服</b>:".getPinglunCnameValue($kefu[0])." ";
$Temp=$Temp."<b>住宿</b>:".getPinglunCnameValue($zhusu[0])." ";
$Temp=$Temp."<b>交通</b>:".getPinglunCnameValue($jiaotong[0])." ";
$Temp=$Temp."<b>导游</b>:".getPinglunCnameValue($daoyou[0])." ";
$Temp=$Temp."<b>行程</b>:".getPinglunCnameValue($xingchen[0])." ";
return $Temp;
/*
$temparr=explode("|",$str);
if(count($temparr)!=6) $temparr=array(6);
$rearr=array();//返回的数组
for($i=0;$i<6;$i++)
{
if($temparr[$i]==1) $rearr[$i]="满意";
if($temparr[$i]==2) $rearr[$i]="一般";
if($temparr[$i]==3) $rearr[$i]="不满意";
if($temparr[$i]=="") $rearr[$i]="满意";
}
$rearr[0]="预定:".$rearr[0];
$rearr[1]="客服:".$rearr[1];
$rearr[2]="住宿:".$rearr[2];
$rearr[3]="交通:".$rearr[3];
$rearr[4]="导游:".$rearr[4];
$rearr[5]="行程:".$rearr[5];
return $rearr;
*/
}
/**
* 显示栏目的下拉列表框
* @param $mydb 实列化后的数据库连接信息,
* @param str $selectname 下拉框的名称,民
* @param string $sqlstr sql语句
* @param $optionStr 为option的值格式"值|表现出的值" 如<option vaule="值">表现出的值</option>
* @param $seletedStr 为默认选定项的值
* @return 返回计算后的html代码
*/
function ui_select($mydb,$selectname,$sqlstr,$optionStr,$seletedStr)
{
$optionArr=explode("|", $optionStr);
?>
<select name="<?php echo $selectname?>">
<option value="0">一级栏目</option>
<?php
$rscf=$mydb->db_select_query($sqlstr);
while($rsf=$mydb->db_fetch_array($rscf))
{
?>
<option value="<?php echo $rsf[$optionArr[0]];?>"><?php echo $rsf[$optionArr[1]];?></option>
<?php
}
?>
</select>
<?php
//函数结束
}
//中文字符串乱码获取
function msubstr($str, $start, $len) {
$tmpstr = "";
$strlen = $start + $len;
for($i = 0; $i < $strlen; $i++) {
if(ord(substr($str, $i, 1)) > 0xa0) {
$tmpstr .= substr($str, $i, 2);
$i++;
} else
$tmpstr .= substr($str, $i, 1);
}
return $tmpstr;
}
/**
* 获取字字符串
* @param $str 源字符串
* @param $start 开始位置
* @param $limit_length 长度
* @param $omit 省略后的替换符
* @return 返回计算后的字符串
*/
function my_substr($str,$start,$limit_length,$omit="...") {
$return_str = "";//返回的字符串
$len = mb_strlen($str,'utf8');// 以utf-8格式求字符串的长度,每个汉字算一个长度
if ( $len > $limit_length )
{
$omit =$omit;
}
else
{
$limit_length = $len;
}
for ($i = $start; $i < $limit_length; $i++)
{
$curr_char = mb_substr($str,$i,1,'utf8');//以utf-8格式取得第$i个位置的字符,取的长度为1
$curr_length = ord($curr_char) > 127 ? 2 : 1;//如果大于127,则此字符为汉字,算两个长度
$return_str .= $curr_char;
}
return $return_str.$omit;
}
/**
* 去除html格式的功能
* @param $str 源字符串
* @return 返回去掉html代码后的字符串
*/
function getDelHtml($str)
{
return preg_replace("/<[\s\S]*?>/","",$str);
}
/**
* 把导航的字符串,转换成成页面标题
* @param $str 源字符串
*/
function navtotitle($str)
{
$temp=getDelHtml($str);
$temp=preg_replace("/>/", "旅游线路,",$temp);
$temp=str_replace(" ", "", $temp);
$temp=str_replace("首页旅游线路,", "", $temp);
$temp=str_replace("您搜索的关键字是:", "", $temp);
$temp=preg_replace("/\,$/", "", $temp);
$temp=$temp."线路";
$temp=str_replace("线路列表查看线路", "", $temp);
$temp=str_replace(",", " ", $temp);
$temp=preg_replace("/( ){2,}/", " ", $temp);
return $temp;
}
/**
* 去除重复值,只留下最开始的一个
* @param $str
* @param $typev 周期类型值
* @param $anydate
* @return 返回替换后的字符串
*/
function getSomeValue($str,$typev,$anydate)
{
if($typev=="每周")
{
return preg_replace("/,周/",",",$str);
}
if($typev=="任意")
{
$temparr=explode(",", $anydate);
sort($temparr);
$temp="";
foreach($temparr as $v)
{
$temp=$temp.$v."<br>";
}
$temp=substr($temp,0,-4);
return $temp;
}
return preg_replace("/,周/",",",$str);
}
/**
* 一个日期的上一个月 传入值格式为
* @param 字符串 $da 一个日期值2010-10-12
*/
function getpmodth($da)
{
$lastmonth = mktime(0, 0, 0, date("m",strtotime($da))-1, date("d",strtotime($da)), date("Y",strtotime($da)));
$lastmonth=date('Y-m',$lastmonth);
return $lastmonth;
}
//返回下一个月的月份
function getnextmodth($da)
{
$lastmonth = mktime(0, 0, 0, date("m",strtotime($da))+1, date("d",strtotime($da)), date("Y",strtotime($da)));
$lastmonth=date('Y-m',$lastmonth);
return $lastmonth;
}
//转换大写数字为小写 一般用于转换日历值
function getTurnDtoXnum($str)
{
$str=str_replace("一","1",$str);
$str=str_replace("二","2",$str);
$str=str_replace("三","3",$str);
$str=str_replace("四","4",$str);
$str=str_replace("五","5",$str);
$str=str_replace("六","6",$str);
$str=str_replace("日","0",$str);
return $str;
}
/**
*获取两标识符中间的字符串,支持正则,所以标识符里有正则常量符时要加转义符
* @param str $str 源字符串
* @param str $lflag 左边标识符 如"\{好人\}"
* @param str $rflag 右边标识符 如 "*\{\/好人\}"
* @param int $retype 默认为0时,只返回第一个 等于"all"时返回所有查到的季符串
* @param $isboder 是否包含原来的两个边界
* @return 返回查找到后的数组
*/
function getMiddleStr($str,$lflag,$rflag,$retype="0",$isboder="no")
{
preg_match_all("/".$lflag."[\s\S]*?".$rflag."/",$str,$arr);
$r=str_replace("\\","",$rflag);
$l=str_replace("\\","",$lflag);
foreach($arr as $kt=> $vt)
{
foreach($vt as $k=>$v)
{
if($isboder=="no")
{
$arr[$k]=str_replace($r,"",$v);
$arr[$k]=str_replace($l,"",$arr[$k]);
}
else
{
$arr[$k]=$v;
$arr[$k]=$arr[$k];
}
}
}
if($retype=="all") return $arr;
return $arr[$retype];
}
/**
* 获取生成排序的select代码值
* @param string $idstr
* @param int $selectedvalue
* @param int $max 默认为5
*/
function ui_select_paixu($idstr,$selectedvalue="",$max=5)
{
$temp="<select name='$idstr' id='$idstr'>";
for ($i=1;$i<=$max;$i++)
{
$t2="";
if($selectedvalue==$i) $t2="selected";
$temp=$temp."<option value='$i' $t2>$i</option>";
}
$temp=$temp."</select>";
return $temp;
}
/**
*返回计算后的复选框的html代码,若实际值和默认值相同时,显示勾选状态,显示一个复选框
* @param $idstr id值或name值
* @param $mvalue 默认值 默认为1
* @param $dvalue 实际值 默认为空
* @return 返回生成后的html代码
*/
function ui_checkbox_shenghe($idstr,$dvalue="",$mvalue="1")
{
$t1="";
if($mvalue==$dvalue) $t1="checked";
$temp="<input type='checkbox' name='$idstr' id='$idstr' value='$mvalue' $t1 />";
return $temp;
}
/**
* 显示是否已审核状态
* @param $str 审核字段的值 ,通常审核通过其值为1
*/
function ui_show_shenghe($str)
{
$tem=($str=="1")?"已审核":"未审核";
return $tem;
}
/**
* 显示多个币种下拉选项
* @param $elename 标签id名称
* @param $dv 当前值
*/
function ui_select_bizhong($elename,$dv)
{
$temp="<select name='$elename' id='$elename'>";
global $DuoBiZhong;
foreach($DuoBiZhong as $k=>$v)
{
$cd="";
if($dv=="人民币" or $dv=="RMB" ) $cd="selected";
if($dv=="美元" or $dv=="USD" ) $cd="selected";
$temp=$temp."<option value='$k' $cd>$v</option>";
}
$temp=$temp."</select>";
return $temp;
}
/**
* 获取显示支付方式的下拉列表框
* @param $elename
* @param $dv
*/
function ui_select_paytype($elename,$dv)
{
$temp="<select name='$elename' id='$elename'>";
global $PayType;
foreach($PayType as $k=>$v)
{
$cd="";
if($dv==$k) $cd="selected";
$temp=$temp."<option value='$k' $cd>$v</option>";
}
$temp=$temp."</select>";
return $temp;
}
/**
* 自动给新闻地址加上前缀和后缀
* @param str $str 保存在数据库里的静态地址名
* @return 返回合并生成后的的新闻地址
*/
function turnnewsurl($str)
{
if($str!="")
{
return "/html/".$str.".htm";
}
else
{
return "";
}
}
/**
* 显示button是否是只读状态,当两个值相等时,显示readonly
* @param $dv 当前值
* @param $mv 默认值,为1
* @return 两个值相等,显示readonly 否则不处理
*/
function ui_button_disabled($dv,$mv="1")
{
if($dv==$mv) return "disabled='disabled'";
}
/**
* 获取线路表里的othercontent字段的其中一个选项值
* @param str $srt为源字段值
* @param str $strflag 选项的标识变量
*/
function getOtherFieldofOne($str,$strflag)
{
if($str!="")
{
preg_match("/\[id\=".$strflag."#[\s\S]*?\]/",$str,$arr);
$temp=str_replace("[id=".$strflag."#","",$arr[0]);
$temp=str_replace("]","",$temp);
return $temp;
}
return "";
}
/**
* 判断用户的权限
* @param int $yuan 用户存储的权限值
* @param int $num 要判断的权限值
* @return 若有权限返回true,失败返回false
*/
function getUserPower($yuan,$num)
{
$tem=array();
for($i=1;$i<=$yuan;$i++)
{
if($i % 2==0 or ($i==1 and $yuan % 2 !=0)) $tem[$i]=$i;
}
foreach($tem as $k=> $v)
{
if($v==$num) return true;
}
return false;
}
/**
* 检查用户某一个模块的某一个权限
* @param str $userpower 用户的存储的权限字段
* @param string $powerclass 认证的哪一个模块的权限
* @param int $powervale 查看什么权限 如查看读取权限
* @param $user 一般用户验证的时候不传值
* @return 若失败,返回false 成功返回true
*/
function checkpower($userpower,$powerclass,$powervale,$user="")
{
global $SystemConest;
//当是超级帐号时,不受限制
//return TRUE;
if($user=="")
{
if(strstr($SystemConest[2],",".$_SESSION["Login"]["username"].",")!=false) return true;
}
if($userpower!="")
{
if(preg_match("/".$powerclass."\|[0-9]+/", $userpower,$a1))
{
$p=preg_replace("/".$powerclass."\|/", "", $a1[0]);
if(getUserPower($p,$powervale)) return true;
return false;
}
}
return false;
}
/**
* 在权限管理处显示是否选中
*/
function showischeckpower($userpower,$powerclass,$powervale,$user="")
{
if(checkpower($userpower,$powerclass,$powervale,$user))
{
return "checked";
}
}
/**
* 在具体模块中检查权限值 应用一例 RunCheckPower($_SESSION["Login"]["power"],"news",2);
* @param str $userpower 用户的存储的权限字段
* @param string $powerclass 认证的哪一个模块的权限
* @param int $powervale 查看什么权限 如查看读取权限
* @return 失败弹出对话框,并返回 成功不做处理
*/
function RunCheckPower($userpower,$powerclass,$powervale)
{
if(checkpower($userpower,$powerclass,$powervale)==false)
{
alert("",1,"你没权限或没有登陆,返回!");
die;
}
}
/**
* 生成任意url地址为静态html页面功能
* @param str $url 源url地址 完整的并以http开头
* @param str $hmtlfile 欲生成的html文件,请以“/”开始 命名名规则为常规文件
* @return 成功返回true 失败返回false
*/
function CreateAnyUrltoHtml($url,$htmlfile)
{
if($url!="" and $htmlfile!="" and strstr($htmlfile,".") )
{
require_once RootDir.'/inc/ActionFile.Class.php';
$myc=new ActionFile();
//die($url."<br>@".$htmlfile);
if($myc->CreateAnyPageToPage($url,RootDir.$htmlfile))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
/**
* 计算订单的状态
* @param $ordercando 订单的有效性,1表示接受此订单,2表示推荐相近产品,3表示拒绝服务
* @param $orderfalg 订单状态 值若是del,表示被删除 默认t表示正常,1表示工作人员已回复
* @param $dingjing 支付成功的订单金额
* @param $orderaddtime 下单时间
* @return 返回值是标题的颜色class
* @
*/
function getorderstatus($ordercando,$orderfalg,$dingjing,$orderaddtime)
{
$temp="nowork";//临时变量,初始状态为没有回复处理
if($ordercando=="3") return "historyword";//当订单是取消状态时,显示历史订单
if($orderfalg==1)
{
$temp="yeswork";//已回复
}
if($dingjing>0)
{
$temp="donework";//已执行
}
//当下单时间小时今天30天,并且工作人员没有回复时,表示已成历史订单
if((time()-$orderaddtime)>=60*60*24*30 and $orderfalg!=1)
{
$temp="historyword";//历史订单
}
return $temp;
}
/**
* 格式化显示订单内容
* @param str $str 订单内容
* @return 返回格式化后的内容
*/
function formatOrderInfo($str)
{
//$temp=$temp." <br><b>优惠金额:</b>".getMiddleStr($str,"\{优惠金额\}","\{\/优惠金额\}");//获取优惠金额
$roomsinfo=getMiddleStr($str,"\{房间信息\}","\{\/房间信息\}");//获取房间信息
//print_r($roomsinfo);
if($roomsinfo!="") $temp=$temp."<b>房间信息:</b><br>".$roomsinfo;
$rooms=getMiddleStr($str,"\{房间数\}","\{\/房间数\}");//获取房间数
if($rooms!="") $temp=$temp."<br><b>房间数:</b>".$rooms;
$tel=getMiddleStr($str,"\{电话\}","\{\/电话\}");//获取联系人电话
if($tel!="") $temp=$temp."<br><b>电话:</b>".$tel;
$guojia=getMiddleStr($str,"\{国家\}","\{\/国家\}");
if($guojia!="") $temp=$temp." <br><br><b>国家:</b>".$guojia;
$shengshi= getMiddleStr($str,"\{省市\}","\{\/省市\}");
if($shengshi!="") $temp=$temp." <br><b>省市:</b>".$shengshi;
$xiangxudizi= getMiddleStr($str,"\{详细地址\}","\{\/详细地址\}");
if($xiangxudizi!="") $temp=$temp." <br><b>详细地址:</b>".$xiangxudizi;
return $temp;
}
/**
* 格式化多个客人的资料格式,
* @param string $str
* @param str $spl 默认的连接符
*/
function formatOrderGuests($str,$spl="<br>")
{
$temp="";
//获取成人信息
$chengren=getMiddleStr($str,"\{第[0-9]{1,}位成人\}?","\{\/第[0-9]{1,}位成人\}","all");
$i=1;
foreach($chengren as $v)
{
$temp=$temp."<br><b>第".$i."位成人信息:</b><br>";
$temp=$temp." 客人姓名英文:".getMiddleStr($v,"\{客人姓名英文\}","\{\/客人姓名英文\}");
$temp=$temp." 性别:".getMiddleStr($v,"\{客人性别\}","\{\/客人性别\}");
$temp=$temp." 护照:".getMiddleStr($v,"\{护照\}","\{\/护照\}");
$temp=$temp." 手机:".getMiddleStr($v,"\{手机\}","\{\/手机\}");
$i++;
}
//获取儿童信息
$ertong=getMiddleStr($str,"\{第[0-9]{1,}位小孩\}","\{\/第[0-9]{1,}位小孩\}","all");
$i=1;
foreach($ertong as $v)
{
$temp=$temp."<br><b>第".$i."位小孩信息:</b><br>";
$temp=$temp." 客人姓名英文:".getMiddleStr($v,"\{客人姓名英文\}","\{\/客人姓名英文\}");
$temp=$temp." 客人性别:".getMiddleStr($v,"\{客人性别\}","\{\/客人性别\}");
$temp=$temp." 护照:".getMiddleStr($v,"\{护照\}","\{\/护照\}");
$temp=$temp." 手机:".getMiddleStr($v,"\{手机\}","\{\/手机\}");
$i++;
}
/*
//获取婴儿信息
$i=1;
$yinger=getMiddleStr($str,"\{第[0-9]{1,}位婴儿\}","\{\/第[0-9]{1,}位婴儿\}","all");
foreach($yinger as $v)
{
$temp=$temp."<br><b>第".$i."位婴儿信息:</b><br>";
$temp=$temp." 客人姓名英文:".getMiddleStr($v,"\{客人姓名英文\}","\{\/客人姓名英文\}");
$temp=$temp." 客人性别:".getMiddleStr($v,"\{客人性别\}","\{\/客人性别\}");
$temp=$temp." 护照:".getMiddleStr($v,"\{护照\}","\{\/护照\}");
$temp=$temp." 手机:".getMiddleStr($v,"\{手机\}","\{\/手机\}");
$i++;
}
*/
return $temp;
}
/**
* 输出"checked"字符串
* @param $ystr 值1
* @param $mstr 值2
* @return 若两个参数的值相等,echo"checked" ,否则不处理
*/
function echoChecked($ystr,$mstr="1")
{
if($ystr==$mstr) echo "checked";
}
/**
生成html标签里的textarea
* @param $idstr id值
* @param $dv 当前值
* @param $width 宽
* @param $height 高
* @param $mv 默认值 当当前值为空时,显示默认值
* @return 返回生成的html代码
*/
function ui_textarea($idstr,$dv,$width,$height,$mv="")
{
//$dv=str_replace("'", "\'", $dv);
iconv("gb2312", "utf-8", $dv);
if($dv=="") $dv=$mv;
return "<textarea name='$idstr' id='$idstr' cols='$width' rows='$height'>".$dv."</textarea>";
}
/**
* 是否显示input类型并默认其值或只显示其值
* @param $inputname
* @param $classname input的classname
* @param $showwhere 显示input的条件 当其值为yes或1时符合
* @param $v 其值
*/
function ui_isinput($inputname,$classname,$showwhere,$v,$inputlength="12",$inputtype="text")
{
if($showwhere=="yes" or $showwhere=="1")
{
if($inputtype=="text")
{
return "<input type='text' id='".$inputname."' name='".$inputname."'
class='".$classname."' size='".$inputlength."' value='".htmlspecialchars($v)."'>";
}
elseif ($inputtype=="textarea")
{
return " <textarea id='".$inputname."' name='".$inputname."' class='".$classname."' cols='".$inputlength."' rows='8'>".htmlspecialchars($v)."</textarea>";
}
}
else
{
return $v;
}
}
/**
* 显示一个百度编辑器,
* 在调用此函数前需要引入文件:
* global $SystemConest;
include_once $SystemConest[0].'/inc/editorfilespath.php';
* @param str $v 原字段值
* @param $filename 字段的名称,用于$_post获取值
* @return 返回一个编辑器源码
*/
function geteditor($v,$filename)
{
$r="
<script type='text/plain' id='".$filename."myEditor'>".$v."</script>
<script type='text/javascript'>
var editor".$filename." = new baidu.editor.ui.Editor({
textarea:\"".$filename."\"
});
editor".$filename.".render('".$filename."myEditor');
</script>
";
return $r;
}
/**
给目标字符串进行格式转换
* @param $mstr 源字符串
*/
function ui_ubb($mstr)
{
$mstr=getDelHtml($mstr);
$mstr=str_replace("[b]","<b>",$mstr);
$mstr=str_replace("[/b]","</b>",$mstr);
$mstr=str_replace("[red]","<span style='color:#F00'>",$mstr);
$mstr=str_replace("[/red]","</span>",$mstr);
$mstr=str_replace("[blue]","<span style='color:blue'>",$mstr);
$mstr=str_replace("[/blue]","</span>",$mstr);
//$mstr=str_replace("[p align=","<p style=\"TEXT-ALIGN: ",$mstr);
$mstr=preg_replace("/\[p[\s]*align\=(\w*)\]/i", "<p style='TEXT-ALIGN:\${1}'> ", $mstr);
//$mstr=preg_replace("/(left)|(center)|(right)\]/", "'>", $mstr);
$mstr=str_replace("[/p]", "</p>", $mstr);
$mstr=str_replace("[a","<a",$mstr);
$mstr=str_replace("']","'>",$mstr);
$mstr=str_replace("\"]","\">",$mstr);
$mstr=str_replace("[/a]","</a>",$mstr);
$mstr=str_replace("[img","<img",$mstr);
$mstr=str_replace("\n","<br>",$mstr);
return $mstr;
}
/**
* 替换字符串中的下划线,应用到的情况,是字符串做为参数传递时
* @param $str
*/
function ui_replacexiahuax($str)
{
return str_replace("_", "@#$", $str);
}
/**
* 还原字符串中的下划线,应用到的情况,是字符串做为参数传递传递,下划线被替换成了特殊字符时
* @param $str
*/
function ui_huanyuanxiahuax($str)
{
return str_replace("@#$", "_", $str);
}
/**
* 根据标识返回订单的处理状态
* @param $sflag 数据库里存的处理标识 订单的有效性,1表示接受此订单,2表示推荐相近产品,3表示拒绝服务
* @return 返回不同状态的字符串
*/
function getorderstatius($sflag)
{
if($sflag==1) return "欢迎你预定本产品,你的定单已接受,受理情况或部份变动请参考我们的处理意见";
if($sflag==2) return "欢迎你预定本产品:您指定的服务不能成行,推荐预订以下相近产品或服务";
if($sflag==3) return "对不起,该订单已经失效,";
return "此订单还没有处理,请等待我们工作人员的处理。";
}
/**
一条线路的一个字段没有值时,调用预设的一个文件里的代码,目录是相对于根目录的绝对目录
@param $dv 当前值
* @param $filename 文件名
*/
function ToursOneFileldDeVal($dv,$filename)
{
if($dv=="") return file_get_contents(RootDir."/Tpl/default/tours/".$filename);
return $dv;
}
/**
* 将浮点数转成整型,一般用于将价格后的小数点去掉
* @param $num 数字
* @return 返回整型
*/
function floattoInt($num)
{
return (int)$num;
}
//将$str数字字符串转成大写的中文人民币方式
function TurnDaxienum($str)
{
if(is_numeric($str))
{
$isfloat=0;//是否有小数标识
if(strstr($str,"."))
{
$strarr=explode(".",$str);
$str=$strarr[0];
$isfloat=1;
}
$str=$str."";
$num=strlen($str);
$returnstr="";
$arr=array();
for($i=0;$i<$num;$i++)
{
$returnstr=$returnstr.numRmb($str[$i]);
$arr[$i]=numRmb($str[$i]);
}
$arr=array_reverse($arr);
$arrnew=array();
$i=1;
foreach($arr as $v)
{
if($v!="零")
{
switch($i)
{
case 2:
case 6:
case 10:
$arrnew[$i]=$v."拾";
break;
case 3:
case 7:
case 11:
$arrnew[$i]=$v."百";
break;
case 4:
case 8:
$arrnew[$i]=$v."仟";
break;
case 5:
$arrnew[$i]=$v."万";
break;
case 9:
$arrnew[$i]=$v."亿";
break;
default :
$arrnew[$i]=$v;
break;
}
}
else
{
$arrnew[$i]="零";
}
$i++;
}
$arrnew=array_reverse($arrnew);
$str=arrValuetoStr($arrnew);
if($isfloat==1)//最后结果加上小数部份
{
$numx=strlen($strarr[1]);
$strx="";
for($i=0;$i<$numx;$i++)
{
$strx=$strx.numRmb($strarr[1][$i]);
}
$str=$str.".".$strx;
}
$pattern="/(零)+/";
$str=preg_replace($pattern,"零",$str);//去掉多个零,只留一个零
$pattern="/(零)\./";
$str=preg_replace($pattern,".",$str);//去掉多个零,只留一个零
if(mb_substr($str,mb_strlen($str)-2,2)=="零")//去掉最后一个零
{
$str=mb_substr($str,0,-2);
}
$pattern="/\.(零)\s+/";
$str=preg_replace($pattern,"",$str);//去掉多个零,只留一个零
if(mb_substr($str,strlen($str)-1,1)==".")//去掉最后一个.
{
$str=substr($str,0,-1);
}
return $str;
}
else
{
return $str;
}
}
/**
* 格式化url地址里的与系统符号相冲突的东西
* @param unknown_type $str
*/
function formaturl($str){
$parr=array("/[\-]+/","/[\/]+/");
$rearr=array("","");
return preg_replace($parr, $rearr, $str);
}
/**
* 获取社区用户的头像
* @param $uid 用户id
* @param $type 头像类型
* @param $width 宽度,
* @param $height 高度
* @param $altstr 提示信息
*/
function getUsertouxiang($uid,$type,$width,$height,$altstr)
{
$uid = abs(intval($uid));
$uid = sprintf("%09d", $uid);
$dir1 = substr($uid, 0, 3);
$dir2 = substr($uid, 3, 2);
$dir3 = substr($uid, 5, 2);
$typeadd = $type == 'real' ? '_real' : '';
$strpath= $dir1 . "/" . $dir2 . "/" . $dir3 . "/" . substr($uid, -2) . $typeadd . "_avatar_$type.jpg";
return "<img width='$width' height='$height' alt='$altstr' src='" . SYS_UCcenter . "/data/avatar/" . $strpath . "' onerror=\"this.onerror=null;this.src='" . SYS_UCcenter . "/images/noavatar_". $type . ".gif'\">";
}
/**
* 获取字符串中的第一个图片地址
*/
function getstrtopic($str)
{
$p="/<img(?!>)[\s\S]src\=['|\"]{0,1}([\S][^>]+)['|\"]{0,1}[\s\S]*?>/";
preg_match($p, $str,$temp);
$r= $temp?$temp[0]:"";
return ($r)?preg_replace($p, "$1", $r):"";
}
?>
<? function Form_check()
{
?>
<script language="javascript" >
function len(s) {
var l = 0;
var a = s.split("");
for (var i=0;i<a.length;i++) {
if (a[i].charCodeAt(0)<299) {
l++;
} else {
l+=2;
}
}
return l;
}
function formatTime(str)
{
//验证jja日期格式"2010-1-1" 和 "2010-2-2 12:12"两种形式的日期
if(str.indexOf(":")>1)
{
var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2})$/;
var r = str.match(reg);
if(r==null) return false;
var d = new Date(r[1], r[3]-1,r[4],r[5],r[6]);
if(d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]) return true;
}
else
{
var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
if(r==null) flag=false;
var d= new Date(r[1], r[3]-1, r[4]);
if((d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]))
{
return true;
}
}
}
//验证日期是否合法
function IsValidDate(Value){
if (Value=="")
{
//alert("截止日期不能为空,请输入!");
//document.vbform.bdaynew.focus();
return false;
}
if (formatTime(Value)==false)
{
//alert("截至日期格式错误!");
//cform.bdaynew.focus();
return false;
}
return true;
}
//检查下拉框
function Check_ListBox(Value,ErrMsg)
{
return (Value<1)?ErrMsg:"";
}
//单/复选框检查
function Check_SelectBox(RadioObject,MinLen,MaxLen,ErrMsg)
{
var Radio,ee;
ee="";
var len = RadioObject.length;
var num=0;
for(i=0;i<len;i++)
{
if(RadioObject[i].checked==true) num=num+1;
}
return (num<=MaxLen && num>=MinLen)?"":ErrMsg;
}
//字符长度验证
function CharLen(Value,MinLen,MaxLen,ErrMsg)
{
if(Value.length<MinLen || Value.length>MaxLen) return ErrMsg;
return "";
}
//数字验证
function IsNum(Value,MinValue,MaxValue,ErrMsg)
{
if(isNaN(Value)) return ErrMsg;
if(Value.length=0) return ErrMsg;
return (parseInt(Value)>=MinValue && parseInt(Value)<=MaxValue)?"":ErrMsg;
if(isNaN(Value)) return ErrMsg;
if(Value.length=0) return ErrMsg;
return (parseInt(Value)>=MinValue && parseInt(Value)<=MaxValue)?"":ErrMsg;
}
//日期验证
function IsDateTime(Value,MinValue,MaxValue,ErrMsg)
{
if(IsValidDate(Value)==true)
{ var t=new Date(Value);
var t1=new Date(MinValue);
var t2=new Date(MaxValue);
return (Date.parse(t)-Date.parse(t1)<0 || Date.parse(t)-Date.parse(t2)>0)?ErrMsg:"";
}
else
{
return ErrMsg;
}
}
//邮箱验证
function IsMail(Value,MinLen,MaxLen,ErrMsg)
{
var Regu,Re,Matches,InfoCout;
//对电子邮件的验证
var myreg = /^[\w\-\_\.]+@[\w\-\_\.]+\.[\w]$/;
if(Value!="")
{
if(myreg.test(Value))
{
if(Value.length>=MinLen && Value.length<=MaxLen) return "";
}
}
return ErrMsg;
}
function url(Value,MinLen,MaxLen,ErrMsg)
{
return (Value.length<2)?ErrMsg:"";
}
//显示一个栏目信息
function showoneid(filedid)
{
$(document).ready(function(){
$("#tr_FieldName_"+filedid).show();
});
}
//当str1的值等于str2的值时,才显示
function showoneidbyv(filedid,str1,str2){
$(document).ready(function(){
if(str1==str2){
$("#tr_FieldName_"+filedid).show();
}else{
$("#tr_FieldName_"+filedid).hide();
}
});
}
//隐藏一个栏目信息
function hidelanmu(filedid)
{
$(document).ready(function(){
$("#tr_FieldName_"+filedid).hide();
});
}
</script>
<? }
/**
* 分数字符串,每个分值之间用,分隔
* @param $str1
*/
function gethaopingdu($str1)
{
$temp=preg_replace("/,$/", "", $str1);
$arr=explode(",",$temp);
$sum=0;
$length=count($arr);
foreach($arr as $v){
$sum+=$v;
}
return number_format(($sum / $length)*20.00,2);
}
/**
*
* @param $name cookie名称
* @param $v cookie值
* @param $times 有效时间 值认为7200秒
* @param $domain 有效的域名 默认为整个域名下有效
*/
function setmycookies($name,$v,$times=40000,$domain="/")
{
$times=($times==40000)?time()+40000:time()+times;
setcookie($name,$v,$times,$domain);
}
/**
* 自定义输出变量并停止执行,参数主要用于数组,也可以是字符串
* 主要作用就是为了方便查看输出的数组的值
* @param $str
*/
function mydie($str){
echo "<pre>";
print_r($str);
die;
}
?>
| 10npsite | trunk/inc/Uifunction.php | PHP | asf20 | 39,873 |
<?php
//本页面是本次项目的特殊函数
function geturl($str,$t)
{
if($t=="p") return preg_replace("/@[\S\s]*/", "", $str);
if($t=="w") return preg_replace("/^[\w\-\_\.\/]*@/", "", $str);
}
?> | 10npsite | trunk/inc/pfunction.php | PHP | asf20 | 212 |
<?php
require_once RootDir."/inc/config.php";
?> | 10npsite | trunk/inc/const.php | PHP | asf20 | 50 |
<?php
session_start();
$_SESSION['SafeCode']="";
$type = 'gif';
$width= 50;
$height= 20;
header("Content-type: image/".$type);
srand((double)microtime()*1000000);
$randval = randStr(4,"");
if($type!='gif' && function_exists('imagecreatetruecolor')){
$im = @imagecreatetruecolor($width,$height);
}else{
$im = @imagecreate($width,$height);
}
$r = Array(225,211,255,223);
$g = Array(225,236,237,215);
$b = Array(225,236,166,125);
$key = rand(0,3);
$backColor = ImageColorAllocate($im,$r[$key],$g[$key],$b[$key]);//背景色(随机)
$borderColor = ImageColorAllocate($im, 0, 0, 0);//边框色
$pointColor = ImageColorAllocate($im, 255, 170, 255);//点颜色
@imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);//背景位置
@imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor); //边框位置
$stringColor = ImageColorAllocate($im, 255,51,153);
for($i=0;$i<=100;$i++){
$pointX = rand(2,$width-2);
$pointY = rand(2,$height-2);
@imagesetpixel($im, $pointX, $pointY, $pointColor);
}
@imagestring($im, 3, 5, 1, $randval, $stringColor);
$ImageFun='Image'.$type;
$ImageFun($im);
@ImageDestroy($im);
$_SESSION['SafeCode'] = $randval;
//产生随机字符串
function randStr($len=6,$format='ALL') {
switch($format) {
case 'ALL':
$chars='abcdefghijklmnopqrstuvwxyz0123456789'; break;
case 'CHAR':
$chars='abcdefghijklmnopqrstuvwxyz'; break;
case 'NUMBER':
$chars='0123456789'; break;
default :
$chars='abcdefghijklmnopqrstuvwxyz0123456789';
break;
}
$string="";
while(strlen($string)<$len)
$string.=substr($chars,(mt_rand()%strlen($chars)),1);
return $string;
}
?> | 10npsite | trunk/inc/checkcode.php | PHP | asf20 | 1,699 |
function atCalendarControl(){
var calendar=this;
this.calendarPad=null;
this.prevMonth=null;
this.nextMonth=null;
this.prevYear=null;
this.nextYear=null;
this.goToday=null;
this.calendarClose=null;
this.calendarAbout=null;
this.head=null;
this.body=null;
this.today=[];
this.currentDate=[];
this.sltDate;
this.target;
this.source;
/************** 加入日历底板及阴影 *********************/
this.addCalendarPad=function(){
document.write("<div id='divCalendarpad' style='position:absolute;top:100;left:0;width:255;height:187;display:none;'>");
document.write("<iframe frameborder=0 height=189 width=250></iframe>");
document.write("<div style='position:absolute;top:2;left:2;width:250;height:187;background-color:#336699;'></div>");
document.write("</div>");
calendar.calendarPad=document.all.divCalendarpad;
}
/************** 加入日历面板 *********************/
this.addCalendarBoard=function(){
var BOARD=this;
var divBoard=document.createElement("div");
calendar.calendarPad.insertAdjacentElement("beforeEnd",divBoard);
divBoard.style.cssText="position:absolute;top:0;left:0;width:250;height:187;border:0 outset;background-color:buttonface;";
var tbBoard=document.createElement("table");
divBoard.insertAdjacentElement("beforeEnd",tbBoard);
tbBoard.style.cssText="position:absolute;top:2;left:2;width:248;height:10;font-size:9pt;";
tbBoard.cellPadding=0;
tbBoard.cellSpacing=1;
/************** 设置各功能按钮的功能 *********************/
/*********** Calendar About Button ***************/
trRow = tbBoard.insertRow(0);
calendar.calendarAbout=calendar.insertTbCell(trRow,0,"-","center");
calendar.calendarAbout.title="帮助 快捷键:H";
calendar.calendarAbout.onclick=function(){calendar.about();}
/*********** Calendar Head ***************/
tbCell=trRow.insertCell(1);
tbCell.colSpan=5;
tbCell.bgColor="#99CCFF";
tbCell.align="center";
tbCell.style.cssText = "cursor:default";
calendar.head=tbCell;
/*********** Calendar Close Button ***************/
tbCell=trRow.insertCell(2);
calendar.calendarClose = calendar.insertTbCell(trRow,2,"x","center");
calendar.calendarClose.title="关闭 快捷键:ESC或X";
calendar.calendarClose.onclick=function(){calendar.hide();}
/*********** Calendar PrevYear Button ***************/
trRow = tbBoard.insertRow(1);
calendar.prevYear = calendar.insertTbCell(trRow,0,"<<","center");
calendar.prevYear.title="上一年 快捷键:↑";
calendar.prevYear.onmousedown=function(){
calendar.currentDate[0]--;
calendar.show(calendar.target,calendar.returnTime,calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(calendar.currentDate[2]),calendar.source);
}
/*********** Calendar PrevMonth Button ***************/
calendar.prevMonth = calendar.insertTbCell(trRow,1,"<","center");
calendar.prevMonth.title="上一月 快捷键:←";
calendar.prevMonth.onmousedown=function(){
calendar.currentDate[1]--;
if(calendar.currentDate[1]==0){
calendar.currentDate[1]=12;
calendar.currentDate[0]--;
}
calendar.show(calendar.target,calendar.returnTime,calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(calendar.currentDate[2]),calendar.source);
}
/*********** Calendar Today Button ***************/
calendar.goToday = calendar.insertTbCell(trRow,2,"今天","center",3);
calendar.goToday.title="选择今天 快捷键:T";
calendar.goToday.onclick=function(){
if(calendar.returnTime)
calendar.sltDate=calendar.today[0]+"-"+calendar.formatTime(calendar.today[1])+"-"+calendar.formatTime(calendar.today[2])+" "+calendar.formatTime(calendar.today[3])+":"+calendar.formatTime(calendar.today[4])
else
calendar.sltDate=calendar.today[0]+"-"+calendar.formatTime(calendar.today[1])+"-"+calendar.formatTime(calendar.today[2]);
calendar.target.value=calendar.sltDate;
calendar.hide();
//calendar.show(calendar.target,calendar.today[0]+"-"+calendar.today[1]+"-"+calendar.today[2],calendar.source);
}
/*********** Calendar NextMonth Button ***************/
calendar.nextMonth = calendar.insertTbCell(trRow,3,">","center");
calendar.nextMonth.title="下一月 快捷键:→";
calendar.nextMonth.onmousedown=function(){
calendar.currentDate[1]++;
if(calendar.currentDate[1]==13){
calendar.currentDate[1]=1;
calendar.currentDate[0]++;
}
calendar.show(calendar.target,calendar.returnTime,calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(calendar.currentDate[2]),calendar.source);
}
/*********** Calendar NextYear Button ***************/
calendar.nextYear = calendar.insertTbCell(trRow,4,">>","center");
calendar.nextYear.title="下一年 快捷键:↓";
calendar.nextYear.onmousedown=function(){
calendar.currentDate[0]++;
calendar.show(calendar.target,calendar.returnTime,calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(calendar.currentDate[2]),calendar.source);
}
trRow = tbBoard.insertRow(2);
var cnDateName = new Array("日","一","二","三","四","五","六");
for (var i = 0; i < 7; i++) {
tbCell=trRow.insertCell(i)
tbCell.innerText=cnDateName[i];
tbCell.align="center";
tbCell.width=35;
tbCell.style.cssText="cursor:default;border:1 solid #99CCCC;background-color:#99CCCC;";
}
/*********** Calendar Body ***************/
trRow = tbBoard.insertRow(3);
tbCell=trRow.insertCell(0);
tbCell.colSpan=7;
tbCell.height=97;
tbCell.vAlign="top";
tbCell.bgColor="#F0F0F0";
var tbBody=document.createElement("table");
tbCell.insertAdjacentElement("beforeEnd",tbBody);
tbBody.style.cssText="position:relative;top:0;left:0;width:245;height:103;font-size:9pt;"
tbBody.cellPadding=0;
tbBody.cellSpacing=1;
calendar.body=tbBody;
/*********** Time Body ***************/
trRow = tbBoard.insertRow(4);
tbCell=trRow.insertCell(0);
calendar.prevHours = calendar.insertTbCell(trRow,0,"-","center");
calendar.prevHours.title="小时调整 快捷键:Home";
calendar.prevHours.onmousedown=function(){
calendar.currentDate[3]--;
if(calendar.currentDate[3]==-1) calendar.currentDate[3]=23;
calendar.bottom.innerText=calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4]);
}
tbCell=trRow.insertCell(1);
calendar.nextHours = calendar.insertTbCell(trRow,1,"+","center");
calendar.nextHours.title="小时调整 快捷键:End";
calendar.nextHours.onmousedown=function(){
calendar.currentDate[3]++;
if(calendar.currentDate[3]==24) calendar.currentDate[3]=0;
calendar.bottom.innerText=calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4]);
}
tbCell=trRow.insertCell(2);
tbCell.colSpan=3;
tbCell.bgColor="#99CCFF";
tbCell.align="center";
tbCell.style.cssText = "cursor:default";
calendar.bottom=tbCell;
tbCell=trRow.insertCell(3);
calendar.prevMinutes = calendar.insertTbCell(trRow,3,"-","center");
calendar.prevMinutes.title="分钟调整 快捷键:PageUp";
calendar.prevMinutes.onmousedown=function(){
calendar.currentDate[4]--;
if(calendar.currentDate[4]==-1) calendar.currentDate[4]=59;
calendar.bottom.innerText=calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4]);
}
tbCell=trRow.insertCell(4);
calendar.nextMinutes = calendar.insertTbCell(trRow,4,"+","center");
calendar.nextMinutes.title="分钟调整 快捷键:PageDown";
calendar.nextMinutes.onmousedown=function(){
calendar.currentDate[4]++;
if(calendar.currentDate[4]==60) calendar.currentDate[4]=0;
calendar.bottom.innerText=calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4]);
}
}
/************** 加入功能按钮公共样式 *********************/
this.insertTbCell=function(trRow,cellIndex,TXT,trAlign,tbColSpan){
var tbCell=trRow.insertCell(cellIndex);
if(tbColSpan!=undefined) tbCell.colSpan=tbColSpan;
var btnCell=document.createElement("button");
tbCell.insertAdjacentElement("beforeEnd",btnCell);
btnCell.value=TXT;
btnCell.style.cssText="width:100%;border:1 outset;background-color:buttonface;";
btnCell.onmouseover=function(){
btnCell.style.cssText="width:100%;border:1 outset;background-color:#F0F0F0;";
}
btnCell.onmouseout=function(){
btnCell.style.cssText="width:100%;border:1 outset;background-color:buttonface;";
}
// btnCell.onmousedown=function(){
// btnCell.style.cssText="width:100%;border:1 inset;background-color:#F0F0F0;";
// }
btnCell.onmouseup=function(){
btnCell.style.cssText="width:100%;border:1 outset;background-color:#F0F0F0;";
}
btnCell.onclick=function(){
btnCell.blur();
}
return btnCell;
}
this.setDefaultDate=function(){
var dftDate=new Date();
calendar.today[0]=dftDate.getYear();
calendar.today[1]=dftDate.getMonth()+1;
calendar.today[2]=dftDate.getDate();
calendar.today[3]=dftDate.getHours();
calendar.today[4]=dftDate.getMinutes();
}
/****************** Show Calendar *********************/
this.show=function(targetObject,returnTime,defaultDate,sourceObject){
if(targetObject==undefined) {
alert("未设置目标对象. \n方法: ATCALENDAR.show(obj 目标对象,boolean 是否返回时间,string 默认日期,obj 点击对象);\n\n目标对象:接受日期返回值的对象.\n默认日期:格式为\"yyyy-mm-dd\",缺省为当前日期.\n点击对象:点击这个对象弹出calendar,默认为目标对象.\n");
return false;
}
else calendar.target=targetObject;
if(sourceObject==undefined) calendar.source=calendar.target;
else calendar.source=sourceObject;
if(returnTime) calendar.returnTime=true;
else calendar.returnTime=false;
var firstDay;
var Cells=new Array();
if((defaultDate==undefined) || (defaultDate=="")){
var theDate=new Array();
calendar.head.innerText = calendar.today[0]+"-"+calendar.formatTime(calendar.today[1])+"-"+calendar.formatTime(calendar.today[2]);
calendar.bottom.innerText = calendar.formatTime(calendar.today[3])+":"+calendar.formatTime(calendar.today[4]);
theDate[0]=calendar.today[0]; theDate[1]=calendar.today[1]; theDate[2]=calendar.today[2];
theDate[3]=calendar.today[3]; theDate[4]=calendar.today[4];
}
else{
var Datereg=/^\d{4}-\d{1,2}-\d{2}$/
var DateTimereg=/^(\d{1,4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2})$/
if((!defaultDate.match(Datereg)) && (!defaultDate.match(DateTimereg))){
alert("默认日期(时间)的格式不正确!\t\n\n默认可接受格式为:\n1、yyyy-mm-dd \n2、yyyy-mm-dd hh:mm\n3、(空)");
calendar.setDefaultDate();
return;
}
if(defaultDate.match(Datereg)) defaultDate=defaultDate+" "+calendar.today[3]+":"+calendar.today[4];
var strDateTime=defaultDate.match(DateTimereg);
var theDate=new Array(4)
theDate[0]=strDateTime[1];
theDate[1]=strDateTime[2];
theDate[2]=strDateTime[3];
theDate[3]=strDateTime[4];
theDate[4]=strDateTime[5];
calendar.head.innerText = theDate[0]+"-"+calendar.formatTime(theDate[1])+"-"+calendar.formatTime(theDate[2]);
calendar.bottom.innerText = calendar.formatTime(theDate[3])+":"+calendar.formatTime(theDate[4]);
}
calendar.currentDate[0]=theDate[0];
calendar.currentDate[1]=theDate[1];
calendar.currentDate[2]=theDate[2];
calendar.currentDate[3]=theDate[3];
calendar.currentDate[4]=theDate[4];
theFirstDay=calendar.getFirstDay(theDate[0],theDate[1]);
theMonthLen=theFirstDay+calendar.getMonthLen(theDate[0],theDate[1]);
//calendar.setEventKey();
calendar.calendarPad.style.display="";
var theRows = Math.ceil((theMonthLen)/7);
//清除旧的日历;
while (calendar.body.rows.length > 0) {
calendar.body.deleteRow(0)
}
//建立新的日历;
var n=0;day=0;
for(i=0;i<theRows;i++){
theRow=calendar.body.insertRow(i);
for(j=0;j<7;j++){
n++;
if(n>theFirstDay && n<=theMonthLen){
day=n-theFirstDay;
calendar.insertBodyCell(theRow,j,day);
}
else{
var theCell=theRow.insertCell(j);
theCell.style.cssText="background-color:#F0F0F0;cursor:default;";
}
}
}
//****************调整日历位置**************//
var offsetPos=calendar.getAbsolutePos(calendar.source);//计算对象的位置;
if((document.body.offsetHeight-(offsetPos.y+calendar.source.offsetHeight-document.body.scrollTop))<calendar.calendarPad.style.pixelHeight){
var calTop=offsetPos.y-calendar.calendarPad.style.pixelHeight;
}
else{
var calTop=offsetPos.y+calendar.source.offsetHeight;
}
if((document.body.offsetWidth-(offsetPos.x+calendar.source.offsetWidth-document.body.scrollLeft))>calendar.calendarPad.style.pixelWidth){
var calLeft=offsetPos.x;
}
else{
var calLeft=calendar.source.offsetLeft+calendar.source.offsetWidth;
}
//alert(offsetPos.x);
calendar.calendarPad.style.pixelLeft=calLeft;
calendar.calendarPad.style.pixelTop=calTop;
}
/****************** 计算对象的位置 *************************/
this.getAbsolutePos = function(el) {
var r = { x: el.offsetLeft, y: el.offsetTop };
if (el.offsetParent) {
var tmp = calendar.getAbsolutePos(el.offsetParent);
r.x += tmp.x;
r.y += tmp.y;
}
return r;
};
//************* 插入日期单元格 **************/
this.insertBodyCell=function(theRow,j,day,targetObject){
var theCell=theRow.insertCell(j);
if(j==0) var theBgColor="#FF9999";
else var theBgColor="#FFFFFF";
if(day==calendar.currentDate[2]) var theBgColor="#CCCCCC";
if(day==calendar.today[2]) var theBgColor="#99FFCC";
theCell.bgColor=theBgColor;
theCell.innerText=day;
theCell.align="center";
theCell.width=35;
theCell.style.cssText="border:1 solid #CCCCCC;cursor:hand;";
theCell.onmouseover=function(){
theCell.bgColor="#FFFFCC";
theCell.style.cssText="border:1 outset;cursor:hand;";
}
theCell.onmouseout=function(){
theCell.bgColor=theBgColor;
theCell.style.cssText="border:1 solid #CCCCCC;cursor:hand;";
}
theCell.onmousedown=function(){
theCell.bgColor="#FFFFCC";
theCell.style.cssText="border:1 inset;cursor:hand;";
}
theCell.onclick=function(){
if(calendar.returnTime)
calendar.sltDate=calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(day)+" "+calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4])
else
calendar.sltDate=calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(day);
calendar.target.value=calendar.sltDate;
calendar.hide();
}
}
/************** 取得月份的第一天为星期几 *********************/
this.getFirstDay=function(theYear, theMonth){
var firstDate = new Date(theYear,theMonth-1,1);
return firstDate.getDay();
}
/************** 取得月份共有几天 *********************/
this.getMonthLen=function(theYear, theMonth) {
theMonth--;
var oneDay = 1000 * 60 * 60 * 24;
var thisMonth = new Date(theYear, theMonth, 1);
var nextMonth = new Date(theYear, theMonth + 1, 1);
var len = Math.ceil((nextMonth.getTime() - thisMonth.getTime())/oneDay);
return len;
}
/************** 隐藏日历 *********************/
this.hide=function(){
//calendar.clearEventKey();
calendar.calendarPad.style.display="none";
}
/************** 从这里开始 *********************/
this.setup=function(defaultDate){
calendar.addCalendarPad();
calendar.addCalendarBoard();
calendar.setDefaultDate();
}
/************** 格式化时间 *********************/
this.formatTime = function(str) {
str = ("00"+str);
return str.substr(str.length-2);
}
/************** 关于AgetimeCalendar *********************/
this.about=function(){
var strAbout = "\nWeb 日历选择输入控件操作说明:\n\n";
strAbout+="-\t: 关于\n";
strAbout+="x\t: 隐藏\n";
strAbout+="<<\t: 上一年\n";
strAbout+="<\t: 上一月\n";
strAbout+="今日\t: 返回当天日期\n";
strAbout+=">\t: 下一月\n";
strAbout+="<<\t: 下一年\n";
strAbout+="\nWeb日历选择输入控件\tVer:v1.0\t\nDesigned By:wxb \t\t2004.11.22\t\n";
alert(strAbout);
}
document.onkeydown=function(){
if(calendar.calendarPad.style.display=="none"){
window.event.returnValue= true;
return true ;
}
switch(window.event.keyCode){
case 27 : calendar.hide(); break; //ESC
case 37 : calendar.prevMonth.onmousedown(); break;//←
case 38 : calendar.prevYear.onmousedown();break; //↑
case 39 : calendar.nextMonth.onmousedown(); break;//→
case 40 : calendar.nextYear.onmousedown(); break;//↓
case 84 : calendar.goToday.onclick(); break;//T
case 88 : calendar.hide(); break; //X
case 72 : calendar.about(); break; //H
case 36 : calendar.prevHours.onmousedown(); break;//Home
case 35 : calendar.nextHours.onmousedown(); break;//End
case 33 : calendar.prevMinutes.onmousedown();break; //PageUp
case 34 : calendar.nextMinutes.onmousedown(); break;//PageDown
}
window.event.keyCode = 0;
window.event.returnValue= false;
}
calendar.setup();
}
var CalendarWebControl = new atCalendarControl();
//<input type="text" name="" onFocus="javascript:CalendarWebControl.show(this,false,this.value);"> | 10npsite | trunk/inc/Calendar.js | JavaScript | asf20 | 17,265 |
<%
Private Const BITS_TO_A_BYTE = 8
Private Const BYTES_TO_A_WORD = 4
Private Const BITS_TO_A_WORD = 32
Private m_lOnBits(30)
Private m_l2Power(30)
Private Function LShift(lValue, iShiftBits)
If iShiftBits = 0 Then
LShift = lValue
Exit Function
ElseIf iShiftBits = 31 Then
If lValue And 1 Then
LShift = &H80000000
Else
LShift = 0
End If
Exit Function
ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
Err.Raise 6
End If
If (lValue And m_l2Power(31 - iShiftBits)) Then
LShift = ((lValue And m_lOnBits(31 - (iShiftBits + 1))) * m_l2Power(iShiftBits)) Or &H80000000
Else
LShift = ((lValue And m_lOnBits(31 - iShiftBits)) * m_l2Power(iShiftBits))
End If
End Function
Private Function RShift(lValue, iShiftBits)
If iShiftBits = 0 Then
RShift = lValue
Exit Function
ElseIf iShiftBits = 31 Then
If lValue And &H80000000 Then
RShift = 1
Else
RShift = 0
End If
Exit Function
ElseIf iShiftBits < 0 Or iShiftBits > 31 Then
Err.Raise 6
End If
RShift = (lValue And &H7FFFFFFE) \ m_l2Power(iShiftBits)
If (lValue And &H80000000) Then
RShift = (RShift Or (&H40000000 \ m_l2Power(iShiftBits - 1)))
End If
End Function
Private Function RotateLeft(lValue, iShiftBits)
RotateLeft = LShift(lValue, iShiftBits) Or RShift(lValue, (32 - iShiftBits))
End Function
Private Function AddUnsigned(lX, lY)
Dim lX4
Dim lY4
Dim lX8
Dim lY8
Dim lResult
lX8 = lX And &H80000000
lY8 = lY And &H80000000
lX4 = lX And &H40000000
lY4 = lY And &H40000000
lResult = (lX And &H3FFFFFFF) + (lY And &H3FFFFFFF)
If lX4 And lY4 Then
lResult = lResult Xor &H80000000 Xor lX8 Xor lY8
ElseIf lX4 Or lY4 Then
If lResult And &H40000000 Then
lResult = lResult Xor &HC0000000 Xor lX8 Xor lY8
Else
lResult = lResult Xor &H40000000 Xor lX8 Xor lY8
End If
Else
lResult = lResult Xor lX8 Xor lY8
End If
AddUnsigned = lResult
End Function
Private Function md5_F(x, y, z)
md5_F = (x And y) Or ((Not x) And z)
End Function
Private Function md5_G(x, y, z)
md5_G = (x And z) Or (y And (Not z))
End Function
Private Function md5_H(x, y, z)
md5_H = (x Xor y Xor z)
End Function
Private Function md5_I(x, y, z)
md5_I = (y Xor (x Or (Not z)))
End Function
Private Sub md5_FF(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(md5_F(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub md5_GG(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(md5_G(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub md5_HH(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(md5_H(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Sub md5_II(a, b, c, d, x, s, ac)
a = AddUnsigned(a, AddUnsigned(AddUnsigned(md5_I(b, c, d), x), ac))
a = RotateLeft(a, s)
a = AddUnsigned(a, b)
End Sub
Private Function ConvertToWordArray(sMessage)
Dim lMessageLength
Dim lNumberOfWords
Dim lWordArray()
Dim lBytePosition
Dim lByteCount
Dim lWordCount
Const MODULUS_BITS = 512
Const CONGRUENT_BITS = 448
lMessageLength = Len(sMessage)
lNumberOfWords = (((lMessageLength + ((MODULUS_BITS - CONGRUENT_BITS) \ BITS_TO_A_BYTE)) \ (MODULUS_BITS \ BITS_TO_A_BYTE)) + 1) * (MODULUS_BITS \ BITS_TO_A_WORD)
ReDim lWordArray(lNumberOfWords - 1)
lBytePosition = 0
lByteCount = 0
Do Until lByteCount >= lMessageLength
lWordCount = lByteCount \ BYTES_TO_A_WORD
lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(Asc(Mid(sMessage, lByteCount + 1, 1)), lBytePosition)
lByteCount = lByteCount + 1
Loop
lWordCount = lByteCount \ BYTES_TO_A_WORD
lBytePosition = (lByteCount Mod BYTES_TO_A_WORD) * BITS_TO_A_BYTE
lWordArray(lWordCount) = lWordArray(lWordCount) Or LShift(&H80, lBytePosition)
lWordArray(lNumberOfWords - 2) = LShift(lMessageLength, 3)
lWordArray(lNumberOfWords - 1) = RShift(lMessageLength, 29)
ConvertToWordArray = lWordArray
End Function
Private Function WordToHex(lValue)
Dim lByte
Dim lCount
For lCount = 0 To 3
lByte = RShift(lValue, lCount * BITS_TO_A_BYTE) And m_lOnBits(BITS_TO_A_BYTE - 1)
WordToHex = WordToHex & Right("0" & Hex(lByte), 2)
Next
End Function
Public Function MD5(sMessage)
m_lOnBits(0) = CLng(1)
m_lOnBits(1) = CLng(3)
m_lOnBits(2) = CLng(7)
m_lOnBits(3) = CLng(15)
m_lOnBits(4) = CLng(31)
m_lOnBits(5) = CLng(63)
m_lOnBits(6) = CLng(127)
m_lOnBits(7) = CLng(255)
m_lOnBits(8) = CLng(511)
m_lOnBits(9) = CLng(1023)
m_lOnBits(10) = CLng(2047)
m_lOnBits(11) = CLng(4095)
m_lOnBits(12) = CLng(8191)
m_lOnBits(13) = CLng(16383)
m_lOnBits(14) = CLng(32767)
m_lOnBits(15) = CLng(65535)
m_lOnBits(16) = CLng(131071)
m_lOnBits(17) = CLng(262143)
m_lOnBits(18) = CLng(524287)
m_lOnBits(19) = CLng(1048575)
m_lOnBits(20) = CLng(2097151)
m_lOnBits(21) = CLng(4194303)
m_lOnBits(22) = CLng(8388607)
m_lOnBits(23) = CLng(16777215)
m_lOnBits(24) = CLng(33554431)
m_lOnBits(25) = CLng(67108863)
m_lOnBits(26) = CLng(134217727)
m_lOnBits(27) = CLng(268435455)
m_lOnBits(28) = CLng(536870911)
m_lOnBits(29) = CLng(1073741823)
m_lOnBits(30) = CLng(2147483647)
m_l2Power(0) = CLng(1)
m_l2Power(1) = CLng(2)
m_l2Power(2) = CLng(4)
m_l2Power(3) = CLng(8)
m_l2Power(4) = CLng(16)
m_l2Power(5) = CLng(32)
m_l2Power(6) = CLng(64)
m_l2Power(7) = CLng(128)
m_l2Power(8) = CLng(256)
m_l2Power(9) = CLng(512)
m_l2Power(10) = CLng(1024)
m_l2Power(11) = CLng(2048)
m_l2Power(12) = CLng(4096)
m_l2Power(13) = CLng(8192)
m_l2Power(14) = CLng(16384)
m_l2Power(15) = CLng(32768)
m_l2Power(16) = CLng(65536)
m_l2Power(17) = CLng(131072)
m_l2Power(18) = CLng(262144)
m_l2Power(19) = CLng(524288)
m_l2Power(20) = CLng(1048576)
m_l2Power(21) = CLng(2097152)
m_l2Power(22) = CLng(4194304)
m_l2Power(23) = CLng(8388608)
m_l2Power(24) = CLng(16777216)
m_l2Power(25) = CLng(33554432)
m_l2Power(26) = CLng(67108864)
m_l2Power(27) = CLng(134217728)
m_l2Power(28) = CLng(268435456)
m_l2Power(29) = CLng(536870912)
m_l2Power(30) = CLng(1073741824)
Dim x
Dim k
Dim AA
Dim BB
Dim CC
Dim DD
Dim a
Dim b
Dim c
Dim d
Const S11 = 7
Const S12 = 12
Const S13 = 17
Const S14 = 22
Const S21 = 5
Const S22 = 9
Const S23 = 14
Const S24 = 20
Const S31 = 4
Const S32 = 11
Const S33 = 16
Const S34 = 23
Const S41 = 6
Const S42 = 10
Const S43 = 15
Const S44 = 21
x = ConvertToWordArray(sMessage)
a = &H67452301
b = &HEFCDAB89
c = &H98BADCFE
d = &H10325476
For k = 0 To UBound(x) Step 16
AA = a
BB = b
CC = c
DD = d
md5_FF a, b, c, d, x(k + 0), S11, &HD76AA478
md5_FF d, a, b, c, x(k + 1), S12, &HE8C7B756
md5_FF c, d, a, b, x(k + 2), S13, &H242070DB
md5_FF b, c, d, a, x(k + 3), S14, &HC1BDCEEE
md5_FF a, b, c, d, x(k + 4), S11, &HF57C0FAF
md5_FF d, a, b, c, x(k + 5), S12, &H4787C62A
md5_FF c, d, a, b, x(k + 6), S13, &HA8304613
md5_FF b, c, d, a, x(k + 7), S14, &HFD469501
md5_FF a, b, c, d, x(k + 8), S11, &H698098D8
md5_FF d, a, b, c, x(k + 9), S12, &H8B44F7AF
md5_FF c, d, a, b, x(k + 10), S13, &HFFFF5BB1
md5_FF b, c, d, a, x(k + 11), S14, &H895CD7BE
md5_FF a, b, c, d, x(k + 12), S11, &H6B901122
md5_FF d, a, b, c, x(k + 13), S12, &HFD987193
md5_FF c, d, a, b, x(k + 14), S13, &HA679438E
md5_FF b, c, d, a, x(k + 15), S14, &H49B40821
md5_GG a, b, c, d, x(k + 1), S21, &HF61E2562
md5_GG d, a, b, c, x(k + 6), S22, &HC040B340
md5_GG c, d, a, b, x(k + 11), S23, &H265E5A51
md5_GG b, c, d, a, x(k + 0), S24, &HE9B6C7AA
md5_GG a, b, c, d, x(k + 5), S21, &HD62F105D
md5_GG d, a, b, c, x(k + 10), S22, &H2441453
md5_GG c, d, a, b, x(k + 15), S23, &HD8A1E681
md5_GG b, c, d, a, x(k + 4), S24, &HE7D3FBC8
md5_GG a, b, c, d, x(k + 9), S21, &H21E1CDE6
md5_GG d, a, b, c, x(k + 14), S22, &HC33707D6
md5_GG c, d, a, b, x(k + 3), S23, &HF4D50D87
md5_GG b, c, d, a, x(k + 8), S24, &H455A14ED
md5_GG a, b, c, d, x(k + 13), S21, &HA9E3E905
md5_GG d, a, b, c, x(k + 2), S22, &HFCEFA3F8
md5_GG c, d, a, b, x(k + 7), S23, &H676F02D9
md5_GG b, c, d, a, x(k + 12), S24, &H8D2A4C8A
md5_HH a, b, c, d, x(k + 5), S31, &HFFFA3942
md5_HH d, a, b, c, x(k + 8), S32, &H8771F681
md5_HH c, d, a, b, x(k + 11), S33, &H6D9D6122
md5_HH b, c, d, a, x(k + 14), S34, &HFDE5380C
md5_HH a, b, c, d, x(k + 1), S31, &HA4BEEA44
md5_HH d, a, b, c, x(k + 4), S32, &H4BDECFA9
md5_HH c, d, a, b, x(k + 7), S33, &HF6BB4B60
md5_HH b, c, d, a, x(k + 10), S34, &HBEBFBC70
md5_HH a, b, c, d, x(k + 13), S31, &H289B7EC6
md5_HH d, a, b, c, x(k + 0), S32, &HEAA127FA
md5_HH c, d, a, b, x(k + 3), S33, &HD4EF3085
md5_HH b, c, d, a, x(k + 6), S34, &H4881D05
md5_HH a, b, c, d, x(k + 9), S31, &HD9D4D039
md5_HH d, a, b, c, x(k + 12), S32, &HE6DB99E5
md5_HH c, d, a, b, x(k + 15), S33, &H1FA27CF8
md5_HH b, c, d, a, x(k + 2), S34, &HC4AC5665
md5_II a, b, c, d, x(k + 0), S41, &HF4292244
md5_II d, a, b, c, x(k + 7), S42, &H432AFF97
md5_II c, d, a, b, x(k + 14), S43, &HAB9423A7
md5_II b, c, d, a, x(k + 5), S44, &HFC93A039
md5_II a, b, c, d, x(k + 12), S41, &H655B59C3
md5_II d, a, b, c, x(k + 3), S42, &H8F0CCC92
md5_II c, d, a, b, x(k + 10), S43, &HFFEFF47D
md5_II b, c, d, a, x(k + 1), S44, &H85845DD1
md5_II a, b, c, d, x(k + 8), S41, &H6FA87E4F
md5_II d, a, b, c, x(k + 15), S42, &HFE2CE6E0
md5_II c, d, a, b, x(k + 6), S43, &HA3014314
md5_II b, c, d, a, x(k + 13), S44, &H4E0811A1
md5_II a, b, c, d, x(k + 4), S41, &HF7537E82
md5_II d, a, b, c, x(k + 11), S42, &HBD3AF235
md5_II c, d, a, b, x(k + 2), S43, &H2AD7D2BB
md5_II b, c, d, a, x(k + 9), S44, &HEB86D391
a = AddUnsigned(a, AA)
b = AddUnsigned(b, BB)
c = AddUnsigned(c, CC)
d = AddUnsigned(d, DD)
Next
'MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d))
MD5=LCase(WordToHex(b) & WordToHex(c)) 'I crop this to fit 16byte database password :D
End Function
%>
| 10npsite | trunk/inc/md5.asp | Classic ASP | asf20 | 11,469 |
<?php
/**
名称:邮件发送类!!!
功能:使用SMTP服务器,在PHP代码中发送邮件。
特点:可以使用要求身份验证的SMTP服务器。
*/
class smtpgn
{
var $smtp_port;
var $time_out;
var $host_name;
var $log_file;
var $relay_host;
var $debug;
var $auth;
var $user;
var $pass;
var $sock;
/**初始化邮件类
* @param $relay_host smtp服务器
* @param $smtp_port smtp服务器端口
* @param $auth 是否使用身份认证
* @param $user MTP服务器的用户帐号 如xxx@163.com
* @param $pass 邮箱密码
*/
function smtpgn($relay_host = "", $smtp_port = 25,$auth = false,$user,$pass)
{
$this->debug = FALSE;
$this->smtp_port = $smtp_port;
$this->relay_host = $relay_host;
$this->time_out = 120; //is used in fsockopen()
$this->auth = $auth;//auth
$this->user = $user;
$this->pass = $pass;
$this->host_name = "localhost"; //is used in HELO command
$this->log_file = "";
$this->sock = FALSE;
}
/**
* 执行发送邮件的操作
* @param $nickname 发送邮件的昵称
* @param $to 接收邮箱
* @param $from 发送邮件
* @param $subject 主题
* @param $body 内容
* @param $mailtype 邮件内容 (HTML/TXT),TXT为文本邮件
* @param $cc 抄送
* @param $bcc 密送
* @param $additional_headers 邮件送
* @return 成功返回true 失败返回false
*/
function sendmail($nickname,$to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
{
$mail_from = $this->get_address($this->strip_comment($from));
$body = ereg_replace("(^|(\r\n))(\.)", "\1.\3", $body);
$header .= "MIME-Version:1.0\r\n";
if($mailtype=="HTML")
{
$header .= "Content-Type:text/html ; charset=utf-8 \r\n";
}
$header .= "To: ".$to."\r\n";
if ($cc != "")
{
$header .= "Cc: ".$cc."\r\n";
}
$header .= "From: ".iconv("gb2312", "utf-8", $nickname)."<".$from.">\r\n";
$header .= "Subject: ".$subject."\r\n";
$header .= $additional_headers;
$header .= "Date: ".date("r")."\r\n";
$header .= "X-Mailer:By Redhat (PHP/".phpversion().")\r\n";
list($msec, $sec) = explode(" ", microtime());
$header .= "Message-ID: <".date("YmdHis", $sec).".".($msec*1000000).".".$mail_from.">\r\n";
$TO = explode(",", $this->strip_comment($to));
if ($cc != "")
{
$TO = array_merge($TO, explode(",", $this->strip_comment($cc)));
}
if ($bcc != "")
{
$TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));
}
$sent = TRUE;
foreach ($TO as $rcpt_to)
{
$rcpt_to = $this->get_address($rcpt_to);
if (!$this->smtp_sockopen($rcpt_to)) {
$this->log_write("Error: Cannot send email to ".$rcpt_to."\n");
$sent = FALSE;
continue;
}
if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body))
{
$this->log_write("E-mail has been sent to <".$rcpt_to.">\n");
}
else
{
$this->log_write("Error: Cannot send email to <".$rcpt_to.">\n");
$sent = FALSE;
}
fclose($this->sock);
$this->log_write("Disconnected from remote host\n");
}
return $sent;
}
/* Private Functions */
function smtp_send($helo, $from, $to, $header, $body = "")
{
if (!$this->smtp_putcmd("HELO", $helo)) {
return $this->smtp_error("sending HELO command");
}
#auth
if($this->auth)
{
if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
return $this->smtp_error("sending HELO command");
}
if (!$this->smtp_putcmd("", base64_encode($this->pass))) {
return $this->smtp_error("sending HELO command");
}
}
#
if (!$this->smtp_putcmd("MAIL", "FROM:<".$from.">")) {
return $this->smtp_error("sending MAIL FROM command");
}
if (!$this->smtp_putcmd("RCPT", "TO:<".$to.">")) {
return $this->smtp_error("sending RCPT TO command");
}
if (!$this->smtp_putcmd("DATA")) {
return $this->smtp_error("sending DATA command");
}
if (!$this->smtp_message($header, $body)) {
return $this->smtp_error("sending message");
}
if (!$this->smtp_eom()) {
return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]");
}
if (!$this->smtp_putcmd("QUIT")) {
return $this->smtp_error("sending QUIT command");
}
return TRUE;
}
function smtp_sockopen($address)
{
if ($this->relay_host == "") {
return $this->smtp_sockopen_mx($address);
}
else
{
return $this->smtp_sockopen_relay();
}
}
function smtp_sockopen_relay()
{
$this->log_write("<li/>Trying to ".$this->relay_host.":".$this->smtp_port."\n");
$this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);
if (!($this->sock && $this->smtp_ok())) {
$this->log_write("<li/>Error: Cannot connenct to relay host ".$this->relay_host."\n");
$this->log_write("<li/>Error: ".$errstr." (".$errno.")\n");
return FALSE;
}
$this->log_write("<li/>Connected to relay host ".$this->relay_host."\n");
return TRUE;;
}
function smtp_sockopen_mx($address)
{
$domain = ereg_replace("^.+@([^@]+)$", "\1", $address);
if (!@getmxrr($domain, $MXHOSTS)) {
$this->log_write("<li/>Error: Cannot resolve MX \"".$domain."\"\n");
return FALSE;
}
foreach ($MXHOSTS as $host) {
$this->log_write("<li/>Trying to ".$host.":".$this->smtp_port."\n");
$this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
if (!($this->sock && $this->smtp_ok())) {
$this->log_write("<li/>Warning: Cannot connect to mx host ".$host."\n");
$this->log_write("<li/>Error: ".$errstr." (".$errno.")\n");
continue;
}
$this->log_write("<li/>Connected to mx host ".$host."\n");
return TRUE;
}
$this->log_write("<li/>Error: Cannot connect to any mx hosts (".implode(", ", $MXHOSTS).")\n");
return FALSE;
}
function smtp_message($header, $body)
{
fputs($this->sock, $header."\r\n".$body);
$this->smtp_debug("> ".str_replace("\r\n", "\n"."> ", $header."\n> ".$body."\n> "));
return TRUE;
}
function smtp_eom()
{
fputs($this->sock, "\r\n.\r\n");
$this->smtp_debug(". [EOM]\n");
return $this->smtp_ok();
}
function smtp_ok()
{
$response = str_replace("\r\n", "", fgets($this->sock, 512));
$this->smtp_debug($response."\n");
if (!ereg("^[23]", $response)) {
fputs($this->sock, "QUIT\r\n");
fgets($this->sock, 512);
$this->log_write("<li/>Error: Remote host returned \"".$response."\"\n");
return FALSE;
}
return TRUE;
}
function smtp_putcmd($cmd, $arg = "")
{
if ($arg != "") {
if($cmd=="") $cmd = $arg;
else $cmd = $cmd." ".$arg;
}
fputs($this->sock, $cmd."\r\n");
$this->smtp_debug("> ".$cmd."\n");
return $this->smtp_ok();
}
function smtp_error($string)
{
$this->log_write("<li/>Error: Error occurred while ".$string.".\n");
return FALSE;
}
function log_write($message)
{
$this->smtp_debug($message);
if ($this->log_file == "") {
return TRUE;
}
$message = date("M d H:i:s ").get_current_user()."[".getmypid()."]: ".$message;
if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {
$this->smtp_debug("Warning: Cannot open log file \"".$this->log_file."\"\n");
return FALSE;;
}
flock($fp, LOCK_EX);
fputs($fp, $message);
fclose($fp);
return TRUE;
}
function strip_comment($address)
{
$comment = "\([^()]*\)";
while (ereg($comment, $address)) {
$address = ereg_replace($comment, "", $address);
}
return $address;
}
function get_address($address)
{
$address = ereg_replace("([ \t\r\n])+", "", $address);
$address = ereg_replace("^.*<(.+)>.*$", "\1", $address);
return $address;
}
function smtp_debug($message)
{
if ($this->debug) {
echo $message;
}
}
}
?>
<?php
/*
//使用方法
##########################################
$smtpserver = "smtp.163.com";//SMTP服务器
$smtpserverport =25;//SMTP服务器端口
$smtpusermail = "111111@163.com";//SMTP服务器的用户邮箱
$nickname="jroam";//发送邮箱的昵称
$smtpemailto = "11111@163.com";//发送给谁
$smtpuser = $smtpusermail;//SMTP服务器的用户帐号
$smtppass = "11111";//SMTP服务器的用户密码
$mailsubject = "正式测试可以的话";//邮件主题
$mailbody = "这是内容!请查看";//邮件内容
$mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件
##########################################
$smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
$smtp->debug = false;//是否显示发送的调试信息
$temp=($smtp->sendmail($nickname,$smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype))?"发送成功":"发送失败";
*/
/**
* 梦之旅发送邮件一例
* @param $tomail 发送到的邮箱
* @param $nickname 邮箱显示的昵称
* @param $titlestr 标题
* @param $contenthtml 内容
* @return 成功返回true 失败返回flase
*/
function sendmymail($tomail,$nickname,$titlestr,$contenthtml,$cc="",$bcc="")
{
$smtpserver = "mail.dreams-travel.com";//SMTP服务器
$smtpserverport =25;//SMTP服务器端口
$smtpusermail = "net1@dreams-travel.com";//SMTP服务器的用户邮箱
$nickname=$nickname;//发送邮箱的昵称
$smtpemailto = $tomail;//发送给谁
$smtpuser = $smtpusermail;//SMTP服务器的用户帐号
$smtppass = "szdreams861";//SMTP服务器的用户密码
$sslhttp="";//是否要求要ssl加密连接,若空就不需要
/**
$smtpserver = "smtp.163.com";//SMTP服务器
$smtpserverport =25;//SMTP服务器端口
$smtpusermail = "cduyi05@163.com";//SMTP服务器的用户邮箱
$nickname=$nickname;//发送邮箱的昵称
$smtpemailto = $tomail;//发送给谁
$smtpuser = $smtpusermail;//SMTP服务器的用户帐号
$smtppass = "";//SMTP服务器的用户密码
*/
$mailsubject = $titlestr;//邮件主题
$mailbody = $contenthtml;//邮件内容
$mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件
##########################################
$smtpgn = new smtpgn($sslhttp.$smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
$smtpgn->debug = false;//是否显示发送的调试信息
$temp=($smtpgn->sendmail($nickname,$smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype,$cc))?true:false;
return $temp;
}
/**
* 如果使用gmail发送邮件,请以下列函数实现
* @param unknown_type $formmailaddress 发件箱
* @param unknown_type $formmailsmtp 发件箱的smtp服务器地址
* @param unknown_type $formport 发件箱的端口 gmail的默认465
* @param unknown_type $formpassword 发件箱的密码
* @param unknown_type $formnick 发件箱的昵称
* @param unknown_type $isssl 是否是ssl
* @param unknown_type $subject 主题
* @param unknown_type $body 内容
* @param unknown_type $tomailaddress 接收邮件地址
* @param unknown_type $addcc 抄送邮件地址
* @param unknown_type $AddBCC 密送邮件地址
* @return 成功返回true 失败返回false
*/
function sendgmail($formmailaddress,$formmailsmtp,$formport=465,$formpassword,$formnick,$isssl="",$subject,$body,$tomailaddress,$addcc="",$AddBCC="")
{
require_once(RootDir.'/Index/lib/Public/class.phpmailer.php');
require_once(RootDir.'/Index/lib/Public/class.smtp.php');
$mail = new PHPMailer();
$body = $body;
$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = $isssl; // sets the prefix to the servier
$mail->Host = $formmailsmtp; // sets GMAIL as the SMTP server
$mail->Port = $formport; // set the SMTP port for the GMAIL server
$mail->Username = $formmailaddress; // GMAIL username
$mail->Password = $formpassword; // GMAIL password
$mail->SetFrom($formmailaddress, $formnick);
//$mail->AddReplyTo("name@yourdomain.com","First Last");
$mail->Subject = $subject;
//$mail->AltBody = "2222"; // optional, comment out and test
$mail->MsgHTML($body);
$address = $tomailaddress;
$mail->AddAddress($address);//发送地址
if($addcc!="") $mail->AddCC($addcc);
if($AddBCC!="") $mail->AddBCC($AddBCC);
/*
$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
*/
return ($mail->Send())?true:false;
}
/**
* 自定义的发送gmail邮件函数
* @param $tomail 接收邮件地址
* @param $title 主题
* @param $body 内容
* @param $acc 抄送
* @param $abcc 密送
* @return 发送成功为true,失败为false
*/
function sendmygmail($nick,$tomail,$title,$body,$acc="",$abcc="")
{
$flag=sendgmail("usdreamstravel@gmail.com","smtp.gmail.com",465,"sz168168",$nick,"ssl",$title,$body,$tomail,$acc,$abcc);
return ($flag)?true:false;
}
?>
| 10npsite | trunk/inc/MailClass.php | PHP | asf20 | 13,465 |
<?
//中文语言包
$charsetsys=array(
"tourstitle" => "线路标题",
"toursname" =>"线路名称",
"add" =>"添加",
"keyword"=>"关键字",
"pagetitle" =>"页面标题",
"bianhao" =>"产品编号",
"chufacity" =>"出发城市",
"jieshucity" =>"结束城市",
"chutuandate" =>"出团日期",
"jifen" =>"积分",
"jifenbeishu" =>"积分倍数",
"mobanfile" =>"模板文件",
"htmlurl" =>"页面静态地址",
"xinchengjieshao" =>"行程介绍",
"xinchengtese" =>"行程特色",
"quxiaogunze" =>"取消规则",
"yudingxize" =>"预定细则",
"fabutime" =>"发布时间",
"edittime" =>"修改时间",
"shenghe" =>"审核",
"createor" =>"创建者",
"paixu1" =>"一级排序",
"paixu2" =>"二级排序",
"classname" =>"类别",
"hots" =>"点击数",
"guanliclass" =>"管理类别",
"view" =>"查看",
"action" =>"操作",
"guanlitour" =>"管理线路",
"systemname" =>"梦之旅旅游后台管理系统",
"addtour" =>"添加线路",
"jiazhai" => "正在加载",
"pleaseChoose" =>"请选择"
);
?> | 10npsite | trunk/inc/CharsetLang/cn/charsetsys.php | PHP | asf20 | 1,069 |
<?php require "../global.php";
require "Uifunction.php";
?>
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="/Public/jsLibrary/Jslibary.js"></script>
<style>
body,td{font-size:12px;}
.spanplace{display:none;}
.xztdbgc{background-color:#FFDD99;}
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
}
</style>
<?php
$thismonth=$_REQUEST["thismonth"];//本月值
if($thismonth=="") $thismonth=date("Y-m");
$thefirstdayofweek=date('w',strtotime($thismonth."-01"));//本月第一天是星期几
//如果这个月的第一天不是星期一,那么,它的前面就以上一个月的补齐
//获取前上一个月的日期,以这个月的第一天为基准
function getqiandate($datestr,$num){
return date("Y-m-d",strtotime($datestr)-$num*3600*24);
}
//获取前一个月的日期,返回值是2012-09
function getqimonth($thismonth){
$yearn=preg_replace("/\-[\d]{1,2}$/","",$thismonth);
$month=preg_replace("/^[\d]{4}\-[0]*/","",$thismonth);
$nowmonth=($month==1)?12:$month-1;
if($month==1){
$nowmonth=12;
$yearn=$yearn-1;
}
else{
$nowmonth=$month-1;
}
return $yearn."-".substr("0".$nowmonth,-2);
}
//获取后一个月的日期
function getnextmonth($thismonth){
$yearn=preg_replace("/\-[\d]{1,2}$/","",$thismonth);
$month=preg_replace("/^[\d]{4}\-[0]*/","",$thismonth);
if($month==12){
$month=1;
$yearn+=1;
}
else{
$month+=1;
}
return $yearn."-".substr("0".$month,-2);
}
$qianbunum=$thefirstdayofweek==0?6:$thefirstdayofweek-1;//前面要补的天数
$monthmaxnum=date("t",strtotime($thismonth."-01"));//这个月有多少天
$lastbunum=7-($monthmaxnum+$qianbunum) % 7;
$lastbunum=$lastbunum==7?0:$lastbunum;//获取后面需要被的天数
//计算这次要循环的次数
$maxfornum=$qianbunum+$lastbunum+$monthmaxnum;
//获取本次的开始天数
$stardate= getqiandate($thismonth,$qianbunum);
?>
<div>
<div style="float:left; width:200px; background-color:#FFF">
<table width="200" border="1" cellspacing="0" cellpadding="0" bordercolor="#ccc" style="border-collapse:collapse">
<tr>
<td height="37" colspan="7" align="center"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="31%" height="27"><a href="?MenuId=<? echo $MenuId;?>&fieldid=<? echo $fieldid;?>&hid=<? echo $hid;?>&tid=<? echo $tid;?>&thismonth=<?php $pmonth= getqimonth($thismonth);echo $pmonth; ?>"><?php echo preg_replace("/^[\d]{4}\-[0]*/","",$pmonth);?>月</a></td>
<td width="39%"><strong><?php echo str_replace("-","年",$thismonth)."月";?></strong><span class="spanplace" id="placeall">全选<input type="checkbox" id="cpall"></span></td>
<td width="30%" align="right"><a href="?MenuId=<? echo $MenuId;?>&fieldid=<? echo $fieldid;?>&hid=<? echo $hid;?>&tid=<? echo $tid;?>&thismonth=<?php $nmonth= getnextmonth($thismonth);echo $nmonth;?>"><?php echo preg_replace("/^[\d]{4}\-[0]*/","",$nmonth);?>月</a></td>
</tr>
</table></td>
</tr>
<tr>
<td width="11%" height="25" align="center">一<span class="spanplace" id="place1"><input type="checkbox" id="cpz1"></span></td>
<td width="11%" align="center">二<span class="spanplace" id="place2"><input type="checkbox" id="cpz2"></span></td>
<td width="11%" align="center">三<span class="spanplace" id="place3"><input type="checkbox" id="cpz3"></span></td>
<td width="11%" align="center">四<span class="spanplace" id="place4"><input type="checkbox" id="cpz4"></span></td>
<td width="11%" align="center">五<span class="spanplace" id="place5"><input type="checkbox" id="cpz5"></span></td>
<td width="11%" align="center">六<span class="spanplace" id="place6"><input type="checkbox" id="cpz6"></span></td>
<td width="11%" align="center">日<span class="spanplace" id="place0"><input type="checkbox" id="cpz0"></span></td>
</tr>
<?php
$zcthismonth=turntostrtozc($thismonth);
preg_match_all("/".$zcthismonth."\-[\d]{1,2}\|[\d\.]+\|[\d\.]+\|[\d]*\|[\d]+/",$datecontent,$datecontentarr);//只获取本月的日期值
$dcontentarr=array();//存放本月分解的数值
for($i=1;$i<=$maxfornum;$i++){
$thisv=date("Y-m-d",strtotime($stardate)+($i-1)*3600*24);
if($i %7 ==1){
?> <tr><?php }?>
<td width="11%" align="center" height="25"
<?php if(strstr($thisv,$thismonth)=="" or date("Y-m")>$thismonth or strtotime(date("Y-m-d")) > strtotime($thisv) ){
echo "style='background-color:#ccc;cursor:pointer;' ";}
else{
echo "data='".$thisv."' week='".date("w",strtotime($thisv))."' style='cursor:pointer;'";
}
?>
class="">
<?php echo preg_replace("/^[\d]{4}\-[\d]{1,2}\-[0]*/","",$thisv);?>
</td>
<?php if($i % 7==0){?> </tr><?php }?>
<?php
}
?>
</table>
</div>
</div>
<script language="javascript">
$(document).ready(function(){
$("td[data^='20']").bind("click",function(){
v=$(this).attr("data");
parent.let_Val("<?php echo $_REQUEST["domid"]?>",v);
});
});
</script> | 10npsite | trunk/inc/calendarqitai.php | PHP | asf20 | 5,155 |
<?PHP
//验证用户权限
function GetReadRule($intRuleValue)
{
$GetReadRule=false;
if(!is_numeric($intRuleValue))
return false;
$strRules="1,3,5,9,7,11,13,15,17,19,21,23,25,27,29,31";
$ArrRules=explode(",",$strRules);
foreach($ArrRules as $values){
if($values==$intRuleValue){
$GetReadRule=true;
}
}
return $GetReadRule;
}
//修改权限 4
function GetUpdateRule($intRuleValue)
{
$GetUpdateRule=false;
if(!is_numeric($intRuleValue)) return false;
$strRules="4,5,6,7,12,13,14,15,20,21,22,23,28,29,30,31";
$ArrRules=explode(",",$strRules);
foreach($ArrRules as $v){
if($v==$intRuleValue){
return true;
}
}
return false;
}
//添加权限 2
function GetAddRule($intRuleValue)
{
if(!is_numeric($intRuleValue)) return false;
$strRules="2,3,6,10,7,11,14,15,18,19,22,23,26,27,30,31";
$ArrRules=explode(",",$strRules);
foreach($ArrRules as $v){
if($intRuleValue==$v) return true;
}
return false;
}
//删除权限8
function GetDeleteRule($intRuleValue)
{
if(!is_numeric($intRuleValue)) return false;
$strRules="8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31";
$ArrRules=explode(",",$strRules);
foreach($ArrRules as $v)
{
if($v==$intRuleValue) return true;
}
return false;
}
//审核权限16
function GetShenHeRule($intRuleValue)
{
if(!is_numeric($intRuleValue)) return false;
$strRules="16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31";
$ArrRules=explode(",",$strRules);
foreach($ArrRules as $v)
{
if($v==$intRuleValue) return true;
}
return false;
}
//数据库类
class YYBDB
{
var $ArrFields;//字段列表
var $FieldsCount;//操作字段数
var $TableName; //操作的数据表名称
var $filesConent;//欲插入的值
var $sCreateSQL; //生成的sql语句
var $countTableName;//计算字段数的表名称
var $Returns; //改变返回的影响行数
//连接数据库
function __construct()
{
global $SystemConest;
$hostipaddress=$SystemConest[9];
$mysql_dbdatabase=$SystemConest[10];
$mysql_username=$SystemConest[11];
$mysql_password=$SystemConest[12];
$FieldsCount=0;
$mysqllink=mysql_connect($hostipaddress.":".$SystemConest[13],$mysql_username,$mysql_password);
if(!$mysqllink) die( "数据库连接失败!");
mysql_select_db($mysql_dbdatabase,$mysqllink); //选择 数据库
mysql_query("set names utf8");
}
//查询数据库
function db_select_query($sqlstr)
{
return mysql_query($sqlstr);
}
//更新数据库
function db_update_query($sqlstr)
{
return mysql_query($sqlstr);//发送一条 MySQL 查询 返回资源类型resource
}
function db_query($sqlstr)
{
return mysql_query($sqlstr);//执行查询语句
}
function db_fetch_array($result)
{
return mysql_fetch_array($result);
}
//返回查询的结果行数 用于select
function db_num_rows($result)
{
return mysql_num_rows($result) ;
}
//返回insert into update del的影响行数
function db_affected_rows()
{
return mysql_affected_rows () ;
}
//返回模块数据库表名,暂时特定使用
function getTableName($MenuID)
{
global $SystemTablename;
global $SystemConest;
$sqlrs="Select ".$SystemTablename[2]."0,".$SystemTablename[2]."9 From ". DQ.$SystemTablename[2]." Where ".$SystemTablename[2]."0=$MenuID Order by ".$SystemTablename[2]."0";
$rsc=$this->db_select_query($sqlrs);
$rs=$this->db_fetch_array($rsc);
if($this->db_num_rows($rsc)>0){
return $rs["".$SystemTablename[2]."9"];
}
else
return "";
}
//创建插入语句
function CreateInsSQL(){
$sqlrs="insert into ".$this->countTableName;
for($i=1;$i<=$this->db_num_fields();$i++){//获取字段列表名称
$sqlrs1=$sqlrs1.$this->countTableName."".$i.",";
}
$sqlrs1=substr($sqlrs1,0,-1);//去最后的逗号
$sqlrs=$sqlrs." (".$sqlrs1.") values";
$sqlrs=$sqlrs."(".$this->filesConent.")";
$this->sCreateSQL=$sqlrs;
}
//创建插入语句,通用
function strCreateInsSQL()
{
$strField="";
global $SystemConest;
$max=max(array_keys($this->ArrFields));
for($i=1;$i<=$max;$i++)
{
if(strlen($this->ArrFields[$i])>0)
{
$strField=$strField .$this->TableName .$i . ",";
$tempddd=$this->ArrFields[$i];
if(!get_magic_quotes_gpc()){
$tempddd=addslashes($this->ArrFields[$i]);
}
$values=$values."'".$tempddd."',";
}
}
if(strlen($values)<1 || strlen($strField)<1)
{
return "";
}
$values=substr($values,0,-1);
$strField=substr($strField,0,-1);
return "insert into ".$SystemConest[7].$this->TableName." ($strField) values ($values)";
}
//创建更新语句,通用
//
function strUpdateSQL()
{
global $SystemConest;
$strField="";
$values="";
$i=1;
$n=max(array_keys($this->ArrFields));
for($i=1;$i<=$n;$i++)
{
if(strlen($this->ArrFields[$i])>0)
{
if(is_numeric($this->ArrFields[$i])==true)
{
$values=$values.$this->TableName.$i."=".$this->ArrFields[$i].",";
}
else
{
$tempddd=$this->ArrFields[$i];
if(!get_magic_quotes_gpc())
{
$tempddd=addslashes($this->ArrFields[$i]);
}
$values=$values.$this->TableName.$i."='".$tempddd."',";
}
}
}
if(strlen($values)<2)
{
return "";
}
$values=substr($values,0,-1);
if(strlen($this->ArrFields[0])>0)
{
return "update ".$SystemConest[7].$this->TableName." set $values where ".$this->TableName."0=".$this->ArrFields[0];
}
else
{
return "update ".$SystemConest[7].$this->TableName." set $values";
}
}
//创建删除语句
function strDeleteSQL()
{
global $SystemConest;
if(strlen($this->ArrFields[0])>0)
{
return "delete from ".$SystemConest[7].$this->TableName." where ".$this->TableName."0=".$this->ArrFields[0];
}
}
//创建更新语句
function CreateUpdateSQL($strWhere)
{ //调用方法
global $SystemConest;
$sqlrs="update ".$SystemConest[7].$this->countTableName." set ";
$filesConent_Arr=explode(","," ,".$this->filesConent);
if($this->countTableName=="")
$this->countTableName=$this->TableName;
$sqlstr="select * from ".$SystemConest[7].$this->countTableName." limit 1";
$result=$this->db_select_query($sqlstr);
if($FieldsCount==0)
{
$FieldsCount=$this->db_num_fields($result)-1;
}
for($i=1;$i<=$FieldsCount;$i++)//获取字段列表名称
{
$sqlrs1=$sqlrs1.$this->countTableName."".$i."=".$filesConent_Arr[$i].",";
}
$sqlrs1=substr($sqlrs1,0,-1);//去最后的逗号
$sqlrs=$sqlrs.$sqlrs1;
$sqlrs=$sqlrs." where ".$strWhere;
$this->sCreateSQL=$sqlrs;
}
//创建插入语句
function CreateInsertIntoSQL($strWhere)
{
}
//返回数据表字段数量
function db_num_fields($result)
{
return mysql_num_fields($result);
}
//从结果集中取得列信息并作为对象返回
function db_fetch_field($result)
{
return mysql_fetch_field($result);
}
//返回某个字段的类型
function db_field_type($result,$i)
{
return mysql_field_type($result,$i);
}
//根据字段的类型更改值,以便sql语句的生成
function file_type_chaValues($result,$i,$flag,$where=" like ",$valude)
{
if(mysql_field_type($result,$i)=="string")
{
return $where."'".$flag.$valude.$flag."'";
}
else
{
return "".$valude."";
}
}
//返回配置单中MenuId所在的字段序列号
function getMenuIdNum($MenuId)
{
global $SystemTablename;
global $SystemConest;
$rsc=$this->db_query("select * from ".$SystemConest[7].$SystemTablename[2]." where ".$SystemTablename[2]."0=".$MenuId);
$rs=$this->db_fetch_array($rsc);
if($rs[7]!="")
{
$arr1=explode(",",$rs[7]);
$i=0;
for($i=0;$i<count($arr1);$i++)
{
if(strstr($arr1[$i],"MenuId"))
{
return $i;
}
}
return 0;
}
}
//执行添加操作
function Add()
{
$sqlrs=$this->strCreateInsSQL();
if(strlen($sqlrs)>2)
{
$this->db_query($sqlrs);
$this->Returns=mysql_affected_rows();
}
}
//执行更新操作
function Update()
{
$sqlrs=$this->strUpdateSQL();
if(strlen($sqlrs)>2)
{
$this->db_query($sqlrs);
$this->Returns=mysql_affected_rows();
}
}
//执行删除操作
function Delete()
{
$sqlrs=$this->strDeleteSQL();
if(strlen($sqlrs)>2)
{
$this->db_query($sqlrs);
$this->Returns=mysql_affected_rows();
}
}
//关闭数据库
function db_close()
{
if(!$this->db_close())
{
mysql_close();
}
}
}
class RsPage extends YYBDB
{
//分页类
//在用new新建类时必须传入下面几个参数
//$page,$numShowStyle,$sql,pagecount
/** 用法实例
mypage=new RsPage();
$sqlstr="";查询的sql语句,不要带limit
$mypage->pagecount=$fanyenum;
$mypage->StrPage="p"; 翻页的变量名
$mypage->otherUrl="";//若有值请以"&"开始
$mypage->numShowStyle=0;//显示分页样式
$mypage->sql=$mypage->FenyeSql($sqlstr);
$bsnum=$mypage->ReturnBeginNumber();//用于那个循环的sql语句的起始记录,$bsnum用于具体翻页时的起始数
$rsc=$mypage->db_query($sqlstr." limit $bsnum,".$mypage->pagecount); //这里的$rsc就是获取到了的翻页记录集
要显示翻页的tml代码:echo $mypage->showFenPage();
*/
var $numPage;//共有多少页
var $page;//初始化时默认第几页
var $pagecount;//每页多少条记录
var $sWhereSql;//查询条件
var $recordcount;//共有多少条记录
var $homepage;//首页
var $nextPage;//下页
var $previous;//上一页
var $lastPage;
var $numShowStyle;//显示样式
var $demo;//临时变量
var $begin;
var $TableName;//表名
var $StrPage; //获取分页样式名称 比如p
var $otherUrl;// 附带其它URL参数
var $sql= "";
function Load()
{
//$sqlrs="select count(*) as countnum from ".$this->TableName." where ".$this->sWhereSql;
$rsc=$this->db_query($this->sql);
$this->rsc=$this->db_fetch_array($rsc);
$this->recordcount=$this->rsc["countnum"];
$this->page=$_GET[$this->StrPage];
if($this->page=="" or $this->page=="0" ) {
$this->page="1";
}
if(!intval($this->page))
{
die("请不要修改页面参数");
}
//确定共有多少页
if($this->recordcount % $this->pagecount >0)
{
$this->numPage=(int)($this->recordcount / $this->pagecount)+1;
}
else
{
$this->numPage=(int)($this->recordcount / $this->pagecount);
}
//获取的页面大于总页数时就为总页数
if((int)($this->page)>$this->numPage)
{
$this->page=$this->numPage;
}
$this->page=(int)($this->page);
}
function showFenPage()
{
switch($this->numShowStyle)
{
case 0:
return $this->fenlei1();
break;
}
}
function FenyeSql($sql)
{//把查询sql替换成能分页的sql语句
if($sql!="")
{
return str_replace("*","count(*) as countnum",$sql);
}
else
{
return "";
}
}
function ReturnBeginNumber()
{
$this-> Load();
$r=(($this->page)-1)*$this->pagecount;
if($r<0){
return 0;
}
else{
return $r;
}
}
//分类样式
function fenlei1()
{
if($this->page<>1){
$this->homepage="<a href='?".$this->StrPage."=1".$this->otherUrl."'>首页</a> | ";
}
if($this->page>1){
$this->demo=$this->page-1;
$this->previous="<a href='?".$this->StrPage."=".$this->demo .$this->otherUrl."'>上一页</a> | ";
}
if($this->page<$this->numPage){
$this->demo=$this->page+1;
$this->nextPage="<a href='?".$this->StrPage."=".$this->demo .$this->otherUrl."'>下一页</a> | ";
}
if($this->page<$this->numPage)
{
$this->demo=$this->numPage;
$this->lastPage="<a href='?".$this->StrPage."=".$this->demo .$this->otherUrl."'>末页</a>";
}
return "<div style='margin-right:30px;'>共有".$this->recordcount."条记录,每页".$this->pagecount."条记录,共分".$this->numPage."页,".$this->homepage.$this->previous.$this->nextPage.$this->lastPage." 现在是第".$this->page."页</div>";
}
}
?>
| 10npsite | trunk/inc/dabase_mysql.php | PHP | asf20 | 12,214 |
<?
//文件操作类
//生成文件、删除文件均只能在本站点内操作
class ActionFile
{
var $Root;
function __construct()
{
$this->Root=RootDir;
}
///创建文件夹 在已有文件夹下
function CreateFolder($dir)
{
$dir=$this->Root.$dir;
if (!file_exists($dir))
{
mkdir($dir, 0777);
return true;
}
return false;
}
//删除某一个具体的文件 路径以根目录为准的相对路径
function DelFile($file)
{
if(!unlink($this->Root.$file))
{
return false;
}
return true;
}
//创建文件 $sFile文件名称,$cotent文件内容
function CreatFile($sFile,$content="")
{
$fp= fopen($this->Root.$sFile,"w+");
if(!fwrite($fp,$content))
{
echo "文件操作失败";
return false;
}
fclose($fp);
return true;
}
//删除文件夹和其下的目录及文件
function DelDir($dir="")
{
$dir=$this->Root.$dir;
if($dir=="") return false;
$dh=opendir($dir);
while ($file=readdir($dh))
{//readdir函数返回目录中下一个文件的文件名。文件名以在文件系统中的排序返回
if($file!="." && $file!="..")
{
$fullpath=$dir."/".$file;
if(!is_dir($fullpath))
{//is_dir函数:如果文件名存在并且为目录则返回 TRUE
unlink($fullpath);//unlink函数删除文件
}
else
{
$this->DelDir($fullpath);
}
}
}
closedir($dh);
if(rmdir($dir))
{//rmdir函数删除目录
return true;
}
else
{
return false;
}
}
/**
* 生成任意Url地址为文件
* @param str_url $anyPagUrl 任意可访问的url地址
* @param str $toPagName 欲生成的文件名,传完整的文件名
* @return 成功返回true 失败返回false
*/
function CreateAnyPageToPage($anyPagUrl,$toPagName)
{
//$_SERVER['HTTP_HOST'];//得到当前网址
//要想更改欲生成的网页,只需把$pagurl改了就行
if(strpos($toPagName,"/")>=0)
{
$path=dirname($toPagName);
}
else
{
$path="";
}
$content=@file($anyPagUrl) or die("Failed to open the url ".$anyPagUrl." !");
$content=@join("",$content);
if($path != "")
{
if(!file_exists($path))
{
$this->CreateFolder($path);
}
}
if ($toPagName<>"")
$fp=@fopen($toPagName,"w+") or die("Failed to open the file ".$toPagName." !");
//$content=preg_replace("/PHPSESSID\=[w]{5,}/",$content);
if( @fwrite($fp,$content) )
{
@fclose($fp);
return true;
}
else
{
@fclose($fp);
return false;
}
}
//列出目录下的所有被允许的文件类型
//$allowType为空时表示返回目录下所有的文件及文件夹 返回array
function listDirTree($dirName = NULL,$allowType)
{
$dirName=$this->ROOT.$dirName;
if(!is_dir($dirName))
exit("This is't any path.");
$tree=array();
if ($handle = opendir($dirName ))
{
while (false !== ($file = readdir($handle)))
{
if($allowType!="")
{
if($file!="." and $file!=".." and !strpos($allowType,end(explode(".",$file)))==false)
{
$tree[]=$file;
}
}
else
{
if($file!="." and $file!="..")
{
$tree[]=$file;
}
}
}
closedir($handle);
}
return $tree;
}
//拷贝源文件夹到目标路径下 返加bool
function xCopy($from_dir, $to_dir, $child)
{
//用法:
// xCopy("feiy","feiy2",1):拷贝feiy下的文件到 feiy2,包括子目录
// xCopy("feiy","feiy2",0):拷贝feiy下的文件到 feiy2,不包括子目录
$from_dir= $this->Root.$from_dir;
$to_dir=$this->Root.$to_dir;
if(!is_dir($from_dir)){
echo("Error:the $source is not a direction!");
return false;
}
if(!is_dir($to_dir)){
mkdir($to_dir,0777);
}
$handle=dir($from_dir);
while($entry=$handle->read()) {
if(($entry!=".")&&($entry!="..")){
if(is_dir($from_dir."/".$entry)){
if($child) $this->xCopy($from_dir."/".$entry,$to_dir."/".$entry,$child);
}else{
copy($from_dir."/".$entry,$to_dir."/".$entry);
}
}
}
return true;
}
//播放swf
function PlaySWF($SWFUrl,$sWidth,$sheight)
{
echo "<embed src='".$SWFUrl."' width='".$sWidth."' height='".$sheight."' wmode='transparent' type='application/x-shockwave-flash'>";
}
//播放视频代码
function PlayVedio($url,$sWidth,$shenght)
{
print "
<OBJECT id='NSPlay' codeBase=http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701 type=application/x-oleobject height=".$shenght." standby='Loading Microsoft? Windows Media? Player components...' width=".$sWidth." classid=CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6>
<PARAM NAME='url' VALUE='".$url."'>
<PARAM NAME='rate' VALUE='1'>
<PARAM NAME='balance' VALUE='0'>
<PARAM NAME='playCount' VALUE='1'>
<PARAM NAME='autoStart' VALUE='-1'>
<PARAM NAME='currentMarker' VALUE='0'>
<PARAM NAME='invokeURLs' VALUE='-1'>
<PARAM NAME='baseURL' VALUE=''>
<PARAM NAME='volume' VALUE='100'>
<PARAM NAME='mute' VALUE='0'>
<PARAM NAME='uiMode' VALUE='full'>
<PARAM NAME='stretchToFit' VALUE='0'>
<PARAM NAME='windowlessVideo' VALUE='0'>
<PARAM NAME='enabled' VALUE='-1'>
<PARAM NAME='enableContextMenu' VALUE='-1'>
<PARAM NAME='fullScreen' VALUE='0'>
<PARAM NAME='enableErrorDialogs' VALUE='0'>
</OBJECT>";
}
//读取文件内容
//当$type=1时为读取本地文件内容 为2时,读取任意url地址的html代码
function readFileContent($sFileName,$type="1")
{
if($type=="1" and is_file($sFileName))
{
return file_get_contents($sFileName);
}
elseif($type=="2")
{
$content=@file($sFileName);
if($content)
{
$content=@join("",$content);
return $content;
}
else
{
return null;
}
}
else
{
return null;
}
}
//当写入数据库时转换欲写入的内容的特殊字符
function turnWrite($strContent="")
{
$content = stripslashes($strContent);
$content = eregi_replace("##textarea","<textarea",$content);
$content = eregi_replace("##/textarea","</textarea",$content);
$content = eregi_replace("##form","<form",$content);
$content = eregi_replace("##/form","</form",$content);
return $content;
}
//当在输入框时显示输入框时转换格式
function turnRead($strContent="")
{
$content = eregi_replace("<textarea","##textarea",$strContent);
$content = eregi_replace("</textarea","##/textarea",$content);
$content = eregi_replace("<form","##form",$content);
$content = eregi_replace("</form","##/form",$content);
return $content;
}
}
?> | 10npsite | trunk/inc/ActionFile.Class.php | PHP | asf20 | 6,818 |
import java.io.*;
public class Name2 {
public static void main(String args[]) throws IOException
{
String name;
BufferedReader eingabe = new BufferedReader
(new InputStreamReader(System.in));
System.out.print("Bitte geben Sie Ihren Name ein: ");
name = eingabe.readLine();
System.out.println ("Guten Tag Herr/Frau " + name);
System.out.println(" ");
System.out.println("Programmende HalloName_2");
}
}
| 12foiatim | src/Name2.java | Java | asf20 | 439 |