<?php
namespace MyProject;
$CONFPATH = '/etc/upmpdcli.conf';
$MODULE = 'upmpdcli';
$MY_VER_UPNP=basename(__FILE__,"")." 1.0 (24.08.2025)";
/***************************************************************************************
	upmpdcli-qobuz Accunt Setting
	http://{Host}/mpdcliconf.php{?mpd=on}

	 mpd=on  : Load TaskServer I/F mpdweb Seriesとして動作
     引数なし: sudo Passwordを入力し動作 WebServer下のmpdを対象
               単独で動作する。他のLibraryを使用しない
	mpdweb Series : Libralyがあれば,mpdweb Series Check : ($G_MPDWEB_MODE=1)

	upmpdcli Qobuz Accunt Input/Update

	※AJAXでPost後表示までを簡単にできる方法を確認した。
***************************************************************************************/
/* -------------------------------------------------------------------------------------
	Post Process
---------------------------------------------------------------------------------------*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	 $G_MPDWEB_MODE = $_POST["MPDWEB_MODE"] ?? '';
	 }
else {
	 $G_MPDWEB_MODE=0;
	 }

/***************************************************************************************
	mpd TaskServer I/F
***************************************************************************************/
if(((isset($_GET["mpd"]))&&($_GET["mpd"]=="on"))||($G_MPDWEB_MODE==1)) {	// 引数?mpd=on || Post時:$G_MPDWEB_MODEを復元場合にTaskServer使用
	$require_ses=dirname(__FILE__).'/mpdcmnses.lib.php';				// Mpd Session id Library ※ mpdtask.if.lib.phpより先にrequireすること
	if  (file_exists($require_ses)) { 
		require_once($require_ses);										// Mpd mpdcmnses.lib.phpの存在確認&require
		if  (file_exists(dirname(__FILE__)."/mpdtask.if.lib.php")) {	// Mpd TaskServer i/fLibrary mpdtask.phpの存在確認
			$require_task=dirname(__FILE__)."/mpdtask.if.lib.php";
			ob_start();													// StanderdOutをセット
			require_once($require_task);								// Mpd XML Library mpd{module}.lib.php
			ob_end_clean();
			$SESSION_CONF=GetSessionConfig();							// mpdtask.if.lib.php:$XML_MPDLIBを判定する(GetEnvCommon経由)
			ArgSessionStart($SESSION_CONF);								// Start Session : Used mpdcmnses.lib.php
			$XML_CONF=NULL;
			if (GetEnvTaskCommon() ===false) { } else {					// mpdtask.if.lib.php mpdtask.xml Get&Edit
				$G_MPDWEB_MODE=1;
				}
			}
		}
	}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	if((isset($_POST['Action']))&&($_POST['Action']=="Restart")) {
		 PostRestart();								// upmpdcli restart
		 }
	else {											// upmpdcli.conf Update
		 PostUpdat();
		 }
	exit;
	}
