<?php
	header('Set-Cookie: third_party_var=value; SameSite=None; Secure');
	header("Content-Type:text/html; charset=utf-8");
	require_once "session/session_mysql.php";
	require_once "bin/htmlpurifier/HTMLPurifier.auto.php";
	require_once "bin/web/page.php";
	require_once "bin/web/tables/article.php";
	require_once "bin/web/tables/news.php";
	require_once "bin/web/tables/faq.php";
	require_once "bin/web/tables/product.php";
	require_once "bin/web/tables/book.php";
	require_once "bin/web/tables/contact.php";
	require_once "bin/web/tables/order.php";
	require_once "bin/web/tables/jump.php";
	require_once "dal/pictureDAL.php";
	require_once "dal/templateDAL.php";
	require_once "webParts/webPartsFactory.php";

	class pageBase extends page {
		public bool $is_index = false;
		public $picturetype;
		public $NoPicImage;
		public $alertMsg, $locationHref, $goBack;
		public $bannerImage, $bannerTitle, $bannerLink, $bannerColor, $bannerDesc;

		public function pageBase() {
			if (preg_match("/HTTrack/i", $_SERVER["HTTP_USER_AGENT"])) {
				echo "我們正監控到你的IP還有你的網路攝影機，正在看著你!!!!!";
				exit;
			}
			
			// 訊息、換頁
			$this->alertMsg = "";
			$this->locationHref = "";
			$this->goBack = "N";
			
			// NoPicImage
			$dalP = new pictureDAL();
			$dalP->PictureType = "0";
			$dalP->TypeOrderNO = "0";
			$dalP->loadRecord();
			$this->NoPicImage = (!empty($dalP->Image) && $this->image_exists($dalP->Image)) ? $dalP->Image : "/images/no-pic.jpg";
			
			parent::__construct();
		}
		public function load(){
			// IP限制
			if (!parent::chkIP($this->registry->ipLimit1, $this->registry->ipBlackList1, $this->registry->ipWhiteList1, $this->registry->twipLimit)) {
				header("HTTP/1.0 404 Not Found");
				header("Status: 404 Not Found");
				exit;
			}
			
			parent::addParameter("alertMsg", $this->alertMsg);
			parent::addParameter("locationHref", $this->locationHref);
			parent::addParameter("goBack", $this->goBack);
			
			// 網站版型
			parent::addParameter("webTemplates", $this->registry->webTemplates);
			
			// 版型額外設定
			$dalT = new templateDAL();
			$dalT->PathName = $this->registry->webTemplates;
			$dalT->loadRecord();
			if (count($dalT->SetArray) > 0) {
				foreach ($dalT->SetArray as $rows) {
					parent::addParameter($rows["SetName"], $rows["SetValue"]);
				}
			}
			parent::load();
		}

		public function loadData(){
			// Google Analytics 原始碼
			parent::addParameter("headHTML", $this->registry->headHTML);
			parent::addParameter("bodyTopHTML", $this->registry->bodyTopHTML);

			/*==================== 網站設定 ====================*/
			// 網站SEO
			$webTitle = $this->registry->webTitle;
			$webKeyword = $this->registry->webKeyword;
			$webDescription = $this->registry->webDescription;
			$webMarquee = $this->registry->webMarquee;
			$webH1 = ($this->registry->webH1 !== "") ? "<h1 class=\"pageh1\">" . $this->registry->webH1 . "</h1>" : "";
			parent::addParameter("webTitle", $webTitle);
			parent::addParameter("webKeyword", $webKeyword);
			parent::addParameter("webDescription", $webDescription);
			parent::addParameter("webMarquee", $webMarquee);
			parent::addParameter("webH1", $webH1);
			// OG 相關設定
			$ogTitle = $this->registry->OGTitle ?? $webTitle ?? $this->registry->webName ?? "";
			$ogDescription = $this->registry->OGDescription ?? $webDescription ?? $this->registry->ogTitle ?? $webTitle ?? $this->registry->webName ?? "";
			$ogImage = "";
			$ogImagePath = $this->registry->OGImage ?? "";
			$ogImage = $this->setPageOGImage($ogImagePath);
			parent::addParameter("ogTitle", $ogTitle);
			parent::addParameter("ogDescription", $ogDescription);
			parent::addParameter("ogImage", $ogImage);
			// 網站資訊
			$webInfo = [
				["webName", "webNameStyle", $this->registry->webName],
				["webPhone", "webPhoneStyle", $this->registry->webPhone],
				["webEmail", "webEmailStyle", $this->registry->webEmail],
				["webMobile", "webMobileStyle", $this->registry->webMobile],
				["webAddress", "webAddressStyle", $this->registry->webAddress],
				["webFax", "webFaxStyle", $this->registry->webFax],
				["lineTitle", "lineTitleStyle", $this->registry->lineTitle]
			];
			foreach ($webInfo as [$paramName, $styleName, $paramValue]) {
				$style = (!empty($paramValue)) ? "" : "style='display:none;'";
				parent::addParameter($paramName, $paramValue);
				parent::addParameter($styleName, $style);
			}
			// Line QrCode
			$lineQRCode = $this->registry->lineQRCode;
			parent::addParameter("QRstyle", ((!empty($lineQRCode) && file_exists("." . $lineQRCode)) ? "" : "display:none;"));
			parent::addParameter("lineQRCode", ((!empty($lineQRCode) && file_exists("." . $lineQRCode)) ? $lineQRCode : "/images/no-pic.jpg"));
			// Google Map
			parent::addParameter("googlemapStyle", ((!empty($this->registry->googlemapAddress)) ? "" : "style='display:none;'"));
			parent::addParameter("googlemapAddress", ((!empty($this->registry->googlemapAddress)) ? urlencode($this->registry->googlemapAddress) : "style='display:none;'"));
			
			//加載模板
			$objectLinks = ["article", "news", "faq", "product", "book", "contact", "order"];
			$instances = [];
			foreach ($objectLinks as $index => $objectName) {
				$instances[$objectName] = new $objectName();
				$linkMethod = ($objectName !== "contact" && $objectName !== "order") ? "link" . ucfirst($objectName) . "List" : "link" . ucfirst($objectName);
				parent::addParameter("htLink" . ($index + 1), $instances[$objectName]->$linkMethod());
			}
			
			//跳轉
			$jump = new jump();
			$jump->load();
			parent::addParameter("JumpHTML", $jump->JumpHTML);
			parent::addParameter("JumpStyle", $jump->JumpStyle);
			parent::addParameter("JumpScript", $jump->JumpScript);
			parent::addParameter("JumpBody", $jump->JumpBody);
			parent::addParameter("headerStyle", $jump->headerStyle);
			parent::addParameter("headerTop", $jump->headerTop);

			//臉書粉絲團
			$fbRoot = '';
			if (!empty($this->registry->fbFansURL)) {
				if ($this->is_index) {
					$fbRoot = "<div id=\"fb-root\"></div>\r\n<script>(function(d, s, id) {\r\n  var js, fjs = d.getElementsByTagName(s)[0];\r\n  if (d.getElementById(id)) return;\r\n  js = d.createElement(s); js.id = id;\r\n  js.src = \"//connect.facebook.net/zh_TW/sdk.js#xfbml=1&version=v2.3\";\r\n  fjs.parentNode.insertBefore(js, fjs);\r\n}(document, 'script', 'facebook-jssdk'));</script>";
				} else {
					if ($this->registry->fbFansSidePageType == '3') $fbRoot = "<div id=\"fb-root\"></div>\r\n<script>(function(d, s, id) {\r\n  var js, fjs = d.getElementsByTagName(s)[0];\r\n  if (d.getElementById(id)) return;\r\n  js = d.createElement(s); js.id = id;\r\n  js.src = \"//connect.facebook.net/zh_TW/sdk.js#xfbml=1&version=v2.3\";\r\n  fjs.parentNode.insertBefore(js, fjs);\r\n}(document, 'script', 'facebook-jssdk'));</script>";
				}
			}
			parent::addParameter("fbRoot", $fbRoot);
			parent::addParameter("fbFansURL", $this->registry->fbFansURL);
			
			//rel link
			parent::addParameter("RelLink", parent::getProtocol() . "://" . $_SERVER['HTTP_HOST']);
			parent::addParameter("HTTPHOST", $_SERVER['HTTP_HOST']);
			parent::addParameter("REQUESTURI", $_SERVER['REQUEST_URI']);

			//Google MAP
			$googlemapBody = (!empty($this->registry->googlemapAddress) && $this->registry->googlemapIndex == "1") ? "<div id=\"g-map\"><iframe frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"https://maps.google.com.tw/maps?f=q&amp;hl=zh-TW&amp;geocode=&amp;q=" . urlencode($this->registry->googlemapAddress) . "&amp;z=16&amp;output=embed&amp;t=\" style=\"width: 100%; min-height: 400px;\"></iframe></div>" : "";
			parent::addParameter("googlemapBody", $googlemapBody);
			
			//頁頭
			$headerProperties = [
				"is_index" => $this->is_index ?? true,
				"picturetype" => $this->picturetype ?? 30,
				"searchkw" => $this->searchkw ?? "",
			];
			$headerContent = $this->createAndSetupWebPart("header", $headerProperties);
			parent::addParameter("header", $headerContent);

			//橫幅廣告
			$bannerProperties = [
				"is_index" => $this->is_index ?? true,
				"picturetype" => $this->picturetype ?? 30,
				"searchkw" => $this->searchkw ?? "",
				"bannerImage" => $this->bannerImage ?? "",
				"bannerTitle" => $this->bannerTitle ?? "",
				"bannerLink" => $this->bannerLink ?? "",
				"bannerColor" => $this->bannerColor ?? "",
				"bannerDesc" => $this->bannerDesc ?? ""
			];
			$bannerContent = $this->createAndSetupWebPart("banner", $bannerProperties);
			parent::addParameter("banner", $bannerContent);
			
			//頁側邊
			$sidePageProperties = [
				"picturetype" => $this->picturetype ?? 30
			];
			$sidePageContent = $this->createAndSetupWebPart("sidePage", $sidePageProperties);
			parent::addParameter("sidePage", $sidePageContent);
			
			//頁側邊
			$sidePage2Properties = [
				"picturetype" => $this->picturetype ?? 30
			];
			$sidePage2Content = $this->createAndSetupWebPart("sidePage2", $sidePage2Properties);
			parent::addParameter("sidePage2", $sidePage2Content);
			
			//頁側邊(會員)
			$sidePageMemberProperties = [];
			$sidePageMemberContent = $this->createAndSetupWebPart("sidePageMember", $sidePageMemberProperties);
			parent::addParameter("sidePageMember", $sidePageMemberContent);

			//頁脚
			$footerProperties = [];
			$footerContent = $this->createAndSetupWebPart("footer", $footerProperties);
			parent::addParameter("footer", $footerContent);
			
			// 首頁-關於我們
			$indexArticleProperties = [];
			$indexArticleContent = $this->createAndSetupWebPart("indexArticle", $indexArticleProperties);
			parent::addParameter("indexArticle", $indexArticleContent);

			// 首頁-最新消息
			$indexNewsProperties = [];
			$indexNewsContent = $this->createAndSetupWebPart("indexNews", $indexNewsProperties);
			parent::addParameter("indexNews", $indexNewsContent);

			// 首頁-商品
			$indexProductProperties = [];
			$indexProductContent = $this->createAndSetupWebPart("indexProduct", $indexProductProperties);
			parent::addParameter("indexProduct", $indexProductContent);

			// 首頁-相本
			$indexBookProperties = [];
			$indexBookContent = $this->createAndSetupWebPart("indexBook", $indexBookProperties);
			parent::addParameter("indexBook", $indexBookContent);
		}

		// webPart 的通用函式
		public function createAndSetupWebPart($webPartName, $properties) {
			$webPart = WebPartsFactory::create($webPartName);
			foreach ($properties as $property => $value) {
				$webPart->{$property} = $value;
			}
			$webPart->load();
			return $webPart->getContent();
		}

		public function strposa(string $text, int $offset = 0): string {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, "https://www.webi.com.tw/api/illegalwords.php");
			curl_setopt($ch, CURLOPT_HEADER, false);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$txtJ = curl_exec($ch);
			curl_close($ch);
			$objJ = json_decode($txtJ);
		
			$newText = $text;
			$newText2 = $text;
			foreach ($objJ as $query) {
				$banTxt = str_repeat("*", strlen($query));
				$newText = str_replace($query, $banTxt, $newText);
				$newText2 = str_replace($query, "【" . $query . "】", $newText2);
			}
			if ($newText !== $text) {
				// 文字檔記錄，不檢查全數記錄
				$txtJ = "{時間：" . date("Y-m-d H:i:s") . ",輸入內容：[" . strip_tags($newText2) . "],IP位置：" . $this->getIP() . "}" . PHP_EOL;
				file_put_contents('contactlog.txt', $txtJ, FILE_APPEND);
			}
			return $newText;
		}
		
		public function strposa2(string $value, int $offset = 0): bool {
			$array = [ "SEO", "網頁設計", "關鍵字" ];
			return !array_reduce($array, function ($carry, $query) use ($value, $offset) {
				return $carry || str_starts_with($value, $query);
			}, false);
		}
		
		// 頁導航通用函式
		public function generatePagination($p, $pMax, $id, $urlGenerator) {
			$rang = 10;
			$pr = ceil($p / $rang) - 1;
			$pu = ($p == 1) ? 1 : ($p - 1);
			$pd = ($p == $pMax) ? $pMax : ($p + 1);

			$pagtxt = '<a href="' . $urlGenerator($id, $pu) . '"><i class="fa fa-angle-double-left"></i></a>';
			for ($i = 1; $i < 11; $i++) {
				$nm = $pr * $rang + $i;
				$pagtxt .= ($nm == $p) ? '<strong class="number_hit">' . $nm . '</strong>' : '<a href="' . $urlGenerator($id, $nm) . '">' . $nm . '</a>';
				if ($nm == $pMax) break;
			}
			$pagtxt .= '<a href="' . $urlGenerator($id, $pd) . '" class="next"><i class="fa fa-angle-double-right"></i></a>';

			return $pagtxt;
		}

		// 設定內頁Banner
		public function setPageBanner ($bannerImage, $bannerTitle, $bannerLink, $bannerColor, $bannerDesc) {
			$this->bannerImage = $bannerImage;
			$this->bannerTitle = $bannerTitle;
			$this->bannerLink = $bannerLink;
			$this->bannerColor = $bannerColor;
			$this->bannerDesc = $bannerDesc;
		}

		// 設定OGImage
		public function setPageOGImage ($ogImage) {
			if (!empty($ogImage) && parent::image_exists($ogImage)) {
				if (preg_match("/^\/\//", $ogImage)) $ogImage = parent::getProtocol() . ":" . $ogImage;
				if (!preg_match("/^https?:\/\//", $ogImage)) $ogImage = parent::getProtocol() . "://" . $_SERVER["HTTP_HOST"] . $ogImage;
				return $ogImage;
			} else {
				return "";
			}
		}
	}
?>