<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<?php
	
    function rootDir(){
        // $rootDir = "../../" のような指定方法では認識されず "" になってしまう
        //return "../../"; // /X/NOA の場合
        return "../"; // /NOA の場合
    }
    
    function decodeSTRING($val){
        // #, &, +  < > などが URI 送信で化けるため encode して送られたものを decode
        $array = explode("%x0;", $val);
        $val = implode("#", $array);
        $array = explode("%x1;", $val);
        $val = implode("&", $array);
        $array = explode("%x2;", $val);
        $val = implode("+", $array);
        $array = explode("%x3;", $val);
        $val = implode("<", $array);
        $array = explode("%x4;", $val);
        $val = implode(">", $array);
        $array = explode("%x5;", $val);
        $val = implode(" ", $array);
        $array = explode("%x6;", $val);
        $val = implode("\n", $array);
        $array = explode("%x7;", $val);
        $val = implode("\"", $array);
        $array = explode("%x8;", $val);
        $val = implode("$", $array);
        $array = explode("%x9;", $val);
        $val = implode("\'", $array);
        return $val;
    }
	
function leftBrackets(){
	// $leftBrackets = "\^\[\^" では誤作動
	return "^[^"; // encode 中で使う '(' -- クライアント側との約束 lib.js
}
function rightBrackets(){
	return "^]^"; // encode 中で使う '(' -- クライアント側との約束 lib.js
}

function decodeObject($buff){
	// "key(value)" 形式の文字列を OBJECT に decode して返す
	$obj = array();
	//	echo "decodeObject ===\n$buff\n"; //##
	for ($p=$begin=$nest=0, $len=strlen($buff); $p < $len; $p++){
		$ch = substr($buff, $p, 1);
		if (strcmp($ch, "(") == 0){
			if ($nest == 0){
				$key = trim(substr($buff, $begin, $p - $begin)); // key 終端
				$begin = $p + 1; // value 開始位置
			}
			$nest++;
		} else if (strcmp($ch, ")") == 0){
			if (--$nest == 0){
				if ($nest == 0){
					// value 終端 ( trim しない )
					$value = substr($buff,$begin,$p-$begin);
					$begin = $p + 1; // key 開始位置
				}
				if (ereg(")", $value)){ // まだ入れ子になっているなら
					$obj[$key] = decodeObject($value);
				} else {
					// 特定文字を "(", ")" へ戻す
					$array = explode(leftBrackets(), $value);
					$value = join("(", $array);
					$array = explode(rightBrackets(), $value);
					$value = join(")", $array);
					
					$obj[$key] = $value;
				}
				//echo "$key{".$obj[$key]."}\n"; //##
			}
		}
	}
	return $obj;
}
	
	
function hasTable($_dbname, $_tablename)
{
	// $db_name 中に $_tablename があれば 1 を、なければ 0 を返す
	$result = mysql_list_tables ($_dbname);
	$i = 0;
	while ($i < mysql_num_rows ($result)) {
		$tb_names[$i] = mysql_tablename ($result, $i);
		if ($tb_names[$i]==$_tablename) return 1;
		$i++;
	}
	return 0;
}

function honin($groupCode, $insFee){
	return ($groupCode == 0) ? $insFee : 0;
}
function kazoku($groupCode, $insFee){
	return ($groupCode == 1) ? $insFee : 0;
}
function kokuho($groupCode, $insFee){
	return ($groupCode == 2) ? $insFee : 0;
}
function calcSum($array, $row){
	if (! $array){
		$array = array();
	}
	$unpaid = 0;
	// $row['mishuu'] は "2009-01-30 19:16:00,3650" のような形式
	$mishuu = $row['mishuu'];
	if ($mishuu && (strlen($mishuu) > 0)){
		$ary = explode(",", $mishuu);
		if (count($ary) > 1){
			$unpaid = $ary[1] * 1;
		}
	}
	
	$array[0] = $array[0] + 1;
	$array[1] = substr($row['entryDate'], 0, 10);
	$array[2] += honin($row['groupCode'], $row['insFee']);
	$array[3] += kazoku($row['groupCode'], $row['insFee']);
	$array[4] += kokuho($row['groupCode'], $row['insFee']);
	$array[5] += $row['ownFee'];
	$array[6] += $unpaid;
	$array[7] += $row['receive'];
	$array[8] += (strlen($row['inOut'])) ? 1 : 0;
	$array[9] += $row['newPatient'];
	$array[10] += $row['point'];
	
	return $array;
}

function getKanjiName($pid){
	$sql = "SELECT `patientKanjiName` FROM `NameSection`
		WHERE `patientId`='$pid' ORDER BY `entryDate` DESC";
	echo "$sql ------------ \n"; //###
	$result=mysql_query($sql);
	while ($row = mysql_fetch_array($result)){
		$kanjiName = $row['patientKanjiName'];
		if (strlen($kanjiName) > 0)
			return $kanjiName;
	}
	return "";
}
	
function getAnotherId($pid){
	$sql = "SELECT `anotherId` FROM `PatientTable`
	WHERE `patientId`='$pid'";
	echo "$sql ------------ \n"; //###
	$result=mysql_query($sql);
	while ($row = mysql_fetch_array($result)){
		$anotherId = $row['anotherId'];
		if (strlen($anotherId) > 0)
			return $anotherId;
	}
	return "";
}

function getPlan($patientId, $entryDate){
	// 前回受診時の plan を返す
	$sql = "SELECT `plan` FROM `FrontTable`
	WHERE `patientId`='$patientId' AND `entryDate`<'$entryDate'
	ORDER BY `entryDate` DESC";
	echo "$sql ------------ \n"; //###
	$result=mysql_query($sql);
	while ($row = mysql_fetch_array($result)){
		return $row['plan'];
	}
	return "";
}
	
function getLastMishuu($pid){
	// PatientTable に記録された未収金を返す
	$sql = "SELECT `unpaid` FROM `PatientTable` WHERE `patientId`='$pid'";
	echo "$sql ------------ \n"; //###
	$result=mysql_query($sql);
	$row = mysql_fetch_array($result);
	return $row['unpaid'];
}
	
function putUnpaid($patientId, $unpaid){
	// 未収金を PatientTable に記録
	// $unpaid : "2009-01-30 19:16:00,3650" 形式
	$timestamp = date("Y-m-d H:i:s",time());
	$sql = "UPDATE `PatientTable`
	SET `unpaid`='$unpaid',`updateTime`='$timestamp'
	WHERE `patientId`='$patientId'";
	echo "$sql ------------ \n"; //###
	$result=mysql_query($sql);
}
	
function hasPatientTable($patientId){
	// この患者が PatientTable に登録されているかどうかを返す
	// PatientRegister がアクセスした PatientTable の更新データをピックアップできない
	$sql = "SELECT * FROM `PatientTable` WHERE `patientId`='$patientId'";
	$result=mysql_query($sql);
	return (mysql_num_rows($result) > 0) ? 1 : 0;
}

