<?php
defined('IN_WEB') or die('Include Error!');
/**
 * 测试环境切换
 * @author LokChen
 * @date 2017/04/19
 */

class LibDev {
	public static $cfg = array();

	public static function initCfg() {
		$file = WWWROOT . 'config/config.dev.php';
		if (file_exists($file)) {
			self::$cfg = include($file);
		}
	}

	public static function proxy() {
		self::initCfg();
		if (empty(self::$cfg)) {
			return false;
		}
		$devUsers = self::$cfg['conf'];
		$uid = (int)$_REQUEST['uid'];
		$ip = $_SERVER['REMOTE_ADDR'];

		$devName = '';
		if (isset(self::$cfg['uids'][$uid])) { // 如果配置UID
			$devName = self::$cfg['uids'][$uid];
		}
		if (isset(self::$cfg['ips'][$ip])) { // 如果有配置IP
			$devName = self::$cfg['ips'][$ip];
		}
		if (empty($devName)) {
			return false;
		}
		$ret = self::curl($devUsers[$devName]['api'], $devUsers[$devName]['host'], $_REQUEST);
		echo $ret;
		exit;
	}

	public static function curl($url, $host, $post_data = array()) {
		$timeout = 30;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: {$host}"));
		if (!empty($post_data)) {
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		}
		$result = curl_exec($ch);
		curl_close($ch);
		return $result;
	}

	public static function test() {
		return "test";
	}
}