<?php
	require_once dirname(dirname(dirname(__FILE__)))."/session/session_mysql.php";
	require_once dirname(dirname(dirname(__FILE__)))."/bin/web/page.php";
	require_once dirname(dirname(dirname(__FILE__)))."/modules/sessionKeys.php";
	require_once dirname(dirname(dirname(__FILE__)))."/dal/registryDAL.php";
	
	class pageBase extends page{
		public function load(){
			if (!isset($_SESSION[sessionKeys::USER_INFO])) parent::redirect("/iweb/login.php");
			parent::load();
		}

		public function getRegistryValue(string $key): mixed {
			return registryDAL::getRegistryValue($key);
		}
	
		public function getCurrentUser(): ?object {
			return isset($_SESSION[sessionKeys::USER_INFO]) ? (object)$_SESSION[sessionKeys::USER_INFO] : null;
		}
	
		public function getCurrentUserID(): int {
			return isset($_SESSION[sessionKeys::ADMIN_USER_ID]) && $_SESSION[sessionKeys::ADMIN_USER_ID] !== "" ? (int)$_SESSION[sessionKeys::ADMIN_USER_ID] : 0;
		}
		
		public function getIP() {
			if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
				$myip = $_SERVER['HTTP_CLIENT_IP'];
			} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
				$myip = $_SERVER['HTTP_X_FORWARDED_FOR'];
			} else {
				$myip = $_SERVER['REMOTE_ADDR'];
			}
			return $myip;
		}

		public function getInput($name, $default = "", $typ = 1) {	//typ=1，一般，所有特殊符號取代；2，編輯器，最低限度特殊符號取代；3，特殊，完全不取代只對單引號加斜線
			$value = $this->getValueFromSuperGlobal($_GET, $name, $default);
			$typ = (int)$typ;
			$value = $this->processValue($value, $typ);
			return $value;
		}
		
		public function getPost($name, $default = "", $typ = 1) {	//typ=1，一般，所有特殊符號取代；2，編輯器，最低限度特殊符號取代；3，特殊，完全不取代只對單引號加斜線
			$value = $this->getValueFromSuperGlobal($_POST, $name, $default);
			$typ = (int)$typ;
			$value = $this->processValue($value, $typ);
			return $value;
		}
		
		public function getGet($name, $default = "", $typ = 1) {	//typ=1，一般，所有特殊符號取代；2，編輯器，最低限度特殊符號取代；3，特殊，完全不取代只對單引號加斜線
			$value = $this->getValueFromSuperGlobal($_GET, $name, $default);
			$typ = (int)$typ;
			$value = $this->processValue($value, $typ);
			return $value;
		}
		
		private function getValueFromSuperGlobal($superGlobal, $name, $default) {
			if (isset($superGlobal[$name]) && $superGlobal[$name] !== "") {
				return $superGlobal[$name];
			}
			return $default;
		}
		
		private function processValue($value, $typ) {
			$value = str_replace(["\r", "\n", "\t"], '', $value);
			$value = stripslashes($value);
			$value = $this->specialtocode($value, $typ);
			return $value;
		}

		public function getInputArray($name, $typ = 1) {	//typ=1，一般，所有特殊符號取代；2，編輯器，最低限度特殊符號取代；3，特殊，完全不取代只對單引號加斜線
			return $this->processArrayValue($_GET, $name, $typ);
		}

		public function getPostArray($name, $typ = 1) {	//typ=1，一般，所有特殊符號取代；2，編輯器，最低限度特殊符號取代；3，特殊，完全不取代只對單引號加斜線
			return $this->processArrayValue($_POST, $name, $typ);
		}

		public function getGetArray($name, $typ = 1) {	//typ=1，一般，所有特殊符號取代；2，編輯器，最低限度特殊符號取代；3，特殊，完全不取代只對單引號加斜線
			return $this->processArrayValue($_GET, $name, $typ);
		}

		public function getInputArray2($name, $typ = 1) {	//typ=1，一般，所有特殊符號取代；2，編輯器，最低限度特殊符號取代；3，特殊，完全不取代只對單引號加斜線
			return $this->processNestedArrayValue($_GET, $name, $typ);
		}

		public function getPostArray2($name, $typ = 1) {	//typ=1，一般，所有特殊符號取代；2，編輯器，最低限度特殊符號取代；3，特殊，完全不取代只對單引號加斜線
			return $this->processNestedArrayValue($_POST, $name, $typ);
		}

		public function getGetArray2($name, $typ = 1) {	//typ=1，一般，所有特殊符號取代；2，編輯器，最低限度特殊符號取代；3，特殊，完全不取代只對單引號加斜線
			return $this->processNestedArrayValue($_GET, $name, $typ);
		}

		private function processArrayValue($source, $name, $typ) {
			$aryV = isset($source[$name]) && is_array($source[$name]) ? $source[$name] : [];
			
			$typ = (int)$typ;
			foreach ($aryV as &$value) {
				$this->processSingleValue($value, $typ);
			}
			
			return $aryV;
		}

		private function processNestedArrayValue($source, $name, $typ) {
			$aryV = isset($source[$name]) && is_array($source[$name]) ? $source[$name] : [];
			
			$typ = (int)$typ;
			foreach ($aryV as &$rows) {
				if (is_array($rows)) {
					foreach ($rows as &$value) {
						$this->processSingleValue($value, $typ);
					}
				} else {
					$this->processSingleValue($rows, $typ);
				}
			}
			
			return $aryV;
		}

		private function processSingleValue(&$value, $typ) {
			$value = str_replace(array("\r", "\n", "\t"), '', $value);
			$value = stripslashes($value);
			$value = $this->specialtocode($value, $typ);
		}
		
		public function specialtocode($value, $typ = 1) {	//typ=1，一般，所有特殊符號取代；2，編輯器，最低限度特殊符號取代；3，特殊，完全不取代只對單引號加斜線；4，先去a和script標籤，再取代所有特殊符號
			$typ = (int)$typ;
			if ($typ == 4) {
				$value = preg_replace("/<\s*a.*<\/\s*a\s*>/iU", "", $value);
				$value = preg_replace("/<\s*s\s*c\s*r\s*i\s*p\s*t.*<\/\s*s\s*c\s*r\s*i\s*p\s*t\s*>/iU", "", $value);
				$typ = 1;
			}
			if ($typ == 3) {
				$value = str_replace("'", "\'", $value);
			} else {
				$value = str_replace(["$", "'"], ["&#36;", "&#39;"], $value);
				if ($typ == 1) $value = str_replace(["\"", "(", ")", "{", "}", "<", ">"], ["&#34;", "&#40;", "&#41;", "&#123;", "&#125;", "&#60;", "&#62;"], $value);
			}
			
			return $value;
		}

		public function codetospecial($value) {
			$value = str_replace(["&#62;", "&#60;", "&#125;", "&#123;", "&#41;", "&#40;", "&#34;", "&#39;", "&#36;"], [">", "<", "}", "{", ")", "(", "\"", "'", "$"], $value);
			return $value;
		}
		
		public function nametopath($value) {
			$value = str_replace(["#", "$", "%", "&", "\\", "/", "?"], "_", $value);
			return $value;
		}

		public function addArray(string $name, string $value, string $type = "", string $number = "") {
			if (!preg_match("/^[1-9]\d*$/", $number)) $number = "";
		
			return [ "Name" => $name, "Value" => $value, "Type" => $type, "Number" => $number ];
		}

		public function image_exists($url) {
			if (preg_match("/^\/\//", $url)) $url = $_SERVER['REQUEST_SCHEME'] . $url;
			if (!preg_match("/^http/", $url)) return (preg_match("/^\//", $url)) ? (file_exists("." . $url)) : (file_exists($url));
			
			$parts = parse_url($url);
			if (isset($parts['user'])) return false;
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0');
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
			curl_setopt($ch, CURLOPT_TIMEOUT, 20);
			curl_setopt($ch, CURLOPT_NOBODY, true);
			curl_setopt($ch, CURLOPT_HEADER, true);
			if ($parts['scheme'] == 'https') {
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			}
			$response = curl_exec($ch);
			curl_close($ch);
		
			$content_type = false;
			if (preg_match('/Content-Type: (.+\/.+?)/i', $response, $matches)) {
				if (preg_match('/image\/.*/', $matches[1])) $content_type = true;
			}
			if (!$content_type) return false;
			
			if (preg_match('/HTTP\/\d+\.?\d*\s+(\d+)/', $response, $matches)) {
				$code = intval($matches[1]);
			} else {
				return false;
			}
		
			return (($code >= 200) && ($code < 400));
		}
		
		public function chklink($url) {
			$parts = parse_url($url);
			if (isset($parts['user'])) return false;
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0');
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
			curl_setopt($ch, CURLOPT_TIMEOUT, 20);
			curl_setopt($ch, CURLOPT_NOBODY, true);
			curl_setopt($ch, CURLOPT_HEADER, true);
			if ($parts['scheme'] == 'https') {
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			}
			$response = curl_exec($ch);
			curl_close($ch);
			
			if (preg_match('/HTTP\/\d+\.?\d*\s+(\d+)/', $response, $matches)) {
				$code = intval($matches[1]);
			} else {
				return false;
			}
		
			return (($code >= 200) && ($code < 400));
		}
	}
?>