function hasPatient($patientId, $entryDate){
	// この患者が登録されているかどうかを返す
	// FrontTable の中で $entryDate に登録されているかどうかを返す
	$date = substr($entryDate, 0, 10);
	$sql = "SELECT * FROM `FrontTable`
	WHERE `patientId`='$patientId' AND `entryDate` like '$date%'";
	echo "$sql --- \n"; //###
	$result=mysql_query($sql);
	if (mysql_num_rows($result) > 0){
		$row=mysql_fetch_array($result);
		if ($row['entryDate'] > $row['updateTime']){
			// 過去に予約されていた場合は entryDate を実際の受付時刻に変更
			$timestamp = date("Y-m-d H:i:s",time());
			$row_id = $row['rowid'];
			$sql = "UPDATE `FrontTable`
			SET `entryDate`='$entryDate',`updateTime`='$timestamp'
			WHERE `rowid`='$row_id'";
			echo "$sql --- \n"; //###
			echo "予約を本登録に変更しました ------------ \n"; //###
			$result=mysql_query($sql);
		}
		return TRUE;
	}
	return FALSE;
}
	
function putTimeStamp(){
	// データ更新にともなうタイムスタンプを更新する
	$timestamp = date("Y-m-d H:i:s",time());
	$sql = "SELECT `rowid` FROM `FrontTable` WHERE `patientId`='STAMP'";
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){	// STAMP が存在した
		$row=mysql_fetch_array($result);
		// entryDate を timeStamp として更新
		$sql = "UPDATE `FrontTable` SET `updateTime`='$timestamp' WHERE `patientId`='STAMP'";
	} else {							// STAMP が存在しなかった
		$sql = "INSERT INTO `FrontTable` (`patientId`,`updateTime` ) VALUES ('STAMP','$timestamp')";
	}
	mysql_query($sql);
}
function getTimeStamp($apps, $entryDate){
	// タイムスタンプと同じものがあれば "same" なければ、旧スタンプを返す
	// $apps はサーバにリクエストを送ったアプリケーション
	$sql = "SELECT * FROM `FrontTable` WHERE `patientId`='STAMP'";
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){	// タイムスタンプが存在した
		$row=mysql_fetch_array($result);
		$updateTime = $row['updateTime'];
		$from = $row['owner']; // メッセージの送付元
		$to = $row['anotherId']; // メッセージの送付先
		$message = $row['plan']; // FRONT へのメッセージ
		$sender = $row['kanjiName']; // FRONT へのメッセージ
		$receiver = $row['mishuu']; // FRONT へのメッセージ
		//	$receive = $row['receive']; // 値が 1 なら FRONT へメッセージを表示
		
		// タイムスタンプが同じなら "same" を返す
		if ($updateTime == $entryDate) 
			return "same";
		else if ($receiver == $apps) // メッセージ・パネルを表示
			return "$updateTime^$from^$to^$sender^$receiver^$message";
		else // FRONT を再描画
			return $updateTime;
	} else { // タイムスタンプが存在しなかった
		return "empty";
	}
}
	
function getSortOrder($owner){
	// Messenger に表示する受付時刻のソート順を返す
	$sql = "SELECT * FROM `FrontTable` WHERE `patientId`='MESSENGER_ORDER' AND `owner`='$owner'";
	$result=mysql_query($sql);
	echo "$sql \n\n"; //##
	if (mysql_num_rows ($result) > 0){	// MESSENGER_ORDER が存在した
		$row=mysql_fetch_array($result);
		return $row['inOut']; // "1" なら降順ソート "0" なら昇順ソート
	} else { // MESSENGER_ORDER が存在しなかった
		return "0";
	}
}	
	
function messagesToFront(){
	// Messenger 用の message list を返す
	$sql = "SELECT * FROM `MenuTable`
	WHERE `tag`='MESSAGE_NOA_TO_FRONT' ORDER BY `freq`";
	echo "$sql \n"; //##
	$array = array();
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){
		while ($row=mysql_fetch_array($result)){
			$rec = array();
			$rec['menu'] = $row['menu'];
			$rec['freq'] = $row['freq'];
			$array[$row['menu']] = $rec;
		}
	}
	return $array;
}
	
