tao.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. <?php
  2. /*
  3. * 请勿使用windows下的记事本修改本文件。推荐使用 notepad++
  4. * * 版本v2.8
  5. * 1.缓存支持https
  6. *
  7. * * 版本v2.7
  8. * 1.优化自动选择最优服务api和增加api数量
  9. *
  10. * 版本v2.6
  11. * 1.自动选择最优服务api地址返回数据
  12. * 2.请求时添加压缩返回
  13. * 版本v2.5
  14. * 1.500页面优化
  15. * 2.数据请求增加重试,减少请求失败
  16. * 版本v2.4
  17. * 新增加cdn节点检测
  18. * 版本 v2.3
  19. * 1.500页面展示
  20. * 版本 v2.2
  21. * 1.增加mbstring检测
  22. * 2.错误显示
  23. *版本 v2.1
  24. * 1.增加cache检测
  25. * 2.增加显示debug信息限制
  26. *
  27. * 版本 v2.0
  28. * 1.documentUrl 做兼容解决部分用户二级目录报错
  29. * 2.增加debug信息方便为用户定位错误
  30. *
  31. * 版本 v1.1.0
  32. * 升级日志:
  33. * 1、添加自动更新
  34. * 2、修正缓存的BUG
  35. * 3、添加自动清理cache
  36. * 4、实现http code的转发
  37. *
  38. * 版本 v1.0.1
  39. * 升级日志:
  40. * 1、修正第一次无法打开,需要刷新才能打开的BUG
  41. * 2、添加对二级目录的支持
  42. * 3、添加对非index.php文件名的支持。
  43. *
  44. * */
  45. $appId = '1350274'; // 站点的APPID (请勿修改和泄漏)
  46. $appKey = '7C8F55348F476C5904F7814E598771E2';// 站点的APP KEY(请勿修改和泄漏)
  47. $proxyVersion = 16;
  48. $autoCleanCache = 100;
  49. //===============================================================================
  50. //===============================================================================
  51. //===============================================================================
  52. //================ 请勿修改以下程序 ====================
  53. //===============================================================================
  54. //===============================================================================
  55. //===============================================================================
  56. $host = "http://cms4.dataoke.com";
  57. @date_default_timezone_set('Asia/Shanghai');
  58. $is_host_data = false;
  59. try {
  60. if (file_exists(dirname(__FILE__) . DIRECTORY_SEPARATOR . '/dtk.data')) {
  61. $host_data = @file_get_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . '/dtk.data');
  62. $host_data = @json_decode($host_data, true);
  63. if (!empty($host_data['host']) && !empty($host_data['time']) && $host_data['time'] > strtotime('-1 day')) {
  64. $is_host_data = true;
  65. }
  66. }
  67. if ($is_host_data == false) {
  68. $host_data = array(
  69. 'http://cms1.dataoke.com' => 0,
  70. 'http://cms2.dataoke.com' => 0,
  71. 'http://cmsserver1.dataoke.com' => 0,
  72. 'http://cmsserver2.dataoke.com' => 0,
  73. );
  74. @file_put_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . '/dtk.data', @json_encode(array('host' => $host_data, 'time' => time())));
  75. }
  76. } catch (Exception $e) {
  77. }
  78. $test_env = strrpos(@$_SERVER['HTTP_USER_AGENT'], 'test') === false ? false : true;
  79. $requestMethod = strtoupper(@$_SERVER["REQUEST_METHOD"]);
  80. $requestUrl = @$_SERVER["REQUEST_URI"];
  81. if ($test_env) {
  82. ini_set("display_errors", "On");
  83. error_reporting(E_ALL | E_STRICT);
  84. } else {
  85. @ini_set("display_errors", "Off");
  86. }
  87. $css_static = @date('Y-m-d');
  88. $html_500 = <<<html
  89. <!DOCTYPE html>
  90. <html>
  91. <head>
  92. <meta charset="utf-8">
  93. <meta http-equiv="x-dns-prefetch-control" content="on"/>
  94. <meta name="apple-mobile-web-app-capable" content="yes"/>
  95. <meta content="telephone=no" name="format-detection"/>
  96. <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
  97. <link href="https://cmsstatic.dataoke.com/error/error.css?v={$css_static}" rel="stylesheet">
  98. </head>
  99. <body>
  100. <div class="error_main">
  101. <p class="img"></p>
  102. <p class="text">咦?出错啦,请稍后再试~ </p>
  103. <p class="botton">
  104. <a onclick="window.location.reload();" href="javascript:;" class="botton_par">点击刷新</a>
  105. </p>
  106. </div>
  107. </body>
  108. <script src="https://cmsstatic.dataoke.com/error/error.js?v={$css_static}"></script>
  109. </html>
  110. html;
  111. //debug
  112. if ($test_env && isset($_GET['debug']) && $_GET['debug'] == 'php') {
  113. header("Content-type: text/html; charset=utf-8");
  114. echo 'cms 版本:' . $proxyVersion . '<br>';
  115. echo 'php 版本:' . PHP_VERSION . '<br>';
  116. if (function_exists('curl_init')) {
  117. echo 'curl 已经开启 ' . '<br>';
  118. } else {
  119. echo 'curl <span style="color: red">未开启,请先开启curl扩展,否则无法运行,请联系您的空间或者服务器提供商</span>' . '<br>';
  120. }
  121. if (function_exists('mb_substr')) {
  122. echo 'mbstring 已经开启 ' . '<br>';
  123. } else {
  124. echo 'mbstring <span style="color: red">未开启,请先开启mbstring扩展,否则无法运行</span>' . '<br>';
  125. }
  126. $test_dir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'cache';
  127. $test_file = $test_dir . '/test.txt';
  128. if (!is_dir($test_dir)) {
  129. @mkdir($test_dir);
  130. }
  131. @file_put_contents($test_file, 'test');
  132. if (file_exists($test_file)) {
  133. echo 'cache:有效<br>';
  134. } else {
  135. echo 'cache <span style="color: red">无效,请设置读写修改权限</span>' . '<br>';
  136. }
  137. if (function_exists('gethostbyname')) {
  138. echo $host . ' --CDN 节点 ---' . gethostbyname(str_replace('http://', '', $host)) . '<br/>';
  139. echo 'www.dataoke.com --CDN 节点 ---' . gethostbyname("www.dataoke.com");
  140. }
  141. exit;
  142. }
  143. if ($test_env && isset($_GET['debug']) && $_GET['debug'] == 'fast') {
  144. var_dump($host_data);
  145. exit;
  146. }
  147. $cache = new CacheHelper();
  148. if (isset($_REQUEST['clean'])) {
  149. $cache->clean();
  150. header("Content-type: text/html; charset=utf-8");
  151. echo '已清除缓存';
  152. exit;
  153. }
  154. if (mt_rand(0, $autoCleanCache) == 1) {
  155. $cache->clean();
  156. }
  157. $key = md5($requestUrl . CacheHelper::isMobile() . CacheHelper::isHttps() . CacheHelper::isIPad() . CacheHelper::isIPhone() . CacheHelper::isMicroMessenger() . CacheHelper::isWeibo() . CacheHelper::isSpider());
  158. if ($requestMethod == 'GET') {
  159. if (!$test_env) {
  160. $cacheData = $cache->Get($key);
  161. if ($cacheData !== false && !empty($cacheData)) {
  162. @header('Dtk-Cache-Check:2');
  163. echo $cacheData;
  164. exit;
  165. }
  166. }
  167. }
  168. $documentUrl = @$_SERVER["PHP_SELF"];
  169. if (empty($documentUrl)) {
  170. $documentUrl = @$_SERVER["SCRIPT_NAME"];
  171. }
  172. if (empty($documentUrl)) {
  173. $documentUrl = @$_SERVER["DOCUMENT_URI"];
  174. }
  175. if (empty($documentUrl)) {
  176. $documentUrl = $requestUrl;
  177. $str_pos = strpos($requestUrl, '?');
  178. if ($str_pos !== false) {
  179. $documentUrl = substr($requestUrl, 0, $str_pos);
  180. }
  181. }
  182. if (empty($documentUrl)) {
  183. $documentUrl = '/index.php';
  184. }
  185. if (!function_exists('gzdecode')) {
  186. if (file_exists('gzinflate')) {
  187. function gzdecode($data)
  188. {
  189. return @gzinflate(substr($data, 10, -8));
  190. }
  191. }
  192. }
  193. $httpHelper = new HttpHelper($appId, $appKey, $proxyVersion, $documentUrl);
  194. $httpHelper->host_data = $host_data;
  195. if ($is_host_data) {
  196. $fast_host = $httpHelper->getFastUrl();
  197. if (!empty($fast_host)) {
  198. $host = $fast_host;
  199. }
  200. }
  201. $html = $httpHelper->getHtml($host, $requestUrl, $requestMethod == 'POST' ? @$_POST : array(), $requestMethod);
  202. if (function_exists('gzdecode')) {
  203. if (!empty($html)) {
  204. $new_html = @gzdecode($html);
  205. if (!empty($new_html)) {
  206. $html = $new_html;
  207. }
  208. }
  209. }
  210. if (strpos($html, 'OR--server error') !== false) {
  211. $html = '';
  212. }
  213. if ($requestMethod == 'GET' && $httpHelper->httpCode == 200 && !empty($html) && !$test_env) {
  214. $cache_check = !empty($_COOKIE['cache_check']) ? $_COOKIE['cache_check'] : null;
  215. $expire = empty($cache_check) ? 60 : 600;
  216. @header('Dtk-Cache-Check-time:' . $expire);
  217. $cache->Set($key, $html, $expire);
  218. }
  219. if (!empty($html)) {
  220. echo $html;
  221. } else {
  222. $duration = 3600 + time();
  223. @setcookie('cache_check', 1, $duration, '/');
  224. echo $html_500;
  225. }
  226. exit;
  227. class HttpHelper
  228. {
  229. protected $appId;
  230. protected $key;
  231. protected $documentUrl;
  232. protected $proxyVersion;
  233. protected $upgradeUrl = "http://www.dataoke.com/pmc/upgrade.html";
  234. public $host_data = array();
  235. public $httpCode = 200;
  236. public function __construct($appId, $key, $proxyVersion, $documentUrl)
  237. {
  238. $this->appId = $appId;
  239. $this->key = $key;
  240. $this->documentUrl = $documentUrl;
  241. $this->proxyVersion = $proxyVersion;
  242. }
  243. /**
  244. * @return int|string
  245. */
  246. public function getFastUrl()
  247. {
  248. $host_data = $this->host_data;
  249. if (!empty($host_data['host'])) {
  250. $temp_v = '';
  251. $temp_k = '';
  252. $first = 0;
  253. foreach ($host_data['host'] as $k => $v) {
  254. if ($first > 0) {
  255. if ($v <= $temp_v) {
  256. $temp_v = $v;
  257. $temp_k = $k;
  258. }
  259. } else {
  260. $temp_v = $v;
  261. $temp_k = $k;
  262. }
  263. $first++;
  264. }
  265. return $temp_k;
  266. }
  267. }
  268. /**域名转换ip
  269. * @param $host
  270. * @return bool
  271. */
  272. public function hostToIp($host)
  273. {
  274. $ip = false;
  275. $host_data = $this->host_data;
  276. if (!empty($host_data['ip'][$host]) && !empty($host_data['ip_time'][$host]) && $host_data['ip_time'][$host] > time()) {
  277. $ip = $host_data['ip'][$host];
  278. } else {
  279. $ip = $this->getIp($host);
  280. if (!empty($ip)) {
  281. $host_data['ip'][$host] = $ip;
  282. $host_data['ip_time'][$host] = time() + 600;
  283. $this->host_data = $host_data;
  284. @file_put_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . '/dtk.data', @json_encode($host_data));
  285. }
  286. }
  287. return $ip;
  288. }
  289. /**获取ip
  290. * @param $host
  291. * @return bool
  292. */
  293. public function getIp($host, $re_try = false)
  294. {
  295. $output = '';
  296. global $test_env;
  297. try {
  298. $host = str_replace('http://', '', $host);
  299. if (strlen($host) != (strpos($host, '.com') + 4)) {
  300. $host = substr($host, 0, strpos($host, '.com') + 4);
  301. }
  302. if ($re_try) {
  303. $url = 'http://39.106.70.132:80/d?dn=' . $host;
  304. $header[] = 'Host: dighttpd.dataoke.com';
  305. } else {
  306. $url = 'http://crab.qingcdn.com/d?dn=' . $host;
  307. }
  308. $ch = curl_init();
  309. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  310. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
  311. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  312. curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
  313. curl_setopt($ch, CURLOPT_URL, $url);
  314. if (!empty($header)) {
  315. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  316. }
  317. $output = curl_exec($ch);
  318. $output = json_decode($output, true);
  319. } catch (Exception $e) {
  320. if ($test_env) {
  321. var_dump($e->getMessage());
  322. }
  323. }
  324. if ($test_env && isset($_GET['debug']) && $_GET['debug'] == 'getip') {
  325. var_dump($output);
  326. var_dump($url);
  327. }
  328. return !empty($output['data'][$host]['ips']) ? $output['data'][$host]['ips'] : ($re_try ? false : $this->getIp($host, true));
  329. }
  330. /**
  331. * @param $url
  332. * @param $requestUrl
  333. * @param array $param
  334. * @param string $method
  335. * @param bool $isAjax
  336. * @param string $cookie
  337. * @param string $refer
  338. * @param null $userAgent
  339. * @param bool $checkNewVersion
  340. * @return string
  341. */
  342. public function getHtml($url, $requestUrl, $param = array(), $method = 'GET', $isAjax = null, $cookie = NULL, $refer = null, $userAgent = null, $checkNewVersion = true, $re_try = true)
  343. {
  344. $begin_time = @microtime(true);
  345. if (strpos($requestUrl, 'auth') !== false) {
  346. $url .= '/auth';
  347. }
  348. if ($requestUrl == '/favicon.ico') {
  349. exit;
  350. }
  351. $ch = curl_init();
  352. curl_setopt($ch, CURLOPT_HEADER, 1);
  353. empty($refer) && $refer = @$_SERVER['HTTP_REFERER'];
  354. $ua = $userAgent;
  355. empty($ua) && $ua = (!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '-');
  356. $curl_time = $re_try == true ? 5 : 40;
  357. curl_setopt($ch, CURLOPT_TIMEOUT, $curl_time);
  358. curl_setopt($ch, CURLOPT_USERAGENT, $ua);
  359. curl_setopt($ch, CURLOPT_REFERER, $refer);
  360. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
  361. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  362. $header = array(
  363. 'APPID: ' . $this->appId,
  364. 'APPKEY: ' . $this->key,
  365. 'PROXY-VERSION: ' . $this->proxyVersion,
  366. 'CMS-HOST: ' . @$_SERVER["HTTP_HOST"],
  367. 'CMS-CONNECTION: ' . (!empty($_SERVER["HTTP_CONNECTION"]) ? $_SERVER["HTTP_CONNECTION"] : '-'),
  368. 'CMS-ACCEPT-ENCODING: ' . (!empty($_SERVER["HTTP_ACCEPT_ENCODING"]) ? $_SERVER["HTTP_ACCEPT_ENCODING"] : '-'),
  369. 'DOCUMENT-URL: ' . $this->documentUrl,
  370. 'REQUEST-URL: ' . $requestUrl,
  371. );
  372. $cdn_ip = $this->hostToIp($url);
  373. if (strpos($ua, 'Baidu') !== false || strpos($ua, 'spider') !== false || $ua == 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36') {
  374. $url = 'http://cms6.dataoke.com';
  375. $cdn_ip = false;
  376. }
  377. $origin_url = $url;
  378. if ($cdn_ip !== false) {
  379. $url = str_replace('http://', '', $url);
  380. $check_url_show = false;
  381. if (strpos($url, '/pmc/upgrade.html') !== false) {
  382. $check_url_show = true;
  383. $url = str_replace('/pmc/upgrade.html', '', $url);
  384. }
  385. $header[] = 'Host: ' . $url;
  386. if ($check_url_show) {
  387. $url = $cdn_ip[0] . '/pmc/upgrade.html';
  388. } else {
  389. $url = $cdn_ip[0];
  390. }
  391. }
  392. if (function_exists('gzdecode')) {
  393. $header[] = 'Accept-Encoding: gzip, deflate';
  394. }
  395. //debug
  396. global $test_env;
  397. if ($test_env && isset($_GET['debug']) && $_GET['debug'] == 'header') {
  398. echo 'CMS-HOST: ' . @$_SERVER["HTTP_HOST"] . '<br>';
  399. echo 'DOCUMENT-URL: ' . $this->documentUrl . '<br>';
  400. echo 'REQUEST-URL: ' . $requestUrl . '<br>';
  401. echo 'api-host-ip: ' . $url . '<br>';
  402. echo 'api-host: ' . $origin_url . '<br>';
  403. exit;
  404. }
  405. $_isAjax = false;
  406. if ($isAjax) {
  407. $_isAjax = true;
  408. }
  409. if (!$_isAjax && $isAjax === null) {
  410. $_isAjax = $this->getIsAjaxRequest();
  411. }
  412. if ($_isAjax) {
  413. $header[] = 'X-Requested-With: XMLHttpRequest';
  414. }
  415. $clientIp = $this->get_real_ip();
  416. if (!empty($clientIp)) {
  417. $header[] = 'CLIENT-IP: ' . $clientIp;
  418. $header[] = 'CMS-CLIENT-IP: ' . $clientIp;
  419. $header[] = 'X-FORWARDED-FOR: ' . $clientIp;
  420. }
  421. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  422. if (empty($cookie)) {
  423. $cookie = $_COOKIE;
  424. }
  425. if (is_array($cookie)) {
  426. $cookie = http_build_query($cookie, '', ";");
  427. }
  428. if (!empty($cookie)) {
  429. curl_setopt($ch, CURLOPT_COOKIE, $cookie);
  430. }
  431. if (strtolower($method) == 'post') {
  432. curl_setopt($ch, CURLOPT_POST, TRUE);
  433. if ($param) {
  434. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
  435. }
  436. curl_setopt($ch, CURLOPT_URL, $url);
  437. } else {
  438. curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
  439. if ($param) {
  440. $urlInfo = parse_url($url);
  441. $q = array();
  442. if (isset($urlInfo['query']) && !empty($urlInfo['query'])) {
  443. parse_str($urlInfo['query'], $q);
  444. }
  445. $q = array_merge($q, $param);
  446. $cUrl = sprintf('%s://%s%s%s%s',
  447. $urlInfo['scheme'],
  448. $urlInfo['host'],
  449. isset($urlInfo['port']) ? ':' . $urlInfo['port'] : '',
  450. isset($urlInfo['path']) ? $urlInfo['path'] : '',
  451. count($q) ? '?' . http_build_query($q) : '');
  452. curl_setopt($ch, CURLOPT_URL, $cUrl);
  453. } else {
  454. curl_setopt($ch, CURLOPT_URL, $url);
  455. }
  456. }
  457. try {
  458. $r = curl_exec($ch);
  459. // $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  460. $curl_info = curl_getinfo($ch);
  461. $headerSize = isset($curl_info['header_size']) ? $curl_info['header_size'] : 0;
  462. $header = mb_substr($r, 0, $headerSize);
  463. $r = mb_substr($r, $headerSize);
  464. try {
  465. if (isset($curl_info['total_time'])) {
  466. $host_data = $this->host_data;
  467. if (isset($host_data['host'][$origin_url])) {
  468. if (empty($r)) {
  469. $host_data['host'][$origin_url] = $curl_info['total_time'] + 20;
  470. } else {
  471. $host_data['host'][$origin_url] = $curl_info['total_time'];
  472. }
  473. $this->host_data = $host_data;
  474. @file_put_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . '/dtk.data', json_encode($host_data));
  475. }
  476. }
  477. } catch (Exception $e) {
  478. }
  479. $this->httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  480. curl_close($ch);
  481. } catch (Exception $e) {
  482. return $re_try == true ? $this->getHtml($origin_url, $requestUrl, $param, $method, $isAjax, $cookie, $refer, $userAgent, $checkNewVersion, false) : '';
  483. }
  484. unset($ch);
  485. $headers = explode("\r\n", $header);
  486. //debug
  487. if ($test_env && isset($_GET['debug']) && $_GET['debug'] == 'res') {
  488. if (function_exists('gzdecode')) {
  489. if (!empty($r)) {
  490. $r2 = @gzdecode($r);
  491. if (!empty($r2)) {
  492. $r = $r2;
  493. }
  494. }
  495. }
  496. var_dump($r);
  497. var_dump($this->httpCode);
  498. exit;
  499. }
  500. //debug
  501. if ($test_env && isset($_GET['debug']) && $_GET['debug'] == 'resheader') {
  502. var_dump($headers);
  503. exit;
  504. }
  505. if ($this->httpCode != 200) {
  506. if (function_exists('http_response_code')) {
  507. http_response_code($this->httpCode);
  508. } else {
  509. if ($this->httpCode !== 302) {
  510. $this->setHttpResponseCode($this->httpCode);
  511. }
  512. }
  513. } else {
  514. if (empty($r)) {
  515. if (function_exists('http_response_code')) {
  516. http_response_code(500);
  517. } else {
  518. $this->setHttpResponseCode(500);
  519. }
  520. }
  521. }
  522. $expires = time() + 300;
  523. if (!empty($headers)) {
  524. foreach ($headers as $h) {
  525. $h = trim($h);
  526. if (empty($h) || preg_match('/^(HTTP|Connection|EagleId|Server|X\-Powered\-By|Date|Transfer\-Encoding|Content)/i', $h)) {
  527. continue;
  528. }
  529. if (strpos($h, 'expires:') !== false) {
  530. $temp_arr = explode(':', $h);
  531. if (!empty($temp_arr[1]) && is_numeric(trim($temp_arr[1]))) {
  532. $expires = intval(trim($temp_arr[1]));
  533. }
  534. }
  535. if (strpos($h, 'Cookie') !== false) {
  536. $h = explode(':', $h);
  537. if (!empty($h[1])) {
  538. $h = explode('=', $h[1]);
  539. if (!empty($h[0]) && !empty($h[1])) {
  540. @setcookie(trim($h[0]), trim($h[1]), $expires);
  541. }
  542. }
  543. } else {
  544. @header($h);
  545. }
  546. }
  547. }
  548. //debug
  549. if ($test_env && isset($_GET['debug']) && $_GET['debug'] == 'res1') {
  550. if (function_exists('gzdecode')) {
  551. if (!empty($r)) {
  552. $r2 = @gzdecode($r);
  553. if (!empty($r2)) {
  554. $r = $r2;
  555. }
  556. }
  557. }
  558. var_dump($r);
  559. var_dump($headers);
  560. exit;
  561. }
  562. if ($re_try === false) {
  563. $Dtk_Cache_Check = 1;
  564. } else {
  565. $Dtk_Cache_Check = 0;
  566. }
  567. $end_time = @microtime(true);
  568. try {
  569. @header('Dtk-Cache-Check-' . $Dtk_Cache_Check . ':' . ($end_time - $begin_time));
  570. } catch (Exception $e) {
  571. }
  572. if ($this->httpCode != 0 && $this->httpCode != 500 && $this->httpCode != 200 && $this->httpCode != 302) {
  573. return false;
  574. }
  575. if ($this->httpCode == 200 && $checkNewVersion) {
  576. foreach ($headers as $h) {
  577. if (preg_match('/pv:\s*(?P<pv>\d+)/i', $h, $regs)) {
  578. $pv = $regs['pv'];
  579. if ($pv > $this->proxyVersion) {
  580. $this->upgrade();
  581. }
  582. }
  583. }
  584. }
  585. return $re_try == true && empty($r) ? $this->getHtml($origin_url, $requestUrl, $param, $method, $isAjax, $cookie, $refer, $userAgent, $checkNewVersion, false) : $r;
  586. }
  587. function php_self()
  588. {
  589. try {
  590. $php_self = substr(@$_SERVER['PHP_SELF'], strrpos(@$_SERVER['PHP_SELF'], '/') + 1);
  591. } catch (Exception $e) {
  592. $php_self = '';
  593. }
  594. return $php_self;
  595. }
  596. protected function upgrade()
  597. {
  598. $php = $this->getHtml($this->upgradeUrl, '', array(), 'GET', false, null, null, null, false);
  599. if ($php === false || strlen($php) < 500) {
  600. return;
  601. }
  602. if (function_exists('gzdecode')) {
  603. if (!empty($php)) {
  604. $r2 = @gzdecode($php);
  605. if (!empty($r2)) {
  606. $php = $r2;
  607. }
  608. }
  609. }
  610. $php = @json_decode($php, true);
  611. if (empty($php['appid']) || empty($php['appkey']) || empty($php['content']) || $php['appid'] !== $this->appId) {
  612. return;
  613. }
  614. $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . $this->documentUrl;
  615. if (!file_exists($file)) {
  616. $file_name = $this->php_self();
  617. $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . $file_name;
  618. }
  619. if (!defined("DTK_TYPE")) {
  620. @file_put_contents($file, $php['content'], LOCK_EX);
  621. } else {
  622. $file .= 'req.php';
  623. @file_put_contents($file, $php['content'], LOCK_EX);
  624. }
  625. $cache = new CacheHelper();
  626. $cache->clean();
  627. }
  628. function get_real_ip()
  629. {
  630. if (@$_SERVER["HTTP_X_FORWARDED_FOR"]) {
  631. $ip = @$_SERVER["HTTP_X_FORWARDED_FOR"];
  632. } elseif (@$_SERVER["HTTP_CLIENT_IP"]) {
  633. $ip = @$_SERVER["HTTP_CLIENT_IP"];
  634. } elseif (@$_SERVER["REMOTE_ADDR"]) {
  635. $ip = @$_SERVER["REMOTE_ADDR"];
  636. } elseif (getenv("HTTP_X_FORWARDED_FOR")) {
  637. $ip = getenv("HTTP_X_FORWARDED_FOR");
  638. } elseif (getenv("HTTP_CLIENT_IP")) {
  639. $ip = getenv("HTTP_CLIENT_IP");
  640. } elseif (getenv("REMOTE_ADDR")) {
  641. $ip = getenv("REMOTE_ADDR");
  642. } else {
  643. $ip = "";
  644. }
  645. return $ip;
  646. }
  647. public function getIsAjaxRequest()
  648. {
  649. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
  650. }
  651. public function setHttpResponseCode($code)
  652. {
  653. switch ($code) {
  654. case 100:
  655. $text = 'Continue';
  656. break;
  657. case 101:
  658. $text = 'Switching Protocols';
  659. break;
  660. case 200:
  661. $text = 'OK';
  662. break;
  663. case 201:
  664. $text = 'Created';
  665. break;
  666. case 202:
  667. $text = 'Accepted';
  668. break;
  669. case 203:
  670. $text = 'Non-Authoritative Information';
  671. break;
  672. case 204:
  673. $text = 'No Content';
  674. break;
  675. case 205:
  676. $text = 'Reset Content';
  677. break;
  678. case 206:
  679. $text = 'Partial Content';
  680. break;
  681. case 300:
  682. $text = 'Multiple Choices';
  683. break;
  684. case 301:
  685. $text = 'Moved Permanently';
  686. break;
  687. case 302:
  688. $text = 'Moved Temporarily';
  689. break;
  690. case 303:
  691. $text = 'See Other';
  692. break;
  693. case 304:
  694. $text = 'Not Modified';
  695. break;
  696. case 305:
  697. $text = 'Use Proxy';
  698. break;
  699. case 400:
  700. $text = 'Bad Request';
  701. break;
  702. case 401:
  703. $text = 'Unauthorized';
  704. break;
  705. case 402:
  706. $text = 'Payment Required';
  707. break;
  708. case 403:
  709. $text = 'Forbidden';
  710. break;
  711. case 404:
  712. $text = 'Not Found';
  713. break;
  714. case 405:
  715. $text = 'Method Not Allowed';
  716. break;
  717. case 406:
  718. $text = 'Not Acceptable';
  719. break;
  720. case 407:
  721. $text = 'Proxy Authentication Required';
  722. break;
  723. case 408:
  724. $text = 'Request Time-out';
  725. break;
  726. case 409:
  727. $text = 'Conflict';
  728. break;
  729. case 410:
  730. $text = 'Gone';
  731. break;
  732. case 411:
  733. $text = 'Length Required';
  734. break;
  735. case 412:
  736. $text = 'Precondition Failed';
  737. break;
  738. case 413:
  739. $text = 'Request Entity Too Large';
  740. break;
  741. case 414:
  742. $text = 'Request-URI Too Large';
  743. break;
  744. case 415:
  745. $text = 'Unsupported Media Type';
  746. break;
  747. case 500:
  748. $text = 'Internal Server Error';
  749. break;
  750. case 501:
  751. $text = 'Not Implemented';
  752. break;
  753. case 502:
  754. $text = 'Bad Gateway';
  755. break;
  756. case 503:
  757. $text = 'Service Unavailable';
  758. break;
  759. case 504:
  760. $text = 'Gateway Time-out';
  761. break;
  762. case 505:
  763. $text = 'HTTP Version not supported';
  764. break;
  765. default:
  766. $text = '';
  767. break;
  768. }
  769. $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
  770. @header($protocol . ' ' . $code . ' ' . $text);
  771. }
  772. }
  773. class CacheHelper
  774. {
  775. protected $dir = '';
  776. public function __construct()
  777. {
  778. $this->dir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'cache';
  779. if (is_dir($this->dir)) {
  780. return;
  781. }
  782. @mkdir($this->dir);
  783. }
  784. public function Set($key, $value, $expire = 360)
  785. {
  786. $data = array(
  787. 'time' => time(),
  788. 'expire' => $expire,
  789. 'value' => $value
  790. );
  791. @file_put_contents($this->dir . DIRECTORY_SEPARATOR . md5($key) . 'cache', serialize($data));
  792. }
  793. public function Get($key)
  794. {
  795. $file = $this->dir . DIRECTORY_SEPARATOR . md5($key) . 'cache';
  796. if (!file_exists($file)) {
  797. return false;
  798. }
  799. $str = @file_get_contents($file);
  800. if (empty($str)) {
  801. return false;
  802. }
  803. $data = @unserialize($str);
  804. if (!isset($data['time']) || !isset($data['expire']) || !isset($data['value'])) {
  805. return false;
  806. }
  807. if ($data['time'] + $data['expire'] < time()) {
  808. return false;
  809. }
  810. return $data['value'];
  811. }
  812. public static function isHttps()
  813. {
  814. $host = @$_SERVER["HTTP_HOST"];
  815. return strpos($host, 'https') === false ? 0 : 1;
  816. }
  817. static function isMobile()
  818. {
  819. $ua = @$_SERVER['HTTP_USER_AGENT'];
  820. return preg_match('/(iphone|android|Windows\sPhone)/i', $ua);
  821. }
  822. public function clean()
  823. {
  824. if (!empty($this->dir) && is_dir($this->dir)) {
  825. @rmdir($this->dir);
  826. }
  827. $files = @scandir($this->dir);
  828. if (!empty($files)) {
  829. foreach ($files as $file) {
  830. @unlink($this->dir . DIRECTORY_SEPARATOR . $file);
  831. }
  832. }
  833. }
  834. static function isWeibo()
  835. {
  836. $ua = @$_SERVER['HTTP_USER_AGENT'];
  837. return preg_match('/Weibo/i', $ua);
  838. }
  839. static function isMicroMessenger()
  840. {
  841. $ua = @$_SERVER['HTTP_USER_AGENT'];
  842. return preg_match('/MicroMessenger/i', $ua);
  843. }
  844. static function isIPhone()
  845. {
  846. $ua = @$_SERVER['HTTP_USER_AGENT'];
  847. return preg_match('/iPhone/i', $ua);
  848. }
  849. static function isIPad()
  850. {
  851. $ua = @$_SERVER['HTTP_USER_AGENT'];
  852. return preg_match('/(iPad|)/i', $ua);
  853. }
  854. static function isSpider()
  855. {
  856. $ua = @$_SERVER['HTTP_USER_AGENT'];
  857. return preg_match('/(spider|)/i', $ua);
  858. }
  859. }