/* -------------------------------------------------------------------------------------
	PostUpdat() : upmpdcli update

  ※preg_replace: 正規表現
	$configContent = preg_replace('/^\s*qobuzuser\s*=.*$/m','${1}qobuzuser = ' . $qobuzuser,$configContent,1);
	先頭から一致,qobuzuser = {Accunt} 1行対象にする
	$_$POST:upmpdcliの項目と同じ。Pass=$_$POST[confirmCode]
  ※shell 実行Form
	echo {su pass} | sudo -S sh -c 'ShellCommand'
	ShellCommand : cat {OutputString} | tee {OutputFilePath} > /dev/null
---------------------------------------------------------------------------------------*/
function PostUpdat() {
	global $CONFPATH,$MODULE,$G_MPDWEB_MODE;

	$matstr=array("0"=> '/^\s*#\s*{key}\s*=\s*([^\s]+)/m'	// "0":Comment行		// $matstr:正規表現Match
				 ,"1"=> '/^\s*{key}\s*=\s*([^\s]+)/m');		// "1":Live
	$repstr=array("0"=> '/^\s*#\s*{key}\s*=.*$/m'			// Key:$matstrに対応	// $repstr:正規表現Replase
				 ,"1"=> '/^\s*{key}\s*=.*$/m');

	$cmdstr="cat ".$CONFPATH."\n";								// Get upmpdcli.conf
	if ($G_MPDWEB_MODE==1) {
		 $trmstr="";
		 $result=GetCmdExec($cmdstr,$termstr);
		 }
	else {
		 exec($cmdstr,$result,$retval);
		 if ($retval===false) { $result=false; }
		 }
	if($result ===false) {
		print "Failed Get :".$CONFPATH."\n";
 		}
	$configContent = implode("\n",$result);
	foreach($_POST as $item => $val) {
		if(($item == 'confirmCode')||($item == 'MPDWEB_MODE')||($item == 'PHPSESSID')) {
			continue;
			}
		if($val =="") {									// Val(値)がない場合コメントにする
			$str=str_replace('{key}',$item,$matstr[1]);
			if (preg_match($str,$configContent,$matches)) {
				$repexp=str_replace('{key}',$item,$repstr[1]);
				$configContent = preg_replace($repexp,'${1}#${2}',$configContent);
				}
			continue;
			}
		$repexp="";
		foreach ($matstr as $key => $mat) {				// $matstr:"# qobazuser = "," qobazuser = "どちらと一致するかチェック
			$str=str_replace('{key}',$item,$mat);
			if (preg_match($str,$configContent,$matches)) {		// Comment→Liveの順に比較しLiveがあれば使用
				if(isset($matches[1])) {
					$repexp=str_replace('{key}',$item,$repstr[$key]);
					}
				}
			}
		if($repexp !=="") {								// 有効行1行置換する
			 $configContent = preg_replace($repexp,'${1}'.$item.' = '.$val,$configContent,1);
			 }
		else {											// Keyがない場合最後に行を追加
			 $configContent=rtrim($configContent)."\n$item=$val\n";
			 }
		}
	$cmdsudo="";										// mpdwebがない場合"sudo"を抑制している場合を想定
	if (((isset($_POST['confirmCode']))&&($_POST['confirmCode'] !==""))||($G_MPDWEB_MODE==1)) {
		$cmdsudo='echo %sudo-pw% | sudo -S ';
		if($G_MPDWEB_MODE !==1) {
			$cmdsudo=str_replace("%sudo-pw%",$_POST['confirmCode'],$cmdsudo);
			}
		}
	if($configContent==$readbuffer) {					// 変更がなければ終了
		print "No changes, so no updates";
		return;
		}
	if($cmdsudo !=="") {	// $G_MPDWEB_MODE:1はPassword必須	// Password=""の場合sudoを抑制しているとして以下sudo commandを実行しない
		$cmdstr=$cmdsudo."sh -c 'chmod 0666 ".$CONFPATH." && cp ".$CONFPATH." ".$CONFPATH.".bak'\n";
		if ($G_MPDWEB_MODE==1) {
			 $trmstr="";$retval=0;
			 $output=GetCmdExec($cmdstr,$termstr,true);
			 if ($output===false) { $retval=false; }
			 }
		else {
			 exec($cmdstr,$result,$retval);
			 }
		if ($retval === 0) { }
		else {
			 print "Failed ".$cmdstr."\n";
			 return;
			 }
		}
	if ($G_MPDWEB_MODE !==1) {										// $G_MPDWEB_MODE:1は必ずsuで動作している
		$perms = substr(sprintf('%o', fileperms($CONFPATH)), -4);	// 書き込み権限チェック
		$owner  = (int) $perms[1]; // 所有者
		$group  = (int) $perms[2]; // グループ
		$others = (int) $perms[3]; // その他
		if (($owner & 2) && ($group & 2) && ($others & 2)) { } else {
		   	print 'Check:'.$CONFPATH." No write permission　!!\n";
			return;
			}
		}
	// 入力内容書き込み : Webでsudo禁止している場合,sudoなしで行うのでshellでConf Faleに直書き込む
$cmdstr = <<<SHELL
cat << EOF | tee {$CONFPATH} > /dev/null
{$configContent}
EOF
SHELL;
	$cmdstr=$cmdsudo.$cmdstr."\n";
	if ($G_MPDWEB_MODE==1) {
		 $trmstr="";$retval=0;
		 $output=GetCmdExec($cmdstr,$termstr,true);
		 if ($output===false) { $retval=false; }
		 }
	else {
		 exec($cmdstr,$result,$retval);
		 }
	if ($retval === 0) {
		 print "Config [$CONFPATH] updated successfully!";
		 if($cmdsudo =="") {
			 print '<BR>sudo not run,'.$MODULE.' manually restart';
			 }
		 }
	else {
		 print "Failed to update config.";
		 }
	if($cmdsudo !=="") {				// $G_MPDWEB_MODE:1はPassword必須	
		$cmdstr=$cmdsudo."sh -c 'chmod 0644 ".$CONFPATH." && systemctl restart ".$MODULE."'\n";
		if ($G_MPDWEB_MODE==1) {
			 $trmstr="";$retval=0;
			 $output=GetCmdExec($cmdstr,$termstr,true);
			 if ($output===false) { $retval=false; }
			 }
		else {
			 exec($cmdstr,$result,$retval);
			 if ($retval === false) {
				 }
			 }
		}
	}

