<?php
date_default_timezone_set('Asia/Taipei');
header('Content-Type: application/json; charset=UTF-8'); //設定資料類型為 json，編碼 utf-8

class _myClass {
	public function load() {
		if ($this->chkIP()) {
			if ($_SERVER['REQUEST_METHOD'] === "POST") {
				$do = $_POST["do"] ?? "";
				$link = 'login_unlock.php';

				if ($do === 'unlock') {
					$msg = '解鎖失敗！';

					if (file_exists(dirname(dirname(__FILE__)) . "/loginerror.txt") && unlink(dirname(dirname(__FILE__)) . '/loginerror.txt')) {
						$msg = '解鎖成功！';
						$link = 'login.php';
					}
				} else {
					$msg = '請求無效，請重新整理再試一次！';
				}
			} else {
				$msg = '請求無效，只允許 POST 方式訪問！';
			}

			echo json_encode(['msg' => $msg, 'link' => $link]);
			exit();
		}else{
			header("Location: " . $this->getProtocol() . "://" . $_SERVER['HTTP_HOST'] . "/iweb/404.php");
			exit;
		}
	}
	
	function chkIP() {
		$txtIP = $this->load_contents("{$this->getProtocol()}://{$_SERVER['HTTP_HOST']}/api/appleip.json");
		$aryIP = json_decode($txtIP);
		$flag = false;
		
		foreach ($aryIP as $v) {
			if (!empty($v)) {
				$aryIPParts = explode(".", $v);

				for ($i = 0; $i < count($aryIPParts); $i++) {
					if (trim($aryIPParts[$i]) == "*" || trim($aryIPParts[$i]) == "") $aryIPParts[$i] = "\d{1,3}";
				}

				for ($i = 4; $i > count($aryIPParts); $i--) {
					$aryIPParts[] = "\d{1,3}";
				}

				$ipW = implode("\.", $aryIPParts);
				$ipW = "/{$ipW}/";
	
				if (preg_match($ipW, $this->getIP())) {
					$flag = true;
					break;
				}
			}
		}

		return $flag;
	}
	
	function getProtocol() {
		return ($_SERVER["HTTPS"] ?? "") === "on" ? "https" : "http";
	}

	function getIP() {
		if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
			$myip = $_SERVER['HTTP_CLIENT_IP'];
		} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			$myip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		} else {
			$myip = $_SERVER['REMOTE_ADDR'];
		}
		return $myip;
	}

	function load_contents($url) {
		$ch = curl_init();
	
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
	
		$data = curl_exec($ch);
		curl_close($ch);
	
		return $data;
	}
}
$page = new _myClass;
$page->load();
?>