<?php
// 太陽能專案設定
// 本系統的URL, 可能供信中連線使用
define("SYSTEM_NAME", "MES系統");
define("HOST_SYS_URL", "http://192.168.10.104/Waychein");
// 上傳檔起始目錄
define("UPLOAD_BASE_DIR", "/hsintungyang_upload");
if (!file_exists(UPLOAD_BASE_DIR)) {
	mkdir(UPLOAD_BASE_DIR, 0777, true);
}
ini_set('upload_max_filesize', '20M'); // 暫時設定檔案上傳大小
ini_set('post_max_size', '20M'); // 暫時設定 HTTP POST 請求的最大

define("Excel_Output_Path", "../../../hsintungyang_excel");
if (!file_exists(Excel_Output_Path)) {
	mkdir(Excel_Output_Path, 0777, true);
}

//資料庫連線設定
// $DataSource			=	"192.168.10.103";			//伺服器名稱 DESKTOP-GII8JNA\SQLEXPRESS
$DataSource			=	"127.0.0.1";			//伺服器名稱 DESKTOP-GII8JNA\SQLEXPRESS
$UserID				=	"sa";				//帳號
$Password			=	"1qaz@WSX";					//密碼
$DataBase_Trend		=	"HsinTungYang_Alarm";			//資料庫名稱
$DataBase_Alarm		=	"HsinTungYang_Alarm";			//資料庫名稱

$Socket_Host = "127.0.0.1";
$Socket_Port = "9001";



define("HTY_Server", "192.72.10.25");
define("HTY_Database", "HTY");
define("HTY_UserID", "sunware");
define("HTY_Password", "#EDC4rfv%TGB");

define("EMS_Server", "192.72.10.6");
define("EMS_Database", "EMS");
define("EMS_UserID", "sunware");
define("EMS_Password", "#EDC4rfv%TGB");

// 登入相關參數
define("_Login_Key", "4f1g23a12aa");
define("_Login_Count_Max", "10"); // 最大的 login user
define("_Login_Time_Minute_Max", "10"); // 遠端網頁未做定時通信 check 超過此時間表示自動 logout, 單位: 分鐘, 範圍 1-59分
define("_Login_Interval_Check", "10"); // 遠端網頁定時通信 check時間, 單位: sec
define("_Login_Interval_Check_msec", _Login_Interval_Check * 1000); // 轉成 msec
define("_Login_Auto_Logout_Interval", "525600"); // 遠端網頁超過此時間未操作自動 logout interval, 單位: sec
// 登出類型設置
define("_Logout_Normal_Mode", "1");   // 使用者, 手動登出
define("_Logout_TimeOut_Mode", "2");  // token超時, 自動登出
define("_Logout_Force_Mode", "3");    // 閒置超時, JS 自動登出
define("_Logout_Close_Mode", "4");    // 頁面關閉自動登出
define("_Logout_Unknow_Mode", "5");   // 非定義的登出
// 檢查Toekn
define("_Check_Login_Token", true);
// SMTP設置
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once 'PHPMailer/src/Exception.php';
require_once 'PHPMailer/src/PHPMailer.php';
require_once 'PHPMailer/src/SMTP.php';

define("_STMP_Host", "smtp.gmail.com");
define("_STMP_Port", 587);
define("_STMP_Secure", "tls");
define("_STMP_Auth", true);
define("_STMP_User", "sunware.sys@gmail.com");
define("_STMP_Password", "povdirrumagpyqnt");
define("_STMP_From", "sunware.sys@gmail.com");
define("_STMP_FromName", "三惟監控系統通知 (Sunware Monitor Notify");
// 允許低安全性應用程式
// https://www.google.com/settings/security/lesssecureapps

date_default_timezone_set("Asia/Taipei");
include_once "class.abs_class.inc";

function getBaseFile($filePath, $utf8 = false)
{
	$output = array();
	$file = fopen($filePath, 'r');
	while ($datas = fgetcsv($file)) {
		if ($utf8) {
			foreach ($datas as $k => $v)
				$datas[$k] = iconv('big5', 'UTF-8', $v); // 轉換編碼
		}
		$output[] = $datas;
	}
	fclose($file);

	return $output;
}

function getIniFile($filePath, $keyString = "*")
{
	$filePath = sprintf("%s.ini", $filePath);
	if (!is_file($filePath)) {
		return array();
	}

	if (is_string($keyString) && $keyString != "*") {
		$keys = explode(",", $keyString);
	}

	$ini = parse_ini_file($filePath, true);
	$output = $keyString == "*" ? $ini : array();
	if (isset($keys)) {
		foreach ($keys as $k) {
			if (strlen(trim($k)) && isset($ini[$k])) {
				$output[$k] = $ini[$k];
			}
		}
	}

	return $output;
}

function getDateRange($first, $last, $rtnEnd = false)
{
	$period = new DatePeriod(
		new DateTime($first),
		new DateInterval("P1D"),
		(new DateTime($last))->modify($rtnEnd ? "+1 day" : "+0 day")
	);

	foreach ($period as $date)
		$dates[] = $date->format("Y-m-d");

	return $dates;
}