/* -------------------------------------------------------------------------------------
	PostRestart() : upmpdcli restart
Pass=$_$POST[confirmCode]
  ※shell 実行Form
	echo {su pass} | sudo -S sh -c 'ShellCommand'
	pass がないとき  sudo -S sh -c 'ShellCommand' で実行して見る
---------------------------------------------------------------------------------------*/
function PostRestart() {
	global $CONFPATH,$MODULE,$G_MPDWEB_MODE;

	$cmdsudo="";
	if (((isset($_POST['confirmCode']))&&($_POST['confirmCode'] !==""))||($G_MPDWEB_MODE==1)) {
		 $cmdsudo='echo %sudo-pw% | sudo -S ';
		 if($G_MPDWEB_MODE !==1) {
			 $cmdsudo=str_replace("%sudo-pw%",$_POST['confirmCode'],$cmdsudo);
			 }
		 }
	else {
		 $cmdsudo='sudo -S ';
		 }
	$cmdstr=$cmdsudo."sh -c 'systemctl restart ".$MODULE."'\n";
	if ($G_MPDWEB_MODE==1) {
		 $trmstr="";$retval=0;
		 $output=GetCmdExec($cmdstr,$termstr,true);
		 if ($output===false) { $retval=false; }
		 }
	else {
		 exec($cmdstr,$result,$retval);
		 if ($retval === 0) { } else {
			 print "mpdcliconf : Restart False,Abend\n";
			 return;
			 }
		 }
	print "mpdcliconf : Restart Upmpdcli End\n";
	}
/***************************************************************************************
	HTML Definition
***************************************************************************************/
?>
<!DOCTYPE html>
<html lang="ja"><link rel="shortcut icon" href="./mpdwebfavicon.ico"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" ><meta http-equiv="Expires" content="1000">
<meta id="idMeta" name="viewport" name="viewport" content="width=device-width,initial-scale=1.2,maximum-scale=1.7">
<script type="text/javascript">
/* View Port 設定 */
SCR_WIDTH=450;
var getDevice = (function(){
		var ua = navigator.userAgent;
		if(ua.indexOf('iPhone') > 0 || ua.indexOf('iPod') > 0 || ua.indexOf('Android') > 0 && ua.indexOf('Mobile') > 0){
			 return 'sp';
			 }
		else if(ua.indexOf('iPad') > 0 || ua.indexOf('Android') > 0){
			 return 'tab';
			 }
		else {
			 return 'other';
			 }
		})();
if(window.outerWidth==0) {										// window.outerWidthが0になるケースがある。(反則的な対応)
	window.outerWidth=window.innerWidth;
	}