function getUser($loginName){
	$sql = "SELECT * FROM `UserTable` WHERE `loginName`='$loginName'";
	echo "===== getUser\n $sql \n";
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){
		for ($i=0; $row=mysql_fetch_assoc($result); $i++){ // 連想配列で取り出す
			if (strcmp($row['loginName'], $loginName) == 0){
				/*
				 $array = array();
				 $array['kanjiName'] = $row['kanjiName'];
				 $array['identifier'] = $row['identifier'];
				 $array['hospitalId'] = $row['hospitalId'];
				 */
				return $row;
			}
		}
	}
	return null;
}
	
    function isInTime($datetime, $fromTime, $toTime){
        // $datetime が $fromTime,$toTime の間にあれば TRUE を返す
        if (strlen($fromTime) == 0) return TRUE;
        if (strlen($toTime) == 0) return TRUE;
        
        $time = substr($datetime, 11, 8);
        if ($time < $fromTime) return FALSE;
        if ($toTime < $time) return FALSE;
        
        return TRUE;
    }

    function timestamp(){
        // 現在のタイムスタンプを返す updateTime に使う
        date_default_timezone_set("Asia/Tokyo");
        return date("Y-m-d H:i:s",time());
    }

    function archiveDir($owner){
        // $dir が無ければ作成
        $dir = rootDir()."NOA_ARCHIVE";
        if (! file_exists($dir)){
            // $dir が無ければ作成
            echo "($dir) is not exist, so I'll make directory. \n"; //##
            mkdir($dir);
        }
        $userDir = rootDir()."Users/$owner";
        if (! file_exists($userDir)){
            // $dir が無ければ作成
            echo "($dir) is not exist, so I'll make directory. \n"; //##
            mkdir($userDir);
        }
        $dir = "$userDir/FRONT_LAYOUT";
        if (! file_exists($dir)){
            // $dir が無ければ作成
            echo "($dir) is not exist, so I'll make directory. \n"; //##
            mkdir($dir);
        }
        
        return $dir;
    }

    function getDir($dir){
        // $dir 内のファイルをリストアップ
        // ##### $dir は HTTP ではなく FILE-SYSTEM の PATH を示す #####
        $files = scandir($dir, 1); // 逆順にソート
        $count=count($files);
        echo "dir($dir) count($count)\n";
        
        for ($i=0; $i < $count; $i++){
            $filename = $files[$i];
            echo "-- ($filename)\n"; //###
            if ($filename == ".") continue;
            if ($filename == "..") continue;
            if (strlen($filename) == 0) continue;
            echo "-- file ($filename)\n"; //###
            
            $array[] = $filename;
        }
        
        $results = array();
        $results['path'] = $dir;
		$results['files'] = $array;
        
        return $results;
    }
    
    function save($owner, $filename, $buff){
        $dir = archiveDir($owner);
        $path = "$dir/$filename";
        
        if (!$handle = fopen($path, 'w')) {
            // $filenameを書き出しモードでオープン
            echo "Cannot open file ($path)";
            return FALSE;
        }
        
        if (fwrite($handle, $buff) === FALSE) {
            // オープンしたファイルに$buffを書き込む
            echo "Cannot write to file ($path)";
            return FALSE;
        } else {
            echo "Saved $patientId to file ($path)";
            fclose($handle);
            return TRUE;
        }
    }
	
    function insScanDate($patientId){
        // patientId の保険証を最後にスキャンした日付を返す
        $results = array();
        $array = array();
        $dir = rootDir()."NOA_ARCHIVE/$patientId/Insurance";
        $files = scandir($dir);
        for ($i=0,$count=count($files); $i < $count; $i++){
            $filename = $files[$i];
            if ($filename == ".") continue;
            if ($filename == "..") continue;
            
            // 行頭に "_" のついた削除済みファイルは無視
            if (substr($filename, 0, 1) == "_") continue;
            
            if (strlen($filename) == 0) continue;
            $array[] = $filename; // filename="03234202_20120113165123.JPG" 形式
        }
        rsort($array); // 逆順にソート
        $results['path'] = $dir;
		$results['filename'] = $array[0]; // 直近のファイル名
        return $results;
    }
    
    function getMessage(){
        // メッセージの入ったレコードをサーチ
        $sql = "SELECT * FROM `FrontTable` WHERE `patientId`='MESSAGE'";
        $result=mysql_query($sql);
        
        echo "GET_MESSAGE:\n"; //##
        $records = array();
        while ($row=mysql_fetch_array($result)){
            $rec = array();
            $rec['sender'] = $row['owner'];
            $rec['receiver'] = $row['mishuu'];
            $rec['message'] = $row['plan'];
            $rec['docId'] = $row['rowid'];
            $rec['updateTime'] = $row['updateTime'];
            $records[] = $rec;
            
            echo $row['plan']."\n"; //##
        }
        return $records;
    }
	
    function newFieldObj(){
        // 新規フィールド・オブジェクトを生成
        $obj = array();
        $obj['flag'] = FALSE;
        return $obj;
    }
    function pickupValue($obj, $row, $fieldName){
        // $obj が空 で $row に値が入っているなら　$obj に値を入れて返す
        // ($row[$fieldName] != NULL) にしないと値が 0 の場合も無視されてしまう
        if (!$obj['flag'] && ($row[$fieldName] != NULL)){
            $obj['val'] = $row[$fieldName];
            $obj['update'] = $row['updateTime'];
            $obj['flag'] = TRUE;
        }
        return $obj;
    }
    
    function getProgressSection($dateTime, $patientId){
        // ProgressSection の全てのレコードを返す
        $sql = "SELECT * FROM `ProgressSection` WHERE `patientId`='$patientId' AND `entryDate`<'$dateTime' AND (`freq` IS NULL OR `freq`<1) ORDER BY `entryDate` DESC";
        echo "getProgressSection -> $sql \n"; //###
        $result=mysql_query($sql);
        
        $subject = newFieldObj();
        $disease = newFieldObj();
        $examination = newFieldObj();
        $prescription = newFieldObj();
        $treatment = newFieldObj();
        while ($row = mysql_fetch_array($result)){
            $subject = pickupValue($subject, $row, 'subject');
            $disease = pickupValue($disease, $row, 'disease');
            $examination = pickupValue($examination, $row, 'examination');
            $prescription = pickupValue($prescription, $row, 'prescription');
            $treatment = pickupValue($treatment, $row, 'treatment');
            
            if ($subject['flag'] && $examination['flag'] && $prescription['flag'] && $disease['flag'] && $treatment['flag']) break;
        }
        $records = array();
        // $records['ProgressSection.subject'] = $subject;
        $records['ProgressSection.disease'] = $disease;
        $records['ProgressSection.examination'] = $examination;
        $records['ProgressSection.prescription'] = $prescription;
        $records['ProgressSection.treatment'] = $treatment;
        return $records;
    }
    function getHealthInsurance($dateTime, $patientId){
        // HealthInsurance の全てのレコードを返す
        $sql = "SELECT * FROM `HealthInsurance` WHERE `patientId`='$patientId' AND `entryDate`<='$dateTime' AND (`freq` IS NULL OR `freq`<1) ORDER BY `entryDate` DESC, `updateTime` DESC";
        echo "$sql \n"; //###
        $result=mysql_query($sql);
        
        $ownerName = newFieldObj();
        $ownerNumber = newFieldObj();
        $ownerPhone = newFieldObj();
        $shubetsu = newFieldObj();
        $kubun = newFieldObj();
        $kigou = newFieldObj();
        $bangou = newFieldObj();
        $continuedDiseases = newFieldObj();
        $paymentRatio = newFieldObj();
        $discountRatio = newFieldObj();
        $confirmation = newFieldObj();
        $startDate = newFieldObj();
        $expiredDate = newFieldObj();
        while ($row=mysql_fetch_array($result)){
            $ownerName = pickupValue($ownerName, $row, 'ownerName');
            $ownerNumber = pickupValue($ownerNumber, $row, 'ownerNumber');
            $ownerPhone = pickupValue($ownerPhone, $row, 'ownerPhone');
            $shubetsu = pickupValue($shubetsu, $row, 'shubetsu');
            $kubun = pickupValue($kubun, $row, 'kubun');
            $kigou = pickupValue($kigou, $row, 'kigou');
            $bangou = pickupValue($bangou, $row, 'bangou');
            $continuedDiseases = pickupValue($continuedDiseases, $row, 'continuedDiseases');
            $paymentRatio = pickupValue($paymentRatio, $row, 'paymentRatio');
            $discountRatio = pickupValue($discountRatio, $row, 'discountRatio');
            $confirmation = pickupValue($confirmation, $row, 'confirmation');
            $startDate = pickupValue($startDate, $row, 'startDate');
            $expiredDate = pickupValue($expiredDate, $row, 'expiredDate');
            
            if ($ownerName['flag'] && $ownerNumber['flag'] && $ownerPhone['flag'] && $shubetsu['flag'] && $kubun['flag'] && $kigou['flag'] && $bangou['flag'] && $continuedDiseases['flag'] && $paymentRatio['flag'] && $discountRatio['flag'] && $confirmation['flag'] && $startDate['flag'] && $expiredDate['flag']) break;
        }
        $records = array();
        $records['HealthInsurance.ownerName'] = $ownerName;
        $records['HealthInsurance.ownerNumber'] = $ownerNumber;
        // $records['HealthInsurance.ownerPhone'] = $ownerPhone;
        $records['HealthInsurance.shubetsu'] = $shubetsu;
        $records['HealthInsurance.kubun'] = $kubun;
        $records['HealthInsurance.paymentRatio'] = $paymentRatio;
        $records['HealthInsurance.kigou'] = $kigou;
        $records['HealthInsurance.bangou'] = $bangou;
        // $records['HealthInsurance.continuedDiseases'] = $continuedDiseases;
        // $records['HealthInsurance.discountRatio'] = $discountRatio;
        $records['HealthInsurance.confirmation'] = $confirmation;
        $records['HealthInsurance.startDate'] = $startDate;
        $records['HealthInsurance.expiredDate'] = $expiredDate;
        return $records;
    }
    function getPublicInsurance($dateTime, $patientId){
        // PublicInsurance の全てのレコードを返す
        $sql = "SELECT * FROM `PublicInsurance` WHERE `patientId`='$patientId' AND `entryDate`<='$dateTime' AND (`freq` IS NULL OR `freq`<1) ORDER BY `entryDate` DESC, `updateTime` DESC";
        echo "$sql \n"; //###
        $result=mysql_query($sql);
        
        $ownerName = newFieldObj();
        $ownerNumber = newFieldObj();
        $recipientNumber = newFieldObj();
        $shubetsu = newFieldObj();
        $paymentRatio = newFieldObj();
        $payment = newFieldObj();
        $startDate = newFieldObj();
        $expiredDate = newFieldObj();
        while ($row=mysql_fetch_array($result)){
            $ownerName = pickupValue($ownerName, $row, 'ownerName');
            $ownerNumber = pickupValue($ownerNumber, $row, 'ownerNumber');
            $recipientNumber = pickupValue($recipientNumber, $row, 'recipientNumber');
            $shubetsu = pickupValue($shubetsu, $row, 'shubetsu');
            $paymentRatio = pickupValue($paymentRatio, $row, 'paymentRatio');
            $payment = pickupValue($payment, $row, 'payment');
            $startDate = pickupValue($startDate, $row, 'startDate');
            $expiredDate = pickupValue($expiredDate, $row, 'expiredDate');
            
            if ($ownerName['flag'] && $ownerNumber['flag'] && $recipientNumber['flag'] && $shubetsu['flag'] && $paymentRatio['flag'] && $payment['flag'] && $startDate['flag'] && $expiredDate['flag']) break;
        }
        $records = array();
        $records['PublicInsurance.ownerName'] = $ownerName;
        $records['PublicInsurance.ownerNumber'] = $ownerNumber;
        $records['PublicInsurance.recipientNumber'] = $recipientNumber;
        $records['PublicInsurance.shubetsu'] = $shubetsu;
        $records['PublicInsurance.paymentRatio'] = $paymentRatio;
        // $records['PublicInsurance.payment'] = $payment;
        $records['PublicInsurance.startDate'] = $startDate;
        $records['PublicInsurance.expiredDate'] = $expiredDate;
        return $records;
    }
    
    function postItColor($patientId, $entryDate){
        // $entryDate 以前の $patientId の postIt があればその色を返す
        
        // entryDate の比較はタイミングによりうまくいかないことがあるので
        // 同日のタイムスタンプならすべて含めることとする
        $st = substr($entryDate, 0, 10);
        $dateTime = "$st 24:00:00";
        
        $sql = "SELECT * FROM `FrontTable` WHERE `patientId`='$patientId' AND `entryDate`<'$dateTime' ORDER BY `entryDate` DESC";
        echo "===\n $sql \n";
        $result=mysql_query($sql);
        
        $frowId = NULL;
        if ($row=mysql_fetch_array($result)){
            $frowId = $row['rowid']; // FrontTable で見つけた行の id
            if ($row['postIt']){
                return ($row['postIt']); // ### postIt 設定されていればここで抜ける ###
            }
        }
        
        // FrontTable の postIt が NULL なら
        $sql = "SELECT * FROM `UniversalSection` WHERE `patientId`='$patientId' AND `field`='postit' AND `entryDate`<'$dateTime' ORDER BY `entryDate` DESC";
        echo "===\n $sql \n";
        $result=mysql_query($sql);
        
        if ($row=mysql_fetch_array($result)){
            $type = $row['type'];
            if ($type == NULL) 
                $colorNum = NULL; // 付箋が無かった
            else if ($type * 1 > 0) 
                $colorNum = -1; // 付箋削除マークがあった
            else {
                $colorNum = $row['dataObject'];
                if (!$colorNum) $colorNum = 0; // postIt の color が入っている
            }
        } else {
            $colorNum = NULL; // 付箋が無かった
        }
        
        if ($frowId){
            // FrontTable の postIt フィールドに UniversalSection から得た値をセットし 
            // 次からは UniversalSectoin 検索をしないですむようにする
            // postIt に NULL を入れると、postIt 未設定と判定されてしまうので -2 を入れる
            if ($colorNum === NULL) $colorNum = -2; // 付箋を持たない場合
            $sql = "UPDATE `FrontTable` SET `postIt`='$colorNum' WHERE `rowid`='$frowId'";
            echo "===\n $sql \n";
            mysql_query($sql);
        }
        
        return $colorNum; // postIt が無かった
    }
    


	
    $command=$_GET['command']; $command=htmlspecialchars($command);
    $patientId=$_GET['patientId']; $patientId=htmlspecialchars($patientId);
    $entryDate=$_GET['entryDate']; $entryDate=htmlspecialchars($entryDate);
    $entryDate = decodeSTRING($entryDate);
    $owner=$_GET['owner']; $owner=htmlspecialchars($owner);
    $value=$_GET['value']; $value=htmlspecialchars($value);
    $value = decodeSTRING($value); // lib.php
    