function diePageAlert($msg)
{
	$json = array("method" => "FnAlert", "message" => $msg);
	$domain = sprintf("%s://%s:%d", $_SERVER["REQUEST_SCHEME"], $_SERVER["SERVER_NAME"], $_SERVER["SERVER_PORT"]);
	die('<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/></head><body>' . $msg . '</body><script>top.postMessage(\'' . json_encode($json) . '\', \'' . $domain . '\')</script></html>');
}


function sysSendEmail($to, $subject, $html_body = "", $cc = array(), $attachment = array())
{
	$mail = new PHPMailer();
	$mail->isSMTP();
	$mail->CharSet    = "UTF-8";
	// $mail->SMTPDebug  = 4;
	$mail->Host       = _STMP_Host;
	$mail->Port       = _STMP_Port;
	$mail->SMTPSecure = _STMP_Secure;
	$mail->Username   = _STMP_User;
	$mail->Password   = _STMP_Password;
	$mail->setFrom(_STMP_From, _STMP_FromName);
	$mail->isHTML(true);
	/*
	$mail->SMTPAutoTLS = false; 
	$mail->SMTPOptions = array(
		"ssl" => array(
			"verify_peer" => false,
			"verify_peer_name" => false,
			"allow_self_signed" => true
		)
	);
	*/
	if (_STMP_Auth == true) {
		$mail->SMTPAuth = true;
	}

	$mail->Subject = $subject;
	$mail->Body = $html_body . "<br><br><br>本信由系統發出, 請勿直接回信<br>(This message is sent by the system, please do not reply directly.)<br><br>" ;

	$hasFiles = false;
	foreach (array("to", "cc", "attachment") as $_arg) {
		if (!${$_arg}) {
			continue;
		} else if (!is_array(${$_arg})) {
			${$_arg} = array(${$_arg});
		}
		foreach (${$_arg} as $_m) {
			switch ($_arg) {
				case "cc":
					$mail->addCC($_m);
					break;
				case "attachment":
					if (is_file($_m)) {
						$zip = new ZipArchive();
						$filename = pathinfo($_m, PATHINFO_FILENAME) . ".zip";   //Zip File Name
						if ($zip->open($filename, ZipArchive::CREATE) === TRUE) {
							// file_put_contents("log/".date("Y-m-d")."_email_sender2.log", print_r($_m, true)."\r\n", FILE_APPEND);
							// $zip->setPassword($file_key);
							$zip->addFile($_m);
							// $zip->setEncryptionName(pathinfo($_m, PATHINFO_BASENAME), ZipArchive::EM_AES_256); //Encryption 
							$zip->close();
							// file_put_contents("log/".date("Y-m-d")."_email_sender2.log", print_r($filename, true)."\r\n", FILE_APPEND);
						}
						if (file_exists($filename)) {
							$hasFiles = true;
							$mail->addAttachment($filename);
						}
					}
					break;
				default:
					$mail->addAddress($_m);
			}
		}
	}
	if ($hasFiles) {
		$mail->Body .= "<br><br>請參閱附件 (Please refer to the attachment.)<br>";
	}
	// 發送
	$is_send = $mail->send() ? true : false;
	if (isset($filename) && file_exists($filename)) {
		@unlink($filename);
	}
	return array(
		"result" => $is_send,
		"data" => array(),
		"message" => !$is_send ? $mail->ErrorInfo : "Ok"
	);
}

// 將檔案目錄組合成路徑, 會判斷是否有 "/" 開頭及結尾
// usage:
// 	FilepathJoin("/upload","test"); // /upload/test
// 	FilepathJoin("/upload/","test","test.txt"); // /upload/test/test.txt
function FilepathJoin(...$paths)
{
	$separator = '/';
	$trimmed = array_map(function ($path) use ($separator) {
		return trim($path, $separator);
	}, $paths);
	$joined = implode($separator, $trimmed);

	// 如果傳入的第一個參數以斜線開頭，則在起點加上斜線
	if (!empty($joined) && strpos($paths[0], $separator) === 0) {
		$joined = $separator . $joined;
	}

	// 如果傳入的最後一個參數是空字串或以斜線結尾，則在終點加上斜線
	if (!empty($paths) && (empty(end($paths)) || substr(end($paths), -1) === $separator)) {
		$joined .= $separator;
	}

	return $joined;
}

// 產生GUID
function NewGUID()
{
	if (function_exists('com_create_guid')) {
		return com_create_guid();
	} else {
		mt_srand((float)microtime() * 10000);
		$charid = strtoupper(md5(uniqid(rand(), true)));
		$hyphen = chr(45);
		$uuid = substr($charid, 0, 8) . $hyphen
			. substr($charid, 8, 4) . $hyphen
			. substr($charid, 12, 4) . $hyphen
			. substr($charid, 16, 4) . $hyphen
			. substr($charid, 20, 12);
		return $uuid;
	}
}

// 輸出格式為 "YYYYMMDDHHmmss毫秒"
function CurrentTimeCompactFormat()
{
	return date("YmdHis") . sprintf("%04d", floor(microtime(true) * 1000) % 1000);
}