if ((getDevice == 'sp' )||(getDevice == 'tab' )){
	 scale=Math.floor((window.outerWidth/SCR_WIDTH)*100)/100;	// 幅比率で表示(小数3位切り捨て)
	 var viewportContent="width=380,initial-scale="+String(scale)+",maximum-scale=1.7";
	 document.getElementById('idMeta').setAttribute('content',viewportContent);
	 }
</script>
<head>
    <title>UpMpdCli-Qobuz Config</title>
</head>
<body>
<style type="text/css">
body  { background-color:#000000;color:#ffffff;font-size:12px;overflow-x: hidden; }
form  { position:fixed;top:10px;left:20px; }
label { position:absolute;top:40px;left:10px; }
input { position:absolute;top:40px;left:140px; }
.formti { font-size:14px;color:#fffff0; }

.title  { position:absolute;top:68px;left:2px;font-size:13px; }
.notes  { position:absolute;top:232px;width:100px;left:334px;font-size:10px; }
.headfc { position:absolute;top:46px;left:22px;width:60px;cursor:pointer; }
.headRs { position:absolute;top:46px;left:350px;width:70px;height:20px;font-size:12px;border: 1px solid #2e8b57;background-color:#008000;color:#ffffff;cursor:pointer; }
.headRtx{ position:absolute;top:48px;left:294px;width:70px;font-size:11px;color:#66cdaa; }

.cf     { position:absolute;top:300px;left:10px;width:160px;color:#ffdab9; }
.submit { position:absolute;top:300px;left:260px;cursor:pointer; }

/* Modal Box Confirmation */
.Modal  { position:fixed;top:0;left:0;width:100%;height:100%;background-color:rgba(0,0,0,0.5);display:none; }
.boxcs { position:fixed;top:140px;left:260px;transform:translateX(-50%);width:90%;max-width:320px;height:130px;text-align:center;background:#282828;border-radius:6px;padding:20px; }
.boxti  { position:absolute;top:10px;left:20px;font-size:14px;color:#fffff0; }
.boxtyp { position:absolute;top:10px;left:156px;font-size:15px;color:#ffffff; }
.boxsb  { position:absolute;top:40px;left:20px;fontsize;9px;color:#ff69b4; }
.boxcf  { position:absolute;top:100px;left:40px;fontsize;9px;color:#ffdab9; }
.boxlb  { position:absolute;top:72px;left:20px; }
.boxin  { position:absolute;top:70px;left:140px; }
.boxok  { position:absolute;bottom:20px;left:40px;width:60px;cursor:pointer; }
.boxng  { position:absolute;bottom:20px;right:40px;width:60px;cursor:pointer; }
.boxtx  { position:absolute;top:66px;width:300px;text-align:center;font-size:16px;color:#7fffd4; }

.ver    { position:fixed;top:6px;left:300px;font-size:9px;color:#a9a9a9; }
.host   { position:fixed;top:20px;left:300px;font-size:9px;color:#ffffff; }
.status { position:fixed;top:340px;left:30px;margin-top:1em;color:#3cb371; }

/* Message Box */
.box {border: 1px solid #888888;position:fixed;top:200px;left:170px;
      width:300px;height:238px;font-size:14px;z-index:120;
      background-color:#2f2f2f;
      display: none;
      }
.boxtitle { position:absolute;top:0px;left:0px;width:100%;height:24px;font-size:14px;background-color:#00008b;color:#b0c4de;text-align:left;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;padding:8px 10px 2px; }
.buttn { position:absolute;left:10px;width:50px;height:14px;font-size:12px;line-height:110%;background-color:#a9a9a9;color:#000000;text-align:center;border-style:none;padding:3px 6 2px;-moz-border-radius:4px;-webkit-border-radius:4px;border-radius: 4px;border: 1px solid #696969;cursor:pointer; }
.buttn:active{ color:#808080; }

</style>
<?php
/*  ------------------------------------------------------------------------------------
	Main PHP Process (HTML:Body)
---------------------------------------------------------------------------------------*/
$friendlyname="";$mpdhost="";$mpdport="";$result="";
$qobuzuser="";$qobuzpass="";$qobuzformatid="";$ermsg="";
$cmdstr="cat ".$CONFPATH."\n";
if ($G_MPDWEB_MODE==1) {
	 $trmstr="";
	 $result=GetCmdExec($cmdstr,$termstr);
	 }
else {
	 exec($cmdstr,$result,$retval);
	 if ($retval===false) { $result=false; }
	 }
$configContent = implode("\n",$result);
if($configContent===false) {
	$ermsg=$CONFPATH.":does not exist";
	}
if (preg_match('/^\s*friendlyname\s*=\s*(.+)$/m', $configContent, $matches)) {
	if(isset($matches[1])) {
		$friendlyname = $matches[1];
		}
	}

if (preg_match('/^\s*mpdhost\s*=\s*([^\s]+)/m', $configContent, $matches)) {
	if(isset($matches[1])) {
		$mpdhost = $matches[1];
		}
	}
if (preg_match('/^\s*qobuzpass\s*=\s*([^\s]+)/m', $configContent, $matches)) {
	if(isset($matches[1])) {
		$qobuzpass = $matches[1];
		}
	}
if (preg_match('/^\s*mpdport\s*=\s*([^\s]+)/m', $configContent, $matches)) {
	if(isset($matches[1])) {
		$mpdport = $matches[1];
		}
	}

if (preg_match('/^\s*qobuzuser\s*=\s*([^\s]+)/m', $configContent, $matches)) {
	if(isset($matches[1])) {
		$qobuzuser = $matches[1];
		}
	}
if (preg_match('/^\s*qobuzpass\s*=\s*([^\s]+)/m', $configContent, $matches)) {
	if(isset($matches[1])) {
		$qobuzpass = $matches[1];
		}
	}
if (preg_match('/^\s*qobuzformatid\s*=\s*([^\s]+)/m', $configContent, $matches)) {
	if(isset($matches[1])) {
		$qobuzformatid = $matches[1];
		}
	}

/*
	Make HTML:Body
*/
$result="";
$cmdstr=$MODULE." -v\n";
if ($G_MPDWEB_MODE==1) {
	 $serverip=$XML_HOST["Host"];
	 if($serverip=="localhost") { $serverip=$_SERVER['SERVER_ADDR']; }
	 $trmstr="";$ret="";
	 $result=GetCmdExec($cmdstr,$termstr);
	 if ($result===false) { $ret=$retval; }
	 }
else {
	 $serverip=$_SERVER['SERVER_ADDR'];
	 exec($cmdstr,$result,$retval);
	 }
$upmpdcli_ver=implode($result);

$disabled="";
if($ermsg !=="") {
	$disabled="disabled";
	}

echo <<<EOM
<div class="ver">{$MY_VER_UPNP}</div>
<div class="host">config server:{$serverip}</div>
<div class="host" style="top:31px">{$upmpdcli_ver}</div>
<form id="idform"><!-- for/nameはupmpdcli.confと同じ名称にする -->
	<div class="formti"> upmpdcli-qobuz Accunt Setting</div><br>
	<div class="title">Renderer</div>
	<label for="friendlyname" style="top:92px;">FriendlyName</label>
	<input type="text" id="friendlyname" name="friendlyname" value="{$friendlyname}"  style="top:90px;"><br>
	<label for="mpdhost" style="top:122px;">mpd Host</label>
	<input type="mpdhost" id="mpdhost" name="mpdhost" value="{$mpdhost}" style="top:120px;"><br>
	<div class="notes" style="top:124px;">blank or localhost</div>
	<label for="mpdport" style="top:152px;">mpd Port</label>
	<input type="text" id="mpdport" name="mpdport" value="{$mpdport}" style="top:150px;"><br>
	<div class="notes" style="top:156px;">blank or 6600</div>
	<div class="title" style="top:176px;">upmpdcli-Qobuz</div>
	<label for="qobuzuser" style="top:202px;">Qobuz User</label>
	<input type="text" id="qobuzuser" name="qobuzuser" value="{$qobuzuser}"  style="top:200px;"><br>
	<label for="qobuzpass" style="top:232px;">Qobuz Password</label>
	<input type="password" id="qobuzpass" name="qobuzpass" value="{$qobuzpass}" style="top:230px;"><br>
	<label for="qobuzformatid" style="top:262px;">Qobuz Format ID</label>
	<input type="text" id="qobuzformatid" name="qobuzformatid" value="{$qobuzformatid}" style="top:260px;"><br>
	<div class="notes" style="top:265px;">MaxLevel:27</div>
	<div class="cf" style="">Blanks are comment lines</div>
	<button type="submit" {$disabled} class="submit">Update</button>
</form>
<button type="button" class="headfc" onclick="window.location.reload(true);">Renew</button>

<div class="headRtx" >{$MODULE}:</div>
<button type="button" id="idRestart" class="headRs">Restart</button>

EOM;
if($G_MPDWEB_MODE==1) {
echo <<<EOM
<div id="idConfirm" class="Modal">
  <div class="boxcs">
    <div class="boxti">Confirmation Box :</div>
	<div id="idType" class="boxtyp">update</div>
    <div class="boxtx">Are you sure you want to proceed ?</div>
	<input type="hidden" id="idCode" value="password" />
    <button id="idOkBtn" class="boxok">OK</button>
    <button id="idCancel" class="boxng">Cancel</button>
  </div>
</div>
EOM;
	 }
else {
echo <<<EOM
<div id="idConfirm" class="Modal">
  <div class="boxcs">
    <div class="boxti">Confirmation Box :</div>
	<div id="idType" class="boxtyp">update</div>
    <div class="boxsb">No password, no permissions, no backup!</div>
	<div class="boxlb" style="font-size:14px;">sudo password</div>
    <input type="text" id="idCode" class="boxin">
    <div class="boxcf">sudo permissions persist for a while</div>
    <button id="idOkBtn" class="boxok">OK</button>
    <button id="idCancel" class="boxng">Cancel</button>
  </div>
</div>
EOM;
	}

echo <<<EOM
<div id="message" class="status" style="">{$ermsg}</div><!-- Status Message Area -->


EOM;

\MyProject\DispMsgBox();			// MessageBox(Form)をDisplay:noneで作成しておく。

/***************************************************************************************
	JSP Process
***************************************************************************************/
$MODPOST=$_SERVER["SCRIPT_NAME"];
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$host     = $_SERVER['HTTP_HOST'];
$MYURL    = $_SERVER['REQUEST_URI'];

$current_url = $protocol . $host . $uri;
echo <<<EOM
<script>
const ObjForm = document.getElementById('idform');
const ObjConfirm = document.getElementById('idConfirm');
const ObjCode   = document.getElementById('idCode');
const ObjOkBtn  = document.getElementById('idOkBtn');
const ObjCancel = document.getElementById('idCancel');
const ObjType   = document.getElementById('idType');

const ObjRestart = document.getElementById('idRestart');

let PostForm = null;

/*  ------------------------------------------------------------------------------------
	EventListener
---------------------------------------------------------------------------------------*/
/*
	Main Form Update Botton EventListener
*/
ObjForm.addEventListener('submit', function(e) {
	e.preventDefault();
	PostForm = new FormData(this);
	const qobuzVal = PostForm.get('qobuzformatid');		// "qobuzformatid" の値を取得
	if (qobuzVal !== null && qobuzVal.trim() !== '') {	// 入力されていれば範囲チェックを行う
		const formatIdValue = parseInt(qobuzVal, 10);
		if (isNaN(formatIdValue) || formatIdValue < 1 || formatIdValue > 27) {
			RequestMsgBox('mpdcliconf Error Message','qobuzformatid must be specified<BR> in the range of 1 to 27.');
			return;
			}
		}
	if (ObjCode && ObjCode.type !== 'hidden') {
		ObjCode.value = '';
		}
	document.getElementById('message').textContent = "";
	ObjConfirm.style.display = 'block';					// モーダル表示
	ObjType.textContent = 'Update';						// ConfirmBox Type
	});

/*
	Main Form Restart Botton EventListener
*/
ObjRestart.addEventListener('click', function() {
	document.getElementById('message').textContent = "";
	ObjConfirm.style.display = 'block';					// モーダル表示
	ObjType.textContent = 'Restart';					// ConfirmBox Type
	});

/* -----------------------------------------------------------------------------
	ConfirmBox
----------------------------------------------------------------------------- */
/*
	ConfirmBox Cancel Botton EventListener
*/
ObjCancel.addEventListener('click', function() {
	ObjConfirm.style.display = 'none';
	PostForm = null;							// POST中止
	});

/*
	ConfirmBox OK Botton EventListener
*/
ObjOkBtn.addEventListener('click', function() {
	const code = ObjCode.value.trim();
	ObjConfirm.style.display = 'none';
	if (ObjType.textContent == 'Update') {
		 PostForm.append('confirmCode', code);				// POST 直前に確認コードを追加
		 PostForm.append('MPDWEB_MODE', '{$G_MPDWEB_MODE}');	// POST $G_MPDWEB_MODE:mpd=on
		 fetch('{$MODPOST}', {
			method: 'POST',
			body: PostForm
			})
		 .then(response => response.text())
		 .then(data => {
			document.getElementById('message').innerHTML = data;
			})
		 .catch(error => {
			document.getElementById('message').textContent = 'Error: ' + error;
			});
		 }
	else if (ObjType.textContent == 'Restart') {
		 const formData = new FormData();					// 送信データの準備（FormData オブジェクト）
		 formData.append('Action', 'Restart');
		 formData.append('MPDWEB_MODE', '{$G_MPDWEB_MODE}');
		 formData.append('confirmCode', code);				// POST 直前に確認コードを追加
		 fetch('{$MODPOST}', {
			method: 'POST',
			body: formData
			})
		 .then(response => response.text())
		 .then(data => {
			document.getElementById('message').innerHTML = data;
			})
		 .catch(error => {
			document.getElementById('message').textContent = 'Error: ' + error;
			});
		 }
	});

/* ----------------------------------------------------------------------------
	RequestMessageBox(title,str,top,left) : MessageBox (mpdweb標準モジュールにStringLength追加)
	 title: i  : Box Title
	 str  : i  : Message
----------------------------------------------------------------------------- */
function RequestMsgBox(title,str,top,left) {
	str=str.replace(/<BR>/g, "\\n");
	var ary=str.split("\\n");
	var leng=0;
	for (i = 0; i < ary.length; i++) {
		if (ary[i].length > leng) {
			leng=ary[i].length;
			}
		}
	if (leng > 50){
		  document.getElementById('idMsgBoxstr').style.fontSize = "9px";
		  document.getElementById('idMsgBoxstr').style.top = "36px";
		  document.getElementById('idMsgBoxstr').style.lineHeight = "130%";
		  }
	else {
		 document.getElementById('idMsgBoxstr').style.fontSize = "13px";
		 document.getElementById('idMsgBoxstr').style.top = "60px";
		 document.getElementById('idMsgBoxstr').style.lineHeight = "20px";
		 }
	if (title == null) { title="Message Box"; }
	if (top == null) { top=160; }
	document.getElementById('idMsgBox').style.display='block';
	document.getElementById('idMsgBox').style.top=top;
	if (left !== null) {
		document.getElementById('idMsgBox').style.left=left;
		}
	document.getElementById('idMsgBoxtitle').textContent=title;
	document.getElementById('idMsgBoxstr').textContent=str;
	}

</script>
EOM;
/*******************************************************************************
	mpdweb Series : $G_MPDWEB_MODE=1
	---------------------------------------------------------------------------
	GetCmdExec($cmd,$TermStr,$multi) : Server Shellを実行
	 $cmd    : i  : Excution Shell Command
	 $TermStr: io : Terminate Sting
	 $multi  : i  : Default:False ,False:LineExec ,True:一括実行,HereDocumentなど。
	                True :一括実行:Perl,HereDocumentなど実行できるが、占有する。
	                False:受信後、即実行
	 @return : o  : Array Shell
*******************************************************************************/
function GetCmdExec($cmd,&$TermStr="",$multi=false) {
	global $XML_HOST,$XML_SHELL;						// $XML_HOST:require module '/mpdtask.php'の設定を共有

	$errno="";$errstr="";
	$host="";$rhost="";
	$cmd=ArgMakeSvrCmd($cmd);
//	$cmd=str_replace("%sudo-pw%",$XML_SHELL["sudo-pw"],$cmd);			// Password SearchShellを使わない場合有効し,上Lineの // $cmd=ArgMakeSvrCmd($cmd);コメントアウト
	$TermStr=$XML_HOST["TermStr"];
	if (isset($_SERVER["REMOTE_ADDR"])) {
		$rhost=$_SERVER["REMOTE_ADDR"];
		}
	if (isset($_SERVER["HTTP_HOST"])) {
		$urlary = parse_url($_SERVER["HTTP_HOST"]);		// {host}:{88}
		if (isset($urlary["host"])) { $host=$urlary["host"]; }
		}
// Task Serverが HTTP Serverと同じ場合,Shellで求める
	$mount=0;$mode=0;
	if ($XML_HOST["Force"] == "off") {					// $XML_HOST["Force"]:on時常にTaskServer使用
		if (($XML_HOST["Host"]=="localhost")||($XML_HOST["Host"]=="127.0.0.1")||(($host !=="")&&($host==$XML_HOST["Host"]))||(($rhost !=="")&&($rhost==$XML_HOST["Host"]))) {
			 $mount=1;
			 }
		}
	if (($XML_HOST["Excludesu"] == "on")&&(strpos($cmd,"sudo") !== false)) {		// sudoはTaskServerで行う。exec:WebからパーミッションをChildProcessに継承するため
		$mount=0;
		}
//$mount=0;
	if ($mount==1) {
//		 print 'exec $cmd['.$cmd.']<BR>';
		 msglog('[mpdsetting][exec]['.$cmd.']');			// Used Debug
		 exec($cmd,$ret);
		 }
	else {
//		 print '$cmd['.$cmd.'] $XML_HOST["Host"]['.$XML_HOST["Host"].'] $XML_HOST["Port"]['.$XML_HOST["Port"].'] $XML_HOST["TermStr"]['.$XML_HOST["TermStr"].'] $mode['.$mode.'] $errno['.$errno.'] $errstr['.$errstr.']<BR>';
		 msglog('[mpdsetting][SockCmdsend]['.$cmd.']Host['.$XML_HOST["Host"].']Port"]['.$XML_HOST["Port"].']');			// Used Debug
		 $TermStr="\e";
		 $ret=SockCmdsend($XML_HOST["Accunt"],$cmd,$XML_HOST["Host"],$XML_HOST["Port"],$XML_HOST["Timeout"],$TermStr,$mode,$errno,$errstr,$multi);
		 }
//global $DEBUG;$save=$DEBUG;$DEBUG=2;msglog($cmd);$DEBUG=$save;
	return($ret);
	}
/* ----------------------------------------------------------------------------
	DispMsgBox() : Display MessageBox (Init)
----------------------------------------------------------------------------- */
function DispMsgBox() {
	$width=360;
	print '<div id=idMsgBox class="box" style="width:'.$width.'px;height:160px;position:fixed;top:200px;left:'.((480-$width)/2).'px;background-color:#f5f5f5;z-index:1000;display:none;">';
	print '<div id=idMsgBoxtitle class=boxtitle align=left style="width:'.($width-20).'px;cursor:pointer;"></div>';
	print '<div id=idMsgBoxstr align=center style="overflow:hidden;word-wrap: break-word;white-space: pre-wrap;text-overflow:ellipsis;width:'.($width-40).'px;height:100px;font-size:15px;position:absolute;top:60px;left:20px;line-height:20px;text-align:center;color:#000000;"></div>';
	print '<input type="button" name="Submit" class="buttn" value="OK" onclick="document.getElementById(\'idMsgBox\').style.display=\'none\';" style="position:absolute;top:120px;left:'.(($width/2)-20).'px;font-size:12px;width:60px;height:24px;" />';
	print '</div>';
	}
//----- Source End --------------------------------------------------------------
?>
</body>
</html>