// DB を開く
// ### セキュリティーを保つには、以下のファイルを外からアクセスできない 
// ### directory に置き、以下の cfg.php の pass をそこへ変更
require_once('../NOA/cfg.php');

$dbc = mysql_connect($db['host'], $db['user'], $db['pwd']);
$db_select=mysql_select_db($db['dbname']);
mysql_query("set names utf8");

    if (strcmp($command,"REMOVE_PATIENT") == 0){
        $args = decodeObject($value);
        $entryDate = $args['entryDate'];
        $patientId = $args['patientId'];

        putTimeStamp(); // タイムスタンプを更新
		
        $sql = "DELETE FROM `FrontTable`
        WHERE `entryDate`='$entryDate' AND `patientId`='$patientId'";
        mysql_query($sql);
        echo "$sql\n";
        
        // 変更結果を返す
        echo "<SEPARATOR>";
        echo "削除しました";
    } else if (strcmp($command,"PUT_PATIENT") == 0){
        // 本日の受診者を FrontTable へ登録
        // 前回受診時の plan を本日へコピー
        $args = decodeObject($value);
        $owner = $args['owner'];
        $patientId = $args['patientId'];
        $kanjiName = $args['kanjiName'];
        $entryDate = $args['entryDate'];
        $userCode = $args['userCode'];
        $groupCode = $args['groupCode'];
        $inOut = $args['inOut'];
        $newPatient = $args['newPatient'];
        $insFee = $args['insFee'];
        $ownFee = $args['ownFee'];
        $receive = $args['receive'];
        $mishuu = $args['mishuu'];
        $regist_mode = $args['duplicate'];
        
        putTimeStamp(); // タイムスタンプを更新
        
        $answer = array();
        if (hasPatientTable($patientId) == 0){
            // patientTable に登録されていない患者は FRONT に登録できない
            echo "<SEPARATOR>";
            $answer['mode'] = "0";
            $answer['message'] = "$patientId は未登録です";
            echo json_encode($answer);
            return;
        }
        
        if (strlen($regist_mode) && hasPatient($patientId, $entryDate)){
            // すでに当日受診歴があれば重複登録しない
            $date = substr($entryDate, 0, 10);
            echo "<SEPARATOR>";
            $answer['mode'] = "1";
            $answer['message'] = "$date: $patientId は既に登録済みです";
            $answer['patientId'] = $patientId;
            $answer['entryDate'] = $entryDate;
            echo json_encode($answer);
            return;
        }
        
        if (strlen($kanjiName) == 0){ // 漢字名を NameSection から補完する
            $kanjiName = getKanjiName($patientId);
        }
        
        $anotherId = getAnotherId($patientId);
        
        if (strlen($mishuu) == 0){
            // $mishuu は "2009-01-30 19:16:00,3650" 形式
            $mishuu = getLastMishuu($patientId);
        }
        
        // 前回受診時の plan を得る
        $plan = getPlan($patientId, $entryDate);
        
        $now = timeStamp();
        $sql = "SELECT `rowid` FROM `FrontTable`
		WHERE `patientId`='$patientId' AND `entryDate`='$entryDate'";
        $result=mysql_query($sql);
        if (mysql_num_rows ($result) > 0){	// 同じ patientId と受付時刻 が存在した
            $row=mysql_fetch_array($result);
            $rowid = $row['rowid'];
            $sql = "UPDATE `FrontTable` SET
			`kanjiName`='$kanjiName',
			`groupCode`='$groupCode',
			`inOut`='$inOut',
			`newPatient`='$newPatient',
			`insFee`='$insFee',
			`ownFee`='$ownFee',
			`mishuu`='$mishuu',
			`receive`='$receive',
			`plan`='$plan',
			`updateTime`='".date("Y-m-d H:i:s",time())."'
			WHERE `rowid` = $rowid";
            $mode = 0;
        } else {					// 同じ patientId と受付時刻 が存在しなかった
			$sql = "INSERT INTO `FrontTable` (
            `patientId`,
            `anotherId`,
            `kanjiName`,
            `userCode`,
            `groupCode`,
            `inOut`,
            `newPatient`,
            `insFee`,
            `ownFee`,
            `mishuu`,
            `receive`,
            `plan`,
            `entryDate`,
            `updateTime`,
            `owner` )
			VALUES (
                    '$patientId',
                    '$anotherId',
                    '$kanjiName',
                    '$userCode',
                    '$groupCode',
                    '$inOut',
                    '$newPatient',
                    '$insFee',
                    '$ownFee',
                    '$mishuu',
                    '$receive',
                    '$plan',
                    '$entryDate',
                    '".date("Y-m-d H:i:s",time())."',
                    '$owner')";
            $mode = 1;
        }
        echo "$sql ------------ \n"; //###
        mysql_query($sql);
        
        // 変更結果を返す
        echo "<SEPARATOR>";
        if ($mode == 0){
            $answer['mode'] = "2";
            $answer['message'] = "$kanjiName を更新しました";
            echo json_encode($answer);
        } else {
            $answer['mode'] = "3";
            $answer['message'] = "$kanjiName を登録しました";
            echo json_encode($answer);
        }
    } else if (strcmp($command,"GET_PATIENT") == 0){
        // $entryDate, $patientId のレコードを返す
        $args = decodeObject($value);
        $entryDate = $args['entryDate'];
        $patientId = $args['patientId'];

        $sql = "SELECT * FROM `FrontTable` WHERE `entryDate`='$entryDate' AND `patientId`='$patientId'";
        echo "GET_PATIENT: $sql \n"; //###
        $result = mysql_query($sql);
        
        $results = array();
        if ($row = mysql_fetch_array($result)){
            $results['userCode'] = $row['userCode'];
            $results['groupCode'] = $row['groupCode'];
            $results['inOut'] = $row['inOut'];
            $results['newPatient'] = $row['newPatient'];
            $results['point'] = $row['point'];
            $results['insFee'] = $row['insFee'];
            $results['ownFee'] = $row['ownFee'];
            $results['mishuu'] = $row['mishuu'];
            $results['receive'] = $row['receive'];
            $results['patientId'] = $row['patientId'];
            $results['anotherId'] = $row['anotherId'];
            $results['kanjiName'] = $row['kanjiName'];
            $results['plan'] = $row['plan'];
            $results['beginTime'] = $row['beginTime'];
            $results['endTime'] = $row['endTime'];
            $results['checkOutTime'] = $row['checkOutTime'];
            $results['reservedDate'] = $row['reservedDate'];
            $results['entryDate'] = $row['entryDate'];
            $results['updateTime'] = $row['updateTime'];
            $results['owner'] = $row['owner'];
       }

        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"PUT_BILL") == 0){
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $entryDate = $args['entryDate'];
        $receive = $args['receive'];
        $mishuu = $args['mishuu'];
        $now = date("Y-m-d H:i:s",time());
        
        $sql = "UPDATE `FrontTable` SET `receive`='$receive',`checkOutTime`='$now',`updateTime`='$now',`mishuu`='$mishuu' WHERE `patientId`='$patientId' AND `entryDate`='$entryDate'";
        echo "$sql ------------ \n"; //###
        mysql_query($sql);
        
        // 未収金 unpaid を PatientTable へ記録する
        putUnpaid($patientId, $mishuu);
        
        putTimeStamp(); // タイムスタンプを更新
        echo "<SEPARATOR>";
        echo "未収金を記録しました";
    } else if (strcmp($command,"PUT_PLAN") == 0){
        // args: value
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $entryDate = $args['entryDate'];
        $owner = $args['owner'];
        $plan = $args['plan'];
        $newEntryDate = $args['newEntryDate'];
        echo "$value ------------ \n"; //###
        
        if ($newEntryDate){
            $sql = "UPDATE `FrontTable`
            SET `plan`='$plan',`entryDate`='$newEntryDate'
            WHERE `patientId`='$patientId' AND `entryDate`='$entryDate'";
        } else {
            $sql = "UPDATE `FrontTable`
            SET `plan`='$plan'
            WHERE `patientId`='$patientId' AND `entryDate`='$entryDate'";
        }
        echo "$sql ------------ \n"; //###
        mysql_query($sql);
        echo "<SEPARATOR>";
        
        putTimeStamp(); // タイムスタンプを更新
    } else if (strcmp($command,"STAMP_BEGIN_TIME") == 0){
        // args  = $patientId, $entryDate, $owner
        // カルテを開いた時刻: biginTime を刻印する
        $min = substr($entryDate, 0, 10)." 00:00:00";
        $max = substr($entryDate, 0, 10)." 23:59:59";
        
        echo "<SEPARATOR>";
        $sql = "SELECT * FROM `FrontTable`
		WHERE `patientId`='$patientId'
		AND `entryDate`<='$max' AND `entryDate`>='$min' ";
        //echo "$sql \n"; // ###
        $result=mysql_query($sql);
        if (mysql_num_rows ($result) > 0){
            $row=mysql_fetch_array($result);
            $sql = "UPDATE `FrontTable` SET
            `beginTime`='".date("Y-m-d H:i:s",time())."',
            `updateTime`='".date("Y-m-d H:i:s",time())."'
            WHERE `rowid` = '".$row['rowid']."'";
            echo "$sql \n"; // ###
            mysql_query($sql);
        }
/*    } else if (strcmp($command,"PUT_ENDTIME") == 0){
        // FrontTable の診療終了時刻を更新
        // Messenger で使う
        $args = decodeObject($value);
        // client 側との約束ごと
        $entryDate = $args['entryDate'];
        $endTime = $args['endTime'];
        $updateTime = date("Y-m-d H:i:s",time());
        
        // endTime が "" の場合は、会計中止のアラート・パネルを表示
        if (strlen($endTime) == 0){
            $owner = $args['owner'];
            $to = $args['to']; // 不特定多数に対する "*" の場合がある
            $sender = $args['sender'];
            $receiver = $args['receiver'];
            $message = $args['message'];
            $sql = "UPDATE `FrontTable`
            SET `plan`='$message',`owner`='$owner'
            ,`kanjiName`='$sender',`mishuu`='$receiver'
            ,`anotherId`='$to',`updateTime`='$updateTime'
            WHERE `patientId`='STAMP'";
            echo "$sql ------------ \n"; //###
            mysql_query($sql);
        }
        
        $sql = "SELECT * FROM `FrontTable` WHERE `entryDate`='$entryDate'";
        echo "PUT_ENDTIME:\n$sql \n"; //##
        $result=mysql_query($sql);
        if (mysql_num_rows ($result) > 0){	// 同じ受診日時のレコードが存在した
            $sql = "UPDATE `FrontTable` SET
            `endTime`='$endTime',
            `updateTime`='$updateTime'
            WHERE `entryDate`='$entryDate'";
            mysql_query($sql);
            echo "$sql \n"; //##
            
            putTimeStamp(); // タイムスタンプを更新
            echo "<SEPARATOR>";
            echo "PUT_ENDTIME -- succeeded \n";
        }*/
    } else if (strcmp($command,"PUT_MESSENGER") == 0){
        // FRONT へメッセージを伝える
        $args = decodeObject($value);
        $owner = $args['owner'];
        $to = $args['to'];
        $sender = $args['sender'];
        $receiver = $args['receiver'];
        $_message = $args['message'];
        //$action = $args['action']; //##
        $updateTime = date("Y-m-d H:i:s",time());
        echo "$value ------------ \n\n"; //###
        
        $sql = "UPDATE `FrontTable`
        SET `plan`='$_message',`owner`='$owner'
        ,`kanjiName`='$sender',`mishuu`='$receiver'
        ,`anotherId`='$to',`updateTime`='$updateTime'
        WHERE `patientId`='STAMP'";
        echo "$sql ------------ \n"; //###
        mysql_query($sql);
        echo "<SEPARATOR>";
        if (strlen($to))
            echo "メッセージを $to へ送りました";
        else
            echo "メッセージを削除しました";
        
        putTimeStamp(); // timeStamp を更新
    } else if (strcmp($command,"PUT_SORT_ORDER") == 0){
        // FrontTable の診療終了時刻を更新
        // Messenger で使う
        $args = decodeObject($value);
        // client 側との約束ごと
        $owner = $args['owner']; // "1" or "0"
        $sortOrder = $args['sortOrder']; // "1" or "0"
        $updateTime = date("Y-m-d H:i:s",time());
        
        $sql = "SELECT `rowid` FROM `FrontTable`
        WHERE `patientId`='MESSENGER_ORDER' AND `owner`='$owner'";
        $result=mysql_query($sql);
        if (mysql_num_rows ($result) > 0){	// MESSENGER_ORDER が存在した
            $row=mysql_fetch_array($result);
            $sql = "UPDATE `FrontTable` SET
            `inOut`='$sortOrder',`updateTime`='$updateTime'
            WHERE `patientId`='MESSENGER_ORDER' AND `owner`='$owner'";
        } else {							// MESSENGER_ORDER が存在しなかった
            $sql = "INSERT INTO `FrontTable` (
            `patientId`,`owner`,`inOut`,`updateTime`)
            VALUES ('MESSENGER_ORDER','$owner','$sortOrder','$updateTime')";
        }
        mysql_query($sql);
        echo "$sql \n"; //##
        echo "<SEPARATOR>";
        
        putTimeStamp(); // timeStamp を更新
    } else if (strcmp($command,"GET_DAILY") == 0){
        // FRONT 日計表レコードを返す
        // Messenger 専用だが、いずれ FRONT もこちらを使う
        $args = decodeObject($value);
        // client 側との約束ごと
        $owner = $args['owner'];
        $entryDate = $args['entryDate'];
        $timeStamp = $args['timeStamp'];
        $apps = $args['application']; // このコマンドを送った元のアプリケーション
        $min = substr($entryDate, 0, 10)." 00:00:00";
        $max = substr($entryDate, 0, 10)." 23:59:59";
        
        // "タイムスタンプ^送信元^メッセージ" を渡す
        // 以前と変わっていなければ "same"
        $results = array();
        $results['timeStamp'] = getTimeStamp($apps, $timeStamp);
        $results['message'] = getMessage();
        $results['sortOrder'] = getSortOrder($owner);

        if (strlen($args['timeZone'])){ // 診療時間帯が指定されている場合
            $array = explode("-", $args['timeZone']);
            $hh = substr($array[0], 0, 2);
            $mm = substr($array[0], 2, 2);
            $fromTime = "$hh:$mm:00";
            $hh = substr($array[1], 0, 2);
            $mm = substr($array[1], 2, 2);
            $toTime = "$hh:$mm:00";
        } else {
            $fromTime = "";
            $toTime = "";
        }
        
        // 日計表のデータを渡す
        if ($results['sortOrder'] == "1"){
            $sql = "SELECT * FROM `FrontTable` WHERE `entryDate`<='$max' AND `entryDate`>='$min' ORDER BY `entryDate` DESC";
        } else {
            $sql = "SELECT * FROM `FrontTable` WHERE `entryDate`<='$max' AND `entryDate`>='$min' ORDER BY `entryDate`";
        }
        echo "GET_DAILY:\n $sql \n"; //##
        $result=mysql_query($sql);
        if (mysql_num_rows ($result) > 0){
            $recs = array();
            while ($row=mysql_fetch_array($result)){
                $rec = array();
                
                // $fromTime が設定されていれば指定された時間帯以外はスキップ
                if (! isInTime($row['entryDate'], $fromTime, $toTime)) continue;
                echo "got ..".$row['entryDate']." \n"; //##
                
                $unpaidDate = "";
                $unpaid = 0;
                // $row['mishuu'] は "2009-01-30 19:16:00,3650" のような形式
                $mishuu = $row['mishuu'];
                if ($mishuu && (strlen($mishuu) > 0)){
                    $array = explode(",", $mishuu);
                    if (count($array) > 1){
                        $unpaidDate = $array[0];
                        $unpaid = $array[1] * 1;
                    }
                }
                
                $dateAndId = $row['entryDate']."^".$row['patientId'];
                $date = $rec['entryDate'] = $row['entryDate'];
                $rec['userCode'] = $row['userCode'];
                $rec['groupCode'] = $row['groupCode'];
                $rec['inOut'] = $row['inOut'];
                $rec['newPatient'] = $row['newPatient'];
                $rec['point'] = $row['point'];
                $rec['insFee'] = $row['insFee'];
                $rec['ownFee'] = $row['ownFee'];
                $rec['mishuu'] = $unpaid;
                $rec['receive'] = $row['receive'];
                $rec['patientId'] = $row['patientId'];
                $rec['anotherId'] = $row['anotherId'];
                $rec['kanjiName'] = $row['kanjiName'];
                $rec['plan'] = $row['plan'];
                $rec['beginTime'] = $row['beginTime'];
                $rec['endTime'] = $row['endTime'];
                $rec['checkOutTime'] = $row['checkOutTime'];
                $rec['reservedDate'] = $row['reservedDate'];
                $rec['updateTime'] = $row['updateTime'];
                $rec['owner'] = $row['owner'];
                $rec['unpaidDate'] = $unpaidDate; // 追加
                // 保険証を最後にスキャンした日付
                $pid = trim($row['patientId']); // patientId に空白がついていることあり
                $obj = insScanDate($pid);
                $rec['scanDataPath'] = $obj["path"];
                $rec['scanDateTime'] = $obj["filename"];

                $color = postItColor($pid, $date);
                $rec['postItColor'] = $color;
                
                // 付箋カラーがあればタイムスタンプを empty にして FRONT を再描画させる
                if ($color) $results['timeStamp'] = "empty";

                $recs[$dateAndId] = $rec;
            }
            if (count($recs) > 0)
                $results['records'] = $recs;
        }
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"GET_MONTHLY_LIST") == 0){
        // args  = $entryDate
        $args = decodeObject($value);
        // client 側との約束ごと
        $entryDate = $args['entryDate'];
        if ($args['timeZone']){
            $array = explode("-", $args['timeZone']);
            $hh = substr($array[0], 0, 2);
            $mm = substr($array[0], 2, 2);
            $fromTime = "$hh:$mm:00";
            $hh = substr($array[1], 0, 2);
            $mm = substr($array[1], 2, 2);
            $toTime = "$hh:$mm:00";
        } else {
            $fromTime = "";
            $toTime = "";
        }
        $in = $args['in'] * 1;
        $out = $args['out'] * 1;
        $min = substr($entryDate, 0, 8)."01 00:00:00";
        $max = substr($entryDate, 0, 8)."31 23:59:59";
        
        if (($in > 0) && ($out > 0)){	// 入院・外来両方
            $sql = "SELECT * FROM `FrontTable`
            WHERE `entryDate`<='$max' AND `entryDate`>='$min'
            ORDER BY `entryDate`";
        } else if (($in > 0) && ($out == 0)){	// 入院のみ
            $sql = "SELECT * FROM `FrontTable`
            WHERE `entryDate`<='$max' AND `entryDate`>='$min' AND `inOut`='on'
            ORDER BY `entryDate`";
        } else if (($in == 0) && ($out > 0)){	// 外来のみ
            $sql = "SELECT * FROM `FrontTable`
            WHERE `entryDate`<='$max' AND `entryDate`>='$min' AND `inOut`=''
            ORDER BY `entryDate`";
        } else {
            echo ""; return;
        }
        echo "$sql <br>"; //##
        
        $records = array();
        $result=mysql_query($sql);
        if (mysql_num_rows ($result) > 0){
            $array = null;
            $_date = "";
            while ($row=mysql_fetch_array($result)){
                // 年月日を取り出す
                // timeZone にマッチしないものはスキップ
                $datetime = $row['entryDate'];
                if (! isInTime($datetime, $fromTime, $toTime)) continue;
                
                // 日毎の配列にその日の集計をその日のobjectへ収納
                $date = substr($datetime, 0, 10);
                $array[$date] = calcSum($array[$date], $row);
                // 日が変る毎に前日の集計を echo
                echo "$datetime -- $_date<br>"; //##
                
                if (strcmp($date, $_date) > 0){
                    
                    if ($_date != ""){
                        echo "-- $_date <br>"; //##
                        $records[] = $array[$_date];
                    }
                }
                $_date = $date;
            }
        }
        echo "-- $_date <br>"; //##
        $records[] = $array[$_date];
        echo "<SEPARATOR>";
        echo json_encode($records);
    } else if (strcmp($command,"GET_YEAR_LIST") == 0){
        $args = decodeObject($value);
        // client 側との約束ごと
        $entryDate = $args['entryDate'];
        if ($args['timeZone']){
            $array = explode("-", $args['timeZone']);
            $hh = substr($array[0], 0, 2);
            $mm = substr($array[0], 2, 2);
            $fromTime = "$hh:$mm:00";
            $hh = substr($array[1], 0, 2);
            $mm = substr($array[1], 2, 2);
            $toTime = "$hh:$mm:00";
        } else {
            $fromTime = "";
            $toTime = "";
        }
        $in = $args['in'] * 1;
        $out = $args['out'] * 1;
        $min = substr($entryDate, 0, 5)."01-01 00:00:00";
        $max = substr($entryDate, 0, 5)."12-31 23:59:59";
        
        if (($in > 0) && ($out > 0)){	// 入院・外来両方
            $sql = "SELECT * FROM `FrontTable`
            WHERE `entryDate`<='$max' AND `entryDate`>='$min'
            ORDER BY `entryDate`";
        } else if (($in > 0) && ($out == 0)){	// 入院のみ
            $sql = "SELECT * FROM `FrontTable`
            WHERE `entryDate`<='$max' AND `entryDate`>='$min' AND `inOut`='on'
            ORDER BY `entryDate`";
        } else if (($in == 0) && ($out > 0)){	// 外来のみ
            $sql = "SELECT * FROM `FrontTable`
            WHERE `entryDate`<='$max' AND `entryDate`>='$min' AND `inOut`=''
            ORDER BY `entryDate`";
        } else {
            echo ""; return;
        }
        echo "$sql <br>"; //##
        
        $records = array();
        $result=mysql_query($sql);
        if (mysql_num_rows ($result) > 0){
            $array = null;
            $_date = "";
            while ($row=mysql_fetch_array($result)){
                // 年月日を取り出す
                // timeZone にマッチしないものはスキップ
                $datetime = $row['entryDate'];
                // $datetime が $fromTime,$toTime の間にあれば TRUE を返す
                if (! isInTime($datetime, $fromTime, $toTime)) continue;
                
                // 月毎の配列にその月の集計をその日のobjectへ収納
                $date = substr($datetime, 0, 7); // yyyy-mm
                $array[$date] = calcSum($array[$date], $row);
                // 日が変る毎に前日の集計を echo
                echo "$datetime -- $_date<br>"; //##
                
                if (strcmp($date, $_date) > 0){
                    if ($_date != ""){
                        echo "-- $_date <br>"; //##
                        $records[] = $array[$_date];
                    }
                }
                $_date = $date;
            }
        }
        echo "-- $_date <br>"; //##
        $records[] = $array[$_date];
        echo "<SEPARATOR>";
        echo json_encode($records);
    } else if (strcmp($command,"GET_MONTHLY_INS_LIST") == 0){
        // args  = $entryDate
        $args = decodeObject($value);
        $date = $args['entryDate'];
        $min = substr($date, 0, 7)."-01 00:00:00";
        $max = substr($date, 0, 7)."-31 23:59:59";
        
        $sql = "SELECT * FROM `FrontTable` WHERE `entryDate`<='$max' AND `entryDate`>='$min' ORDER BY `patientId`";
        
        echo "$sql \n"; //##
        $result=mysql_query($sql);
        $record = array();
        while ($row=mysql_fetch_array($result)){
            $array = array();
            if ($patientId == $row['patientId']) continue; // 重複を避ける
            
            $patientId = $row['patientId'];
            $array['patientId'] = $row['patientId'];
            $array['kanjiName'] = $row['kanjiName'];
            $record[] = $array;
        }
        
        echo "<SEPARATOR>";
        echo json_encode($record);
    } else if (strcmp($command,"GET_USER_LIST") == 0){
        // UserTable の内容を配列に入れて返す
        // Messenger で使う
        $results = array();
        
        // user list を作成
        $sql = "SELECT * FROM `UserTable`";
        echo "$sql \n"; //##
        $array = array();
        $result=mysql_query($sql);
        if (mysql_num_rows ($result) > 0){
            while ($row=mysql_fetch_array($result)){
                $ary = array();
                $logname = $row['loginName'];
                $ary['kanjiName'] = $row['kanjiName'];
                $ary['hospitalId'] = $row['hospitalId'];
                $array[$logname] = $ary;
                echo "$logname -> ".$ary."\n"; //##
            }
        }
        $results['userList'] = $array;
        
        // Messenger 用の message list を作成
        $results['messageList'] = messagesToFront();
        
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"PUT_MESSAGE") == 0){
        // MenuTable にメッセージ項目を追加
        $args = decodeObject($value);
        // client 側との約束ごと
        $tag = "MESSAGE_NOA_TO_FRONT";
        $menuItem = $args['menuItem'];
        $owner = $args['owner'];
        $freq = $args['freq'];
        
        $sql = "SELECT * FROM `MenuTable`
        WHERE `tag`='$tag' AND `menu`='$menuItem'";
        echo "$sql ========\n"; //###
        $result=mysql_query($sql);
        if (mysql_num_rows ($result) > 0){	// 同じ menuItem が存在した
            $row=mysql_fetch_array($result);
            $rowid = $row['rowid'];
            // menuItem は同じなので freq のみ更新
            if ($freq) $freq = $row['freq'] + 1; // 頻度インクリメント
            
            $sql = "UPDATE `MenuTable` 
            SET `freq`='$freq',`owner`='$owner'
            WHERE `tag`='$tag' AND `menu`='$menuItem'";
        } else { // 同じ menuItem が存在しなかった
            $sql = "INSERT INTO `MenuTable` 
            ( `tag`,`freq`,`menu`,`value`,`public`,`updateTime`,`owner` )
            VALUES ( '$tag','0','$menuItem','','','','$owner')";
        }
        echo "$sql ========\n"; //###
        mysql_query($sql);
        
        $array = messagesToFront();
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"REMOVE_MESSAGE") == 0){
        // MenuTable からメッセージ項目を削除
        $args = decodeObject($value);
        // client 側との約束ごと
        $tag = "MESSAGE_NOA_TO_FRONT";
        $menuItem = $args['menuItem'];
        $owner = $args['owner'];
        
        $sql = "DELETE FROM `MenuTable` 
        WHERE `tag`='$tag' AND `menu`='$menuItem'";
        echo "$sql ========\n"; //###
        mysql_query($sql);
        
        $array = messagesToFront();
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"LOGIN") == 0){
        // Messenger で使う
        $args = decodeObject($value);
        // client 側との約束ごと
        $loginName = $args['loginName'];
        $passwd = $args['passwd'];
        
        $row = getUser($loginName);
        echo $row['identifier']."\n"; //##
        echo md5($passwd)."\n"; //##
        if (strcmp($row['identifier'], md5($passwd)) == 0){
            // 暗号化してから DB 値と比較する
            // <SEPARATOR> の後に文字があれば成功を示す
            echo "<SEPARATOR>";
            echo json_encode($row);
        }
    } else if (strcmp($command,"PUT_TIMEZONE") == 0){
        $args = decodeObject($value);
        // client 側との約束ごと
        $script = $args['script'];
        $owner = $args['owner'];
        
        $sql = "SELECT * FROM `FieldTable` 
        WHERE `tag`='FRONT_TIMEZONE' AND `owner`='$owner'";
        echo "$sql ========\n"; //###
        $result=mysql_query($sql);
        if (mysql_num_rows ($result) > 0){	// 同じ tag が存在した
            $sql = "UPDATE `FieldTable` 
            SET `script`='$script'
            WHERE `tag`='FRONT_TIMEZONE' AND `owner`='$owner'";
        } else { // 同じ menuItem が存在しなかった
            $sql = "INSERT INTO `FieldTable` 
            ( `tag`,`script`,`owner` )
            VALUES ( 'FRONT_TIMEZONE','$script','$owner')";
        }
        echo "$sql ========\n"; //###
        mysql_query($sql);
        
        echo "<SEPARATOR>$script";
    } else if (strcmp($command,"GET_TIMEZONE") == 0){
        $args = decodeObject($value);
        $hospitalId = $args['hospitalId'];
        $key = $args['key'];
        
        $sql = "SELECT * FROM `HospitalTable` WHERE `hospitalId`='$hospitalId' AND `key`='$key'";
        $result=mysql_query($sql);
        echo "$sql ========\n"; //###
        $row = mysql_fetch_array($result);
        echo "<SEPARATOR>";
        if ($row) echo $row['value'];
    } else if (strcmp($command,"PUT_LAYOUT_PARTS") == 0){
        // 初期設定のパーツ部分を保存
        $args = decodeObject($value);
        $owner = $args['owner'];
        $updateTime = timeStamp();
        
        $sql = "SELECT * FROM `FrontTable` WHERE `patientId`='LAYOUT_PARTS' AND `owner`='$owner'";
        echo "$sql ========\n"; //###
        $result=mysql_query($sql);
        
        // checkBox, firstItem, timeZone をアーカイブした $value のまま格納
        if (mysql_num_rows ($result) > 0){	// 同じ tag が存在した
            $row=mysql_fetch_array($result);
            $rowid = $row['rowid'];
            $sql = "UPDATE `FrontTable` SET `plan`='$value', `updateTime`='$updateTime' WHERE `rowid`='$rowid'";
        } else { // 同じ menuItem が存在しなかった
            $sql = "INSERT INTO `FrontTable` ( `patientId`,`owner`,`plan`,`updateTime` ) VALUES ( 'LAYOUT_PARTS','$owner','$value','$updateTime')";
        }
        echo "$sql ========\n"; //###
        mysql_query($sql);
        
        // 同時にアーカイブも保存
        $st = date("YmdHi",time());
        $filename = "$st.txt";
        if (save($owner, $filename, $value)){
            echo "<SEPARATOR>";
            echo "バックアップを保存しました";
        } else {
            echo "<SEPARATOR>";
            echo "バックアップが保存できませんでした";
        }
    } else if (strcmp($command,"GET_LAYOUT_PARTS") == 0){
        // 初期設定のパーツ部分を読み込む
        $args = decodeObject($value);
        $owner = $args['owner'];
        $hospitalId = $args['hospitalId'];
        
        $sql = "SELECT * FROM `FrontTable` WHERE `patientId`='LAYOUT_PARTS' AND `owner`='$owner'";
        $result=mysql_query($sql);
        echo "$sql ========\n"; //###
        
        $results = array();
        $row = mysql_fetch_array($result);
        if ($row) $results['args'] = $row['plan'];
        
        // 診療時間帯を検索
        $sql = "SELECT * FROM `HospitalTable` WHERE `hospitalId`='$hospitalId' AND `key`='診療時間'";
        $result=mysql_query($sql);
        echo "$sql ========\n"; //###
        $row = mysql_fetch_array($result);
        if ($row) $results['timezones'] = $row['value'];

        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"REMOVE_LAYOUT_PARTS") == 0){
        // 初期設定のパーツ部分を削除
        $args = decodeObject($value);
        $owner = $args['owner'];
        
        $sql = "DELETE FROM `FrontTable` WHERE `patientId`='LAYOUT_PARTS' AND `owner`='$owner'";
        mysql_query($sql);
        echo "$sql\n";
        
        // 変更結果を返す
        echo "<SEPARATOR>";
        echo "$owner のレイアウトを削除しました";
    } else if (strcmp($command,"GET_ARCHIVE_FILES") == 0){
        // アーカイブのファイル名の配列を取得
        $args = decodeObject($value);
        $owner = $args['owner'];
        
        $dir = archiveDir($owner);
        echo "dir($dir)"; //###
        
        $results = getDir($dir);
        //rsort($results); // 逆順にソート
        echo "results($results)"; //###
        
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"GET_ARCHIVE_FILE") == 0){
        // NOA 形式で保存された配列データを読み出す
        $args = decodeObject($value);
        $owner = $args['owner'];
        $filename = $args['filename'];
        
        $dir = archiveDir($owner);
        $path = "$dir/$filename";
        
        echo "<SEPARATOR>";
        $json = file_get_contents($path);
        echo $json;
    } else if (strcmp($command,"REMOVE_ARCHIVE_FILE") == 0){
        $args = decodeObject($value);
        $owner = $args['owner'];
        $filename = $args['filename'];
        
        $dir = archiveDir($owner);
        $path = "$dir/$filename";
        unlink($path);
        
        echo "<SEPARATOR>";
        echo "$filename を削除しました";
    } else if (strcmp($command,"GET_VIEWER") == 0){
        // $patientId $dateTime のデータを返す
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $date = $args['dateTime'];
        
        $results = array();
        $results['progressSection'] = getProgressSection($date, $patientId);
        $results['healthInsurance'] = getHealthInsurance($date, $patientId);
        $results['publicInsurance'] = getPublicInsurance($date, $patientId);
        
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else {
        echo "<SEPARATOR>";
        echo "*** Unknown command: $command ***";
    }


?>
