├── .htaccess ├── Application ├── Common │ ├── Common │ │ └── index.html │ ├── Conf │ │ ├── config.php │ │ └── index.html │ └── index.html ├── Home │ ├── Common │ │ ├── function.php │ │ └── index.html │ ├── Conf │ │ ├── app.php │ │ ├── config.php │ │ └── index.html │ ├── Controller │ │ ├── ApiController.class.php │ │ └── index.html │ ├── Model │ │ ├── AppModel.class.php │ │ └── index.html │ ├── Org │ │ └── Api │ │ │ ├── ApiTool.class.php │ │ │ ├── ApiUtil.class.php │ │ │ ├── ErrorCode.class.php │ │ │ ├── PKCS7Encoder.class.php │ │ │ ├── Prpcrypt.class.php │ │ │ └── SHA1.class.php │ ├── View │ │ └── index.html │ └── index.html ├── README.md ├── Runtime │ ├── Cache │ │ ├── Home │ │ │ ├── 20914c0f075f91df3579ffbdf5180b02.php │ │ │ └── index.html │ │ └── index.html │ ├── Data │ │ └── index.html │ ├── Logs │ │ ├── Home │ │ │ ├── 16_03_18.log │ │ │ └── index.html │ │ └── index.html │ ├── Temp │ │ └── index.html │ └── index.html └── index.html ├── Public └── README.md ├── README.md ├── ThinkPHP ├── Common │ └── functions.php ├── Conf │ ├── convention.php │ └── debug.php ├── LICENSE.txt ├── Lang │ ├── en-us.php │ ├── pt-br.php │ ├── zh-cn.php │ └── zh-tw.php ├── Library │ ├── Behavior │ │ ├── BuildLiteBehavior.class.php │ │ ├── CheckLangBehavior.class.php │ │ ├── ContentReplaceBehavior.class.php │ │ ├── ParseTemplateBehavior.class.php │ │ ├── ReadHtmlCacheBehavior.class.php │ │ ├── ShowPageTraceBehavior.class.php │ │ ├── ShowRuntimeBehavior.class.php │ │ ├── TokenBuildBehavior.class.php │ │ └── WriteHtmlCacheBehavior.class.php │ ├── Think │ │ ├── App.class.php │ │ ├── Build.class.php │ │ ├── Cache.class.php │ │ ├── Cache │ │ │ └── Driver │ │ │ │ ├── Apachenote.class.php │ │ │ │ ├── Apc.class.php │ │ │ │ ├── Db.class.php │ │ │ │ ├── Eaccelerator.class.php │ │ │ │ ├── File.class.php │ │ │ │ ├── Memcache.class.php │ │ │ │ ├── Memcached.class.php │ │ │ │ ├── Memcachesae.class.php │ │ │ │ ├── Redis.class.php │ │ │ │ ├── Shmop.class.php │ │ │ │ ├── Sqlite.class.php │ │ │ │ ├── Wincache.class.php │ │ │ │ └── Xcache.class.php │ │ ├── Controller.class.php │ │ ├── Db.class.php │ │ ├── Db │ │ │ ├── Driver.class.php │ │ │ ├── Driver │ │ │ │ ├── Firebird.class.php │ │ │ │ ├── Mongo.class.php │ │ │ │ ├── Mysql.class.php │ │ │ │ ├── Oracle.class.php │ │ │ │ ├── Pgsql.class.php │ │ │ │ ├── Sqlite.class.php │ │ │ │ └── Sqlsrv.class.php │ │ │ └── Lite.class.php │ │ ├── Dispatcher.class.php │ │ ├── Exception.class.php │ │ ├── Hook.class.php │ │ ├── Log.class.php │ │ ├── Log │ │ │ └── Driver │ │ │ │ ├── File.class.php │ │ │ │ └── Sae.class.php │ │ ├── Model.class.php │ │ ├── Route.class.php │ │ ├── Storage.class.php │ │ ├── Storage │ │ │ └── Driver │ │ │ │ ├── File.class.php │ │ │ │ └── Sae.class.php │ │ ├── Template.class.php │ │ ├── Template │ │ │ ├── Driver │ │ │ │ ├── Ease.class.php │ │ │ │ ├── Lite.class.php │ │ │ │ ├── Mobile.class.php │ │ │ │ ├── Smart.class.php │ │ │ │ └── Smarty.class.php │ │ │ ├── TagLib.class.php │ │ │ └── TagLib │ │ │ │ ├── Cx.class.php │ │ │ │ └── Html.class.php │ │ ├── Think.class.php │ │ └── View.class.php │ └── Vendor │ │ └── README.txt ├── Mode │ └── common.php ├── ThinkPHP.php ├── Tpl │ ├── dispatch_jump.tpl │ ├── page_trace.tpl │ └── think_exception.tpl └── logo.png └── index.php /.htaccess: -------------------------------------------------------------------------------- 1 | 2 | Options +FollowSymlinks 3 | RewriteEngine On 4 | 5 | RewriteCond %{REQUEST_FILENAME} !-d 6 | RewriteCond %{REQUEST_FILENAME} !-f 7 | RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L] 8 | -------------------------------------------------------------------------------- /Application/Common/Common/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/Common/Conf/config.php: -------------------------------------------------------------------------------- 1 | '配置值' 4 | ); -------------------------------------------------------------------------------- /Application/Common/Conf/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/Common/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/Home/Common/function.php: -------------------------------------------------------------------------------- 1 | 6 | * @since 2016-03-18 7 | */ 8 | 9 | /** 10 | * 接口权限检测 11 | */ 12 | function api_check() { 13 | $appid = isset($_POST['appid'])?$_POST['appid']:''; 14 | 15 | if(!$appid) { 16 | return Response(1001, '参数异常'); 17 | } 18 | 19 | //查询应用信息 20 | $appInfo = D('App')->getAppInfo($appid); 21 | if(!$appInfo) { 22 | return Response(1002, '您没有访问权限'); 23 | } 24 | 25 | //判断应用是否需要加密 26 | if($appInfo['is_encryption'] == 1) { 27 | //需要加密 28 | $encrypt = isset($_POST['Encrypt'])?$_POST['Encrypt']:''; 29 | $msgSignature = isset($_POST['MsgSignature'])?$_POST['MsgSignature']:''; 30 | $timeStamp = isset($_POST['TimeStamp'])?$_POST['TimeStamp']:''; 31 | $nonce = isset($_POST['Nonce'])?$_POST['Nonce']:''; 32 | 33 | //判断参数是否完整 34 | if(!$encrypt || !$msgSignature || !$timeStamp || !$nonce) { 35 | return Response(1003, '参数异常'); 36 | } 37 | 38 | //解密数据 39 | $apiTool = new \Home\Org\Api\ApiTool($appInfo); 40 | $decryptData = array(); 41 | $errCode = $apiTool->decryptMsg($msgSignature, $timeStamp, $nonce, $encrypt, $decryptData); 42 | if($errCode == 0) { 43 | $decryptData['_AppInfo'] = $appInfo; 44 | return $decryptData; 45 | } else { 46 | return Response(1004, '您没有访问权限'); 47 | } 48 | } 49 | 50 | //不需要加密 51 | $requestData = $_POST; 52 | 53 | //验证token是否合法 54 | $sign = $requestData['sign']; 55 | if(!$sign) { 56 | return Response(1005, '您没有访问权限'); 57 | } 58 | 59 | $timeStamp = $requestData['timestamp']; 60 | if(!$timeStamp) { 61 | return Response(1006, '请求不合法'); 62 | } 63 | 64 | $newSign = md5($appInfo['token'] . $timeStamp . $appInfo['token']); 65 | 66 | if($newSign != $sign) { 67 | return Response(1007, '您没有访问权限'); 68 | } 69 | 70 | $requestData['_AppInfo'] = $appInfo; 71 | 72 | return $requestData; 73 | } 74 | 75 | /** 76 | * 接口数据响应 77 | * @param type $ResponseCode 响应码 78 | * @param type $ResponseMsg 响应消息 79 | * @param type $ResponseData 响应数据 80 | * @param type $ResponseType 响应数据类型 81 | */ 82 | function Response($ResponseCode = 999,$ResponseMsg = '接口请求成功',$ResponseData = array(),$ResponseType = 'json'){ 83 | if(!is_numeric($ResponseCode)) { 84 | return ''; 85 | } 86 | 87 | //判断数据是否需要加密 88 | $appid = isset($_POST['appid'])?$_POST['appid']:''; 89 | if($appid && is_array($ResponseData) && count($ResponseData)>0) { 90 | $appInfo = D('App')->getAppInfo($appid); 91 | if($appInfo && $appInfo['is_encryption'] == 1) { 92 | $apiTool = new \Home\Org\Api\ApiTool($appInfo); 93 | $encryptData = array(); 94 | $errCode = $apiTool->encryptMsg($ResponseData,$encryptData); 95 | if($errCode == 0) { 96 | $ResponseData = $encryptData; 97 | } 98 | } 99 | } 100 | 101 | $ResponseType = isset($_GET['format']) ? $_GET['format'] : $ResponseType; 102 | 103 | $result = array( 104 | 'Code'=>$ResponseCode, 105 | 'Msg'=>$ResponseMsg, 106 | 'Data'=>$ResponseData 107 | ); 108 | 109 | if($ResponseType == 'json') { 110 | Json($ResponseCode, $ResponseMsg, $ResponseData); 111 | exit(); 112 | } else if($ResponseType == 'xml') { 113 | xmlEncode($ResponseCode, $ResponseMsg, $ResponseData); 114 | exit(); 115 | } else if($ResponseType == 'array') { 116 | var_dump($result); 117 | exit(); 118 | } else { 119 | Json($ResponseCode, $ResponseMsg, $ResponseData); 120 | exit(); 121 | } 122 | } 123 | 124 | /** 125 | * 响应Json格式数据 126 | * @param type $ResponseCode 响应码 127 | * @param type $ResponseMsg 响应消息 128 | * @param type $ResponseData 响应数据 129 | */ 130 | function Json($ResponseCode = 999,$ResponseMsg = '接口请求成功',$ResponseData = array()){ 131 | if(!is_numeric($ResponseCode)) { 132 | return ''; 133 | } 134 | 135 | $result = array( 136 | 'Code'=>$ResponseCode, 137 | 'Msg'=>$ResponseMsg, 138 | 'Data'=>$ResponseData, 139 | 'Type'=>'json' 140 | ); 141 | header("Content-type: text/html; charset=utf-8"); 142 | echo json_encode($result); 143 | exit(); 144 | } 145 | 146 | /** 147 | * 响应xml格式数据 148 | * @param type $ResponseCode 响应码 149 | * @param type $ResponseMsg 响应消息 150 | * @param type $ResponseData 响应数据 151 | */ 152 | function xmlEncode($ResponseCode = 999,$ResponseMsg = '接口请求成功',$ResponseData = array()) { 153 | if (!is_numeric($ResponseCode)) { 154 | return ''; 155 | } 156 | 157 | $result = array( 158 | 'Code'=>$ResponseCode, 159 | 'Msg'=>$ResponseMsg, 160 | 'Data'=>$ResponseData, 161 | 'Type'=>'xml' 162 | ); 163 | 164 | header("Content-Type:text/xml"); 165 | $xml = "\n"; 166 | $xml .= "\n"; 167 | 168 | $xml .= xmlToEncode($result); 169 | 170 | $xml .= ""; 171 | echo $xml; 172 | } 173 | 174 | /** 175 | * 将数据编码成xml格式 176 | * @param type $data 177 | * @return type 178 | */ 179 | function xmlToEncode($data) { 180 | $xml = $attr = ""; 181 | foreach($data as $key => $value) { 182 | if(is_numeric($key)) { 183 | $attr = " id='{$key}'"; 184 | $key = "item"; 185 | } 186 | $xml .= "<{$key}{$attr}>"; 187 | $xml .= is_array($value) ? xmlToEncode($value) : $value; 188 | $xml .= "\n"; 189 | } 190 | return $xml; 191 | } -------------------------------------------------------------------------------- /Application/Home/Common/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/Home/Conf/app.php: -------------------------------------------------------------------------------- 1 | array( 7 | 'testApp' => array( 8 | 'app_id' => 'testApp',//应用id 9 | 'name' => '测试app',//应用名称 10 | 'app_secret' => 'LXnNLLPeFMF839IGzbBRVYMmFvUuB5Q1',//应用秘钥 11 | 'token' => 'MYj0NQn4kBGNc545nc4yCk5Z9j44Y75G',//令牌 12 | 'encoding_AESKey' => 'aIOtFulgOxx2eKKQkhQFbZAqaHjHe8N1FAvYiWA5kpa',//消息加解密密钥 13 | 'is_encryption' => 0,//是否需要加密1是0否 14 | ) 15 | ) 16 | ); -------------------------------------------------------------------------------- /Application/Home/Conf/config.php: -------------------------------------------------------------------------------- 1 | 'app', 5 | ); -------------------------------------------------------------------------------- /Application/Home/Conf/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/Home/Controller/ApiController.class.php: -------------------------------------------------------------------------------- 1 | 8 | * @since 2016-03-18 9 | */ 10 | 11 | class ApiController extends Controller { 12 | 13 | public function __construct() { 14 | parent::__construct(); 15 | } 16 | 17 | /** 18 | * 接口入口 19 | */ 20 | public function index(){ 21 | //检测请求是否合法 22 | $params = api_check(); 23 | 24 | //判断请求接口是否存在 25 | $action = $params['action']; 26 | if(!method_exists($this,$action)) { 27 | return Response(1008, '请求不合法'); 28 | } 29 | 30 | //调用接口 31 | $this->$action($params); 32 | } 33 | 34 | /** 35 | * 测试api接口 36 | * @param type $params 37 | */ 38 | private function testApi($params) { 39 | //应用信息 40 | $appInfo = $params['_AppInfo']; 41 | return Response(999, '数据获取成功',$appInfo); 42 | } 43 | } -------------------------------------------------------------------------------- /Application/Home/Controller/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/Home/Model/AppModel.class.php: -------------------------------------------------------------------------------- 1 | 8 | * @since 2016-03-18 9 | */ 10 | 11 | class AppModel extends Model { 12 | protected $trueTableName = ''; 13 | 14 | /** 15 | * 根据appId获取app信息 16 | * @param type $appId 17 | */ 18 | public function getAppInfo($appId) { 19 | $appList = C('APP'); 20 | 21 | if(isset($appList[$appId])) { 22 | return $appList[$appId]; 23 | } else { 24 | return false; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Application/Home/Model/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/Home/Org/Api/ApiTool.class.php: -------------------------------------------------------------------------------- 1 | 7 | * @since 2016-03-18 8 | */ 9 | 10 | class ApiTool { 11 | //应用ID 12 | private $AppID; 13 | //应用秘钥 14 | private $AppSecret; 15 | //令牌 16 | private $Token; 17 | //消息加解密密钥 18 | private $EncodingAESKey; 19 | 20 | /** 21 | * 构造函数 22 | */ 23 | public function __construct($appInfo) { 24 | //初始化应用配置 25 | $this->AppID = $appInfo['app_id']; 26 | $this->AppSecret = $appInfo['app_secret']; 27 | $this->Token = $appInfo['token']; 28 | $this->EncodingAESKey = $appInfo['encoding_aeskey']; 29 | } 30 | 31 | /** 32 | * 加密数据 33 | * @param type $replyData 需要加密的数据 34 | * @param type $encryptData 加密后的数据 35 | */ 36 | public function encryptMsg($replyData,&$encryptData) { 37 | $timeStamp = time(); 38 | $nonce = \Home\Org\Api\ApiUtil::getNonce(); 39 | $text = json_encode($replyData); 40 | 41 | $apiUtil = new \Home\Org\Api\ApiUtil($this->AppID,$this->AppSecret,$this->Token,$this->EncodingAESKey); 42 | $encryptMsg = ''; 43 | $errCode = $apiUtil->encryptMsg($text, $timeStamp, $nonce, $encryptMsg); 44 | if ($errCode == 0) { 45 | $encryptData = $encryptMsg; 46 | } 47 | return $errCode; 48 | } 49 | 50 | /** 51 | * 解密数据 52 | * @param type $MsgSignature 签名串 53 | * @param type $TimeStamp 时间戳 54 | * @param type $Nonce 随机串 55 | * @param type $Encrypt 密文 56 | * @param type $decryptData 解密后的原文 57 | */ 58 | public function decryptMsg($MsgSignature, $TimeStamp = null, $Nonce, $Encrypt, &$decryptData) { 59 | $apiUtil = new \Home\Org\Api\ApiUtil($this->AppID,$this->AppSecret,$this->Token,$this->EncodingAESKey); 60 | $decryptMsg = ''; 61 | $errCode = $apiUtil->decryptMsg($MsgSignature, $TimeStamp, $Nonce, $Encrypt,$decryptMsg); 62 | if ($errCode == 0) { 63 | $decryptData = json_decode($decryptMsg,true); 64 | } 65 | return $errCode; 66 | } 67 | } -------------------------------------------------------------------------------- /Application/Home/Org/Api/ApiUtil.class.php: -------------------------------------------------------------------------------- 1 | 7 | * @since 2016-03-18 8 | */ 9 | 10 | class ApiUtil { 11 | //应用ID 12 | private $AppID; 13 | //应用秘钥 14 | private $AppSecret; 15 | //令牌 16 | private $Token; 17 | //消息加解密密钥 18 | private $EncodingAESKey; 19 | 20 | /** 21 | * 构造函数 22 | */ 23 | public function __construct($appId,$appSecret,$token,$encodingAESKey) { 24 | //初始化应用配置 25 | $this->AppID = $appId; 26 | $this->AppSecret = $appSecret; 27 | $this->Token = $token; 28 | $this->EncodingAESKey = $encodingAESKey; 29 | } 30 | 31 | /** 32 | * 消息加密 33 | *
    34 | *
  1. 对要发送的消息进行AES-CBC加密
  2. 35 | *
  3. 生成安全签名
  4. 36 | *
  5. 将消息密文和安全签名打包成数组格式
  6. 37 | *
38 | * @param type $replyMsg 需要加密的json数据 39 | * @param type $timeStamp 时间戳 40 | * @param type $nonce 随机串 41 | * @param type $encryptMsg 加密后的可以直接回复用户的密文 42 | */ 43 | public function encryptMsg($replyMsg, $timeStamp, $nonce, &$encryptMsg) { 44 | $pc = new \Home\Org\Api\Prpcrypt($this->EncodingAESKey); 45 | 46 | //加密 47 | $array = $pc->encrypt($replyMsg, $this->AppID); 48 | $ret = $array[0]; 49 | if ($ret != 0) { 50 | return $ret; 51 | } 52 | 53 | if ($timeStamp == null) { 54 | $timeStamp = time(); 55 | } 56 | $encrypt = $array[1]; 57 | 58 | //生成安全签名 59 | $sha1 = new \Home\Org\Api\SHA1; 60 | $array = $sha1->getSHA1($this->Token, $timeStamp, $nonce, $encrypt); 61 | $ret = $array[0]; 62 | if ($ret != 0) { 63 | return $ret; 64 | } 65 | $signature = $array[1]; 66 | 67 | //生成加密数据包 68 | $dataPack = array(); 69 | $dataPack['Encrypt'] = $encrypt; 70 | $dataPack['MsgSignature'] = $signature; 71 | $dataPack['TimeStamp'] = $timeStamp; 72 | $dataPack['Nonce'] = $nonce; 73 | 74 | $encryptMsg = $dataPack; 75 | return \Home\Org\Api\ErrorCode::$OK; 76 | } 77 | 78 | /** 79 | * 检验消息的真实性,并且获取解密后的明文. 80 | *
    81 | *
  1. 利用收到的密文生成安全签名,进行签名验证
  2. 82 | *
  3. 若验证通过,则提取数据包中的加密消息
  4. 83 | *
  5. 对消息进行解密
  6. 84 | *
85 | * 86 | * @param $msgSignature string 签名串,对应URL参数的msg_signature 87 | * @param $timestamp string 时间戳 对应URL参数的timestamp 88 | * @param $nonce string 随机串,对应URL参数的nonce 89 | * @param $postData string 密文,对应POST请求的数据 90 | * @param &$msg string 解密后的原文,当return返回0时有效 91 | * 92 | * @return int 成功0,失败返回对应的错误码 93 | */ 94 | public function decryptMsg($msgSignature, $timestamp = null, $nonce, $encrypt, &$msg) { 95 | if (strlen($this->EncodingAESKey) != 43) { 96 | return \Home\Org\Api\ErrorCode::$IllegalAesKey; 97 | } 98 | 99 | $pc = new \Home\Org\Api\Prpcrypt($this->EncodingAESKey); 100 | 101 | if ($timestamp == null) { 102 | $timestamp = time(); 103 | } 104 | 105 | //验证安全签名 106 | $sha1 = new \Home\Org\Api\SHA1; 107 | $array = $sha1->getSHA1($this->Token, $timestamp, $nonce, $encrypt); 108 | 109 | $ret = $array[0]; 110 | 111 | if ($ret != 0) { 112 | return $ret; 113 | } 114 | 115 | $signature = $array[1]; 116 | if ($signature != $msgSignature) { 117 | return \Home\Org\Api\ErrorCode::$ValidateSignatureError; 118 | } 119 | 120 | $result = $pc->decrypt($encrypt, $this->AppID); 121 | if ($result[0] != 0) { 122 | return $result[0]; 123 | } 124 | $msg = $result[1]; 125 | 126 | return \Home\Org\Api\ErrorCode::$OK; 127 | } 128 | 129 | /** 130 | * 获取随机字符串 131 | * @return string 132 | */ 133 | public static function getNonce($length = 6){ 134 | $length = intval($length); 135 | $str = ""; 136 | $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; 137 | $max = strlen($str_pol) - 1; 138 | for ($i = 0; $i < $length; $i++) { 139 | $str .= $str_pol[mt_rand(0, $max)]; 140 | } 141 | return $str; 142 | } 143 | } -------------------------------------------------------------------------------- /Application/Home/Org/Api/ErrorCode.class.php: -------------------------------------------------------------------------------- 1 | 6 | *
  • -40001: 签名验证错误
  • 7 | *
  • -40002: xml解析失败
  • 8 | *
  • -40003: sha加密生成签名失败
  • 9 | *
  • -40004: encodingAesKey 非法
  • 10 | *
  • -40005: appid 校验错误
  • 11 | *
  • -40006: aes 加密失败
  • 12 | *
  • -40007: aes 解密失败
  • 13 | *
  • -40008: 解密后得到的buffer非法
  • 14 | *
  • -40009: base64加密失败
  • 15 | *
  • -40010: base64解密失败
  • 16 | *
  • -40011: 生成xml失败
  • 17 | * 18 | */ 19 | class ErrorCode { 20 | 21 | public static $OK = 0; 22 | public static $ValidateSignatureError = -40001; 23 | public static $ParseXmlError = -40002; 24 | public static $ComputeSignatureError = -40003; 25 | public static $IllegalAesKey = -40004; 26 | public static $ValidateAppidError = -40005; 27 | public static $EncryptAESError = -40006; 28 | public static $DecryptAESError = -40007; 29 | public static $IllegalBuffer = -40008; 30 | public static $EncodeBase64Error = -40009; 31 | public static $DecodeBase64Error = -40010; 32 | public static $GenReturnXmlError = -40011; 33 | 34 | } -------------------------------------------------------------------------------- /Application/Home/Org/Api/PKCS7Encoder.class.php: -------------------------------------------------------------------------------- 1 | 7 | * @since 2016-03-18 8 | */ 9 | 10 | class PKCS7Encoder { 11 | public static $block_size = 32; 12 | 13 | /** 14 | * 对需要加密的明文进行填充补位 15 | * @param $text 需要进行填充补位操作的明文 16 | * @return 补齐明文字符串 17 | */ 18 | function encode($text) { 19 | $block_size = PKCS7Encoder::$block_size; 20 | $text_length = strlen($text); 21 | //计算需要填充的位数 22 | $amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size); 23 | if ($amount_to_pad == 0) { 24 | $amount_to_pad = PKCS7Encoder::block_size; 25 | } 26 | //获得补位所用的字符 27 | $pad_chr = chr($amount_to_pad); 28 | $tmp = ""; 29 | for ($index = 0; $index < $amount_to_pad; $index++) { 30 | $tmp .= $pad_chr; 31 | } 32 | return $text . $tmp; 33 | } 34 | 35 | /** 36 | * 对解密后的明文进行补位删除 37 | * @param decrypted 解密后的明文 38 | * @return 删除填充补位后的明文 39 | */ 40 | function decode($text) { 41 | 42 | $pad = ord(substr($text, -1)); 43 | if ($pad < 1 || $pad > 32) { 44 | $pad = 0; 45 | } 46 | return substr($text, 0, (strlen($text) - $pad)); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Application/Home/Org/Api/Prpcrypt.class.php: -------------------------------------------------------------------------------- 1 | 7 | * @since 2016-03-18 8 | */ 9 | 10 | class Prpcrypt { 11 | public $key; 12 | function __construct($k) { 13 | $this->key = base64_decode($k . "="); 14 | } 15 | 16 | /** 17 | * 对明文进行加密 18 | * @param string $text 需要加密的明文 19 | * @return string 加密后的密文 20 | */ 21 | public function encrypt($text, $appid) { 22 | try { 23 | //获得16位随机字符串,填充到明文之前 24 | $random = $this->getRandomStr(); 25 | $text = $random . pack("N", strlen($text)) . $text . $appid; 26 | 27 | // 网络字节序 28 | $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); 29 | $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); 30 | $iv = substr($this->key, 0, 16); 31 | 32 | //使用自定义的填充方式对明文进行补位填充 33 | $pkc_encoder = new \Home\Org\Api\PKCS7Encoder; 34 | $text = $pkc_encoder->encode($text); 35 | mcrypt_generic_init($module, $this->key, $iv); 36 | 37 | //加密 38 | $encrypted = mcrypt_generic($module, $text); 39 | mcrypt_generic_deinit($module); 40 | mcrypt_module_close($module); 41 | 42 | //使用BASE64对加密后的字符串进行编码 43 | return array(\Home\Org\Api\ErrorCode::$OK, base64_encode($encrypted)); 44 | } catch (Exception $e) { 45 | return array(\Home\Org\Api\ErrorCode::$EncryptAESError, null); 46 | } 47 | } 48 | 49 | /** 50 | * 对密文进行解密 51 | * @param string $encrypted 需要解密的密文 52 | * @return string 解密得到的明文 53 | */ 54 | public function decrypt($encrypted, $appid) { 55 | try { 56 | //使用BASE64对需要解密的字符串进行解码 57 | $ciphertext_dec = base64_decode($encrypted); 58 | $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); 59 | $iv = substr($this->key, 0, 16); 60 | mcrypt_generic_init($module, $this->key, $iv); 61 | 62 | //解密 63 | $decrypted = mdecrypt_generic($module, $ciphertext_dec); 64 | mcrypt_generic_deinit($module); 65 | mcrypt_module_close($module); 66 | } catch (Exception $e) { 67 | return array(\Home\Org\Api\ErrorCode::$DecryptAESError, null); 68 | } 69 | 70 | try { 71 | //去除补位字符 72 | $pkc_encoder = new \Home\Org\Api\PKCS7Encoder; 73 | $result = $pkc_encoder->decode($decrypted); 74 | //去除16位随机字符串,网络字节序和AppId 75 | if (strlen($result) < 16) 76 | return ""; 77 | $content = substr($result, 16, strlen($result)); 78 | $len_list = unpack("N", substr($content, 0, 4)); 79 | $xml_len = $len_list[1]; 80 | $xml_content = substr($content, 4, $xml_len); 81 | $from_appid = substr($content, $xml_len + 4); 82 | } catch (Exception $e) { 83 | return array(\Home\Org\Api\ErrorCode::$IllegalBuffer, null); 84 | } 85 | if ($from_appid != $appid) 86 | return array(\Home\Org\Api\ErrorCode::$ValidateAppidError, null); 87 | return array(0, $xml_content); 88 | } 89 | 90 | /** 91 | * 随机生成16位字符串 92 | * @return string 生成的字符串 93 | */ 94 | function getRandomStr() { 95 | $str = ""; 96 | $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; 97 | $max = strlen($str_pol) - 1; 98 | for ($i = 0; $i < 16; $i++) { 99 | $str .= $str_pol[mt_rand(0, $max)]; 100 | } 101 | return $str; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /Application/Home/Org/Api/SHA1.class.php: -------------------------------------------------------------------------------- 1 | 7 | * @since 2016-03-18 8 | */ 9 | class SHA1 { 10 | /** 11 | * 用SHA1算法生成安全签名 12 | * @param string $token 票据 13 | * @param string $timestamp 时间戳 14 | * @param string $nonce 随机字符串 15 | * @param string $encrypt 密文消息 16 | */ 17 | public function getSHA1($token, $timestamp, $nonce, $encrypt_msg) { 18 | //排序 19 | try { 20 | $array = array($encrypt_msg, $token, $timestamp, $nonce); 21 | sort($array, SORT_STRING); 22 | $str = implode($array); 23 | return array(\Home\Org\Api\ErrorCode::$OK, sha1($str)); 24 | } catch (Exception $e) { 25 | //print $e . "\n"; 26 | return array(\Home\Org\Api\ErrorCode::$ComputeSignatureError, null); 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Application/Home/View/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/Home/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/README.md: -------------------------------------------------------------------------------- 1 | 项目目录 -------------------------------------------------------------------------------- /Application/Runtime/Cache/Home/20914c0f075f91df3579ffbdf5180b02.php: -------------------------------------------------------------------------------- 1 |

    :)

    欢迎使用 ThinkPHP


    版本 V
    -------------------------------------------------------------------------------- /Application/Runtime/Cache/Home/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/Runtime/Cache/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/Runtime/Data/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/Runtime/Logs/Home/16_03_18.log: -------------------------------------------------------------------------------- 1 | [ 2016-03-18T22:32:37+08:00 ] 127.0.0.1 / 2 | INFO: [ app_init ] --START-- 3 | INFO: Run Behavior\BuildLiteBehavior [ RunTime:0.000024s ] 4 | INFO: [ app_init ] --END-- [ RunTime:0.001216s ] 5 | INFO: [ app_begin ] --START-- 6 | INFO: Run Behavior\ReadHtmlCacheBehavior [ RunTime:0.001378s ] 7 | INFO: [ app_begin ] --END-- [ RunTime:0.001525s ] 8 | INFO: [ view_parse ] --START-- 9 | INFO: [ template_filter ] --START-- 10 | INFO: Run Behavior\ContentReplaceBehavior [ RunTime:0.000726s ] 11 | INFO: [ template_filter ] --END-- [ RunTime:0.000847s ] 12 | INFO: Run Behavior\ParseTemplateBehavior [ RunTime:0.031647s ] 13 | INFO: [ view_parse ] --END-- [ RunTime:0.031761s ] 14 | INFO: [ view_filter ] --START-- 15 | INFO: Run Behavior\WriteHtmlCacheBehavior [ RunTime:0.000370s ] 16 | INFO: [ view_filter ] --END-- [ RunTime:0.000419s ] 17 | INFO: [ app_end ] --START-- 18 | INFO: Run Behavior\ShowPageTraceBehavior [ RunTime:0.000727s ] 19 | INFO: [ app_end ] --END-- [ RunTime:0.000805s ] 20 | 21 | [ 2016-03-18T22:32:37+08:00 ] 127.0.0.1 /favicon.ico 22 | INFO: [ app_init ] --START-- 23 | INFO: Run Behavior\BuildLiteBehavior [ RunTime:0.000018s ] 24 | INFO: [ app_init ] --END-- [ RunTime:0.000525s ] 25 | 26 | [ 2016-03-18T22:32:38+08:00 ] 127.0.0.1 /favicon.ico 27 | INFO: [ app_init ] --START-- 28 | INFO: Run Behavior\BuildLiteBehavior [ RunTime:0.000017s ] 29 | INFO: [ app_init ] --END-- [ RunTime:0.000513s ] 30 | 31 | [ 2016-03-18T23:38:23+08:00 ] 127.0.0.1 / 32 | INFO: [ app_init ] --START-- 33 | INFO: Run Behavior\BuildLiteBehavior [ RunTime:0.000011s ] 34 | INFO: [ app_init ] --END-- [ RunTime:0.000340s ] 35 | INFO: [ app_begin ] --START-- 36 | INFO: Run Behavior\ReadHtmlCacheBehavior [ RunTime:0.000440s ] 37 | INFO: [ app_begin ] --END-- [ RunTime:0.000485s ] 38 | ERR: 无法加载控制器:Index 39 | 40 | -------------------------------------------------------------------------------- /Application/Runtime/Logs/Home/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/Runtime/Logs/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/Runtime/Temp/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/Runtime/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Application/index.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Public/README.md: -------------------------------------------------------------------------------- 1 | 资源文件目录 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # thinkphp-api 2 | 基于thinkphp开发api接口,支持数据加密 3 | 4 | ## 非加密调用 5 | 需要传递以下参数: 6 | 1. appid:分配给每个应用的标识(必传) 7 | 2. timestamp:时间戳(必传) 8 | 3. sign:签名(必传) 9 | 4. action:接口名(必传) 10 | 5. 其他参数 11 | 签名生成规则:md5(token + timestamp + token) 12 | 13 | ## 加密调用 14 | 需要传递以下参数: 15 | 1. appid:分配给每个应用的标识(必传) 16 | 2. Encrypt:密文(必传) 17 | 3. MsgSignature:签名串(必传) 18 | 4. TimeStamp:时间戳(必传) 19 | 5. Nonce:随机串(必传) 20 | 加密方式:AES-CBC -------------------------------------------------------------------------------- /ThinkPHP/Conf/debug.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | /** 13 | * ThinkPHP 默认的调试模式配置文件 14 | */ 15 | defined('THINK_PATH') or exit(); 16 | // 调试模式下面默认设置 可以在应用配置目录下重新定义 debug.php 覆盖 17 | return array( 18 | 'LOG_RECORD' => true, // 进行日志记录 19 | 'LOG_EXCEPTION_RECORD' => true, // 是否记录异常信息日志 20 | 'LOG_LEVEL' => 'EMERG,ALERT,CRIT,ERR,WARN,NOTIC,INFO,DEBUG,SQL', // 允许记录的日志级别 21 | 'DB_FIELDS_CACHE' => false, // 字段缓存信息 22 | 'DB_DEBUG' => true, // 开启调试模式 记录SQL日志 23 | 'TMPL_CACHE_ON' => false, // 是否开启模板编译缓存,设为false则每次都会重新编译 24 | 'TMPL_STRIP_SPACE' => false, // 是否去除模板文件里面的html空格与换行 25 | 'SHOW_ERROR_MSG' => true, // 显示错误信息 26 | 'URL_CASE_INSENSITIVE' => false, // URL区分大小写 27 | ); -------------------------------------------------------------------------------- /ThinkPHP/LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | ThinkPHP遵循Apache2开源协议发布,并提供免费使用。 3 | 版权所有Copyright © 2006-2014 by ThinkPHP (http://thinkphp.cn) 4 | All rights reserved。 5 | ThinkPHP® 商标和著作权所有者为上海顶想信息科技有限公司。 6 | 7 | Apache Licence是著名的非盈利开源组织Apache采用的协议。 8 | 该协议和BSD类似,鼓励代码共享和尊重原作者的著作权, 9 | 允许代码修改,再作为开源或商业软件发布。需要满足 10 | 的条件: 11 | 1. 需要给代码的用户一份Apache Licence ; 12 | 2. 如果你修改了代码,需要在被修改的文件中说明; 13 | 3. 在延伸的代码中(修改和有源代码衍生的代码中)需要 14 | 带有原来代码中的协议,商标,专利声明和其他原来作者规 15 | 定需要包含的说明; 16 | 4. 如果再发布的产品中包含一个Notice文件,则在Notice文 17 | 件中需要带有本协议内容。你可以在Notice中增加自己的 18 | 许可,但不可以表现为对Apache Licence构成更改。 19 | 具体的协议参考:http://www.apache.org/licenses/LICENSE-2.0 20 | 21 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 22 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 23 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 24 | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 25 | COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 26 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 27 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 28 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 29 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 31 | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 32 | POSSIBILITY OF SUCH DAMAGE. 33 | -------------------------------------------------------------------------------- /ThinkPHP/Lang/en-us.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | /** 13 | * ThinkPHP English language package 14 | */ 15 | return array( 16 | /* core language package */ 17 | '_MODULE_NOT_EXIST_' => "Module can't be loaded", 18 | '_CONTROLLER_NOT_EXIST_' => "Controller can't be loaded", 19 | '_ERROR_ACTION_' => 'Illegal Action', 20 | '_LANGUAGE_NOT_LOAD_' => "Can't load language package", 21 | '_TEMPLATE_NOT_EXIST_' => "Template doesn't exist", 22 | '_MODULE_' => 'Module', 23 | '_ACTION_' => 'Action', 24 | '_MODEL_NOT_EXIST_' => "Model can't be loaded", 25 | '_VALID_ACCESS_' => 'No access', 26 | '_XML_TAG_ERROR_' => 'XML tag syntax errors', 27 | '_DATA_TYPE_INVALID_' => 'Illegal data objects!', 28 | '_OPERATION_WRONG_' => 'Operation error occurs', 29 | '_NOT_LOAD_DB_' => 'Unable to load the database', 30 | '_NO_DB_DRIVER_' => 'Unable to load database driver', 31 | '_NOT_SUPPORT_DB_' => 'The system is temporarily not support database', 32 | '_NO_DB_CONFIG_' => 'Not define the database configuration', 33 | '_NOT_SUPPORT_' => 'The system does not support', 34 | '_CACHE_TYPE_INVALID_' => 'Unable to load the cache type', 35 | '_FILE_NOT_WRITABLE_' => 'Directory (file) is not writable', 36 | '_METHOD_NOT_EXIST_' => 'The method you requested does not exist!', 37 | '_CLASS_NOT_EXIST_' => 'Instantiating a class does not exist!', 38 | '_CLASS_CONFLICT_' => 'Class name conflicts', 39 | '_TEMPLATE_ERROR_' => 'Template Engine errors', 40 | '_CACHE_WRITE_ERROR_' => 'Cache file write failed!', 41 | '_TAGLIB_NOT_EXIST_' => 'Tag library is not defined', 42 | '_OPERATION_FAIL_' => 'Operation failed!', 43 | '_OPERATION_SUCCESS_' => 'Operation succeed!', 44 | '_SELECT_NOT_EXIST_' => 'Record does not exist!', 45 | '_EXPRESS_ERROR_' => 'Expression errors', 46 | '_TOKEN_ERROR_' => "Form's token errors", 47 | '_RECORD_HAS_UPDATE_' => 'Record has been updated', 48 | '_NOT_ALLOW_PHP_' => 'PHP codes are not allowed in the template', 49 | '_PARAM_ERROR_' => 'Parameter error or undefined', 50 | '_ERROR_QUERY_EXPRESS_' => 'Query express error', 51 | ); 52 | -------------------------------------------------------------------------------- /ThinkPHP/Lang/pt-br.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | /** 13 | * ThinkPHP Portuguese language package 14 | */ 15 | return array( 16 | /* core language package */ 17 | '_MODULE_NOT_EXIST_' => "Módulo não pode ser carregado", 18 | '_CONTROLLER_NOT_EXIST_' => "Controller não pode ser carregado", 19 | '_ERROR_ACTION_' => 'Ação ilegal', 20 | '_LANGUAGE_NOT_LOAD_' => "Não é possível carregar pacote da linguagem", 21 | '_TEMPLATE_NOT_EXIST_' => "Template não existe", 22 | '_MODULE_' => 'Módulo', 23 | '_ACTION_' => 'Ação', 24 | '_MODEL_NOT_EXIST_' => "Modelo não pode ser carregado", 25 | '_VALID_ACCESS_' => 'Sem acesso', 26 | '_XML_TAG_ERROR_' => 'Erro de sintaxe - XML tag', 27 | '_DATA_TYPE_INVALID_' => 'Tipos de dados ilegais!', 28 | '_OPERATION_WRONG_' => 'Erro na operação', 29 | '_NOT_LOAD_DB_' => 'Impossível carregar banco de dados', 30 | '_NO_DB_DRIVER_' => 'Impossível carregar driver do bando de dados', 31 | '_NOT_SUPPORT_DB_' => 'Temporariamente sem suporte ao banco', 32 | '_NO_DB_CONFIG_' => 'Não define a configuração do banco', 33 | '_NOT_SUPPORT_' => 'O sistema não suporta', 34 | '_CACHE_TYPE_INVALID_' => 'Impossível carregar o tipo de cache', 35 | '_FILE_NOT_WRITABLE_' => 'Diretório (arquivo) não pode ser escrito', 36 | '_METHOD_NOT_EXIST_' => 'O método solicitado não existe!', 37 | '_CLASS_NOT_EXIST_' => 'Não existe instância da classe', 38 | '_CLASS_CONFLICT_' => 'Conflitos com nome da classe', 39 | '_TEMPLATE_ERROR_' => 'Erros na contrução do template', 40 | '_CACHE_WRITE_ERROR_' => 'Escrita do arquivo de cache falhou!', 41 | '_TAGLIB_NOT_EXIST_' => 'Biblioteca da tag não foi definida', 42 | '_OPERATION_FAIL_' => 'Operação falhou!', 43 | '_OPERATION_SUCCESS_' => 'Operação bem sucessida!', 44 | '_SELECT_NOT_EXIST_' => 'Gravação não existe!', 45 | '_EXPRESS_ERROR_' => 'Erros de expressão', 46 | '_TOKEN_ERROR_' => 'Erro no token do formulário', 47 | '_RECORD_HAS_UPDATE_' => 'Gravação não foi atualizada', 48 | '_NOT_ALLOW_PHP_' => 'Código PHP não é permitido no template', 49 | '_PARAM_ERROR_' => 'Parâmetro errado ou indefinido', 50 | '_ERROR_QUERY_EXPRESS_' => 'Erros na expressão da query', 51 | ); 52 | -------------------------------------------------------------------------------- /ThinkPHP/Lang/zh-cn.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | /** 13 | * ThinkPHP 简体中文语言包 14 | */ 15 | return array( 16 | /* 核心语言变量 */ 17 | '_MODULE_NOT_EXIST_' => '无法加载模块', 18 | '_CONTROLLER_NOT_EXIST_' => '无法加载控制器', 19 | '_ERROR_ACTION_' => '非法操作', 20 | '_LANGUAGE_NOT_LOAD_' => '无法加载语言包', 21 | '_TEMPLATE_NOT_EXIST_' => '模板不存在', 22 | '_MODULE_' => '模块', 23 | '_ACTION_' => '操作', 24 | '_MODEL_NOT_EXIST_' => '模型不存在或者没有定义', 25 | '_VALID_ACCESS_' => '没有权限', 26 | '_XML_TAG_ERROR_' => 'XML标签语法错误', 27 | '_DATA_TYPE_INVALID_' => '非法数据对象!', 28 | '_OPERATION_WRONG_' => '操作出现错误', 29 | '_NOT_LOAD_DB_' => '无法加载数据库', 30 | '_NO_DB_DRIVER_' => '无法加载数据库驱动', 31 | '_NOT_SUPPORT_DB_' => '系统暂时不支持数据库', 32 | '_NO_DB_CONFIG_' => '没有定义数据库配置', 33 | '_NOT_SUPPORT_' => '系统不支持', 34 | '_CACHE_TYPE_INVALID_' => '无法加载缓存类型', 35 | '_FILE_NOT_WRITABLE_' => '目录(文件)不可写', 36 | '_METHOD_NOT_EXIST_' => '方法不存在!', 37 | '_CLASS_NOT_EXIST_' => '实例化一个不存在的类!', 38 | '_CLASS_CONFLICT_' => '类名冲突', 39 | '_TEMPLATE_ERROR_' => '模板引擎错误', 40 | '_CACHE_WRITE_ERROR_' => '缓存文件写入失败!', 41 | '_TAGLIB_NOT_EXIST_' => '标签库未定义', 42 | '_OPERATION_FAIL_' => '操作失败!', 43 | '_OPERATION_SUCCESS_' => '操作成功!', 44 | '_SELECT_NOT_EXIST_' => '记录不存在!', 45 | '_EXPRESS_ERROR_' => '表达式错误', 46 | '_TOKEN_ERROR_' => '表单令牌错误', 47 | '_RECORD_HAS_UPDATE_' => '记录已经更新', 48 | '_NOT_ALLOW_PHP_' => '模板禁用PHP代码', 49 | '_PARAM_ERROR_' => '参数错误或者未定义', 50 | '_ERROR_QUERY_EXPRESS_' => '错误的查询条件', 51 | ); 52 | -------------------------------------------------------------------------------- /ThinkPHP/Lang/zh-tw.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | /** 13 | * ThinkPHP 繁体中文語言包 14 | */ 15 | return array( 16 | /* 核心語言變數 */ 17 | '_MODULE_NOT_EXIST_' => '無法載入模組', 18 | '_CONTROLLER_NOT_EXIST_' => '無法載入控制器', 19 | '_ERROR_ACTION_' => '非法操作', 20 | '_LANGUAGE_NOT_LOAD_' => '無法載入語言包', 21 | '_TEMPLATE_NOT_EXIST_' => '模板不存在', 22 | '_MODULE_' => '模組', 23 | '_ACTION_' => '操作', 24 | '_MODEL_NOT_EXIST_' => '模型不存在或者沒有定義', 25 | '_VALID_ACCESS_' => '沒有權限', 26 | '_XML_TAG_ERROR_' => 'XML標籤語法錯誤', 27 | '_DATA_TYPE_INVALID_' => '非法資料物件!', 28 | '_OPERATION_WRONG_' => '操作出現錯誤', 29 | '_NOT_LOAD_DB_' => '無法載入資料庫', 30 | '_NO_DB_DRIVER_' => '無法載入資料庫驅動', 31 | '_NOT_SUPPORT_DB_' => '系統暫時不支援資料庫', 32 | '_NO_DB_CONFIG_' => '沒有定義資料庫設定', 33 | '_NOT_SUPPORT_' => '系統不支援', 34 | '_CACHE_TYPE_INVALID_' => '無法載入快取類型', 35 | '_FILE_NOT_WRITABLE_' => '目錄(檔案)不可寫', 36 | '_METHOD_NOT_EXIST_' => '方法不存在!', 37 | '_CLASS_NOT_EXIST_' => '實例化一個不存在的類別!', 38 | '_CLASS_CONFLICT_' => '類別名稱衝突', 39 | '_TEMPLATE_ERROR_' => '模板引擎錯誤', 40 | '_CACHE_WRITE_ERROR_' => '快取檔案寫入失敗!', 41 | '_TAGLIB_NOT_EXIST_' => '標籤庫未定義', 42 | '_OPERATION_FAIL_' => '操作失敗!', 43 | '_OPERATION_SUCCESS_' => '操作成功!', 44 | '_SELECT_NOT_EXIST_' => '記錄不存在!', 45 | '_EXPRESS_ERROR_' => '運算式錯誤', 46 | '_TOKEN_ERROR_' => '表單權限錯誤', 47 | '_RECORD_HAS_UPDATE_' => '記錄已經更新', 48 | '_NOT_ALLOW_PHP_' => '模板禁用PHP代碼', 49 | '_PARAM_ERROR_' => '參數錯誤或者未定義', 50 | '_ERROR_QUERY_EXPRESS_' => '錯誤的查詢條件', 51 | ); 52 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Behavior/BuildLiteBehavior.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Behavior; 12 | // 创建Lite运行文件 13 | // 可以替换框架入口文件运行 14 | // 建议绑定位置app_init 15 | class BuildLiteBehavior { 16 | public function run(&$params) { 17 | if(!defined('BUILD_LITE_FILE')) return ; 18 | $litefile = C('RUNTIME_LITE_FILE',null,RUNTIME_PATH.'lite.php'); 19 | if(is_file($litefile)) return; 20 | 21 | $defs = get_defined_constants(TRUE); 22 | $content = 'namespace {$GLOBALS[\'_beginTime\'] = microtime(TRUE);'; 23 | if(MEMORY_LIMIT_ON) { 24 | $content .= '$GLOBALS[\'_startUseMems\'] = memory_get_usage();'; 25 | } 26 | 27 | // 生成数组定义 28 | unset($defs['user']['BUILD_LITE_FILE']); 29 | $content .= $this->buildArrayDefine($defs['user']).'}'; 30 | 31 | // 读取编译列表文件 32 | $filelist = is_file(CONF_PATH.'lite.php')? 33 | include CONF_PATH.'lite.php': 34 | array( 35 | THINK_PATH.'Common/functions.php', 36 | COMMON_PATH.'Common/function.php', 37 | CORE_PATH . 'Think'.EXT, 38 | CORE_PATH . 'Hook'.EXT, 39 | CORE_PATH . 'App'.EXT, 40 | CORE_PATH . 'Dispatcher'.EXT, 41 | CORE_PATH . 'Log'.EXT, 42 | CORE_PATH . 'Log/Driver/File'.EXT, 43 | CORE_PATH . 'Route'.EXT, 44 | CORE_PATH . 'Controller'.EXT, 45 | CORE_PATH . 'View'.EXT, 46 | CORE_PATH . 'Storage'.EXT, 47 | CORE_PATH . 'Storage/Driver/File'.EXT, 48 | CORE_PATH . 'Exception'.EXT, 49 | BEHAVIOR_PATH . 'ParseTemplateBehavior'.EXT, 50 | BEHAVIOR_PATH . 'ContentReplaceBehavior'.EXT, 51 | ); 52 | 53 | // 编译文件 54 | foreach ($filelist as $file){ 55 | if(is_file($file)) { 56 | $content .= compile($file); 57 | } 58 | } 59 | 60 | // 处理Think类的start方法 61 | $content = preg_replace('/\$runtimefile = RUNTIME_PATH(.+?)(if\(APP_STATUS)/','\2',$content,1); 62 | $content .= "\nnamespace { Think\Think::addMap(".var_export(\Think\Think::getMap(),true).");"; 63 | $content .= "\nL(".var_export(L(),true).");\nC(".var_export(C(),true).');Think\Hook::import('.var_export(\Think\Hook::get(),true).');Think\Think::start();}'; 64 | 65 | // 生成运行Lite文件 66 | file_put_contents($litefile,strip_whitespace(' $val) { 73 | $key = strtoupper($key); 74 | $content .= 'defined(\'' . $key . '\') or '; 75 | if (is_int($val) || is_float($val)) { 76 | $content .= "define('" . $key . "'," . $val . ');'; 77 | } elseif (is_bool($val)) { 78 | $val = ($val) ? 'true' : 'false'; 79 | $content .= "define('" . $key . "'," . $val . ');'; 80 | } elseif (is_string($val)) { 81 | $content .= "define('" . $key . "','" . addslashes($val) . "');"; 82 | } 83 | $content .= "\n"; 84 | } 85 | return $content; 86 | } 87 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Behavior/CheckLangBehavior.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Behavior; 12 | /** 13 | * 语言检测 并自动加载语言包 14 | */ 15 | class CheckLangBehavior { 16 | 17 | // 行为扩展的执行入口必须是run 18 | public function run(&$params){ 19 | // 检测语言 20 | $this->checkLanguage(); 21 | } 22 | 23 | /** 24 | * 语言检查 25 | * 检查浏览器支持语言,并自动加载语言包 26 | * @access private 27 | * @return void 28 | */ 29 | private function checkLanguage() { 30 | // 不开启语言包功能,仅仅加载框架语言文件直接返回 31 | if (!C('LANG_SWITCH_ON',null,false)){ 32 | return; 33 | } 34 | $langSet = C('DEFAULT_LANG'); 35 | $varLang = C('VAR_LANGUAGE',null,'l'); 36 | $langList = C('LANG_LIST',null,'zh-cn'); 37 | // 启用了语言包功能 38 | // 根据是否启用自动侦测设置获取语言选择 39 | if (C('LANG_AUTO_DETECT',null,true)){ 40 | if(isset($_GET[$varLang])){ 41 | $langSet = $_GET[$varLang];// url中设置了语言变量 42 | cookie('think_language',$langSet,3600); 43 | }elseif(cookie('think_language')){// 获取上次用户的选择 44 | $langSet = cookie('think_language'); 45 | }elseif(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){// 自动侦测浏览器语言 46 | preg_match('/^([a-z\d\-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches); 47 | $langSet = $matches[1]; 48 | cookie('think_language',$langSet,3600); 49 | } 50 | if(false === stripos($langList,$langSet)) { // 非法语言参数 51 | $langSet = C('DEFAULT_LANG'); 52 | } 53 | } 54 | // 定义当前语言 55 | define('LANG_SET',strtolower($langSet)); 56 | 57 | // 读取框架语言包 58 | $file = THINK_PATH.'Lang/'.LANG_SET.'.php'; 59 | if(LANG_SET != C('DEFAULT_LANG') && is_file($file)) 60 | L(include $file); 61 | 62 | // 读取应用公共语言包 63 | $file = LANG_PATH.LANG_SET.'.php'; 64 | if(is_file($file)) 65 | L(include $file); 66 | 67 | // 读取模块语言包 68 | $file = MODULE_PATH.'Lang/'.LANG_SET.'.php'; 69 | if(is_file($file)) 70 | L(include $file); 71 | 72 | // 读取当前控制器语言包 73 | $file = MODULE_PATH.'Lang/'.LANG_SET.'/'.strtolower(CONTROLLER_NAME).'.php'; 74 | if (is_file($file)) 75 | L(include $file); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Behavior/ContentReplaceBehavior.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Behavior; 12 | /** 13 | * 系统行为扩展:模板内容输出替换 14 | */ 15 | class ContentReplaceBehavior { 16 | 17 | // 行为扩展的执行入口必须是run 18 | public function run(&$content){ 19 | $content = $this->templateContentReplace($content); 20 | } 21 | 22 | /** 23 | * 模板内容替换 24 | * @access protected 25 | * @param string $content 模板内容 26 | * @return string 27 | */ 28 | protected function templateContentReplace($content) { 29 | // 系统默认的特殊变量替换 30 | $replace = array( 31 | '__ROOT__' => __ROOT__, // 当前网站地址 32 | '__APP__' => __APP__, // 当前应用地址 33 | '__MODULE__' => __MODULE__, 34 | '__ACTION__' => __ACTION__, // 当前操作地址 35 | '__SELF__' => htmlentities(__SELF__), // 当前页面地址 36 | '__CONTROLLER__'=> __CONTROLLER__, 37 | '__URL__' => __CONTROLLER__, 38 | '__PUBLIC__' => __ROOT__.'/Public',// 站点公共目录 39 | ); 40 | // 允许用户自定义模板的字符串替换 41 | if(is_array(C('TMPL_PARSE_STRING')) ) 42 | $replace = array_merge($replace,C('TMPL_PARSE_STRING')); 43 | $content = str_replace(array_keys($replace),array_values($replace),$content); 44 | return $content; 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Behavior/ParseTemplateBehavior.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Behavior; 12 | use Think\Storage; 13 | use Think\Think; 14 | /** 15 | * 系统行为扩展:模板解析 16 | */ 17 | class ParseTemplateBehavior { 18 | 19 | // 行为扩展的执行入口必须是run 20 | public function run(&$_data){ 21 | $engine = strtolower(C('TMPL_ENGINE_TYPE')); 22 | $_content = empty($_data['content'])?$_data['file']:$_data['content']; 23 | $_data['prefix'] = !empty($_data['prefix'])?$_data['prefix']:C('TMPL_CACHE_PREFIX'); 24 | if('think'==$engine){ // 采用Think模板引擎 25 | if((!empty($_data['content']) && $this->checkContentCache($_data['content'],$_data['prefix'])) 26 | || $this->checkCache($_data['file'],$_data['prefix'])) { // 缓存有效 27 | //载入模版缓存文件 28 | Storage::load(C('CACHE_PATH').$_data['prefix'].md5($_content).C('TMPL_CACHFILE_SUFFIX'),$_data['var']); 29 | }else{ 30 | $tpl = Think::instance('Think\\Template'); 31 | // 编译并加载模板文件 32 | $tpl->fetch($_content,$_data['var'],$_data['prefix']); 33 | } 34 | }else{ 35 | // 调用第三方模板引擎解析和输出 36 | if(strpos($engine,'\\')){ 37 | $class = $engine; 38 | }else{ 39 | $class = 'Think\\Template\\Driver\\'.ucwords($engine); 40 | } 41 | if(class_exists($class)) { 42 | $tpl = new $class; 43 | $tpl->fetch($_content,$_data['var']); 44 | }else { // 类没有定义 45 | E(L('_NOT_SUPPORT_').': ' . $class); 46 | } 47 | } 48 | } 49 | 50 | /** 51 | * 检查缓存文件是否有效 52 | * 如果无效则需要重新编译 53 | * @access public 54 | * @param string $tmplTemplateFile 模板文件名 55 | * @return boolean 56 | */ 57 | protected function checkCache($tmplTemplateFile,$prefix='') { 58 | if (!C('TMPL_CACHE_ON')) // 优先对配置设定检测 59 | return false; 60 | $tmplCacheFile = C('CACHE_PATH').$prefix.md5($tmplTemplateFile).C('TMPL_CACHFILE_SUFFIX'); 61 | if(!Storage::has($tmplCacheFile)){ 62 | return false; 63 | }elseif (filemtime($tmplTemplateFile) > Storage::get($tmplCacheFile,'mtime')) { 64 | // 模板文件如果有更新则缓存需要更新 65 | return false; 66 | }elseif (C('TMPL_CACHE_TIME') != 0 && time() > Storage::get($tmplCacheFile,'mtime')+C('TMPL_CACHE_TIME')) { 67 | // 缓存是否在有效期 68 | return false; 69 | } 70 | // 开启布局模板 71 | if(C('LAYOUT_ON')) { 72 | $layoutFile = THEME_PATH.C('LAYOUT_NAME').C('TMPL_TEMPLATE_SUFFIX'); 73 | if(filemtime($layoutFile) > Storage::get($tmplCacheFile,'mtime')) { 74 | return false; 75 | } 76 | } 77 | // 缓存有效 78 | return true; 79 | } 80 | 81 | /** 82 | * 检查缓存内容是否有效 83 | * 如果无效则需要重新编译 84 | * @access public 85 | * @param string $tmplContent 模板内容 86 | * @return boolean 87 | */ 88 | protected function checkContentCache($tmplContent,$prefix='') { 89 | if(Storage::has(C('CACHE_PATH').$prefix.md5($tmplContent).C('TMPL_CACHFILE_SUFFIX'))){ 90 | return true; 91 | }else{ 92 | return false; 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Behavior/ReadHtmlCacheBehavior.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Behavior; 12 | use Think\Storage; 13 | /** 14 | * 系统行为扩展:静态缓存读取 15 | */ 16 | class ReadHtmlCacheBehavior { 17 | // 行为扩展的执行入口必须是run 18 | public function run(&$params){ 19 | // 开启静态缓存 20 | if(IS_GET && C('HTML_CACHE_ON')) { 21 | $cacheTime = $this->requireHtmlCache(); 22 | if( false !== $cacheTime && $this->checkHTMLCache(HTML_FILE_NAME,$cacheTime)) { //静态页面有效 23 | // 读取静态页面输出 24 | echo Storage::read(HTML_FILE_NAME,'html'); 25 | exit(); 26 | } 27 | } 28 | } 29 | 30 | // 判断是否需要静态缓存 31 | static private function requireHtmlCache() { 32 | // 分析当前的静态规则 33 | $htmls = C('HTML_CACHE_RULES'); // 读取静态规则 34 | if(!empty($htmls)) { 35 | $htmls = array_change_key_case($htmls); 36 | // 静态规则文件定义格式 actionName=>array('静态规则','缓存时间','附加规则') 37 | // 'read'=>array('{id},{name}',60,'md5') 必须保证静态规则的唯一性 和 可判断性 38 | // 检测静态规则 39 | $controllerName = strtolower(CONTROLLER_NAME); 40 | $actionName = strtolower(ACTION_NAME); 41 | if(isset($htmls[$controllerName.':'.$actionName])) { 42 | $html = $htmls[$controllerName.':'.$actionName]; // 某个控制器的操作的静态规则 43 | }elseif(isset($htmls[$controllerName.':'])){// 某个控制器的静态规则 44 | $html = $htmls[$controllerName.':']; 45 | }elseif(isset($htmls[$actionName])){ 46 | $html = $htmls[$actionName]; // 所有操作的静态规则 47 | }elseif(isset($htmls['*'])){ 48 | $html = $htmls['*']; // 全局静态规则 49 | } 50 | if(!empty($html)) { 51 | // 解读静态规则 52 | $rule = is_array($html)?$html[0]:$html; 53 | // 以$_开头的系统变量 54 | $callback = function($match){ 55 | switch($match[1]){ 56 | case '_GET': $var = $_GET[$match[2]]; break; 57 | case '_POST': $var = $_POST[$match[2]]; break; 58 | case '_REQUEST': $var = $_REQUEST[$match[2]]; break; 59 | case '_SERVER': $var = $_SERVER[$match[2]]; break; 60 | case '_SESSION': $var = $_SESSION[$match[2]]; break; 61 | case '_COOKIE': $var = $_COOKIE[$match[2]]; break; 62 | } 63 | return (count($match) == 4) ? $match[3]($var) : $var; 64 | }; 65 | $rule = preg_replace_callback('/{\$(_\w+)\.(\w+)(?:\|(\w+))?}/', $callback, $rule); 66 | // {ID|FUN} GET变量的简写 67 | $rule = preg_replace_callback('/{(\w+)\|(\w+)}/', function($match){return $match[2]($_GET[$match[1]]);}, $rule); 68 | $rule = preg_replace_callback('/{(\w+)}/', function($match){return $_GET[$match[1]];}, $rule); 69 | // 特殊系统变量 70 | $rule = str_ireplace( 71 | array('{:controller}','{:action}','{:module}'), 72 | array(CONTROLLER_NAME,ACTION_NAME,MODULE_NAME), 73 | $rule); 74 | // {|FUN} 单独使用函数 75 | $rule = preg_replace_callback('/{|(\w+)}/', function($match){return $match[1]();},$rule); 76 | $cacheTime = C('HTML_CACHE_TIME',null,60); 77 | if(is_array($html)){ 78 | if(!empty($html[2])) $rule = $html[2]($rule); // 应用附加函数 79 | $cacheTime = isset($html[1])?$html[1]:$cacheTime; // 缓存有效期 80 | }else{ 81 | $cacheTime = $cacheTime; 82 | } 83 | 84 | // 当前缓存文件 85 | define('HTML_FILE_NAME',HTML_PATH . $rule.C('HTML_FILE_SUFFIX',null,'.html')); 86 | return $cacheTime; 87 | } 88 | } 89 | // 无需缓存 90 | return false; 91 | } 92 | 93 | /** 94 | * 检查静态HTML文件是否有效 95 | * 如果无效需要重新更新 96 | * @access public 97 | * @param string $cacheFile 静态文件名 98 | * @param integer $cacheTime 缓存有效期 99 | * @return boolean 100 | */ 101 | static public function checkHTMLCache($cacheFile='',$cacheTime='') { 102 | if(!is_file($cacheFile) && 'sae' != APP_MODE ){ 103 | return false; 104 | }elseif (filemtime(\Think\Think::instance('Think\View')->parseTemplate()) > Storage::get($cacheFile,'mtime','html')) { 105 | // 模板文件如果更新静态文件需要更新 106 | return false; 107 | }elseif(!is_numeric($cacheTime) && function_exists($cacheTime)){ 108 | return $cacheTime($cacheFile); 109 | }elseif ($cacheTime != 0 && NOW_TIME > Storage::get($cacheFile,'mtime','html')+$cacheTime) { 110 | // 文件是否在有效期 111 | return false; 112 | } 113 | //静态文件有效 114 | return true; 115 | } 116 | 117 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Behavior/ShowPageTraceBehavior.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Behavior; 12 | use Think\Log; 13 | /** 14 | * 系统行为扩展:页面Trace显示输出 15 | */ 16 | class ShowPageTraceBehavior { 17 | protected $tracePageTabs = array('BASE'=>'基本','FILE'=>'文件','INFO'=>'流程','ERR|NOTIC'=>'错误','SQL'=>'SQL','DEBUG'=>'调试'); 18 | 19 | // 行为扩展的执行入口必须是run 20 | public function run(&$params){ 21 | if(!IS_AJAX && !IS_CLI && C('SHOW_PAGE_TRACE')) { 22 | echo $this->showTrace(); 23 | } 24 | } 25 | 26 | /** 27 | * 显示页面Trace信息 28 | * @access private 29 | */ 30 | private function showTrace() { 31 | // 系统默认显示信息 32 | $files = get_included_files(); 33 | $info = array(); 34 | foreach ($files as $key=>$file){ 35 | $info[] = $file.' ( '.number_format(filesize($file)/1024,2).' KB )'; 36 | } 37 | $trace = array(); 38 | $base = array( 39 | '请求信息' => date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']).' '.$_SERVER['SERVER_PROTOCOL'].' '.$_SERVER['REQUEST_METHOD'].' : '.__SELF__, 40 | '运行时间' => $this->showTime(), 41 | '吞吐率' => number_format(1/G('beginTime','viewEndTime'),2).'req/s', 42 | '内存开销' => MEMORY_LIMIT_ON?number_format((memory_get_usage() - $GLOBALS['_startUseMems'])/1024,2).' kb':'不支持', 43 | '查询信息' => N('db_query').' queries '.N('db_write').' writes ', 44 | '文件加载' => count(get_included_files()), 45 | '缓存信息' => N('cache_read').' gets '.N('cache_write').' writes ', 46 | '配置加载' => count(C()), 47 | '会话信息' => 'SESSION_ID='.session_id(), 48 | ); 49 | // 读取应用定义的Trace文件 50 | $traceFile = COMMON_PATH.'Conf/trace.php'; 51 | if(is_file($traceFile)) { 52 | $base = array_merge($base,include $traceFile); 53 | } 54 | $debug = trace(); 55 | $tabs = C('TRACE_PAGE_TABS',null,$this->tracePageTabs); 56 | foreach ($tabs as $name=>$title){ 57 | switch(strtoupper($name)) { 58 | case 'BASE':// 基本信息 59 | $trace[$title] = $base; 60 | break; 61 | case 'FILE': // 文件信息 62 | $trace[$title] = $info; 63 | break; 64 | default:// 调试信息 65 | $name = strtoupper($name); 66 | if(strpos($name,'|')) {// 多组信息 67 | $names = explode('|',$name); 68 | $result = array(); 69 | foreach($names as $name){ 70 | $result += isset($debug[$name])?$debug[$name]:array(); 71 | } 72 | $trace[$title] = $result; 73 | }else{ 74 | $trace[$title] = isset($debug[$name])?$debug[$name]:''; 75 | } 76 | } 77 | } 78 | if($save = C('PAGE_TRACE_SAVE')) { // 保存页面Trace日志 79 | if(is_array($save)) {// 选择选项卡保存 80 | $tabs = C('TRACE_PAGE_TABS',null,$this->tracePageTabs); 81 | $array = array(); 82 | foreach ($save as $tab){ 83 | $array[] = $tabs[$tab]; 84 | } 85 | } 86 | $content = date('[ c ]').' '.get_client_ip().' '.$_SERVER['REQUEST_URI']."\r\n"; 87 | foreach ($trace as $key=>$val){ 88 | if(!isset($array) || in_array_case($key,$array)) { 89 | $content .= '[ '.$key." ]\r\n"; 90 | if(is_array($val)) { 91 | foreach ($val as $k=>$v){ 92 | $content .= (!is_numeric($k)?$k.':':'').print_r($v,true)."\r\n"; 93 | } 94 | }else{ 95 | $content .= print_r($val,true)."\r\n"; 96 | } 97 | $content .= "\r\n"; 98 | } 99 | } 100 | error_log(str_replace('
    ',"\r\n",$content), 3,C('LOG_PATH').date('y_m_d').'_trace.log'); 101 | } 102 | unset($files,$info,$base); 103 | // 调用Trace页面模板 104 | ob_start(); 105 | include C('TMPL_TRACE_FILE')?C('TMPL_TRACE_FILE'):THINK_PATH.'Tpl/page_trace.tpl'; 106 | return ob_get_clean(); 107 | } 108 | 109 | /** 110 | * 获取运行时间 111 | */ 112 | private function showTime() { 113 | // 显示运行时间 114 | G('beginTime',$GLOBALS['_beginTime']); 115 | G('viewEndTime'); 116 | // 显示详细运行时间 117 | return G('beginTime','viewEndTime').'s ( Load:'.G('beginTime','loadTime').'s Init:'.G('loadTime','initTime').'s Exec:'.G('initTime','viewStartTime').'s Template:'.G('viewStartTime','viewEndTime').'s )'; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Behavior/ShowRuntimeBehavior.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Behavior; 12 | /** 13 | * 系统行为扩展:运行时间信息显示 14 | */ 15 | class ShowRuntimeBehavior { 16 | 17 | // 行为扩展的执行入口必须是run 18 | public function run(&$content){ 19 | if(C('SHOW_RUN_TIME')){ 20 | if(false !== strpos($content,'{__NORUNTIME__}')) { 21 | $content = str_replace('{__NORUNTIME__}','',$content); 22 | }else{ 23 | $runtime = $this->showTime(); 24 | if(strpos($content,'{__RUNTIME__}')) 25 | $content = str_replace('{__RUNTIME__}',$runtime,$content); 26 | else 27 | $content .= $runtime; 28 | } 29 | }else{ 30 | $content = str_replace(array('{__NORUNTIME__}','{__RUNTIME__}'),'',$content); 31 | } 32 | } 33 | 34 | /** 35 | * 显示运行时间、数据库操作、缓存次数、内存使用信息 36 | * @access private 37 | * @return string 38 | */ 39 | private function showTime() { 40 | // 显示运行时间 41 | G('beginTime',$GLOBALS['_beginTime']); 42 | G('viewEndTime'); 43 | $showTime = 'Process: '.G('beginTime','viewEndTime').'s '; 44 | if(C('SHOW_ADV_TIME')) { 45 | // 显示详细运行时间 46 | $showTime .= '( Load:'.G('beginTime','loadTime').'s Init:'.G('loadTime','initTime').'s Exec:'.G('initTime','viewStartTime').'s Template:'.G('viewStartTime','viewEndTime').'s )'; 47 | } 48 | if(C('SHOW_DB_TIMES') ) { 49 | // 显示数据库操作次数 50 | $showTime .= ' | DB :'.N('db_query').' queries '.N('db_write').' writes '; 51 | } 52 | if(C('SHOW_CACHE_TIMES') ) { 53 | // 显示缓存读写次数 54 | $showTime .= ' | Cache :'.N('cache_read').' gets '.N('cache_write').' writes '; 55 | } 56 | if(MEMORY_LIMIT_ON && C('SHOW_USE_MEM')) { 57 | // 显示内存开销 58 | $showTime .= ' | UseMem:'. number_format((memory_get_usage() - $GLOBALS['_startUseMems'])/1024).' kb'; 59 | } 60 | if(C('SHOW_LOAD_FILE')) { 61 | $showTime .= ' | LoadFile:'.count(get_included_files()); 62 | } 63 | if(C('SHOW_FUN_TIMES')) { 64 | $fun = get_defined_functions(); 65 | $showTime .= ' | CallFun:'.count($fun['user']).','.count($fun['internal']); 66 | } 67 | return $showTime; 68 | } 69 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Behavior/TokenBuildBehavior.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Behavior; 12 | /** 13 | * 系统行为扩展:表单令牌生成 14 | */ 15 | class TokenBuildBehavior { 16 | 17 | public function run(&$content){ 18 | if(C('TOKEN_ON')) { 19 | list($tokenName,$tokenKey,$tokenValue)=$this->getToken(); 20 | $input_token = ''; 21 | $meta_token = ''; 22 | if(strpos($content,'{__TOKEN__}')) { 23 | // 指定表单令牌隐藏域位置 24 | $content = str_replace('{__TOKEN__}',$input_token,$content); 25 | }elseif(preg_match('/<\/form(\s*)>/is',$content,$match)) { 26 | // 智能生成表单令牌隐藏域 27 | $content = str_replace($match[0],$input_token.$match[0],$content); 28 | } 29 | $content = str_ireplace('',$meta_token.'',$content); 30 | }else{ 31 | $content = str_replace('{__TOKEN__}','',$content); 32 | } 33 | } 34 | 35 | //获得token 36 | private function getToken(){ 37 | $tokenName = C('TOKEN_NAME',null,'__hash__'); 38 | $tokenType = C('TOKEN_TYPE',null,'md5'); 39 | if(!isset($_SESSION[$tokenName])) { 40 | $_SESSION[$tokenName] = array(); 41 | } 42 | // 标识当前页面唯一性 43 | $tokenKey = md5($_SERVER['REQUEST_URI']); 44 | if(isset($_SESSION[$tokenName][$tokenKey])) {// 相同页面不重复生成session 45 | $tokenValue = $_SESSION[$tokenName][$tokenKey]; 46 | }else{ 47 | $tokenValue = is_callable($tokenType) ? $tokenType(microtime(true)) : md5(microtime(true)); 48 | $_SESSION[$tokenName][$tokenKey] = $tokenValue; 49 | if(IS_AJAX && C('TOKEN_RESET',null,true)) 50 | header($tokenName.': '.$tokenKey.'_'.$tokenValue); //ajax需要获得这个header并替换页面中meta中的token值 51 | } 52 | return array($tokenName,$tokenKey,$tokenValue); 53 | } 54 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Behavior/WriteHtmlCacheBehavior.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Behavior; 12 | use Think\Storage; 13 | /** 14 | * 系统行为扩展:静态缓存写入 15 | */ 16 | class WriteHtmlCacheBehavior { 17 | 18 | // 行为扩展的执行入口必须是run 19 | public function run(&$content) { 20 | //2014-11-28 修改 如果有HTTP 4xx 3xx 5xx 头部,禁止存储 21 | //2014-12-1 修改 对注入的网址 防止生成,例如 /game/lst/SortType/hot/-e8-90-8c-e5-85-94-e7-88-b1-e6-b6-88-e9-99-a4/-e8-bf-9b-e5-87-bb-e7-9a-84-e9-83-a8-e8-90-bd/-e9-a3-8e-e4-ba-91-e5-a4-a9-e4-b8-8b/index.shtml 22 | if (C('HTML_CACHE_ON') && defined('HTML_FILE_NAME') 23 | && !preg_match('/Status.*[345]{1}\d{2}/i', implode(' ', headers_list())) 24 | && !preg_match('/(-[a-z0-9]{2}){3,}/i',HTML_FILE_NAME)) { 25 | //静态文件写入 26 | Storage::put(HTML_FILE_NAME, $content, 'html'); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Build.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think; 12 | /** 13 | * 用于ThinkPHP的自动生成 14 | */ 15 | class Build { 16 | 17 | static protected $controller = 'show(\'

    :)

    欢迎使用 ThinkPHP


    版本 V{$Think.version}
    \',\'utf-8\'); 23 | } 24 | }'; 25 | 26 | static protected $model = ''配置值'\n);":''); 74 | // 写入模块配置文件 75 | if(!is_file(APP_PATH.$module.'/Conf/config'.CONF_EXT)) 76 | file_put_contents(APP_PATH.$module.'/Conf/config'.CONF_EXT,'.php' == CONF_EXT ? "'配置值'\n);":''); 77 | // 生成模块的测试控制器 78 | if(defined('BUILD_CONTROLLER_LIST')){ 79 | // 自动生成的控制器列表(注意大小写) 80 | $list = explode(',',BUILD_CONTROLLER_LIST); 81 | foreach($list as $controller){ 82 | self::buildController($module,$controller); 83 | } 84 | }else{ 85 | // 生成默认的控制器 86 | self::buildController($module); 87 | } 88 | // 生成模块的模型 89 | if(defined('BUILD_MODEL_LIST')){ 90 | // 自动生成的控制器列表(注意大小写) 91 | $list = explode(',',BUILD_MODEL_LIST); 92 | foreach($list as $model){ 93 | self::buildModel($module,$model); 94 | } 95 | } 96 | }else{ 97 | header('Content-Type:text/html; charset=utf-8'); 98 | exit('应用目录['.APP_PATH.']不可写,目录无法自动生成!
    请手动生成项目目录~'); 99 | } 100 | } 101 | 102 | // 检查缓存目录(Runtime) 如果不存在则自动创建 103 | static public function buildRuntime() { 104 | if(!is_dir(RUNTIME_PATH)) { 105 | mkdir(RUNTIME_PATH); 106 | }elseif(!is_writeable(RUNTIME_PATH)) { 107 | header('Content-Type:text/html; charset=utf-8'); 108 | exit('目录 [ '.RUNTIME_PATH.' ] 不可写!'); 109 | } 110 | mkdir(CACHE_PATH); // 模板缓存目录 111 | if(!is_dir(LOG_PATH)) mkdir(LOG_PATH); // 日志目录 112 | if(!is_dir(TEMP_PATH)) mkdir(TEMP_PATH); // 数据缓存目录 113 | if(!is_dir(DATA_PATH)) mkdir(DATA_PATH); // 数据文件目录 114 | return true; 115 | } 116 | 117 | // 创建控制器类 118 | static public function buildController($module,$controller='Index') { 119 | $file = APP_PATH.$module.'/Controller/'.$controller.'Controller'.EXT; 120 | if(!is_file($file)){ 121 | $content = str_replace(array('[MODULE]','[CONTROLLER]'),array($module,$controller),self::$controller); 122 | if(!C('APP_USE_NAMESPACE')){ 123 | $content = preg_replace('/namespace\s(.*?);/','',$content,1); 124 | } 125 | $dir = dirname($file); 126 | if(!is_dir($dir)){ 127 | mkdir($dir, 0755, true); 128 | } 129 | file_put_contents($file,$content); 130 | } 131 | } 132 | 133 | // 创建模型类 134 | static public function buildModel($module,$model) { 135 | $file = APP_PATH.$module.'/Model/'.$model.'Model'.EXT; 136 | if(!is_file($file)){ 137 | $content = str_replace(array('[MODULE]','[MODEL]'),array($module,$model),self::$model); 138 | if(!C('APP_USE_NAMESPACE')){ 139 | $content = preg_replace('/namespace\s(.*?);/','',$content,1); 140 | } 141 | $dir = dirname($file); 142 | if(!is_dir($dir)){ 143 | mkdir($dir, 0755, true); 144 | } 145 | file_put_contents($file,$content); 146 | } 147 | } 148 | 149 | // 生成目录安全文件 150 | static public function buildDirSecure($dirs=array()) { 151 | // 目录安全写入(默认开启) 152 | defined('BUILD_DIR_SECURE') or define('BUILD_DIR_SECURE', true); 153 | if(BUILD_DIR_SECURE) { 154 | defined('DIR_SECURE_FILENAME') or define('DIR_SECURE_FILENAME', 'index.html'); 155 | defined('DIR_SECURE_CONTENT') or define('DIR_SECURE_CONTENT', ' '); 156 | // 自动写入目录安全文件 157 | $content = DIR_SECURE_CONTENT; 158 | $files = explode(',', DIR_SECURE_FILENAME); 159 | foreach ($files as $filename){ 160 | foreach ($dirs as $dir) 161 | file_put_contents($dir.$filename,$content); 162 | } 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Cache.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think; 12 | /** 13 | * 缓存管理类 14 | */ 15 | class Cache { 16 | 17 | /** 18 | * 操作句柄 19 | * @var string 20 | * @access protected 21 | */ 22 | protected $handler ; 23 | 24 | /** 25 | * 缓存连接参数 26 | * @var integer 27 | * @access protected 28 | */ 29 | protected $options = array(); 30 | 31 | /** 32 | * 连接缓存 33 | * @access public 34 | * @param string $type 缓存类型 35 | * @param array $options 配置数组 36 | * @return object 37 | */ 38 | public function connect($type='',$options=array()) { 39 | if(empty($type)) $type = C('DATA_CACHE_TYPE'); 40 | $class = strpos($type,'\\')? $type : 'Think\\Cache\\Driver\\'.ucwords(strtolower($type)); 41 | if(class_exists($class)) 42 | $cache = new $class($options); 43 | else 44 | E(L('_CACHE_TYPE_INVALID_').':'.$type); 45 | return $cache; 46 | } 47 | 48 | /** 49 | * 取得缓存类实例 50 | * @static 51 | * @access public 52 | * @return mixed 53 | */ 54 | static function getInstance($type='',$options=array()) { 55 | static $_instance = array(); 56 | $guid = $type.to_guid_string($options); 57 | if(!isset($_instance[$guid])){ 58 | $obj = new Cache(); 59 | $_instance[$guid] = $obj->connect($type,$options); 60 | } 61 | return $_instance[$guid]; 62 | } 63 | 64 | public function __get($name) { 65 | return $this->get($name); 66 | } 67 | 68 | public function __set($name,$value) { 69 | return $this->set($name,$value); 70 | } 71 | 72 | public function __unset($name) { 73 | $this->rm($name); 74 | } 75 | public function setOptions($name,$value) { 76 | $this->options[$name] = $value; 77 | } 78 | 79 | public function getOptions($name) { 80 | return $this->options[$name]; 81 | } 82 | 83 | /** 84 | * 队列缓存 85 | * @access protected 86 | * @param string $key 队列名 87 | * @return mixed 88 | */ 89 | // 90 | protected function queue($key) { 91 | static $_handler = array( 92 | 'file' => array('F','F'), 93 | 'xcache'=> array('xcache_get','xcache_set'), 94 | 'apc' => array('apc_fetch','apc_store'), 95 | ); 96 | $queue = isset($this->options['queue'])?$this->options['queue']:'file'; 97 | $fun = isset($_handler[$queue])?$_handler[$queue]:$_handler['file']; 98 | $queue_name = isset($this->options['queue_name'])?$this->options['queue_name']:'think_queue'; 99 | $value = $fun[0]($queue_name); 100 | if(!$value) { 101 | $value = array(); 102 | } 103 | // 进列 104 | if(false===array_search($key, $value)) array_push($value,$key); 105 | if(count($value) > $this->options['length']) { 106 | // 出列 107 | $key = array_shift($value); 108 | // 删除缓存 109 | $this->rm($key); 110 | if(APP_DEBUG){ 111 | //调试模式下,记录出列次数 112 | N($queue_name.'_out_times',1); 113 | } 114 | } 115 | return $fun[1]($queue_name,$value); 116 | } 117 | 118 | public function __call($method,$args){ 119 | //调用缓存类型自己的方法 120 | if(method_exists($this->handler, $method)){ 121 | return call_user_func_array(array($this->handler,$method), $args); 122 | }else{ 123 | E(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); 124 | return; 125 | } 126 | } 127 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Cache/Driver/Apachenote.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Cache\Driver; 12 | use Think\Cache; 13 | defined('THINK_PATH') or exit(); 14 | /** 15 | * Apachenote缓存驱动 16 | */ 17 | class Apachenote extends Cache { 18 | 19 | /** 20 | * 架构函数 21 | * @param array $options 缓存参数 22 | * @access public 23 | */ 24 | public function __construct($options=array()) { 25 | if(!empty($options)) { 26 | $this->options = $options; 27 | } 28 | if(empty($options)) { 29 | $options = array ( 30 | 'host' => '127.0.0.1', 31 | 'port' => 1042, 32 | 'timeout' => 10, 33 | ); 34 | } 35 | $this->options = $options; 36 | $this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX'); 37 | $this->options['length'] = isset($options['length'])? $options['length'] : 0; 38 | $this->handler = null; 39 | $this->open(); 40 | } 41 | 42 | /** 43 | * 读取缓存 44 | * @access public 45 | * @param string $name 缓存变量名 46 | * @return mixed 47 | */ 48 | public function get($name) { 49 | $this->open(); 50 | $name = $this->options['prefix'].$name; 51 | $s = 'F' . pack('N', strlen($name)) . $name; 52 | fwrite($this->handler, $s); 53 | 54 | for ($data = ''; !feof($this->handler);) { 55 | $data .= fread($this->handler, 4096); 56 | } 57 | N('cache_read',1); 58 | $this->close(); 59 | return $data === '' ? '' : unserialize($data); 60 | } 61 | 62 | /** 63 | * 写入缓存 64 | * @access public 65 | * @param string $name 缓存变量名 66 | * @param mixed $value 存储数据 67 | * @return boolean 68 | */ 69 | public function set($name, $value) { 70 | N('cache_write',1); 71 | $this->open(); 72 | $value = serialize($value); 73 | $name = $this->options['prefix'].$name; 74 | $s = 'S' . pack('NN', strlen($name), strlen($value)) . $name . $value; 75 | 76 | fwrite($this->handler, $s); 77 | $ret = fgets($this->handler); 78 | $this->close(); 79 | if($ret === "OK\n") { 80 | if($this->options['length']>0) { 81 | // 记录缓存队列 82 | $this->queue($name); 83 | } 84 | return true; 85 | } 86 | return false; 87 | } 88 | 89 | /** 90 | * 删除缓存 91 | * @access public 92 | * @param string $name 缓存变量名 93 | * @return boolean 94 | */ 95 | public function rm($name) { 96 | $this->open(); 97 | $name = $this->options['prefix'].$name; 98 | $s = 'D' . pack('N', strlen($name)) . $name; 99 | fwrite($this->handler, $s); 100 | $ret = fgets($this->handler); 101 | $this->close(); 102 | return $ret === "OK\n"; 103 | } 104 | 105 | /** 106 | * 关闭缓存 107 | * @access private 108 | */ 109 | private function close() { 110 | fclose($this->handler); 111 | $this->handler = false; 112 | } 113 | 114 | /** 115 | * 打开缓存 116 | * @access private 117 | */ 118 | private function open() { 119 | if (!is_resource($this->handler)) { 120 | $this->handler = fsockopen($this->options['host'], $this->options['port'], $_, $_, $this->options['timeout']); 121 | } 122 | } 123 | 124 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Cache/Driver/Apc.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Cache\Driver; 12 | use Think\Cache; 13 | defined('THINK_PATH') or exit(); 14 | /** 15 | * Apc缓存驱动 16 | */ 17 | class Apc extends Cache { 18 | 19 | /** 20 | * 架构函数 21 | * @param array $options 缓存参数 22 | * @access public 23 | */ 24 | public function __construct($options=array()) { 25 | if(!function_exists('apc_cache_info')) { 26 | E(L('_NOT_SUPPORT_').':Apc'); 27 | } 28 | $this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX'); 29 | $this->options['length'] = isset($options['length'])? $options['length'] : 0; 30 | $this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME'); 31 | } 32 | 33 | /** 34 | * 读取缓存 35 | * @access public 36 | * @param string $name 缓存变量名 37 | * @return mixed 38 | */ 39 | public function get($name) { 40 | N('cache_read',1); 41 | return apc_fetch($this->options['prefix'].$name); 42 | } 43 | 44 | /** 45 | * 写入缓存 46 | * @access public 47 | * @param string $name 缓存变量名 48 | * @param mixed $value 存储数据 49 | * @param integer $expire 有效时间(秒) 50 | * @return boolean 51 | */ 52 | public function set($name, $value, $expire = null) { 53 | N('cache_write',1); 54 | if(is_null($expire)) { 55 | $expire = $this->options['expire']; 56 | } 57 | $name = $this->options['prefix'].$name; 58 | if($result = apc_store($name, $value, $expire)) { 59 | if($this->options['length']>0) { 60 | // 记录缓存队列 61 | $this->queue($name); 62 | } 63 | } 64 | return $result; 65 | } 66 | 67 | /** 68 | * 删除缓存 69 | * @access public 70 | * @param string $name 缓存变量名 71 | * @return boolean 72 | */ 73 | public function rm($name) { 74 | return apc_delete($this->options['prefix'].$name); 75 | } 76 | 77 | /** 78 | * 清除缓存 79 | * @access public 80 | * @return boolean 81 | */ 82 | public function clear() { 83 | return apc_clear_cache(); 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Cache/Driver/Db.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Cache\Driver; 12 | use Think\Cache; 13 | defined('THINK_PATH') or exit(); 14 | /** 15 | * 数据库方式缓存驱动 16 | * CREATE TABLE think_cache ( 17 | * cachekey varchar(255) NOT NULL, 18 | * expire int(11) NOT NULL, 19 | * data blob, 20 | * datacrc int(32), 21 | * UNIQUE KEY `cachekey` (`cachekey`) 22 | * ); 23 | */ 24 | class Db extends Cache { 25 | 26 | /** 27 | * 架构函数 28 | * @param array $options 缓存参数 29 | * @access public 30 | */ 31 | public function __construct($options=array()) { 32 | if(empty($options)) { 33 | $options = array ( 34 | 'table' => C('DATA_CACHE_TABLE'), 35 | ); 36 | } 37 | $this->options = $options; 38 | $this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX'); 39 | $this->options['length'] = isset($options['length'])? $options['length'] : 0; 40 | $this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME'); 41 | $this->handler = \Think\Db::getInstance(); 42 | } 43 | 44 | /** 45 | * 读取缓存 46 | * @access public 47 | * @param string $name 缓存变量名 48 | * @return mixed 49 | */ 50 | public function get($name) { 51 | $name = $this->options['prefix'].addslashes($name); 52 | N('cache_read',1); 53 | $result = $this->handler->query('SELECT `data`,`datacrc` FROM `'.$this->options['table'].'` WHERE `cachekey`=\''.$name.'\' AND (`expire` =0 OR `expire`>'.time().') LIMIT 0,1'); 54 | if(false !== $result ) { 55 | $result = $result[0]; 56 | if(C('DATA_CACHE_CHECK')) {//开启数据校验 57 | if($result['datacrc'] != md5($result['data'])) {//校验错误 58 | return false; 59 | } 60 | } 61 | $content = $result['data']; 62 | if(C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { 63 | //启用数据压缩 64 | $content = gzuncompress($content); 65 | } 66 | $content = unserialize($content); 67 | return $content; 68 | } 69 | else { 70 | return false; 71 | } 72 | } 73 | 74 | /** 75 | * 写入缓存 76 | * @access public 77 | * @param string $name 缓存变量名 78 | * @param mixed $value 存储数据 79 | * @param integer $expire 有效时间(秒) 80 | * @return boolean 81 | */ 82 | public function set($name, $value,$expire=null) { 83 | $data = serialize($value); 84 | $name = $this->options['prefix'].addslashes($name); 85 | N('cache_write',1); 86 | if( C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { 87 | //数据压缩 88 | $data = gzcompress($data,3); 89 | } 90 | if(C('DATA_CACHE_CHECK')) {//开启数据校验 91 | $crc = md5($data); 92 | }else { 93 | $crc = ''; 94 | } 95 | if(is_null($expire)) { 96 | $expire = $this->options['expire']; 97 | } 98 | $expire = ($expire==0)?0: (time()+$expire) ;//缓存有效期为0表示永久缓存 99 | $result = $this->handler->query('select `cachekey` from `'.$this->options['table'].'` where `cachekey`=\''.$name.'\' limit 0,1'); 100 | if(!empty($result) ) { 101 | //更新记录 102 | $result = $this->handler->execute('UPDATE '.$this->options['table'].' SET data=\''.$data.'\' ,datacrc=\''.$crc.'\',expire='.$expire.' WHERE `cachekey`=\''.$name.'\''); 103 | }else { 104 | //新增记录 105 | $result = $this->handler->execute('INSERT INTO '.$this->options['table'].' (`cachekey`,`data`,`datacrc`,`expire`) VALUES (\''.$name.'\',\''.$data.'\',\''.$crc.'\','.$expire.')'); 106 | } 107 | if($result) { 108 | if($this->options['length']>0) { 109 | // 记录缓存队列 110 | $this->queue($name); 111 | } 112 | return true; 113 | }else { 114 | return false; 115 | } 116 | } 117 | 118 | /** 119 | * 删除缓存 120 | * @access public 121 | * @param string $name 缓存变量名 122 | * @return boolean 123 | */ 124 | public function rm($name) { 125 | $name = $this->options['prefix'].addslashes($name); 126 | return $this->handler->execute('DELETE FROM `'.$this->options['table'].'` WHERE `cachekey`=\''.$name.'\''); 127 | } 128 | 129 | /** 130 | * 清除缓存 131 | * @access public 132 | * @return boolean 133 | */ 134 | public function clear() { 135 | return $this->handler->execute('TRUNCATE TABLE `'.$this->options['table'].'`'); 136 | } 137 | 138 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Cache/Driver/Eaccelerator.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Cache\Driver; 12 | use Think\Cache; 13 | defined('THINK_PATH') or exit(); 14 | /** 15 | * Eaccelerator缓存驱动 16 | */ 17 | class Eaccelerator extends Cache { 18 | 19 | /** 20 | * 架构函数 21 | * @param array $options 缓存参数 22 | * @access public 23 | */ 24 | public function __construct($options=array()) { 25 | $this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME'); 26 | $this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX'); 27 | $this->options['length'] = isset($options['length'])? $options['length'] : 0; 28 | } 29 | 30 | /** 31 | * 读取缓存 32 | * @access public 33 | * @param string $name 缓存变量名 34 | * @return mixed 35 | */ 36 | public function get($name) { 37 | N('cache_read',1); 38 | return eaccelerator_get($this->options['prefix'].$name); 39 | } 40 | 41 | /** 42 | * 写入缓存 43 | * @access public 44 | * @param string $name 缓存变量名 45 | * @param mixed $value 存储数据 46 | * @param integer $expire 有效时间(秒) 47 | * @return boolean 48 | */ 49 | public function set($name, $value, $expire = null) { 50 | N('cache_write',1); 51 | if(is_null($expire)) { 52 | $expire = $this->options['expire']; 53 | } 54 | $name = $this->options['prefix'].$name; 55 | eaccelerator_lock($name); 56 | if(eaccelerator_put($name, $value, $expire)) { 57 | if($this->options['length']>0) { 58 | // 记录缓存队列 59 | $this->queue($name); 60 | } 61 | return true; 62 | } 63 | return false; 64 | } 65 | 66 | 67 | /** 68 | * 删除缓存 69 | * @access public 70 | * @param string $name 缓存变量名 71 | * @return boolean 72 | */ 73 | public function rm($name) { 74 | return eaccelerator_rm($this->options['prefix'].$name); 75 | } 76 | 77 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Cache/Driver/File.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Cache\Driver; 12 | use Think\Cache; 13 | defined('THINK_PATH') or exit(); 14 | /** 15 | * 文件类型缓存类 16 | */ 17 | class File extends Cache { 18 | 19 | /** 20 | * 架构函数 21 | * @access public 22 | */ 23 | public function __construct($options=array()) { 24 | if(!empty($options)) { 25 | $this->options = $options; 26 | } 27 | $this->options['temp'] = !empty($options['temp'])? $options['temp'] : C('DATA_CACHE_PATH'); 28 | $this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX'); 29 | $this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME'); 30 | $this->options['length'] = isset($options['length'])? $options['length'] : 0; 31 | if(substr($this->options['temp'], -1) != '/') $this->options['temp'] .= '/'; 32 | $this->init(); 33 | } 34 | 35 | /** 36 | * 初始化检查 37 | * @access private 38 | * @return boolean 39 | */ 40 | private function init() { 41 | // 创建应用缓存目录 42 | if (!is_dir($this->options['temp'])) { 43 | mkdir($this->options['temp']); 44 | } 45 | } 46 | 47 | /** 48 | * 取得变量的存储文件名 49 | * @access private 50 | * @param string $name 缓存变量名 51 | * @return string 52 | */ 53 | private function filename($name) { 54 | $name = md5(C('DATA_CACHE_KEY').$name); 55 | if(C('DATA_CACHE_SUBDIR')) { 56 | // 使用子目录 57 | $dir =''; 58 | for($i=0;$ioptions['temp'].$dir)) { 62 | mkdir($this->options['temp'].$dir,0755,true); 63 | } 64 | $filename = $dir.$this->options['prefix'].$name.'.php'; 65 | }else{ 66 | $filename = $this->options['prefix'].$name.'.php'; 67 | } 68 | return $this->options['temp'].$filename; 69 | } 70 | 71 | /** 72 | * 读取缓存 73 | * @access public 74 | * @param string $name 缓存变量名 75 | * @return mixed 76 | */ 77 | public function get($name) { 78 | $filename = $this->filename($name); 79 | if (!is_file($filename)) { 80 | return false; 81 | } 82 | N('cache_read',1); 83 | $content = file_get_contents($filename); 84 | if( false !== $content) { 85 | $expire = (int)substr($content,8, 12); 86 | if($expire != 0 && time() > filemtime($filename) + $expire) { 87 | //缓存过期删除缓存文件 88 | unlink($filename); 89 | return false; 90 | } 91 | if(C('DATA_CACHE_CHECK')) {//开启数据校验 92 | $check = substr($content,20, 32); 93 | $content = substr($content,52, -3); 94 | if($check != md5($content)) {//校验错误 95 | return false; 96 | } 97 | }else { 98 | $content = substr($content,20, -3); 99 | } 100 | if(C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { 101 | //启用数据压缩 102 | $content = gzuncompress($content); 103 | } 104 | $content = unserialize($content); 105 | return $content; 106 | } 107 | else { 108 | return false; 109 | } 110 | } 111 | 112 | /** 113 | * 写入缓存 114 | * @access public 115 | * @param string $name 缓存变量名 116 | * @param mixed $value 存储数据 117 | * @param int $expire 有效时间 0为永久 118 | * @return boolean 119 | */ 120 | public function set($name,$value,$expire=null) { 121 | N('cache_write',1); 122 | if(is_null($expire)) { 123 | $expire = $this->options['expire']; 124 | } 125 | $filename = $this->filename($name); 126 | $data = serialize($value); 127 | if( C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { 128 | //数据压缩 129 | $data = gzcompress($data,3); 130 | } 131 | if(C('DATA_CACHE_CHECK')) {//开启数据校验 132 | $check = md5($data); 133 | }else { 134 | $check = ''; 135 | } 136 | $data = ""; 137 | $result = file_put_contents($filename,$data); 138 | if($result) { 139 | if($this->options['length']>0) { 140 | // 记录缓存队列 141 | $this->queue($name); 142 | } 143 | clearstatcache(); 144 | return true; 145 | }else { 146 | return false; 147 | } 148 | } 149 | 150 | /** 151 | * 删除缓存 152 | * @access public 153 | * @param string $name 缓存变量名 154 | * @return boolean 155 | */ 156 | public function rm($name) { 157 | return unlink($this->filename($name)); 158 | } 159 | 160 | /** 161 | * 清除缓存 162 | * @access public 163 | * @param string $name 缓存变量名 164 | * @return boolean 165 | */ 166 | public function clear() { 167 | $path = $this->options['temp']; 168 | $files = scandir($path); 169 | if($files){ 170 | foreach($files as $file){ 171 | if ($file != '.' && $file != '..' && is_dir($path.$file) ){ 172 | array_map( 'unlink', glob( $path.$file.'/*.*' ) ); 173 | }elseif(is_file($path.$file)){ 174 | unlink( $path . $file ); 175 | } 176 | } 177 | return true; 178 | } 179 | return false; 180 | } 181 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Cache/Driver/Memcache.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Cache\Driver; 12 | use Think\Cache; 13 | defined('THINK_PATH') or exit(); 14 | /** 15 | * Memcache缓存驱动 16 | */ 17 | class Memcache extends Cache { 18 | 19 | /** 20 | * 架构函数 21 | * @param array $options 缓存参数 22 | * @access public 23 | */ 24 | function __construct($options=array()) { 25 | if ( !extension_loaded('memcache') ) { 26 | E(L('_NOT_SUPPORT_').':memcache'); 27 | } 28 | 29 | $options = array_merge(array ( 30 | 'host' => C('MEMCACHE_HOST') ? : '127.0.0.1', 31 | 'port' => C('MEMCACHE_PORT') ? : 11211, 32 | 'timeout' => C('DATA_CACHE_TIMEOUT') ? : false, 33 | 'persistent' => false, 34 | ),$options); 35 | 36 | $this->options = $options; 37 | $this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME'); 38 | $this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX'); 39 | $this->options['length'] = isset($options['length'])? $options['length'] : 0; 40 | $func = $options['persistent'] ? 'pconnect' : 'connect'; 41 | $this->handler = new \Memcache; 42 | $options['timeout'] === false ? 43 | $this->handler->$func($options['host'], $options['port']) : 44 | $this->handler->$func($options['host'], $options['port'], $options['timeout']); 45 | } 46 | 47 | /** 48 | * 读取缓存 49 | * @access public 50 | * @param string $name 缓存变量名 51 | * @return mixed 52 | */ 53 | public function get($name) { 54 | N('cache_read',1); 55 | return $this->handler->get($this->options['prefix'].$name); 56 | } 57 | 58 | /** 59 | * 写入缓存 60 | * @access public 61 | * @param string $name 缓存变量名 62 | * @param mixed $value 存储数据 63 | * @param integer $expire 有效时间(秒) 64 | * @return boolean 65 | */ 66 | public function set($name, $value, $expire = null) { 67 | N('cache_write',1); 68 | if(is_null($expire)) { 69 | $expire = $this->options['expire']; 70 | } 71 | $name = $this->options['prefix'].$name; 72 | if($this->handler->set($name, $value, 0, $expire)) { 73 | if($this->options['length']>0) { 74 | // 记录缓存队列 75 | $this->queue($name); 76 | } 77 | return true; 78 | } 79 | return false; 80 | } 81 | 82 | /** 83 | * 删除缓存 84 | * @access public 85 | * @param string $name 缓存变量名 86 | * @return boolean 87 | */ 88 | public function rm($name, $ttl = false) { 89 | $name = $this->options['prefix'].$name; 90 | return $ttl === false ? 91 | $this->handler->delete($name) : 92 | $this->handler->delete($name, $ttl); 93 | } 94 | 95 | /** 96 | * 清除缓存 97 | * @access public 98 | * @return boolean 99 | */ 100 | public function clear() { 101 | return $this->handler->flush(); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Cache/Driver/Memcached.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | namespace Think\Cache\Driver; 13 | 14 | use Memcached as MemcachedResource; 15 | use Think\Cache; 16 | 17 | /** 18 | * Memcached缓存驱动 19 | */ 20 | class Memcached extends Cache { 21 | 22 | /** 23 | * 24 | * @param array $options 25 | */ 26 | public function __construct($options = array()) { 27 | if ( !extension_loaded('memcached') ) { 28 | E(L('_NOT_SUPPORT_').':memcached'); 29 | } 30 | 31 | $options = array_merge(array( 32 | 'servers' => C('MEMCACHED_SERVER') ? : null, 33 | 'lib_options' => C('MEMCACHED_LIB') ? : null 34 | ), $options); 35 | 36 | $this->options = $options; 37 | $this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME'); 38 | $this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX'); 39 | $this->options['length'] = isset($options['length'])? $options['length'] : 0; 40 | 41 | $this->handler = new MemcachedResource; 42 | $options['servers'] && $this->handler->addServers($options['servers']); 43 | $options['lib_options'] && $this->handler->setOptions($options['lib_options']); 44 | } 45 | 46 | /** 47 | * 读取缓存 48 | * @access public 49 | * @param string $name 缓存变量名 50 | * @return mixed 51 | */ 52 | public function get($name) { 53 | N('cache_read',1); 54 | return $this->handler->get($this->options['prefix'].$name); 55 | } 56 | 57 | /** 58 | * 写入缓存 59 | * @access public 60 | * @param string $name 缓存变量名 61 | * @param mixed $value 存储数据 62 | * @param integer $expire 有效时间(秒) 63 | * @return boolean 64 | */ 65 | public function set($name, $value, $expire = null) { 66 | N('cache_write',1); 67 | if(is_null($expire)) { 68 | $expire = $this->options['expire']; 69 | } 70 | $name = $this->options['prefix'].$name; 71 | if($this->handler->set($name, $value, time() + $expire)) { 72 | if($this->options['length']>0) { 73 | // 记录缓存队列 74 | $this->queue($name); 75 | } 76 | return true; 77 | } 78 | return false; 79 | } 80 | 81 | /** 82 | * 删除缓存 83 | * @access public 84 | * @param string $name 缓存变量名 85 | * @return boolean 86 | */ 87 | public function rm($name, $ttl = false) { 88 | $name = $this->options['prefix'].$name; 89 | return $ttl === false ? 90 | $this->handler->delete($name) : 91 | $this->handler->delete($name, $ttl); 92 | } 93 | 94 | /** 95 | * 清除缓存 96 | * @access public 97 | * @return boolean 98 | */ 99 | public function clear() { 100 | return $this->handler->flush(); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Cache/Driver/Memcachesae.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Cache\Driver; 12 | use Think\Cache; 13 | 14 | defined('THINK_PATH') or exit(); 15 | /** 16 | * Memcache缓存驱动 17 | * @category Extend 18 | * @package Extend 19 | * @subpackage Driver.Cache 20 | * @author liu21st 21 | */ 22 | class Memcachesae extends Cache { 23 | 24 | /** 25 | * 架构函数 26 | * @param array $options 缓存参数 27 | * @access public 28 | */ 29 | function __construct($options=array()) { 30 | $options = array_merge(array ( 31 | 'host' => C('MEMCACHE_HOST') ? : '127.0.0.1', 32 | 'port' => C('MEMCACHE_PORT') ? : 11211, 33 | 'timeout' => C('DATA_CACHE_TIMEOUT') ? : false, 34 | 'persistent' => false, 35 | ),$options); 36 | 37 | $this->options = $options; 38 | $this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME'); 39 | $this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX'); 40 | $this->options['length'] = isset($options['length'])? $options['length'] : 0; 41 | $this->handler = memcache_init();//[sae] 下实例化 42 | //[sae] 下不用链接 43 | $this->connected=true; 44 | } 45 | 46 | /** 47 | * 是否连接 48 | * @access private 49 | * @return boolean 50 | */ 51 | private function isConnected() { 52 | return $this->connected; 53 | } 54 | 55 | /** 56 | * 读取缓存 57 | * @access public 58 | * @param string $name 缓存变量名 59 | * @return mixed 60 | */ 61 | public function get($name) { 62 | N('cache_read',1); 63 | return $this->handler->get($_SERVER['HTTP_APPVERSION'].'/'.$this->options['prefix'].$name); 64 | } 65 | 66 | /** 67 | * 写入缓存 68 | * @access public 69 | * @param string $name 缓存变量名 70 | * @param mixed $value 存储数据 71 | * @param integer $expire 有效时间(秒) 72 | * @return boolean 73 | */ 74 | public function set($name, $value, $expire = null) { 75 | N('cache_write',1); 76 | if(is_null($expire)) { 77 | $expire = $this->options['expire']; 78 | } 79 | $name = $this->options['prefix'].$name; 80 | if($this->handler->set($_SERVER['HTTP_APPVERSION'].'/'.$name, $value, 0, $expire)) { 81 | if($this->options['length']>0) { 82 | // 记录缓存队列 83 | $this->queue($name); 84 | } 85 | return true; 86 | } 87 | return false; 88 | } 89 | 90 | /** 91 | * 删除缓存 92 | * @access public 93 | * @param string $name 缓存变量名 94 | * @return boolean 95 | */ 96 | public function rm($name, $ttl = false) { 97 | $name = $_SERVER['HTTP_APPVERSION'].'/'.$this->options['prefix'].$name; 98 | return $ttl === false ? 99 | $this->handler->delete($name) : 100 | $this->handler->delete($name, $ttl); 101 | } 102 | 103 | /** 104 | * 清除缓存 105 | * @access public 106 | * @return boolean 107 | */ 108 | public function clear() { 109 | return $this->handler->flush(); 110 | } 111 | 112 | /** 113 | * 队列缓存 114 | * @access protected 115 | * @param string $key 队列名 116 | * @return mixed 117 | */ 118 | //[sae] 下重写queque队列缓存方法 119 | protected function queue($key) { 120 | $queue_name=isset($this->options['queue_name'])?$this->options['queue_name']:'think_queue'; 121 | $value = F($queue_name); 122 | if(!$value) { 123 | $value = array(); 124 | } 125 | // 进列 126 | if(false===array_search($key, $value)) array_push($value,$key); 127 | if(count($value) > $this->options['length']) { 128 | // 出列 129 | $key = array_shift($value); 130 | // 删除缓存 131 | $this->rm($key); 132 | if (APP_DEBUG) { 133 | //调试模式下记录出队次数 134 | $counter = Think::instance('SaeCounter'); 135 | if ($counter->exists($queue_name.'_out_times')) 136 | $counter->incr($queue_name.'_out_times'); 137 | else 138 | $counter->create($queue_name.'_out_times', 1); 139 | } 140 | } 141 | return F($queue_name,$value); 142 | } 143 | 144 | } 145 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Cache/Driver/Redis.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Cache\Driver; 12 | use Think\Cache; 13 | defined('THINK_PATH') or exit(); 14 | 15 | /** 16 | * Redis缓存驱动 17 | * 要求安装phpredis扩展:https://github.com/nicolasff/phpredis 18 | */ 19 | class Redis extends Cache { 20 | /** 21 | * 架构函数 22 | * @param array $options 缓存参数 23 | * @access public 24 | */ 25 | public function __construct($options=array()) { 26 | if ( !extension_loaded('redis') ) { 27 | E(L('_NOT_SUPPORT_').':redis'); 28 | } 29 | $options = array_merge(array ( 30 | 'host' => C('REDIS_HOST') ? : '127.0.0.1', 31 | 'port' => C('REDIS_PORT') ? : 6379, 32 | 'timeout' => C('DATA_CACHE_TIMEOUT') ? : false, 33 | 'persistent' => false, 34 | ),$options); 35 | 36 | $this->options = $options; 37 | $this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME'); 38 | $this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX'); 39 | $this->options['length'] = isset($options['length'])? $options['length'] : 0; 40 | $func = $options['persistent'] ? 'pconnect' : 'connect'; 41 | $this->handler = new \Redis; 42 | $options['timeout'] === false ? 43 | $this->handler->$func($options['host'], $options['port']) : 44 | $this->handler->$func($options['host'], $options['port'], $options['timeout']); 45 | } 46 | 47 | /** 48 | * 读取缓存 49 | * @access public 50 | * @param string $name 缓存变量名 51 | * @return mixed 52 | */ 53 | public function get($name) { 54 | N('cache_read',1); 55 | $value = $this->handler->get($this->options['prefix'].$name); 56 | $jsonData = json_decode( $value, true ); 57 | return ($jsonData === NULL) ? $value : $jsonData; //检测是否为JSON数据 true 返回JSON解析数组, false返回源数据 58 | } 59 | 60 | /** 61 | * 写入缓存 62 | * @access public 63 | * @param string $name 缓存变量名 64 | * @param mixed $value 存储数据 65 | * @param integer $expire 有效时间(秒) 66 | * @return boolean 67 | */ 68 | public function set($name, $value, $expire = null) { 69 | N('cache_write',1); 70 | if(is_null($expire)) { 71 | $expire = $this->options['expire']; 72 | } 73 | $name = $this->options['prefix'].$name; 74 | //对数组/对象数据进行缓存处理,保证数据完整性 75 | $value = (is_object($value) || is_array($value)) ? json_encode($value) : $value; 76 | if(is_int($expire) && $expire) { 77 | $result = $this->handler->setex($name, $expire, $value); 78 | }else{ 79 | $result = $this->handler->set($name, $value); 80 | } 81 | if($result && $this->options['length']>0) { 82 | // 记录缓存队列 83 | $this->queue($name); 84 | } 85 | return $result; 86 | } 87 | 88 | /** 89 | * 删除缓存 90 | * @access public 91 | * @param string $name 缓存变量名 92 | * @return boolean 93 | */ 94 | public function rm($name) { 95 | return $this->handler->delete($this->options['prefix'].$name); 96 | } 97 | 98 | /** 99 | * 清除缓存 100 | * @access public 101 | * @return boolean 102 | */ 103 | public function clear() { 104 | return $this->handler->flushDB(); 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Cache/Driver/Shmop.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Cache\Driver; 12 | use Think\Cache; 13 | defined('THINK_PATH') or exit(); 14 | /** 15 | * Shmop缓存驱动 16 | */ 17 | class Shmop extends Cache { 18 | 19 | /** 20 | * 架构函数 21 | * @param array $options 缓存参数 22 | * @access public 23 | */ 24 | public function __construct($options=array()) { 25 | if ( !extension_loaded('shmop') ) { 26 | E(L('_NOT_SUPPORT_').':shmop'); 27 | } 28 | if(!empty($options)){ 29 | $options = array( 30 | 'size' => C('SHARE_MEM_SIZE'), 31 | 'temp' => TEMP_PATH, 32 | 'project' => 's', 33 | 'length' => 0, 34 | ); 35 | } 36 | $this->options = $options; 37 | $this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX'); 38 | $this->options['length'] = isset($options['length'])? $options['length'] : 0; 39 | $this->handler = $this->_ftok($this->options['project']); 40 | } 41 | 42 | /** 43 | * 读取缓存 44 | * @access public 45 | * @param string $name 缓存变量名 46 | * @return mixed 47 | */ 48 | public function get($name = false) { 49 | N('cache_read',1); 50 | $id = shmop_open($this->handler, 'c', 0600, 0); 51 | if ($id !== false) { 52 | $ret = unserialize(shmop_read($id, 0, shmop_size($id))); 53 | shmop_close($id); 54 | 55 | if ($name === false) { 56 | return $ret; 57 | } 58 | $name = $this->options['prefix'].$name; 59 | if(isset($ret[$name])) { 60 | $content = $ret[$name]; 61 | if(C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { 62 | //启用数据压缩 63 | $content = gzuncompress($content); 64 | } 65 | return $content; 66 | }else { 67 | return null; 68 | } 69 | }else { 70 | return false; 71 | } 72 | } 73 | 74 | /** 75 | * 写入缓存 76 | * @access public 77 | * @param string $name 缓存变量名 78 | * @param mixed $value 存储数据 79 | * @return boolean 80 | */ 81 | public function set($name, $value) { 82 | N('cache_write',1); 83 | $lh = $this->_lock(); 84 | $val = $this->get(); 85 | if (!is_array($val)) $val = array(); 86 | if( C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { 87 | //数据压缩 88 | $value = gzcompress($value,3); 89 | } 90 | $name = $this->options['prefix'].$name; 91 | $val[$name] = $value; 92 | $val = serialize($val); 93 | if($this->_write($val, $lh)) { 94 | if($this->options['length']>0) { 95 | // 记录缓存队列 96 | $this->queue($name); 97 | } 98 | return true; 99 | } 100 | return false; 101 | } 102 | 103 | /** 104 | * 删除缓存 105 | * @access public 106 | * @param string $name 缓存变量名 107 | * @return boolean 108 | */ 109 | public function rm($name) { 110 | $lh = $this->_lock(); 111 | $val = $this->get(); 112 | if (!is_array($val)) $val = array(); 113 | $name = $this->options['prefix'].$name; 114 | unset($val[$name]); 115 | $val = serialize($val); 116 | return $this->_write($val, $lh); 117 | } 118 | 119 | /** 120 | * 生成IPC key 121 | * @access private 122 | * @param string $project 项目标识名 123 | * @return integer 124 | */ 125 | private function _ftok($project) { 126 | if (function_exists('ftok')) return ftok(__FILE__, $project); 127 | if(strtoupper(PHP_OS) == 'WINNT'){ 128 | $s = stat(__FILE__); 129 | return sprintf("%u", (($s['ino'] & 0xffff) | (($s['dev'] & 0xff) << 16) | 130 | (($project & 0xff) << 24))); 131 | }else { 132 | $filename = __FILE__ . (string) $project; 133 | for($key = array(); sizeof($key) < strlen($filename); $key[] = ord(substr($filename, sizeof($key), 1))); 134 | return dechex(array_sum($key)); 135 | } 136 | } 137 | 138 | /** 139 | * 写入操作 140 | * @access private 141 | * @param string $name 缓存变量名 142 | * @return integer|boolean 143 | */ 144 | private function _write(&$val, &$lh) { 145 | $id = shmop_open($this->handler, 'c', 0600, $this->options['size']); 146 | if ($id) { 147 | $ret = shmop_write($id, $val, 0) == strlen($val); 148 | shmop_close($id); 149 | $this->_unlock($lh); 150 | return $ret; 151 | } 152 | $this->_unlock($lh); 153 | return false; 154 | } 155 | 156 | /** 157 | * 共享锁定 158 | * @access private 159 | * @param string $name 缓存变量名 160 | * @return boolean 161 | */ 162 | private function _lock() { 163 | if (function_exists('sem_get')) { 164 | $fp = sem_get($this->handler, 1, 0600, 1); 165 | sem_acquire ($fp); 166 | } else { 167 | $fp = fopen($this->options['temp'].$this->options['prefix'].md5($this->handler), 'w'); 168 | flock($fp, LOCK_EX); 169 | } 170 | return $fp; 171 | } 172 | 173 | /** 174 | * 解除共享锁定 175 | * @access private 176 | * @param string $name 缓存变量名 177 | * @return boolean 178 | */ 179 | private function _unlock(&$fp) { 180 | if (function_exists('sem_release')) { 181 | sem_release($fp); 182 | } else { 183 | fclose($fp); 184 | } 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Cache/Driver/Sqlite.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Cache\Driver; 12 | use Think\Cache; 13 | defined('THINK_PATH') or exit(); 14 | /** 15 | * Sqlite缓存驱动 16 | */ 17 | class Sqlite extends Cache { 18 | 19 | /** 20 | * 架构函数 21 | * @param array $options 缓存参数 22 | * @access public 23 | */ 24 | public function __construct($options=array()) { 25 | if ( !extension_loaded('sqlite') ) { 26 | E(L('_NOT_SUPPORT_').':sqlite'); 27 | } 28 | if(empty($options)) { 29 | $options = array ( 30 | 'db' => ':memory:', 31 | 'table' => 'sharedmemory', 32 | ); 33 | } 34 | $this->options = $options; 35 | $this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX'); 36 | $this->options['length'] = isset($options['length'])? $options['length'] : 0; 37 | $this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME'); 38 | 39 | $func = $this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open'; 40 | $this->handler = $func($this->options['db']); 41 | } 42 | 43 | /** 44 | * 读取缓存 45 | * @access public 46 | * @param string $name 缓存变量名 47 | * @return mixed 48 | */ 49 | public function get($name) { 50 | N('cache_read',1); 51 | $name = $this->options['prefix'].sqlite_escape_string($name); 52 | $sql = 'SELECT value FROM '.$this->options['table'].' WHERE var=\''.$name.'\' AND (expire=0 OR expire >'.time().') LIMIT 1'; 53 | $result = sqlite_query($this->handler, $sql); 54 | if (sqlite_num_rows($result)) { 55 | $content = sqlite_fetch_single($result); 56 | if(C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { 57 | //启用数据压缩 58 | $content = gzuncompress($content); 59 | } 60 | return unserialize($content); 61 | } 62 | return false; 63 | } 64 | 65 | /** 66 | * 写入缓存 67 | * @access public 68 | * @param string $name 缓存变量名 69 | * @param mixed $value 存储数据 70 | * @param integer $expire 有效时间(秒) 71 | * @return boolean 72 | */ 73 | public function set($name, $value,$expire=null) { 74 | N('cache_write',1); 75 | $name = $this->options['prefix'].sqlite_escape_string($name); 76 | $value = sqlite_escape_string(serialize($value)); 77 | if(is_null($expire)) { 78 | $expire = $this->options['expire']; 79 | } 80 | $expire = ($expire==0)?0: (time()+$expire) ;//缓存有效期为0表示永久缓存 81 | if( C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { 82 | //数据压缩 83 | $value = gzcompress($value,3); 84 | } 85 | $sql = 'REPLACE INTO '.$this->options['table'].' (var, value,expire) VALUES (\''.$name.'\', \''.$value.'\', \''.$expire.'\')'; 86 | if(sqlite_query($this->handler, $sql)){ 87 | if($this->options['length']>0) { 88 | // 记录缓存队列 89 | $this->queue($name); 90 | } 91 | return true; 92 | } 93 | return false; 94 | } 95 | 96 | /** 97 | * 删除缓存 98 | * @access public 99 | * @param string $name 缓存变量名 100 | * @return boolean 101 | */ 102 | public function rm($name) { 103 | $name = $this->options['prefix'].sqlite_escape_string($name); 104 | $sql = 'DELETE FROM '.$this->options['table'].' WHERE var=\''.$name.'\''; 105 | sqlite_query($this->handler, $sql); 106 | return true; 107 | } 108 | 109 | /** 110 | * 清除缓存 111 | * @access public 112 | * @return boolean 113 | */ 114 | public function clear() { 115 | $sql = 'DELETE FROM '.$this->options['table']; 116 | sqlite_query($this->handler, $sql); 117 | return ; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Cache/Driver/Wincache.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Cache\Driver; 12 | use Think\Cache; 13 | defined('THINK_PATH') or exit(); 14 | /** 15 | * Wincache缓存驱动 16 | */ 17 | class Wincache extends Cache { 18 | 19 | /** 20 | * 架构函数 21 | * @param array $options 缓存参数 22 | * @access public 23 | */ 24 | public function __construct($options=array()) { 25 | if ( !function_exists('wincache_ucache_info') ) { 26 | E(L('_NOT_SUPPORT_').':WinCache'); 27 | } 28 | $this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME'); 29 | $this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX'); 30 | $this->options['length'] = isset($options['length'])? $options['length'] : 0; 31 | } 32 | 33 | /** 34 | * 读取缓存 35 | * @access public 36 | * @param string $name 缓存变量名 37 | * @return mixed 38 | */ 39 | public function get($name) { 40 | N('cache_read',1); 41 | $name = $this->options['prefix'].$name; 42 | return wincache_ucache_exists($name)? wincache_ucache_get($name) : false; 43 | } 44 | 45 | /** 46 | * 写入缓存 47 | * @access public 48 | * @param string $name 缓存变量名 49 | * @param mixed $value 存储数据 50 | * @param integer $expire 有效时间(秒) 51 | * @return boolean 52 | */ 53 | public function set($name, $value,$expire=null) { 54 | N('cache_write',1); 55 | if(is_null($expire)) { 56 | $expire = $this->options['expire']; 57 | } 58 | $name = $this->options['prefix'].$name; 59 | if(wincache_ucache_set($name, $value, $expire)) { 60 | if($this->options['length']>0) { 61 | // 记录缓存队列 62 | $this->queue($name); 63 | } 64 | return true; 65 | } 66 | return false; 67 | } 68 | 69 | /** 70 | * 删除缓存 71 | * @access public 72 | * @param string $name 缓存变量名 73 | * @return boolean 74 | */ 75 | public function rm($name) { 76 | return wincache_ucache_delete($this->options['prefix'].$name); 77 | } 78 | 79 | /** 80 | * 清除缓存 81 | * @access public 82 | * @return boolean 83 | */ 84 | public function clear() { 85 | return wincache_ucache_clear(); 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Cache/Driver/Xcache.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Cache\Driver; 12 | use Think\Cache; 13 | defined('THINK_PATH') or exit(); 14 | /** 15 | * Xcache缓存驱动 16 | */ 17 | class Xcache extends Cache { 18 | 19 | /** 20 | * 架构函数 21 | * @param array $options 缓存参数 22 | * @access public 23 | */ 24 | public function __construct($options=array()) { 25 | if ( !function_exists('xcache_info') ) { 26 | E(L('_NOT_SUPPORT_').':Xcache'); 27 | } 28 | $this->options['expire'] = isset($options['expire'])?$options['expire']:C('DATA_CACHE_TIME'); 29 | $this->options['prefix'] = isset($options['prefix'])?$options['prefix']:C('DATA_CACHE_PREFIX'); 30 | $this->options['length'] = isset($options['length'])?$options['length']:0; 31 | } 32 | 33 | /** 34 | * 读取缓存 35 | * @access public 36 | * @param string $name 缓存变量名 37 | * @return mixed 38 | */ 39 | public function get($name) { 40 | N('cache_read',1); 41 | $name = $this->options['prefix'].$name; 42 | if (xcache_isset($name)) { 43 | return xcache_get($name); 44 | } 45 | return false; 46 | } 47 | 48 | /** 49 | * 写入缓存 50 | * @access public 51 | * @param string $name 缓存变量名 52 | * @param mixed $value 存储数据 53 | * @param integer $expire 有效时间(秒) 54 | * @return boolean 55 | */ 56 | public function set($name, $value,$expire=null) { 57 | N('cache_write',1); 58 | if(is_null($expire)) { 59 | $expire = $this->options['expire'] ; 60 | } 61 | $name = $this->options['prefix'].$name; 62 | if(xcache_set($name, $value, $expire)) { 63 | if($this->options['length']>0) { 64 | // 记录缓存队列 65 | $this->queue($name); 66 | } 67 | return true; 68 | } 69 | return false; 70 | } 71 | 72 | /** 73 | * 删除缓存 74 | * @access public 75 | * @param string $name 缓存变量名 76 | * @return boolean 77 | */ 78 | public function rm($name) { 79 | return xcache_unset($this->options['prefix'].$name); 80 | } 81 | 82 | /** 83 | * 清除缓存 84 | * @access public 85 | * @return boolean 86 | */ 87 | public function clear() { 88 | return xcache_clear_cache(1, -1); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Db.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | namespace Think; 13 | 14 | /** 15 | * ThinkPHP 数据库中间层实现类 16 | */ 17 | class Db { 18 | 19 | static private $instance = array(); // 数据库连接实例 20 | static private $_instance = null; // 当前数据库连接实例 21 | 22 | /** 23 | * 取得数据库类实例 24 | * @static 25 | * @access public 26 | * @param mixed $config 连接配置 27 | * @return Object 返回数据库驱动类 28 | */ 29 | static public function getInstance($config=array()) { 30 | $md5 = md5(serialize($config)); 31 | if(!isset(self::$instance[$md5])) { 32 | // 解析连接参数 支持数组和字符串 33 | $options = self::parseConfig($config); 34 | // 兼容mysqli 35 | if('mysqli' == $options['type']) $options['type'] = 'mysql'; 36 | // 如果采用lite方式 仅支持原生SQL 包括query和execute方法 37 | $class = !empty($options['lite'])? 'Think\Db\Lite' : 'Think\\Db\\Driver\\'.ucwords(strtolower($options['type'])); 38 | if(class_exists($class)){ 39 | self::$instance[$md5] = new $class($options); 40 | }else{ 41 | // 类没有定义 42 | E(L('_NO_DB_DRIVER_').': ' . $class); 43 | } 44 | } 45 | self::$_instance = self::$instance[$md5]; 46 | return self::$_instance; 47 | } 48 | 49 | /** 50 | * 数据库连接参数解析 51 | * @static 52 | * @access private 53 | * @param mixed $config 54 | * @return array 55 | */ 56 | static private function parseConfig($config){ 57 | if(!empty($config)){ 58 | if(is_string($config)) { 59 | return self::parseDsn($config); 60 | } 61 | $config = array_change_key_case($config); 62 | $config = array ( 63 | 'type' => $config['db_type'], 64 | 'username' => $config['db_user'], 65 | 'password' => $config['db_pwd'], 66 | 'hostname' => $config['db_host'], 67 | 'hostport' => $config['db_port'], 68 | 'database' => $config['db_name'], 69 | 'dsn' => isset($config['db_dsn'])?$config['db_dsn']:null, 70 | 'params' => isset($config['db_params'])?$config['db_params']:null, 71 | 'charset' => isset($config['db_charset'])?$config['db_charset']:'utf8', 72 | 'deploy' => isset($config['db_deploy_type'])?$config['db_deploy_type']:0, 73 | 'rw_separate' => isset($config['db_rw_separate'])?$config['db_rw_separate']:false, 74 | 'master_num' => isset($config['db_master_num'])?$config['db_master_num']:1, 75 | 'slave_no' => isset($config['db_slave_no'])?$config['db_slave_no']:'', 76 | 'debug' => isset($config['db_debug'])?$config['db_debug']:APP_DEBUG, 77 | 'lite' => isset($config['db_lite'])?$config['db_lite']:false, 78 | ); 79 | }else { 80 | $config = array ( 81 | 'type' => C('DB_TYPE'), 82 | 'username' => C('DB_USER'), 83 | 'password' => C('DB_PWD'), 84 | 'hostname' => C('DB_HOST'), 85 | 'hostport' => C('DB_PORT'), 86 | 'database' => C('DB_NAME'), 87 | 'dsn' => C('DB_DSN'), 88 | 'params' => C('DB_PARAMS'), 89 | 'charset' => C('DB_CHARSET'), 90 | 'deploy' => C('DB_DEPLOY_TYPE'), 91 | 'rw_separate' => C('DB_RW_SEPARATE'), 92 | 'master_num' => C('DB_MASTER_NUM'), 93 | 'slave_no' => C('DB_SLAVE_NO'), 94 | 'debug' => C('DB_DEBUG',null,APP_DEBUG), 95 | 'lite' => C('DB_LITE'), 96 | ); 97 | } 98 | return $config; 99 | } 100 | 101 | /** 102 | * DSN解析 103 | * 格式: mysql://username:passwd@localhost:3306/DbName?param1=val1¶m2=val2#utf8 104 | * @static 105 | * @access private 106 | * @param string $dsnStr 107 | * @return array 108 | */ 109 | static private function parseDsn($dsnStr) { 110 | if( empty($dsnStr) ){return false;} 111 | $info = parse_url($dsnStr); 112 | if(!$info) { 113 | return false; 114 | } 115 | $dsn = array( 116 | 'type' => $info['scheme'], 117 | 'username' => isset($info['user']) ? $info['user'] : '', 118 | 'password' => isset($info['pass']) ? $info['pass'] : '', 119 | 'hostname' => isset($info['host']) ? $info['host'] : '', 120 | 'hostport' => isset($info['port']) ? $info['port'] : '', 121 | 'database' => isset($info['path']) ? substr($info['path'],1) : '', 122 | 'charset' => isset($info['fragment'])?$info['fragment']:'utf8', 123 | ); 124 | 125 | if(isset($info['query'])) { 126 | parse_str($info['query'],$dsn['params']); 127 | }else{ 128 | $dsn['params'] = array(); 129 | } 130 | return $dsn; 131 | } 132 | 133 | // 调用驱动类的方法 134 | static public function __callStatic($method, $params){ 135 | return call_user_func_array(array(self::$_instance, $method), $params); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Db/Driver/Firebird.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Db\Driver; 12 | use Think\Db\Driver; 13 | 14 | /** 15 | * Firebird数据库驱动 16 | */ 17 | class Firebird extends Driver{ 18 | protected $selectSql = 'SELECT %LIMIT% %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%'; 19 | 20 | /** 21 | * 解析pdo连接的dsn信息 22 | * @access public 23 | * @param array $config 连接信息 24 | * @return string 25 | */ 26 | protected function parseDsn($config){ 27 | $dsn = 'firebird:dbname='.$config['hostname'].'/'.($config['hostport']?:3050).':'.$config['database']; 28 | return $dsn; 29 | } 30 | 31 | /** 32 | * 执行语句 33 | * @access public 34 | * @param string $str sql指令 35 | * @param boolean $fetchSql 不执行只是获取SQL 36 | * @return mixed 37 | */ 38 | public function execute($str,$fetchSql=false) { 39 | $this->initConnect(true); 40 | if ( !$this->_linkID ) return false; 41 | $this->queryStr = $str; 42 | if(!empty($this->bind)){ 43 | $that = $this; 44 | $this->queryStr = strtr($this->queryStr,array_map(function($val) use($that){ return '\''.$that->escapeString($val).'\''; },$this->bind)); 45 | } 46 | if($fetchSql){ 47 | return $this->queryStr; 48 | } 49 | //释放前次的查询结果 50 | if ( !empty($this->PDOStatement) ) $this->free(); 51 | $this->executeTimes++; 52 | N('db_write',1); // 兼容代码 53 | // 记录开始执行时间 54 | $this->debug(true); 55 | $this->PDOStatement = $this->_linkID->prepare($str); 56 | if(false === $this->PDOStatement) { 57 | E($this->error()); 58 | } 59 | foreach ($this->bind as $key => $val) { 60 | if(is_array($val)){ 61 | $this->PDOStatement->bindValue($key, $val[0], $val[1]); 62 | }else{ 63 | $this->PDOStatement->bindValue($key, $val); 64 | } 65 | } 66 | $this->bind = array(); 67 | $result = $this->PDOStatement->execute(); 68 | $this->debug(false); 69 | if ( false === $result) { 70 | $this->error(); 71 | return false; 72 | } else { 73 | $this->numRows = $this->PDOStatement->rowCount(); 74 | return $this->numRows; 75 | } 76 | } 77 | 78 | /** 79 | * 取得数据表的字段信息 80 | * @access public 81 | */ 82 | public function getFields($tableName) { 83 | $this->initConnect(true); 84 | list($tableName) = explode(' ', $tableName); 85 | $sql='SELECT RF.RDB$FIELD_NAME AS FIELD,RF.RDB$DEFAULT_VALUE AS DEFAULT1,RF.RDB$NULL_FLAG AS NULL1,TRIM(T.RDB$TYPE_NAME) || \'(\' || F.RDB$FIELD_LENGTH || \')\' as TYPE FROM RDB$RELATION_FIELDS RF LEFT JOIN RDB$FIELDS F ON (F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE) LEFT JOIN RDB$TYPES T ON (T.RDB$TYPE = F.RDB$FIELD_TYPE) WHERE RDB$RELATION_NAME=UPPER(\''.$tableName.'\') AND T.RDB$FIELD_NAME = \'RDB$FIELD_TYPE\' ORDER By RDB$FIELD_POSITION'; 86 | $result = $this->query($sql); 87 | $info = array(); 88 | if($result){ 89 | foreach($result as $key => $val){ 90 | $info[trim($val['field'])] = array( 91 | 'name' => trim($val['field']), 92 | 'type' => $val['type'], 93 | 'notnull' => (bool) ($val['null1'] ==1), // 1表示不为Null 94 | 'default' => $val['default1'], 95 | 'primary' => false, 96 | 'autoinc' => false, 97 | ); 98 | } 99 | } 100 | //获取主键 101 | $sql='select b.rdb$field_name as field_name from rdb$relation_constraints a join rdb$index_segments b on a.rdb$index_name=b.rdb$index_name where a.rdb$constraint_type=\'PRIMARY KEY\' and a.rdb$relation_name=UPPER(\''.$tableName.'\')'; 102 | $rs_temp = $this->query($sql); 103 | foreach($rs_temp as $row) { 104 | $info[trim($row['field_name'])]['primary']= true; 105 | } 106 | return $info; 107 | } 108 | 109 | /** 110 | * 取得数据库的表信息 111 | * @access public 112 | */ 113 | public function getTables($dbName='') { 114 | $sql='SELECT DISTINCT RDB$RELATION_NAME FROM RDB$RELATION_FIELDS WHERE RDB$SYSTEM_FLAG=0'; 115 | $result = $this->query($sql); 116 | $info = array(); 117 | foreach ($result as $key => $val) { 118 | $info[$key] = trim(current($val)); 119 | } 120 | return $info; 121 | } 122 | 123 | /** 124 | * SQL指令安全过滤 125 | * @access public 126 | * @param string $str SQL指令 127 | * @return string 128 | */ 129 | public function escapeString($str) { 130 | return str_replace("'", "''", $str); 131 | } 132 | 133 | /** 134 | * limit 135 | * @access public 136 | * @param $limit limit表达式 137 | * @return string 138 | */ 139 | public function parseLimit($limit) { 140 | $limitStr = ''; 141 | if(!empty($limit)) { 142 | $limit = explode(',',$limit); 143 | if(count($limit)>1) { 144 | $limitStr = ' FIRST '.$limit[1].' SKIP '.$limit[0].' '; 145 | }else{ 146 | $limitStr = ' FIRST '.$limit[0].' '; 147 | } 148 | } 149 | return $limitStr; 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Db/Driver/Oracle.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | namespace Think\Db\Driver; 13 | use Think\Db\Driver; 14 | 15 | /** 16 | * Oracle数据库驱动 17 | */ 18 | class Oracle extends Driver{ 19 | 20 | private $table = ''; 21 | protected $selectSql = 'SELECT * FROM (SELECT thinkphp.*, rownum AS numrow FROM (SELECT %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%) thinkphp ) %LIMIT%%COMMENT%'; 22 | 23 | /** 24 | * 解析pdo连接的dsn信息 25 | * @access public 26 | * @param array $config 连接信息 27 | * @return string 28 | */ 29 | protected function parseDsn($config){ 30 | $dsn = 'oci:dbname=//'.$config['hostname'].($config['hostport']?':'.$config['hostport']:'').'/'.$config['database']; 31 | if(!empty($config['charset'])) { 32 | $dsn .= ';charset='.$config['charset']; 33 | } 34 | return $dsn; 35 | } 36 | 37 | /** 38 | * 执行语句 39 | * @access public 40 | * @param string $str sql指令 41 | * @param boolean $fetchSql 不执行只是获取SQL 42 | * @return integer 43 | */ 44 | public function execute($str,$fetchSql=false) { 45 | $this->initConnect(true); 46 | if ( !$this->_linkID ) return false; 47 | $this->queryStr = $str; 48 | if(!empty($this->bind)){ 49 | $that = $this; 50 | $this->queryStr = strtr($this->queryStr,array_map(function($val) use($that){ return '\''.$that->escapeString($val).'\''; },$this->bind)); 51 | } 52 | if($fetchSql){ 53 | return $this->queryStr; 54 | } 55 | $flag = false; 56 | if(preg_match("/^\s*(INSERT\s+INTO)\s+(\w+)\s+/i", $str, $match)) { 57 | $this->table = C("DB_SEQUENCE_PREFIX").str_ireplace(C("DB_PREFIX"), "", $match[2]); 58 | $flag = (boolean)$this->query("SELECT * FROM user_sequences WHERE sequence_name='" . strtoupper($this->table) . "'"); 59 | } 60 | //释放前次的查询结果 61 | if ( !empty($this->PDOStatement) ) $this->free(); 62 | $this->executeTimes++; 63 | N('db_write',1); // 兼容代码 64 | // 记录开始执行时间 65 | $this->debug(true); 66 | $this->PDOStatement = $this->_linkID->prepare($str); 67 | if(false === $this->PDOStatement) { 68 | $this->error(); 69 | return false; 70 | } 71 | foreach ($this->bind as $key => $val) { 72 | if(is_array($val)){ 73 | $this->PDOStatement->bindValue($key, $val[0], $val[1]); 74 | }else{ 75 | $this->PDOStatement->bindValue($key, $val); 76 | } 77 | } 78 | $this->bind = array(); 79 | $result = $this->PDOStatement->execute(); 80 | $this->debug(false); 81 | if ( false === $result) { 82 | $this->error(); 83 | return false; 84 | } else { 85 | $this->numRows = $this->PDOStatement->rowCount(); 86 | if($flag || preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) { 87 | $this->lastInsID = $this->_linkID->lastInsertId(); 88 | } 89 | return $this->numRows; 90 | } 91 | } 92 | 93 | /** 94 | * 取得数据表的字段信息 95 | * @access public 96 | */ 97 | public function getFields($tableName) { 98 | list($tableName) = explode(' ', $tableName); 99 | $result = $this->query("select a.column_name,data_type,decode(nullable,'Y',0,1) notnull,data_default,decode(a.column_name,b.column_name,1,0) pk " 100 | ."from user_tab_columns a,(select column_name from user_constraints c,user_cons_columns col " 101 | ."where c.constraint_name=col.constraint_name and c.constraint_type='P'and c.table_name='".strtoupper($tableName) 102 | ."') b where table_name='".strtoupper($tableName)."' and a.column_name=b.column_name(+)"); 103 | $info = array(); 104 | if($result) { 105 | foreach ($result as $key => $val) { 106 | $info[strtolower($val['column_name'])] = array( 107 | 'name' => strtolower($val['column_name']), 108 | 'type' => strtolower($val['data_type']), 109 | 'notnull' => $val['notnull'], 110 | 'default' => $val['data_default'], 111 | 'primary' => $val['pk'], 112 | 'autoinc' => $val['pk'], 113 | ); 114 | } 115 | } 116 | return $info; 117 | } 118 | 119 | /** 120 | * 取得数据库的表信息(暂时实现取得用户表信息) 121 | * @access public 122 | */ 123 | public function getTables($dbName='') { 124 | $result = $this->query("select table_name from user_tables"); 125 | $info = array(); 126 | foreach ($result as $key => $val) { 127 | $info[$key] = current($val); 128 | } 129 | return $info; 130 | } 131 | 132 | /** 133 | * SQL指令安全过滤 134 | * @access public 135 | * @param string $str SQL指令 136 | * @return string 137 | */ 138 | public function escapeString($str) { 139 | return str_ireplace("'", "''", $str); 140 | } 141 | 142 | /** 143 | * limit 144 | * @access public 145 | * @return string 146 | */ 147 | public function parseLimit($limit) { 148 | $limitStr = ''; 149 | if(!empty($limit)) { 150 | $limit = explode(',',$limit); 151 | if(count($limit)>1) 152 | $limitStr = "(numrow>" . $limit[0] . ") AND (numrow<=" . ($limit[0]+$limit[1]) . ")"; 153 | else 154 | $limitStr = "(numrow>0 AND numrow<=".$limit[0].")"; 155 | } 156 | return $limitStr?' WHERE '.$limitStr:''; 157 | } 158 | 159 | /** 160 | * 设置锁机制 161 | * @access protected 162 | * @return string 163 | */ 164 | protected function parseLock($lock=false) { 165 | if(!$lock) return ''; 166 | return ' FOR UPDATE NOWAIT '; 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Db/Driver/Pgsql.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | namespace Think\Db\Driver; 13 | use Think\Db\Driver; 14 | 15 | /** 16 | * Pgsql数据库驱动 17 | */ 18 | class Pgsql extends Driver{ 19 | 20 | /** 21 | * 解析pdo连接的dsn信息 22 | * @access public 23 | * @param array $config 连接信息 24 | * @return string 25 | */ 26 | protected function parseDsn($config){ 27 | $dsn = 'pgsql:dbname='.$config['database'].';host='.$config['hostname']; 28 | if(!empty($config['hostport'])) { 29 | $dsn .= ';port='.$config['hostport']; 30 | } 31 | return $dsn; 32 | } 33 | 34 | /** 35 | * 取得数据表的字段信息 36 | * @access public 37 | * @return array 38 | */ 39 | public function getFields($tableName) { 40 | list($tableName) = explode(' ', $tableName); 41 | $result = $this->query('select fields_name as "field",fields_type as "type",fields_not_null as "null",fields_key_name as "key",fields_default as "default",fields_default as "extra" from table_msg('.$tableName.');'); 42 | $info = array(); 43 | if($result){ 44 | foreach ($result as $key => $val) { 45 | $info[$val['field']] = array( 46 | 'name' => $val['field'], 47 | 'type' => $val['type'], 48 | 'notnull' => (bool) ($val['null'] === ''), // not null is empty, null is yes 49 | 'default' => $val['default'], 50 | 'primary' => (strtolower($val['key']) == 'pri'), 51 | 'autoinc' => (strtolower($val['extra']) == 'auto_increment'), 52 | ); 53 | } 54 | } 55 | return $info; 56 | } 57 | 58 | /** 59 | * 取得数据库的表信息 60 | * @access public 61 | * @return array 62 | */ 63 | public function getTables($dbName='') { 64 | $result = $this->query("select tablename as Tables_in_test from pg_tables where schemaname ='public'"); 65 | $info = array(); 66 | foreach ($result as $key => $val) { 67 | $info[$key] = current($val); 68 | } 69 | return $info; 70 | } 71 | 72 | /** 73 | * limit分析 74 | * @access protected 75 | * @param mixed $lmit 76 | * @return string 77 | */ 78 | public function parseLimit($limit) { 79 | $limitStr = ''; 80 | if(!empty($limit)) { 81 | $limit = explode(',',$limit); 82 | if(count($limit)>1) { 83 | $limitStr .= ' LIMIT '.$limit[1].' OFFSET '.$limit[0].' '; 84 | }else{ 85 | $limitStr .= ' LIMIT '.$limit[0].' '; 86 | } 87 | } 88 | return $limitStr; 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Db/Driver/Sqlite.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | namespace Think\Db\Driver; 13 | use Think\Db\Driver; 14 | 15 | /** 16 | * Sqlite数据库驱动 17 | */ 18 | class Sqlite extends Driver { 19 | 20 | /** 21 | * 解析pdo连接的dsn信息 22 | * @access public 23 | * @param array $config 连接信息 24 | * @return string 25 | */ 26 | protected function parseDsn($config){ 27 | $dsn = 'sqlite:'.$config['database']; 28 | return $dsn; 29 | } 30 | 31 | /** 32 | * 取得数据表的字段信息 33 | * @access public 34 | * @return array 35 | */ 36 | public function getFields($tableName) { 37 | list($tableName) = explode(' ', $tableName); 38 | $result = $this->query('PRAGMA table_info( '.$tableName.' )'); 39 | $info = array(); 40 | if($result){ 41 | foreach ($result as $key => $val) { 42 | $info[$val['field']] = array( 43 | 'name' => $val['field'], 44 | 'type' => $val['type'], 45 | 'notnull' => (bool) ($val['null'] === ''), // not null is empty, null is yes 46 | 'default' => $val['default'], 47 | 'primary' => (strtolower($val['dey']) == 'pri'), 48 | 'autoinc' => (strtolower($val['extra']) == 'auto_increment'), 49 | ); 50 | } 51 | } 52 | return $info; 53 | } 54 | 55 | /** 56 | * 取得数据库的表信息 57 | * @access public 58 | * @return array 59 | */ 60 | public function getTables($dbName='') { 61 | $result = $this->query("SELECT name FROM sqlite_master WHERE type='table' " 62 | . "UNION ALL SELECT name FROM sqlite_temp_master " 63 | . "WHERE type='table' ORDER BY name"); 64 | $info = array(); 65 | foreach ($result as $key => $val) { 66 | $info[$key] = current($val); 67 | } 68 | return $info; 69 | } 70 | 71 | /** 72 | * SQL指令安全过滤 73 | * @access public 74 | * @param string $str SQL指令 75 | * @return string 76 | */ 77 | public function escapeString($str) { 78 | return str_ireplace("'", "''", $str); 79 | } 80 | 81 | /** 82 | * limit 83 | * @access public 84 | * @return string 85 | */ 86 | public function parseLimit($limit) { 87 | $limitStr = ''; 88 | if(!empty($limit)) { 89 | $limit = explode(',',$limit); 90 | if(count($limit)>1) { 91 | $limitStr .= ' LIMIT '.$limit[1].' OFFSET '.$limit[0].' '; 92 | }else{ 93 | $limitStr .= ' LIMIT '.$limit[0].' '; 94 | } 95 | } 96 | return $limitStr; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Db/Driver/Sqlsrv.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | namespace Think\Db\Driver; 13 | use Think\Db\Driver; 14 | use PDO; 15 | 16 | /** 17 | * Sqlsrv数据库驱动 18 | */ 19 | class Sqlsrv extends Driver{ 20 | protected $selectSql = 'SELECT T1.* FROM (SELECT thinkphp.*, ROW_NUMBER() OVER (%ORDER%) AS ROW_NUMBER FROM (SELECT %DISTINCT% %FIELD% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING% %UNION%) AS thinkphp) AS T1 %LIMIT%%COMMENT%'; 21 | // PDO连接参数 22 | protected $options = array( 23 | PDO::ATTR_CASE => PDO::CASE_LOWER, 24 | PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 25 | PDO::ATTR_STRINGIFY_FETCHES => false, 26 | PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8, 27 | ); 28 | 29 | /** 30 | * 解析pdo连接的dsn信息 31 | * @access public 32 | * @param array $config 连接信息 33 | * @return string 34 | */ 35 | protected function parseDsn($config){ 36 | $dsn = 'sqlsrv:Database='.$config['database'].';Server='.$config['hostname']; 37 | if(!empty($config['hostport'])) { 38 | $dsn .= ','.$config['hostport']; 39 | } 40 | return $dsn; 41 | } 42 | 43 | /** 44 | * 取得数据表的字段信息 45 | * @access public 46 | * @return array 47 | */ 48 | public function getFields($tableName) { 49 | list($tableName) = explode(' ', $tableName); 50 | $result = $this->query("SELECT column_name, data_type, column_default, is_nullable 51 | FROM information_schema.tables AS t 52 | JOIN information_schema.columns AS c 53 | ON t.table_catalog = c.table_catalog 54 | AND t.table_schema = c.table_schema 55 | AND t.table_name = c.table_name 56 | WHERE t.table_name = '$tableName'"); 57 | $info = array(); 58 | if($result) { 59 | foreach ($result as $key => $val) { 60 | $info[$val['column_name']] = array( 61 | 'name' => $val['column_name'], 62 | 'type' => $val['data_type'], 63 | 'notnull' => (bool) ($val['is_nullable'] === ''), // not null is empty, null is yes 64 | 'default' => $val['column_default'], 65 | 'primary' => false, 66 | 'autoinc' => false, 67 | ); 68 | } 69 | } 70 | return $info; 71 | } 72 | 73 | /** 74 | * 取得数据表的字段信息 75 | * @access public 76 | * @return array 77 | */ 78 | public function getTables($dbName='') { 79 | $result = $this->query("SELECT TABLE_NAME 80 | FROM INFORMATION_SCHEMA.TABLES 81 | WHERE TABLE_TYPE = 'BASE TABLE' 82 | "); 83 | $info = array(); 84 | foreach ($result as $key => $val) { 85 | $info[$key] = current($val); 86 | } 87 | return $info; 88 | } 89 | 90 | /** 91 | * order分析 92 | * @access protected 93 | * @param mixed $order 94 | * @return string 95 | */ 96 | protected function parseOrder($order) { 97 | return !empty($order)? ' ORDER BY '.$order:' ORDER BY rand()'; 98 | } 99 | 100 | /** 101 | * 字段名分析 102 | * @access protected 103 | * @param string $key 104 | * @return string 105 | */ 106 | protected function parseKey(&$key) { 107 | $key = trim($key); 108 | if(!is_numeric($key) && !preg_match('/[,\'\"\*\(\)\[.\s]/',$key)) { 109 | $key = '['.$key.']'; 110 | } 111 | return $key; 112 | } 113 | 114 | /** 115 | * limit 116 | * @access public 117 | * @param mixed $limit 118 | * @return string 119 | */ 120 | public function parseLimit($limit) { 121 | if(empty($limit)) return ''; 122 | $limit = explode(',',$limit); 123 | if(count($limit)>1) 124 | $limitStr = '(T1.ROW_NUMBER BETWEEN '.$limit[0].' + 1 AND '.$limit[0].' + '.$limit[1].')'; 125 | else 126 | $limitStr = '(T1.ROW_NUMBER BETWEEN 1 AND '.$limit[0].")"; 127 | return 'WHERE '.$limitStr; 128 | } 129 | 130 | /** 131 | * 更新记录 132 | * @access public 133 | * @param mixed $data 数据 134 | * @param array $options 表达式 135 | * @return false | integer 136 | */ 137 | public function update($data,$options) { 138 | $this->model = $options['model']; 139 | $this->parseBind(!empty($options['bind'])?$options['bind']:array()); 140 | $sql = 'UPDATE ' 141 | .$this->parseTable($options['table']) 142 | .$this->parseSet($data) 143 | .$this->parseWhere(!empty($options['where'])?$options['where']:'') 144 | .$this->parseLock(isset($options['lock'])?$options['lock']:false) 145 | .$this->parseComment(!empty($options['comment'])?$options['comment']:''); 146 | return $this->execute($sql,!empty($options['fetch_sql']) ? true : false); 147 | } 148 | 149 | /** 150 | * 删除记录 151 | * @access public 152 | * @param array $options 表达式 153 | * @return false | integer 154 | */ 155 | public function delete($options=array()) { 156 | $this->model = $options['model']; 157 | $this->parseBind(!empty($options['bind'])?$options['bind']:array()); 158 | $sql = 'DELETE FROM ' 159 | .$this->parseTable($options['table']) 160 | .$this->parseWhere(!empty($options['where'])?$options['where']:'') 161 | .$this->parseLock(isset($options['lock'])?$options['lock']:false) 162 | .$this->parseComment(!empty($options['comment'])?$options['comment']:''); 163 | return $this->execute($sql,!empty($options['fetch_sql']) ? true : false); 164 | } 165 | 166 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Exception.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think; 12 | /** 13 | * ThinkPHP系统异常基类 14 | */ 15 | class Exception extends \Exception { 16 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Hook.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think; 12 | /** 13 | * ThinkPHP系统钩子实现 14 | */ 15 | class Hook { 16 | 17 | static private $tags = array(); 18 | 19 | /** 20 | * 动态添加插件到某个标签 21 | * @param string $tag 标签名称 22 | * @param mixed $name 插件名称 23 | * @return void 24 | */ 25 | static public function add($tag,$name) { 26 | if(!isset(self::$tags[$tag])){ 27 | self::$tags[$tag] = array(); 28 | } 29 | if(is_array($name)){ 30 | self::$tags[$tag] = array_merge(self::$tags[$tag],$name); 31 | }else{ 32 | self::$tags[$tag][] = $name; 33 | } 34 | } 35 | 36 | /** 37 | * 批量导入插件 38 | * @param array $data 插件信息 39 | * @param boolean $recursive 是否递归合并 40 | * @return void 41 | */ 42 | static public function import($data,$recursive=true) { 43 | if(!$recursive){ // 覆盖导入 44 | self::$tags = array_merge(self::$tags,$data); 45 | }else{ // 合并导入 46 | foreach ($data as $tag=>$val){ 47 | if(!isset(self::$tags[$tag])) 48 | self::$tags[$tag] = array(); 49 | if(!empty($val['_overlay'])){ 50 | // 可以针对某个标签指定覆盖模式 51 | unset($val['_overlay']); 52 | self::$tags[$tag] = $val; 53 | }else{ 54 | // 合并模式 55 | self::$tags[$tag] = array_merge(self::$tags[$tag],$val); 56 | } 57 | } 58 | } 59 | } 60 | 61 | /** 62 | * 获取插件信息 63 | * @param string $tag 插件位置 留空获取全部 64 | * @return array 65 | */ 66 | static public function get($tag='') { 67 | if(empty($tag)){ 68 | // 获取全部的插件信息 69 | return self::$tags; 70 | }else{ 71 | return self::$tags[$tag]; 72 | } 73 | } 74 | 75 | /** 76 | * 监听标签的插件 77 | * @param string $tag 标签名称 78 | * @param mixed $params 传入参数 79 | * @return void 80 | */ 81 | static public function listen($tag, &$params=NULL) { 82 | if(isset(self::$tags[$tag])) { 83 | if(APP_DEBUG) { 84 | G($tag.'Start'); 85 | trace('[ '.$tag.' ] --START--','','INFO'); 86 | } 87 | foreach (self::$tags[$tag] as $name) { 88 | APP_DEBUG && G($name.'_start'); 89 | $result = self::exec($name, $tag,$params); 90 | if(APP_DEBUG){ 91 | G($name.'_end'); 92 | trace('Run '.$name.' [ RunTime:'.G($name.'_start',$name.'_end',6).'s ]','','INFO'); 93 | } 94 | if(false === $result) { 95 | // 如果返回false 则中断插件执行 96 | return ; 97 | } 98 | } 99 | if(APP_DEBUG) { // 记录行为的执行日志 100 | trace('[ '.$tag.' ] --END-- [ RunTime:'.G($tag.'Start',$tag.'End',6).'s ]','','INFO'); 101 | } 102 | } 103 | return; 104 | } 105 | 106 | /** 107 | * 执行某个插件 108 | * @param string $name 插件名称 109 | * @param string $tag 方法名(标签名) 110 | * @param Mixed $params 传入的参数 111 | * @return void 112 | */ 113 | static public function exec($name, $tag,&$params=NULL) { 114 | if('Behavior' == substr($name,-8) ){ 115 | // 行为扩展必须用run入口方法 116 | $tag = 'run'; 117 | } 118 | $addon = new $name(); 119 | return $addon->$tag($params); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Log.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think; 12 | /** 13 | * 日志处理类 14 | */ 15 | class Log { 16 | 17 | // 日志级别 从上到下,由低到高 18 | const EMERG = 'EMERG'; // 严重错误: 导致系统崩溃无法使用 19 | const ALERT = 'ALERT'; // 警戒性错误: 必须被立即修改的错误 20 | const CRIT = 'CRIT'; // 临界值错误: 超过临界值的错误,例如一天24小时,而输入的是25小时这样 21 | const ERR = 'ERR'; // 一般错误: 一般性错误 22 | const WARN = 'WARN'; // 警告性错误: 需要发出警告的错误 23 | const NOTICE = 'NOTIC'; // 通知: 程序可以运行但是还不够完美的错误 24 | const INFO = 'INFO'; // 信息: 程序输出信息 25 | const DEBUG = 'DEBUG'; // 调试: 调试信息 26 | const SQL = 'SQL'; // SQL:SQL语句 注意只在调试模式开启时有效 27 | 28 | // 日志信息 29 | static protected $log = array(); 30 | 31 | // 日志存储 32 | static protected $storage = null; 33 | 34 | // 日志初始化 35 | static public function init($config=array()){ 36 | $type = isset($config['type']) ? $config['type'] : 'File'; 37 | $class = strpos($type,'\\')? $type: 'Think\\Log\\Driver\\'. ucwords(strtolower($type)); 38 | unset($config['type']); 39 | self::$storage = new $class($config); 40 | } 41 | 42 | /** 43 | * 记录日志 并且会过滤未经设置的级别 44 | * @static 45 | * @access public 46 | * @param string $message 日志信息 47 | * @param string $level 日志级别 48 | * @param boolean $record 是否强制记录 49 | * @return void 50 | */ 51 | static function record($message,$level=self::ERR,$record=false) { 52 | if($record || false !== strpos(C('LOG_LEVEL'),$level)) { 53 | self::$log[] = "{$level}: {$message}\r\n"; 54 | } 55 | } 56 | 57 | /** 58 | * 日志保存 59 | * @static 60 | * @access public 61 | * @param integer $type 日志记录方式 62 | * @param string $destination 写入目标 63 | * @return void 64 | */ 65 | static function save($type='',$destination='') { 66 | if(empty(self::$log)) return ; 67 | 68 | if(empty($destination)){ 69 | $destination = C('LOG_PATH').date('y_m_d').'.log'; 70 | } 71 | if(!self::$storage){ 72 | $type = $type ? : C('LOG_TYPE'); 73 | $class = 'Think\\Log\\Driver\\'. ucwords($type); 74 | self::$storage = new $class(); 75 | } 76 | $message = implode('',self::$log); 77 | self::$storage->write($message,$destination); 78 | // 保存后清空日志缓存 79 | self::$log = array(); 80 | } 81 | 82 | /** 83 | * 日志直接写入 84 | * @static 85 | * @access public 86 | * @param string $message 日志信息 87 | * @param string $level 日志级别 88 | * @param integer $type 日志记录方式 89 | * @param string $destination 写入目标 90 | * @return void 91 | */ 92 | static function write($message,$level=self::ERR,$type='',$destination='') { 93 | if(!self::$storage){ 94 | $type = $type ? : C('LOG_TYPE'); 95 | $class = 'Think\\Log\\Driver\\'. ucwords($type); 96 | $config['log_path'] = C('LOG_PATH'); 97 | self::$storage = new $class($config); 98 | } 99 | if(empty($destination)){ 100 | $destination = C('LOG_PATH').date('y_m_d').'.log'; 101 | } 102 | self::$storage->write("{$level}: {$message}", $destination); 103 | } 104 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Log/Driver/File.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | namespace Think\Log\Driver; 13 | 14 | class File { 15 | 16 | protected $config = array( 17 | 'log_time_format' => ' c ', 18 | 'log_file_size' => 2097152, 19 | 'log_path' => '', 20 | ); 21 | 22 | // 实例化并传入参数 23 | public function __construct($config=array()){ 24 | $this->config = array_merge($this->config,$config); 25 | } 26 | 27 | /** 28 | * 日志写入接口 29 | * @access public 30 | * @param string $log 日志信息 31 | * @param string $destination 写入目标 32 | * @return void 33 | */ 34 | public function write($log,$destination='') { 35 | $now = date($this->config['log_time_format']); 36 | if(empty($destination)){ 37 | $destination = $this->config['log_path'].date('y_m_d').'.log'; 38 | } 39 | // 自动创建日志目录 40 | $log_dir = dirname($destination); 41 | if (!is_dir($log_dir)) { 42 | mkdir($log_dir, 0755, true); 43 | } 44 | //检测日志文件大小,超过配置大小则备份日志文件重新生成 45 | if(is_file($destination) && floor($this->config['log_file_size']) <= filesize($destination) ){ 46 | rename($destination,dirname($destination).'/'.time().'-'.basename($destination)); 47 | } 48 | error_log("[{$now}] ".$_SERVER['REMOTE_ADDR'].' '.$_SERVER['REQUEST_URI']."\r\n{$log}\r\n", 3,$destination); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Log/Driver/Sae.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | namespace Think\Log\Driver; 13 | 14 | class Sae { 15 | 16 | protected $config = array( 17 | 'log_time_format' => ' c ', 18 | ); 19 | 20 | // 实例化并传入参数 21 | public function __construct($config=array()){ 22 | $this->config = array_merge($this->config,$config); 23 | } 24 | 25 | /** 26 | * 日志写入接口 27 | * @access public 28 | * @param string $log 日志信息 29 | * @param string $destination 写入目标 30 | * @return void 31 | */ 32 | public function write($log,$destination='') { 33 | static $is_debug=null; 34 | $now = date($this->config['log_time_format']); 35 | $logstr="[{$now}] ".$_SERVER['REMOTE_ADDR'].' '.$_SERVER['REQUEST_URI']."\r\n{$log}\r\n"; 36 | if(is_null($is_debug)){ 37 | preg_replace('@(\w+)\=([^;]*)@e', '$appSettings[\'\\1\']="\\2";', $_SERVER['HTTP_APPCOOKIE']); 38 | $is_debug = in_array($_SERVER['HTTP_APPVERSION'], explode(',', $appSettings['debug'])) ? true : false; 39 | } 40 | if($is_debug){ 41 | sae_set_display_errors(false);//记录日志不将日志打印出来 42 | } 43 | sae_debug($logstr); 44 | if($is_debug){ 45 | sae_set_display_errors(true); 46 | } 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Storage.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think; 12 | // 分布式文件存储类 13 | class Storage { 14 | 15 | /** 16 | * 操作句柄 17 | * @var string 18 | * @access protected 19 | */ 20 | static protected $handler ; 21 | 22 | /** 23 | * 连接分布式文件系统 24 | * @access public 25 | * @param string $type 文件类型 26 | * @param array $options 配置数组 27 | * @return void 28 | */ 29 | static public function connect($type='File',$options=array()) { 30 | $class = 'Think\\Storage\\Driver\\'.ucwords($type); 31 | self::$handler = new $class($options); 32 | } 33 | 34 | static public function __callstatic($method,$args){ 35 | //调用缓存驱动的方法 36 | if(method_exists(self::$handler, $method)){ 37 | return call_user_func_array(array(self::$handler,$method), $args); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Storage/Driver/File.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Storage\Driver; 12 | use Think\Storage; 13 | // 本地文件写入存储类 14 | class File extends Storage{ 15 | 16 | private $contents=array(); 17 | 18 | /** 19 | * 架构函数 20 | * @access public 21 | */ 22 | public function __construct() { 23 | } 24 | 25 | /** 26 | * 文件内容读取 27 | * @access public 28 | * @param string $filename 文件名 29 | * @return string 30 | */ 31 | public function read($filename,$type=''){ 32 | return $this->get($filename,'content',$type); 33 | } 34 | 35 | /** 36 | * 文件写入 37 | * @access public 38 | * @param string $filename 文件名 39 | * @param string $content 文件内容 40 | * @return boolean 41 | */ 42 | public function put($filename,$content,$type=''){ 43 | $dir = dirname($filename); 44 | if(!is_dir($dir)){ 45 | mkdir($dir,0777,true); 46 | } 47 | if(false === file_put_contents($filename,$content)){ 48 | E(L('_STORAGE_WRITE_ERROR_').':'.$filename); 49 | }else{ 50 | $this->contents[$filename]=$content; 51 | return true; 52 | } 53 | } 54 | 55 | /** 56 | * 文件追加写入 57 | * @access public 58 | * @param string $filename 文件名 59 | * @param string $content 追加的文件内容 60 | * @return boolean 61 | */ 62 | public function append($filename,$content,$type=''){ 63 | if(is_file($filename)){ 64 | $content = $this->read($filename,$type).$content; 65 | } 66 | return $this->put($filename,$content,$type); 67 | } 68 | 69 | /** 70 | * 加载文件 71 | * @access public 72 | * @param string $filename 文件名 73 | * @param array $vars 传入变量 74 | * @return void 75 | */ 76 | public function load($_filename,$vars=null){ 77 | if(!is_null($vars)){ 78 | extract($vars, EXTR_OVERWRITE); 79 | } 80 | include $_filename; 81 | } 82 | 83 | /** 84 | * 文件是否存在 85 | * @access public 86 | * @param string $filename 文件名 87 | * @return boolean 88 | */ 89 | public function has($filename,$type=''){ 90 | return is_file($filename); 91 | } 92 | 93 | /** 94 | * 文件删除 95 | * @access public 96 | * @param string $filename 文件名 97 | * @return boolean 98 | */ 99 | public function unlink($filename,$type=''){ 100 | unset($this->contents[$filename]); 101 | return is_file($filename) ? unlink($filename) : false; 102 | } 103 | 104 | /** 105 | * 读取文件信息 106 | * @access public 107 | * @param string $filename 文件名 108 | * @param string $name 信息名 mtime或者content 109 | * @return boolean 110 | */ 111 | public function get($filename,$name,$type=''){ 112 | if(!isset($this->contents[$filename])){ 113 | if(!is_file($filename)) return false; 114 | $this->contents[$filename]=file_get_contents($filename); 115 | } 116 | $content=$this->contents[$filename]; 117 | $info = array( 118 | 'mtime' => filemtime($filename), 119 | 'content' => $content 120 | ); 121 | return $info[$name]; 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Storage/Driver/Sae.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Storage\Driver; 12 | use Think\Storage; 13 | // SAE环境文件写入存储类 14 | class Sae extends Storage{ 15 | 16 | /** 17 | * 架构函数 18 | * @access public 19 | */ 20 | private $mc; 21 | private $kvs = array(); 22 | private $htmls = array(); 23 | private $contents = array(); 24 | public function __construct() { 25 | if(!function_exists('memcache_init')){ 26 | header('Content-Type:text/html;charset=utf-8'); 27 | exit('请在SAE平台上运行代码。'); 28 | } 29 | $this->mc = @memcache_init(); 30 | if(!$this->mc){ 31 | header('Content-Type:text/html;charset=utf-8'); 32 | exit('您未开通Memcache服务,请在SAE管理平台初始化Memcache服务'); 33 | } 34 | } 35 | 36 | /** 37 | * 获得SaeKv对象 38 | */ 39 | private function getKv(){ 40 | static $kv; 41 | if(!$kv){ 42 | $kv = new \SaeKV(); 43 | if(!$kv->init()) 44 | E('您没有初始化KVDB,请在SAE管理平台初始化KVDB服务'); 45 | } 46 | return $kv; 47 | } 48 | 49 | 50 | /** 51 | * 文件内容读取 52 | * @access public 53 | * @param string $filename 文件名 54 | * @return string 55 | */ 56 | public function read($filename,$type=''){ 57 | switch(strtolower($type)){ 58 | case 'f': 59 | $kv = $this->getKv(); 60 | if(!isset($this->kvs[$filename])){ 61 | $this->kvs[$filename]=$kv->get($filename); 62 | } 63 | return $this->kvs[$filename]; 64 | default: 65 | return $this->get($filename,'content',$type); 66 | } 67 | } 68 | 69 | /** 70 | * 文件写入 71 | * @access public 72 | * @param string $filename 文件名 73 | * @param string $content 文件内容 74 | * @return boolean 75 | */ 76 | public function put($filename,$content,$type=''){ 77 | switch(strtolower($type)){ 78 | case 'f': 79 | $kv = $this->getKv(); 80 | $this->kvs[$filename] = $content; 81 | return $kv->set($filename,$content); 82 | case 'html': 83 | $kv = $this->getKv(); 84 | $content = time().$content; 85 | $this->htmls[$filename] = $content; 86 | return $kv->set($filename,$content); 87 | default: 88 | $content = time().$content; 89 | if(!$this->mc->set($filename,$content,MEMCACHE_COMPRESSED,0)){ 90 | E(L('_STORAGE_WRITE_ERROR_').':'.$filename); 91 | }else{ 92 | $this->contents[$filename] = $content; 93 | return true; 94 | } 95 | } 96 | } 97 | 98 | /** 99 | * 文件追加写入 100 | * @access public 101 | * @param string $filename 文件名 102 | * @param string $content 追加的文件内容 103 | * @return boolean 104 | */ 105 | public function append($filename,$content,$type=''){ 106 | if($old_content = $this->read($filename,$type)){ 107 | $content = $old_content.$content; 108 | } 109 | return $this->put($filename,$content,$type); 110 | } 111 | 112 | /** 113 | * 加载文件 114 | * @access public 115 | * @param string $_filename 文件名 116 | * @param array $vars 传入变量 117 | * @return void 118 | */ 119 | public function load($_filename,$vars=null){ 120 | if(!is_null($vars)) 121 | extract($vars, EXTR_OVERWRITE); 122 | eval('?>'.$this->read($_filename)); 123 | } 124 | 125 | /** 126 | * 文件是否存在 127 | * @access public 128 | * @param string $filename 文件名 129 | * @return boolean 130 | */ 131 | public function has($filename,$type=''){ 132 | if($this->read($filename,$type)){ 133 | return true; 134 | }else{ 135 | return false; 136 | } 137 | } 138 | 139 | /** 140 | * 文件删除 141 | * @access public 142 | * @param string $filename 文件名 143 | * @return boolean 144 | */ 145 | public function unlink($filename,$type=''){ 146 | switch(strtolower($type)){ 147 | case 'f': 148 | $kv = $this->getKv(); 149 | unset($this->kvs[$filename]); 150 | return $kv->delete($filename); 151 | case 'html': 152 | $kv = $this->getKv(); 153 | unset($this->htmls[$filename]); 154 | return $kv->delete($filename); 155 | default: 156 | unset($this->contents[$filename]); 157 | return $this->mc->delete($filename); 158 | } 159 | } 160 | 161 | /** 162 | * 读取文件信息 163 | * @access public 164 | * @param string $filename 文件名 165 | * @param string $name 信息名 mtime或者content 166 | * @return boolean 167 | */ 168 | public function get($filename,$name,$type=''){ 169 | switch(strtolower($type)){ 170 | case 'html': 171 | if(!isset($this->htmls[$filename])){ 172 | $kv = $this->getKv(); 173 | $this->htmls[$filename] = $kv->get($filename); 174 | } 175 | $content = $this->htmls[$filename]; 176 | break; 177 | default: 178 | if(!isset($this->contents[$filename])){ 179 | $this->contents[$filename] = $this->mc->get($filename); 180 | } 181 | $content = $this->contents[$filename]; 182 | } 183 | if(false===$content){ 184 | return false; 185 | } 186 | $info = array( 187 | 'mtime' => substr($content,0,10), 188 | 'content' => substr($content,10) 189 | ); 190 | return $info[$name]; 191 | } 192 | 193 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Template/Driver/Ease.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Template\Driver; 12 | /** 13 | * EaseTemplate模板引擎驱动 14 | */ 15 | class Ease { 16 | /** 17 | * 渲染模板输出 18 | * @access public 19 | * @param string $templateFile 模板文件名 20 | * @param array $var 模板变量 21 | * @return void 22 | */ 23 | public function fetch($templateFile,$var) { 24 | $templateFile = substr($templateFile,strlen(THEME_PATH),-5); 25 | $CacheDir = substr(CACHE_PATH,0,-1); 26 | $TemplateDir = substr(THEME_PATH,0,-1); 27 | vendor('EaseTemplate.template#ease'); 28 | $config = array( 29 | 'CacheDir' => $CacheDir, 30 | 'TemplateDir' => $TemplateDir, 31 | 'TplType' => 'html' 32 | ); 33 | if(C('TMPL_ENGINE_CONFIG')) { 34 | $config = array_merge($config,C('TMPL_ENGINE_CONFIG')); 35 | } 36 | $tpl = new \EaseTemplate($config); 37 | $tpl->set_var($var); 38 | $tpl->set_file($templateFile); 39 | $tpl->p(); 40 | } 41 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Template/Driver/Lite.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Template\Driver; 12 | /** 13 | * TemplateLite模板引擎驱动 14 | */ 15 | class Lite { 16 | /** 17 | * 渲染模板输出 18 | * @access public 19 | * @param string $templateFile 模板文件名 20 | * @param array $var 模板变量 21 | * @return void 22 | */ 23 | public function fetch($templateFile,$var) { 24 | vendor("TemplateLite.class#template"); 25 | $templateFile = substr($templateFile,strlen(THEME_PATH)); 26 | $tpl = new \Template_Lite(); 27 | $tpl->template_dir = THEME_PATH; 28 | $tpl->compile_dir = CACHE_PATH ; 29 | $tpl->cache_dir = TEMP_PATH ; 30 | if(C('TMPL_ENGINE_CONFIG')) { 31 | $config = C('TMPL_ENGINE_CONFIG'); 32 | foreach ($config as $key=>$val){ 33 | $tpl->{$key} = $val; 34 | } 35 | } 36 | $tpl->assign($var); 37 | $tpl->display($templateFile); 38 | } 39 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Template/Driver/Mobile.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Template\Driver; 12 | /** 13 | * MobileTemplate模板引擎驱动 14 | */ 15 | class Mobile { 16 | /** 17 | * 渲染模板输出 18 | * @access public 19 | * @param string $templateFile 模板文件名 20 | * @param array $var 模板变量 21 | * @return void 22 | */ 23 | public function fetch($templateFile,$var) { 24 | $templateFile=substr($templateFile,strlen(THEME_PATH)); 25 | $var['_think_template_path']=$templateFile; 26 | exit(json_encode($var)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Template/Driver/Smart.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Template\Driver; 12 | /** 13 | * Smart模板引擎驱动 14 | */ 15 | class Smart { 16 | /** 17 | * 渲染模板输出 18 | * @access public 19 | * @param string $templateFile 模板文件名 20 | * @param array $var 模板变量 21 | * @return void 22 | */ 23 | public function fetch($templateFile,$var) { 24 | $templateFile = substr($templateFile,strlen(THEME_PATH)); 25 | vendor('SmartTemplate.class#smarttemplate'); 26 | $tpl = new \SmartTemplate($templateFile); 27 | $tpl->caching = C('TMPL_CACHE_ON'); 28 | $tpl->template_dir = THEME_PATH; 29 | $tpl->compile_dir = CACHE_PATH ; 30 | $tpl->cache_dir = TEMP_PATH ; 31 | if(C('TMPL_ENGINE_CONFIG')) { 32 | $config = C('TMPL_ENGINE_CONFIG'); 33 | foreach ($config as $key=>$val){ 34 | $tpl->{$key} = $val; 35 | } 36 | } 37 | $tpl->assign($var); 38 | $tpl->output(); 39 | } 40 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Think/Template/Driver/Smarty.class.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | namespace Think\Template\Driver; 12 | /** 13 | * Smarty模板引擎驱动 14 | */ 15 | class Smarty { 16 | 17 | /** 18 | * 渲染模板输出 19 | * @access public 20 | * @param string $templateFile 模板文件名 21 | * @param array $var 模板变量 22 | * @return void 23 | */ 24 | public function fetch($templateFile,$var) { 25 | $templateFile = substr($templateFile,strlen(THEME_PATH)); 26 | vendor('Smarty.Smarty#class'); 27 | $tpl = new \Smarty(); 28 | $tpl->caching = C('TMPL_CACHE_ON'); 29 | $tpl->template_dir = THEME_PATH; 30 | $tpl->compile_dir = CACHE_PATH ; 31 | $tpl->cache_dir = TEMP_PATH ; 32 | if(C('TMPL_ENGINE_CONFIG')) { 33 | $config = C('TMPL_ENGINE_CONFIG'); 34 | foreach ($config as $key=>$val){ 35 | $tpl->{$key} = $val; 36 | } 37 | } 38 | $tpl->assign($var); 39 | $tpl->display($templateFile); 40 | } 41 | } -------------------------------------------------------------------------------- /ThinkPHP/Library/Vendor/README.txt: -------------------------------------------------------------------------------- 1 | 第三方类库包目录 -------------------------------------------------------------------------------- /ThinkPHP/Mode/common.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | /** 13 | * ThinkPHP 普通模式定义 14 | */ 15 | return array( 16 | // 配置文件 17 | 'config' => array( 18 | THINK_PATH.'Conf/convention.php', // 系统惯例配置 19 | CONF_PATH.'config'.CONF_EXT, // 应用公共配置 20 | ), 21 | 22 | // 别名定义 23 | 'alias' => array( 24 | 'Think\Log' => CORE_PATH . 'Log'.EXT, 25 | 'Think\Log\Driver\File' => CORE_PATH . 'Log/Driver/File'.EXT, 26 | 'Think\Exception' => CORE_PATH . 'Exception'.EXT, 27 | 'Think\Model' => CORE_PATH . 'Model'.EXT, 28 | 'Think\Db' => CORE_PATH . 'Db'.EXT, 29 | 'Think\Template' => CORE_PATH . 'Template'.EXT, 30 | 'Think\Cache' => CORE_PATH . 'Cache'.EXT, 31 | 'Think\Cache\Driver\File' => CORE_PATH . 'Cache/Driver/File'.EXT, 32 | 'Think\Storage' => CORE_PATH . 'Storage'.EXT, 33 | ), 34 | 35 | // 函数和类文件 36 | 'core' => array( 37 | THINK_PATH.'Common/functions.php', 38 | COMMON_PATH.'Common/function.php', 39 | CORE_PATH . 'Hook'.EXT, 40 | CORE_PATH . 'App'.EXT, 41 | CORE_PATH . 'Dispatcher'.EXT, 42 | //CORE_PATH . 'Log'.EXT, 43 | CORE_PATH . 'Route'.EXT, 44 | CORE_PATH . 'Controller'.EXT, 45 | CORE_PATH . 'View'.EXT, 46 | BEHAVIOR_PATH . 'BuildLiteBehavior'.EXT, 47 | BEHAVIOR_PATH . 'ParseTemplateBehavior'.EXT, 48 | BEHAVIOR_PATH . 'ContentReplaceBehavior'.EXT, 49 | ), 50 | // 行为扩展定义 51 | 'tags' => array( 52 | 'app_init' => array( 53 | 'Behavior\BuildLiteBehavior', // 生成运行Lite文件 54 | ), 55 | 'app_begin' => array( 56 | 'Behavior\ReadHtmlCacheBehavior', // 读取静态缓存 57 | ), 58 | 'app_end' => array( 59 | 'Behavior\ShowPageTraceBehavior', // 页面Trace显示 60 | ), 61 | 'view_parse' => array( 62 | 'Behavior\ParseTemplateBehavior', // 模板解析 支持PHP、内置模板引擎和第三方模板引擎 63 | ), 64 | 'template_filter'=> array( 65 | 'Behavior\ContentReplaceBehavior', // 模板输出替换 66 | ), 67 | 'view_filter' => array( 68 | 'Behavior\WriteHtmlCacheBehavior', // 写入静态缓存 69 | ), 70 | ), 71 | ); 72 | -------------------------------------------------------------------------------- /ThinkPHP/ThinkPHP.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | //---------------------------------- 13 | // ThinkPHP公共入口文件 14 | //---------------------------------- 15 | 16 | // 记录开始运行时间 17 | $GLOBALS['_beginTime'] = microtime(TRUE); 18 | // 记录内存初始使用 19 | define('MEMORY_LIMIT_ON',function_exists('memory_get_usage')); 20 | if(MEMORY_LIMIT_ON) $GLOBALS['_startUseMems'] = memory_get_usage(); 21 | 22 | // 版本信息 23 | const THINK_VERSION = '3.2.3'; 24 | 25 | // URL 模式定义 26 | const URL_COMMON = 0; //普通模式 27 | const URL_PATHINFO = 1; //PATHINFO模式 28 | const URL_REWRITE = 2; //REWRITE模式 29 | const URL_COMPAT = 3; // 兼容模式 30 | 31 | // 类文件后缀 32 | const EXT = '.class.php'; 33 | 34 | // 系统常量定义 35 | defined('THINK_PATH') or define('THINK_PATH', __DIR__.'/'); 36 | defined('APP_PATH') or define('APP_PATH', dirname($_SERVER['SCRIPT_FILENAME']).'/'); 37 | defined('APP_STATUS') or define('APP_STATUS', ''); // 应用状态 加载对应的配置文件 38 | defined('APP_DEBUG') or define('APP_DEBUG', false); // 是否调试模式 39 | 40 | if(function_exists('saeAutoLoader')){// 自动识别SAE环境 41 | defined('APP_MODE') or define('APP_MODE', 'sae'); 42 | defined('STORAGE_TYPE') or define('STORAGE_TYPE', 'Sae'); 43 | }else{ 44 | defined('APP_MODE') or define('APP_MODE', 'common'); // 应用模式 默认为普通模式 45 | defined('STORAGE_TYPE') or define('STORAGE_TYPE', 'File'); // 存储类型 默认为File 46 | } 47 | 48 | defined('RUNTIME_PATH') or define('RUNTIME_PATH', APP_PATH.'Runtime/'); // 系统运行时目录 49 | defined('LIB_PATH') or define('LIB_PATH', realpath(THINK_PATH.'Library').'/'); // 系统核心类库目录 50 | defined('CORE_PATH') or define('CORE_PATH', LIB_PATH.'Think/'); // Think类库目录 51 | defined('BEHAVIOR_PATH')or define('BEHAVIOR_PATH', LIB_PATH.'Behavior/'); // 行为类库目录 52 | defined('MODE_PATH') or define('MODE_PATH', THINK_PATH.'Mode/'); // 系统应用模式目录 53 | defined('VENDOR_PATH') or define('VENDOR_PATH', LIB_PATH.'Vendor/'); // 第三方类库目录 54 | defined('COMMON_PATH') or define('COMMON_PATH', APP_PATH.'Common/'); // 应用公共目录 55 | defined('CONF_PATH') or define('CONF_PATH', COMMON_PATH.'Conf/'); // 应用配置目录 56 | defined('LANG_PATH') or define('LANG_PATH', COMMON_PATH.'Lang/'); // 应用语言目录 57 | defined('HTML_PATH') or define('HTML_PATH', APP_PATH.'Html/'); // 应用静态目录 58 | defined('LOG_PATH') or define('LOG_PATH', RUNTIME_PATH.'Logs/'); // 应用日志目录 59 | defined('TEMP_PATH') or define('TEMP_PATH', RUNTIME_PATH.'Temp/'); // 应用缓存目录 60 | defined('DATA_PATH') or define('DATA_PATH', RUNTIME_PATH.'Data/'); // 应用数据目录 61 | defined('CACHE_PATH') or define('CACHE_PATH', RUNTIME_PATH.'Cache/'); // 应用模板缓存目录 62 | defined('CONF_EXT') or define('CONF_EXT', '.php'); // 配置文件后缀 63 | defined('CONF_PARSE') or define('CONF_PARSE', ''); // 配置文件解析方法 64 | defined('ADDON_PATH') or define('ADDON_PATH', APP_PATH.'Addon'); 65 | 66 | // 系统信息 67 | if(version_compare(PHP_VERSION,'5.4.0','<')) { 68 | ini_set('magic_quotes_runtime',0); 69 | define('MAGIC_QUOTES_GPC',get_magic_quotes_gpc()? true : false); 70 | }else{ 71 | define('MAGIC_QUOTES_GPC',false); 72 | } 73 | define('IS_CGI',(0 === strpos(PHP_SAPI,'cgi') || false !== strpos(PHP_SAPI,'fcgi')) ? 1 : 0 ); 74 | define('IS_WIN',strstr(PHP_OS, 'WIN') ? 1 : 0 ); 75 | define('IS_CLI',PHP_SAPI=='cli'? 1 : 0); 76 | 77 | if(!IS_CLI) { 78 | // 当前文件名 79 | if(!defined('_PHP_FILE_')) { 80 | if(IS_CGI) { 81 | //CGI/FASTCGI模式下 82 | $_temp = explode('.php',$_SERVER['PHP_SELF']); 83 | define('_PHP_FILE_', rtrim(str_replace($_SERVER['HTTP_HOST'],'',$_temp[0].'.php'),'/')); 84 | }else { 85 | define('_PHP_FILE_', rtrim($_SERVER['SCRIPT_NAME'],'/')); 86 | } 87 | } 88 | if(!defined('__ROOT__')) { 89 | $_root = rtrim(dirname(_PHP_FILE_),'/'); 90 | define('__ROOT__', (($_root=='/' || $_root=='\\')?'':$_root)); 91 | } 92 | } 93 | 94 | // 加载核心Think类 95 | require CORE_PATH.'Think'.EXT; 96 | // 应用初始化 97 | Think\Think::start(); -------------------------------------------------------------------------------- /ThinkPHP/Tpl/dispatch_jump.tpl: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 9 | 10 | 跳转提示 11 | 21 | 22 | 23 |
    24 | 25 |

    :)

    26 |

    27 | 28 |

    :(

    29 |

    30 | 31 |

    32 |

    33 | 页面自动 跳转 等待时间: 34 |

    35 |
    36 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /ThinkPHP/Tpl/page_trace.tpl: -------------------------------------------------------------------------------- 1 |
    2 | 24 | 25 |
    26 |
    27 | 68 | -------------------------------------------------------------------------------- /ThinkPHP/Tpl/think_exception.tpl: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 9 | 系统发生错误 10 | 26 | 27 | 28 |
    29 |

    :(

    30 |

    31 |
    32 | 33 |
    34 |
    35 |

    错误位置

    36 |
    37 |
    38 |

    FILE:  LINE:

    39 |
    40 |
    41 | 42 | 43 |
    44 |
    45 |

    TRACE

    46 |
    47 |
    48 |

    49 |
    50 |
    51 | 52 |
    53 |
    54 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /ThinkPHP/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tangzwgo/thinkphp-api/fbef4b2d37fac7bfed21f1133c74080b1ae185ec/ThinkPHP/logo.png -------------------------------------------------------------------------------- /index.php: -------------------------------------------------------------------------------- 1 | 10 | // +---------------------------------------------------------------------- 11 | 12 | // 应用入口文件 13 | 14 | // 检测PHP环境 15 | if(version_compare(PHP_VERSION,'5.3.0','<')) die('require PHP > 5.3.0 !'); 16 | 17 | // 开启调试模式 建议开发阶段开启 部署阶段注释或者设为false 18 | define('APP_DEBUG',True); 19 | 20 | // 定义应用目录 21 | define('APP_PATH','./Application/'); 22 | 23 | // 引入ThinkPHP入口文件 24 | require './ThinkPHP/ThinkPHP.php'; 25 | 26 | // 亲^_^ 后面不需要任何代码了 就是如此简单 --------------------------------------------------------------------------------