<?php
	header('Set-Cookie: third_party_var=value; SameSite=None; Secure');
	require_once dirname(dirname(__FILE__))."/session/session_mysql.php";
	require_once dirname(dirname(__FILE__))."/bin/htmlpurifier/HTMLPurifier.auto.php";
	require_once dirname(dirname(__FILE__))."/bin/web/page.php";
	require_once dirname(dirname(__FILE__))."/dal/htaccessDAL.php";
	require_once dirname(dirname(__FILE__))."/dal/limitDAL.php";
	require_once dirname(dirname(__FILE__))."/dal/menuDAL.php";
	require_once dirname(dirname(__FILE__))."/dal/registryDAL.php";
	require_once dirname(dirname(__FILE__))."/modules/userInfo.php";
	require_once dirname(dirname(__FILE__))."/modules/userType.php";
	require_once dirname(dirname(__FILE__))."/modules/sessionKeys.php";
	require_once dirname(__FILE__)."/header.php";
	require_once dirname(__FILE__)."/footer.php";
	require_once dirname(__FILE__)."/sidePage.php";
	
	/* 錯誤鎖定 */
	$errlogFilePath = dirname(__FILE__) . "/loginerror.txt";
	if (file_exists($errlogFilePath)) {
		$errlog = file_get_contents($errlogFilePath, false, null, 0, 8192); // 讀取最多 8KB 的內容
		if ($errlog !== false && $errlog !== "") {
			$aryErr = json_decode($errlog, true);
			if (is_array($aryErr) && count($aryErr) > 5) {
				echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
				echo "<script language=\"javascript\">window.alert(\"我們發現您的後台有可疑的活動，為了安全起見，我們已暫時鎖住您的後台。如有疑問請洽客服人員。\");location.href=\"/\";</script>";
				exit;
			}
		}
	}
	/* 錯誤鎖定 */
	
	class pageBase extends page {
		public $htLinks = [];
		public $alertMsg = "";
		public $locationHref = "";
		public $goBack = "N";
		public $limitID = "0";

		public function __construct() {
			// 網頁網址設定
			$dalHT = new htaccessDAL();
			for ($i = 1; $i <= 7; $i++) {
				$dalHT->ID = (string) $i;
				$dalHT->loadRecord();
				$this->htLinks[$i] = $dalHT->HtmlName;
			}
			
			// 訊息、換頁
			$this->alertMsg = "";
			$this->locationHref = "";
			$this->goBack = "N";

			// 主選單展開依據
			$this->limitID = "0";
			
			// 更新Line登入資料
			$lastMonth = strtotime("-1 month");
			$upLineTasonTime = $this->getRegistryValue("upLineTasonTime");
			if ($upLineTasonTime !== null) {
				$upLineTasonTime = strtotime($upLineTasonTime);
				if ($upLineTasonTime < $lastMonth) {
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, "https://www.appleseo.com.tw/line/srever.json");
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					$linesString = curl_exec($ch);
					curl_close($ch);
					if ($linesString != false && file_put_contents("./line/srever.json", $linesString)) registryDAL::saveRegistry("upLineTasonTime", date("Y-m-d H:i:s"));
				}
			}
			
			parent::__construct();
		}

		//覆蓋父類load()方法
		public function load() {
			//IP限制
			$ipLimit2 = $this->getRegistryValue("ipLimit2");
			$ipBlackList2 = $this->getRegistryValue("ipBlackList2");
			$ipWhiteList2 = $this->getRegistryValue("ipWhiteList2");
			$twipLimit2 = $this->getRegistryValue("twipLimit2");
			
			if (!$this->chkIP($ipLimit2, $ipBlackList2, $ipWhiteList2, $twipLimit2)) {
				header("Location: " . parent::getProtocol() . "://{$_SERVER['HTTP_HOST']}/iweb/404.php");
				exit;
			}
    
			$whiteList = [
				'/iweb/gmailLoginSend.php',
				'/iweb/loginGmail.php',
				'/iweb/lineLoginSend.php',
				'/iweb/lineLogin.php',
				'/iweb/fbLoginSend.php',
				'/iweb/loginFacebook.php'
			];
			
			if (!in_array($_SERVER["SCRIPT_NAME"], $whiteList) && !isset($_SESSION[sessionKeys::USER_INFO]) && $_SERVER["SCRIPT_NAME"] != '/iweb/login.php') {
				header("Location: /iweb/login.php");
				exit;
			}
			
			parent::addParameter("alertMsg", $this->alertMsg);
			parent::addParameter("locationHref", $this->locationHref);
			parent::addParameter("goBack", $this->goBack);
			
			parent::load();
		}

		public function loadData() {
			parent::addParameter("page_name", $this->getMenuName($this->limitID));
			
			$header = new _header();
			$header->userID = $this->getCurrentUserID();
			$header->load();
			parent::addParameter("header",$header->getContent());

			$footer = new _footer();
			$footer->load();
			parent::addParameter("footer",$footer->getContent());

			$sidePage = new _sidePage();
			$sidePage->userID = $this->getCurrentUserID();
			$sidePage->limitID = $this->limitID;
			$sidePage->load();
			parent::addParameter("sidePage",$sidePage->getContent());
		}
	
		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 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));
		}
		
		public function chkUserLimit($limitID=0) {
			$dalL = new limitDAL();
			if ($limitID == 0) $limitID = $this->limitID;
			return ($this->getCurrentUserID() === 1) ? true : $dalL->checkLimit($this->getCurrentUserID(), $limitID);
		}
		
		public function getMenuName($menuID) {
			$dal = new menuDAL();
			$dal->MenuID = $menuID;
			$dal->loadRecord();
			return ($dal->Visible === 1) ? $dal->MenuName : "";
		}
		
		public function getRegistryValue($key) {
			return registryDAL::getRegistryValue($key);
		}
		
		public function BannerSetHtml($BannerTitle, $BannerLink, $BannerColor, $BannerImage, $BannerDesc, $type) {
			return <<<HTML
			<div id="banset" class="d_md_flex flex_wrap tab_content">
				<div class="col_md_6 d_flex form_list"><label>Banner標題</label><input type="text" id="BannerTitle" name="BannerTitle" value="{$BannerTitle}" /></div>
				<div class="col_md_6 d_flex form_list"><label>Banner超連結</label><input type="text" id="BannerLink" name="BannerLink" value="{$BannerLink}" /></div>
				<div class="col_md_6 d_flex form_list"><label>Banner底色</label><p><input type="text" id="BannerColor" class="form-control" data-position="bottom left" name="BannerColor" value="{$BannerColor}" style="padding-left: 40px; cursor:pointer;" maxlength="11" /></p></div>
				<div class="col_md_6 d_flex form_list"><label>Banner圖</label><p class="d_flex upBox"><a class="img_box"></a><font class="col_12 in_group"><input type="text" id="BannerImage" name="BannerImage" data-action="Image" value="{$BannerImage}" /><b class="group"><a class="btn btn_dark" href="javascript:void(0);" data-action="btnImg" data-type="{$type}"><svg class="fa"><use xlink:href="svg/icons.svg#folder"></use></svg></a></b></font></p></div>
				<div class="col_12 form_list"><label>Banner描述</label><textarea id="BannerDesc" name="BannerDesc">{$BannerDesc}</textarea></div>
				<div class="col_12 d_flex form_btn"><a class="ml_2 btn btn_orange" data-action="upPage" href="javascript:void(0);">上一步</a><a class="ml_2 btn btn_tertiary" data-action="nextPage" href="javascript:void(0);">下一步</a></div>
			</div>
		HTML;
		}
		
		public function MetaogSetHtml($OGTitle, $OGImage, $OGDescription, $type) {
			return <<<HTML
			<div id="ogset" class="d_md_flex flex_wrap tab_content">
				<div class="col_md_6 d_flex form_list"><label>社群分享標題</label><input type="text" id="OGTitle" name="OGTitle" value="{$OGTitle}" /></div>
				<div class="col_md_6 d_flex form_list"><label>社群分享縮圖</label><p class="d_flex upBox"><a class="img_box"></a><font class="col_12 in_group"><input type="text" id="OGImage" name="OGImage" data-action="Image" value="{$OGImage}" /><b class="group"><a class="btn btn_dark" href="javascript:void(0);" data-action="btnImg" data-type="{$type}"><svg class="fa"><use xlink:href="svg/icons.svg#folder"></use></svg></a></b></font></p></div>
				<div class="col_12 form_list"><label>社群分享描述</label><textarea id="OGDescription" name="OGDescription">{$OGDescription}</textarea></div>
				<div class="col_12 d_flex form_btn"><a class="ml_2 btn btn_orange" data-action="upPage" href="javascript:void(0);">上一步</a><a class="ml_2 btn btn_tertiary" data-action="nextPage" href="javascript:void(0);">下一步</a></div>
			</div>
		HTML;
		}

		public function GoogleSearchHtml($bestRating, $ratingValue, $reviewCount, $ratingCount, $isShowJason, $isShowStars, $type = 1) {
			$openJason = ($isShowJason === 1) ? " checked" : "";
			$openStars = ($isShowStars === 1) ? " checked" : "";
			$nextPage = ($type === 1) ? "<a class=\"ml_2 btn btn_tertiary\" data-action=\"nextPage\" href=\"javascript:void(0);\">下一步</a>" : "";
			return <<<HTML
			<div id="boxgseo" class="d_md_flex flex_wrap tab_content">
				<div class="col_md_4 d_flex form_list"><label>評分最高值</label><input type="text" id="BestRating" name="BestRating" value="{$bestRating}" placeholder="如果空白預設為5分。" /></div>
				<div class="col_md_4 d_flex form_list"><label>內容評分</label><input type="text" id="RatingValue" name="RatingValue" value="{$ratingValue}" /></div>
				<div class="col_md_4 d_flex form_list"><label>總評分數</label><input type="text" id="RatingCount" name="RatingCount" value="{$ratingCount}" /></div>
				<div class="col_md_4 d_flex form_list"><label>總評論數</label><input type="text" id="ReviewCount" name="ReviewCount" value="{$reviewCount}" /></div>
				<div class="col_md_4 d_flex form_list"><label>結構化資料</label><p class="open"><font class="checkbox"><input type="checkbox" id="IsShowJason" name="IsShowJason" value="1"{$openJason}><span></span></font></p></div>
				<div class="col_md_4 d_flex form_list"><label>星級/評論</label><p class="IsIndex"><font class="checkbox"><input type="checkbox" id="IsShowStars" name="IsShowStars" value="1"{$openStars}><span></span></font></p></div>
				<div class="col_12 d_flex form_btn"><a class="ml_2 btn btn_orange" data-action="upPage" href="javascript:void(0);">上一步</a>{$nextPage}</div>
			</div>
		HTML;
		}

		public function SeoSetHtml($WebTitle, $WebKeyword, $WebDescription) {
			return <<<HTML
			<div id="seoset" class="tab_content">
				<div class="d_flex form_list"><label>頁面標題</label><input type="text" id="WebTitle" name="WebTitle" value="{$WebTitle}" /></div>
				<div class="d_flex form_list"><label>頁面關鍵字</label><input type="text" id="WebKeyword" name="WebKeyword" value="{$WebKeyword}" /></div>
				<div class="form_list"><label>頁面描述</label><textarea id="WebDescription" name="WebDescription">{$WebDescription}</textarea></div>
				<div class="col_12 d_flex form_btn"><a class="ml_2 btn btn_orange" data-action="upPage" href="javascript:void(0);">上一步</a></div>
			</div>
		HTML;
		}
		
		/* 產生刪除鈕 */
		public function generateDelButton($disable, $id) {
			$isUserOne = $this->getCurrentUserID() == "1";
			$isItemDisabled = $disable == "1";
		
			$btnClass = $isUserOne && $isItemDisabled ? 'btn_success' : 'btn_danger';
			$btnType = $isUserOne && $isItemDisabled ? '0' : '1';
			$btnText = $isUserOne && $isItemDisabled ? '復原' : '刪除';
		
			$delBtn = '<a class="btn ' . $btnClass . '" data-action="delItem" data-type="' . $btnType . '" data-id="'.$id.'" href="javascript:void(0);">' . $btnText . '</a>';
		
			return $delBtn;
		}
		
		/* 產生換頁結構 */
		public function generatePagination($p, $pMax) {
			$rang = 10;
			$pagtxt = '';
		
			if ($pMax > 0) {
				$pr = ceil($p / $rang) - 1;
				$pu = ($p == 1) ? 1 : ($p - 1);
				$pd = ($p == $pMax) ? $pMax : ($p + 1);
				$n1 = 1;
				$n2 = 11;
				if ($p > 6) {
					$n1 = ($p == $pMax) ? ($p - 9) : ($p - 5);
					$n2 = ($p == $pMax) ? ($p + 1) : ($p + 5);
				}
				$pagtxt .= '<a data-action="goPage" data-id="1" href="javascript:void(0);"><i class="fas fa-angle-double-left"></i></a>';
				for ($i = $n1; $i < $n2; $i++) {
					if ($i > 0) $pagtxt .= ($i == $p) ? ('<b class="bg_dark txt_white">' . $i . '</b>') : ('<a data-action="goPage" data-id="' . $i . '" href="javascript:void(0);">' . $i . '</a>');
					if ($i == $pMax) break;
				}
				$pagtxt .= '<a data-action="goPage" data-id="' . $pMax . '" href="javascript:void(0);"><i class="fas fa-angle-double-right"></i></a>';
			}
		
			return $pagtxt;
		}

		/* 中文路徑生成 */
		public function generateTwPathName($name) {
			$twPathName = $this->codetospecial($name);
			$twPathName = sbc2Dbc($twPathName);
			$twPathName = preg_replace("/\s+/", "+", $twPathName);
			$twPathName = $this->nametopath($twPathName);
			
			return $twPathName;
		}
	}
?>