
<?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);
        $array = explode("%xa;", $val); // DocMaker の Image 用：htmlForValue()
        $val = implode("\'", $array);
        return $val;
    }
    
    function leftBrackets(){
        // $leftBrackets = "\^\[\^" では誤作動
        //	return "\^\[\^"; // encode 中で使う '(' -- クライアント側との約束 lib.js
        return "^[^"; // encode 中で使う '(' -- クライアント側との約束 lib.js
    }
    function rightBrackets(){
        return "^]^"; // encode 中で使う '(' -- クライアント側との約束 lib.js
        //	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;
                    }
                }
            }
        }
        return $obj;
    }
    
    function timestamp(){
        // 現在のタイムスタンプを返す updateTime に使う
        date_default_timezone_set("Asia/Tokyo");
        return date("Y-m-d H:i:s",time());
    }
    
    function checkDB(){
        // DB をチェックし欠けているフィールドなどあれば追加
        if (! hasField('NOA', 'ProgressSection', 'note')){
            // ProgressSection に note フィールドが無ければ追加
            $sql = "ALTER TABLE `ProgressSection` ADD `note` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL AFTER `plan`";
            echo "checkDB: $sql ======\n"; //##
            $result = mysql_query($sql);
        }
    }
    
    function hasField($_dbname, $_tablename, $_fieldname){
        // $db_name 中に $_tablename があれば TRUE を、なければ FALSE を返す
        $result = mysql_query("SHOW COLUMNS FROM $_tablename");
        echo 'hasField: $_dbname $_tablename $_fieldname \n';
        if ($result) {
            if (mysql_num_rows($result) > 0) {
                while ($row = mysql_fetch_assoc($result)) {
                    $fieldname = $row['Field'];
                    echo "$_tablename ..... $fieldname \n";
                    if (strcmp($fieldname, $_fieldname) == 0) return TRUE;
                }
            }
        } else
            echo 'Could not run query: ' . mysql_error().' \n';
        return FALSE;
    }
    
    function getHospitalNames(){
        // $array に 施設名と hospitalId の対象テーブルを挿入
        $array = array();
        $sql = "SELECT * FROM `HospitalTable` WHERE `key`='施設名'";
        echo "=== getHospitalNames\n $sql \n";
        $result=mysql_query($sql);
        while ($row=mysql_fetch_array($result)){
            $hospitalId = $row['hospitalId'];
            $name = $row['value'];
            $array[$name] = $hospitalId;
        }
        return $array;
    }
	
    function getUserList(){
        // ユーザのリストを返す
        $sql = "SELECT * FROM `UserTable`";
        echo "$sql \n"; //##
        $result=mysql_query($sql);
        $array = array();
        while ($row=mysql_fetch_array($result)){
            $logname = $row['loginName'];
            $array[$logname] = $row['kanjiName'];
            echo "$logname -> ".$row['kanjiName']."\n"; //##
        }
        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){
            while ($row = mysql_fetch_assoc($result)){ // 連想配列で取り出す
                if (strcmp($row['loginName'], $loginName) == 0){
                    echo "--- $row \n";
                    return $row;
                }
            }
        }
        return null;
    }
    
	function nameSectionWithPatientId($patientId){
        $sql = "SELECT * FROM `NameSection` WHERE `patientId`='$patientId' ORDER BY `entryDate` DESC";
        $result=mysql_query($sql);
        
        while ($row=mysql_fetch_array($result)){
            if (strlen($row['patientKanjiName']) > 0)
                return $row;
        }
        return "???";
    }
    
	function patientTableWithPatientId($patientId){
        $sql = "SELECT * FROM `PatientTable` WHERE `patientId`='$patientId' ORDER BY `updateTime`";
        $result=mysql_query($sql);
        $row=mysql_fetch_array($result);
        return $row;
    }
    
    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 pickupProgressValue($obj, $row, $fieldName){
        $val = $row[$fieldName];
        if ($val && (strlen($val) > 0)){
            $obj[$fieldName]['val'] = $val;
            $obj[$fieldName]['update'] = $row['updateTime'];
        }
        return $obj;
    }
    
    function getPatientTable($owner, $patientId){
        // PatientTable の全てのレコードを返す
        // PatientTable のみは updateTime を持つ必要がないので構造が他と異なる
        $sql = "SELECT * FROM `PatientTable` WHERE `patientId`='$patientId'";
        echo "$sql \n"; //###
        $result=mysql_query($sql);
        
        $records = array();
        if ($row = mysql_fetch_array($result)){
            $array = array();
            $array['date'] = $row['entryDate'];
            $array['anotherId'] = $row['anotherId'];
            $array['receiptId'] = $row['receiptId'];
            $array['sex'] = $row['sex'];
            $array['unpaid'] = $row['unpaid'];
            $array['birthDate'] = $row['birthDate'];
            $array['lastVisitDate'] = $row['lastVisitDate'];
        }
        return $array;
    }
    function getFrontTable($owner, $patientId){
        // FrontTable の全てのレコードを返す
        $sql = "SELECT * FROM `FrontTable` WHERE `patientId`='$patientId' ORDER BY `entryDate` DESC, `updateTime` DESC";
        echo "$sql \n"; //###
        $result=mysql_query($sql);
        
        $recs = array();
        while ($row = mysql_fetch_array($result)){
            // ### FrontTable の entryDate は患者受付時刻で NOA の新規ページ作成時刻
            // ### より少し早い可能性があるので entryDate は当日午前０時０分として検索
            $st = $row['entryDate'];
            $date = substr($st, 0, 10)." 00:00:00";
            $recs[$date] = array();
            $recs[$date]['plan'] = array();
            
            // 空データを過去へ遡る動作はクライアント側で行う
            if (strlen($row['plan']) > 0){
                $recs[$date]['plan']['val'] = $row['plan'];
                $recs[$date]['plan']['update'] = $row['updateTime'];
            }
        }
        return $recs;
    }
    function getProgressSection($owner, $patientId, $entryDate){
        // ProgressSection の全てのレコードを返す
        $sql = "SELECT * FROM `ProgressSection` WHERE `patientId`='$patientId' AND (`freq` IS NULL OR `freq`<1) ORDER BY `entryDate` DESC, `updateTime` DESC";
        echo "getProgressSection-> $sql \n"; //###
        $result=mysql_query($sql);
        // 受診日毎の ProgressSection
        $recs = array();
        while ($row=mysql_fetch_array($result)){
            $date = $row['entryDate'];
            if ($entryDate){ // 指定した受診日:$entryDate 以外のレコードはスキップ
                if (strcmp(substr($date, 0, 10), substr($entryDate, 0, 10)) != 0) continue;
            }
            
            // ProgressSection の場合は空データを過去へ遡る動作はクライアント側で行う
            if (!$recs[$date]) $recs[$date] = array();
            $recs[$date] = pickupProgressValue($recs[$date], $row, 'pageHeader');
            $recs[$date] = pickupProgressValue($recs[$date], $row, 'subject');
            $recs[$date] = pickupProgressValue($recs[$date], $row, 'object');
            $recs[$date] = pickupProgressValue($recs[$date], $row, 'examination');
            $recs[$date] = pickupProgressValue($recs[$date], $row, 'prescription');
            $recs[$date] = pickupProgressValue($recs[$date], $row, 'disease');
            $recs[$date] = pickupProgressValue($recs[$date], $row, 'treatment');
            $recs[$date] = pickupProgressValue($recs[$date], $row, 'assessment');
            $recs[$date] = pickupProgressValue($recs[$date], $row, 'plan');
            $recs[$date] = pickupProgressValue($recs[$date], $row, 'note');
        }
        // アクセス・ログにも patientId を記憶
        $limit = 200; // $limit の数しかアクセス・ログを記憶しない
        putAccessLog($patientId, $owner, $limit);
        
        return $recs;
    }
    function getUniversalSection($owner, $patientId, $dateTime){
        // UniversalSection の全てのレコードを返す
        $sql = "SELECT * FROM `UniversalSection` 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);
        
        $array = array();
        while ($row=mysql_fetch_array($result)){
            if (strcmp($row['field'], '_REMINDER_') == 0) continue;
            
            // ### UniversalSection を全て読み込むことになるので効率悪い
            // ### 必要な field を指定した方がよい
            $field = $row['field'];
            if (strlen($array[$field]['val']) == 0){
                $array[$field]['data'] = $row['dataString'];
                $array[$field]['val'] = $row['dataString'];
                $array[$field]['type'] = $row['type'];
                $array[$field]['update'] = $row['updateTime'];
            }
        }
        return $array;
    }
    function getPostIt($owner, $pid){
        // PostIt の内容を返す
        $sql = "SELECT * FROM `UniversalSection` WHERE `patientId`='$pid' AND `owner`='$owner' AND `field`='postit' ORDER BY `entryDate` DESC";
        echo "===\n $sql \n";
        $result=mysql_query($sql);
        
        $records= array();
        while ($row=mysql_fetch_array($result)){
            $date = $row['entryDate'];
            
            $array = array();
            $array['value'] = $row['dataString'];
            $array['type'] = $row['type'];
            $array['color'] = $row['dataObject'];
            $array['entryDate'] = $row['entryDate']; // $date とダブっても必要
            $array['updateTime'] = $row['updateTime'];
            $records[$date] = $array;
        }
        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)){
            if ($row['postIt']) 
                return ($row['postIt']); // ### postIt 設定されていればここで抜ける ###
            $frowId = $row['rowid']; // FrontTable で見つけた行の id
        }
        
        // 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 が無かった
    }
    
    function getNameSection($owner, $patientId, $dateTime){
        // NameSection の全てのレコードを返す
        if ($dateTime){
            $sql = "SELECT * FROM `NameSection` WHERE `patientId`='$patientId' AND `entryDate`<='$dateTime' ORDER BY `entryDate` DESC, `updateTime` DESC";
        } else {
            $sql = "SELECT * FROM `NameSection` WHERE `patientId`='$patientId' ORDER BY `entryDate` DESC, `updateTime` DESC";
        }
        echo "$sql \n"; //###
        $result=mysql_query($sql);
        
        $kanji = newFieldObj();
        $kana = newFieldObj();
        $roma = newFieldObj();
        while ($row = mysql_fetch_array($result)){
            $kanji = pickupValue($kanji, $row, 'patientKanjiName');
            $kana = pickupValue($kana, $row, 'patientKanaName');
            $roma = pickupValue($roma, $row, 'patientRomajiName');
            
            if ($kanji['flag'] && $kana['flag'] && $roma['flag']) break;
        }
        $records = array();
        $records['patientKanjiName'] = $kanji;
        $records['patientKanaName'] = $kana;
        $records['patientRomajiName'] = $roma;
        return $records;
    }
    function getAddressSection($owner, $patientId, $dateTime){
        // AddressSection の $dateTime 直近のレコードを返す
        $sql = "SELECT * FROM `AddressSection` 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);
        
        $address = newFieldObj();
        $phone = newFieldObj();
        $fax = newFieldObj();
        $email = newFieldObj();
        while ($row = mysql_fetch_array($result)){
            $address = pickupValue($address, $row, 'address');
            $phone = pickupValue($phone, $row, 'phone');
            $fax = pickupValue($fax, $row, 'fax');
            $email = pickupValue($email, $row, 'email');
            $memo = pickupValue($memo, $row, 'memo');
            
            if ($address['flag'] && $phone['flag'] && $fax['flag'] && $email['flag'] && $memo['flag']) break;
        }
        $records = array();
        $records['address'] = $address;
        $records['phone'] = $phone;
        $records['fax'] = $fax;
        $records['email'] = $email;
        $records['memo'] = $memo;
        return $records;
    }
    function getBasicSection($owner, $patientId, $dateTime){
        // BasicSection の全てのレコードを返す
        $sql = "SELECT * FROM `BasicSection` 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);
        
        $allergy = newFieldObj();
        $drinking = newFieldObj();
        $smoking = newFieldObj();
        $bloodtype = newFieldObj();
        $history = newFieldObj();
        $job = newFieldObj();
        while ($row=mysql_fetch_array($result)){
            // 参照履歴用レコードはスキップ
            if (strcmp($row['drinking'], "ACCESS_LOG") == 0)
                continue;
            
            $allergy = pickupValue($allergy, $row, 'allergy');
            $drinking = pickupValue($drinking, $row, 'drinking');
            $smoking = pickupValue($smoking, $row, 'smoking');
            $bloodtype = pickupValue($bloodtype, $row, 'bloodtype');
            $history = pickupValue($history, $row, 'history');
            $job = pickupValue($job, $row, 'job');
            
            if ($allergy['flag'] && $drinking['flag'] && $smoking['flag'] && $bloodtype['flag'] && $history['flag'] && $job['flag']) break;
        }
        $records = array();
        $records['allergy'] = $allergy;
        $records['drinking'] = $drinking;
        $records['smoking'] = $smoking;
        $records['bloodtype'] = $bloodtype;
        $records['history'] = $history;
        $records['job'] = $job;
        return $records;
    }
    function getMaritalSection($owner, $patientId, $dateTime){
        // MalitalSection の全てのレコードを返す
        $sql = "SELECT * FROM `MalitalSection` 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);
        
        $type = newFieldObj();
        $partner = newFieldObj();
        $partnersJob = newFieldObj();
        $partnersOffice = newFieldObj();
        $memo = newFieldObj();
        $startDate = newFieldObj();
        $expiredDate = newFieldObj();
        while ($row=mysql_fetch_array($result)){
            $type = pickupValue($type, $row, 'type');
            $partner = pickupValue($partner, $row, 'partner');
            $partnersJob = pickupValue($partnersJob, $row, 'partnersJob');
            $partnersOffice = pickupValue($partnersOffice, $row, 'partnersOffice');
            $memo = pickupValue($memo, $row, 'memo');
            $startDate = pickupValue($startDate, $row, 'startDate');
            $expiredDate = pickupValue($expiredDate, $row, 'expiredDate');
            
            if ($type['flag'] && $partner['flag'] && $partnersJob['flag'] && $partnersOffice['flag'] && $memo['flag'] && $startDate['flag'] && $expiredDate['flag']) break;
        }
        $records = array();
        $records['type'] = $type;
        $records['partner'] = $partner;
        $records['partnersJob'] = $partnersJob;
        $records['partnersOffice'] = $partnersOffice;
        $records['memo'] = $memo;
        $records['startDate'] = $startDate;
        $records['expiredDate'] = $expiredDate;
        return $records;
    }
    function getHealthInsurance($owner, $patientId, $dateTime){
        // 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['ownerName'] = $ownerName;
        $records['ownerNumber'] = $ownerNumber;
        $records['ownerPhone'] = $ownerPhone;
        $records['shubetsu'] = $shubetsu;
        $records['kubun'] = $kubun;
        $records['kigou'] = $kigou;
        $records['bangou'] = $bangou;
        $records['continuedDiseases'] = $continuedDiseases;
        $records['paymentRatio'] = $paymentRatio;
        $records['discountRatio'] = $discountRatio;
        $records['confirmation'] = $confirmation;
        $records['startDate'] = $startDate;
        $records['expiredDate'] = $expiredDate;
        return $records;
    }
    function getPublicInsurance($owner, $patientId, $dateTime){
        // 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['ownerName'] = $ownerName;
        $records['ownerNumber'] = $ownerNumber;
        $records['recipientNumber'] = $recipientNumber;
        $records['shubetsu'] = $shubetsu;
        $records['paymentRatio'] = $paymentRatio;
        $records['payment'] = $payment;
        $records['startDate'] = $startDate;
        $records['expiredDate'] = $expiredDate;
        return $records;
    }
    
    function getHospitalTable($hid){
        $sql = "SELECT * FROM `HospitalTable` WHERE `hospitalId`='$hid'";
        echo "----- getHospital\n $sql \n";
        $result=mysql_query($sql);
        $array = array();
        while ($row=mysql_fetch_assoc($result)){ // 連想配列でレコードを取り出す
            $key = $row['key'];
            $value = $row['value'];
            $array[$key] = $value;
            echo "  $key -> $value \n"; //##
        }
        
        return $array;
    }
    
    function getAccessLog($owner, $reverse){
        // owner のアクセス・ログを返す
        if ($reverse && ($reverse * 1 > 0)){ // updateTime で逆ソート
            $sql = "SELECT * FROM `BasicSection` WHERE `drinking`='ACCESS_LOG' AND `owner`='$owner' ORDER BY `updateTime` DESC";
        } else {  // updateTime でソート
            $sql = "SELECT * FROM `BasicSection` WHERE `drinking`='ACCESS_LOG' AND `owner`='$owner' ORDER BY `updateTime`";
        }
        $result=mysql_query($sql);
        echo "$sql \n";

        $records = array();
        while ($row=mysql_fetch_array($result)){
            $rec = array();
            $rec['pid'] = $row['patientId'];
            // $rec['pid'] = $pid; // なぜかここでセットすると順序が狂う
            $date = $rec['date'] = $row['updateTime'];
            $rec['name'] = $row['bloodtype'];
            $rec['rowid'] = $row['rowid']; // putAccessLog() で必要
            $records[] = $rec;
        }
        return $records;
    }
    function putAccessLog($patientId, $owner, $limit){
        // アクセス・ログにも patientId を記憶: BasicSection に記憶
        // ## 日時を entryDate に格納すると BasicSection データとして表示されてしまうので
        // ## entryDate は空白とし updateTime に日時を格納
        // ## 目印のため 'drinking' に 'ACCESS_LOG' を格納
        $namrow = nameSectionWithPatientId($patientId);
        $patientName = $namrow['patientKanjiName'];
        $updateTime = timestamp();
        
        // $recrds 内の $patientId の有無を調べ、最終レコード $rec を得る
        $found = 0;
        // 逆ソートにしておかないと置換の場合、最終レコードではなく最初のレコードになってしまう
        $records = getAccessLog($owner, TRUE);
        foreach ($records as $num=>$rec){
            if ($rec['pid'] == $patientId)
                $found = 1; // $lastRowId を得るため、ここで break しない
            $lastRowId = $rec['rowid'];
        }
        
        if ($found > 0){
            // $patientId が過去ログに存在したので $updateTime のみ更新
            // 名前が変更される場合もあるので patientName も更新
            
            // １レコードのみ updateTime を更新
            $sql = "SELECT * FROM `BasicSection` WHERE `drinking`='ACCESS_LOG' AND `patientId`='$patientId' AND `owner`='$owner' ORDER BY `updateTime`";
            $result=mysql_query($sql);
            if ($row=mysql_fetch_array($result)){
                $rowid = $row['rowid'];
                $sql = "UPDATE `BasicSection` SET `updateTime`='$updateTime',`bloodType`='$patientName' WHERE `rowid`=$rowid";
                $result=mysql_query($sql);
                echo "$sql \n";
            }
            
            // 重複しているものが他にもあれば全て削除
            $sql = "DELETE FROM `BasicSection` WHERE `drinking`='ACCESS_LOG' AND `patientId`='$patientId' AND `owner`='$owner' AND `rowid`!=$rowid";
            $result=mysql_query($sql);
            echo "$sql \n";
        } else if (count($records) >= $limit){
            // 最終レコード $lastRowId のレコードを指定されたデータと置換する
            $sql = "UPDATE `BasicSection` SET `patientId`='$patientId',`bloodType`='$patientName',`updateTime`='$updateTime' WHERE `rowid`='$lastRowId'";
            $result=mysql_query($sql);
            echo "$sql \n";
        } else {
            $sql = "INSERT INTO `BasicSection` (`patientId`,`drinking`,`bloodType`,`updateTime`,`owner`) VALUES ('$patientId','ACCESS_LOG','$patientName','$updateTime','$owner')";
            $result=mysql_query($sql);
            echo "$sql \n";
       }
    }
    function removeAccessLog($patientId, $owner){
        $sql = "DELETE FROM `BasicSection` WHERE `patientId`='$patientId' AND `owner`='$owner'";
        echo "$sql ========\n"; //###
        mysql_query($sql);
        
        return getAccessLog($owner);
    }
    
    function putTimeStamp(){
        // データ更新のタイムスタンプを記憶
        $timestamp = timestamp();
        $sql = "SELECT `rowid` FROM `FrontTable` WHERE `patientId`='STAMP'";
        $result=mysql_query($sql);
        if (mysql_num_rows ($result) > 0){	// STAMP が存在した
            $row=mysql_fetch_array($result);
            $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($entryDate){
        // タイムスタンプと同じものがあれば "same" なければ、旧スタンプを返す
        $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'];
            
            // タイムスタンプが同じなら "same" を返す
            if ($updateTime == $entryDate)
                return "same";
            else // FRONT を再描画
                return $updateTime;
        } else { // タイムスタンプが存在しなかった
            return "empty";
        }
    }
	
    function insScanDate($patientId, $dir){
        // patientId の保険証を最後にスキャンした日付を返す
        $results = array();
        $array = array();
        $files = scandir($dir);
     //   if ($files == FALSE) return  $results; // $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;
            
            // filename = "03234202_20120113165123.JPG" 形式 -- drag and drop
            // filename = "03234200_20130119072744_0.jpg" 形式 -- upload
            $array[] = $filename;
        }
        rsort($array); // 逆順にソート
        $results['path'] = $dir;
		$results['filename'] = $array[0]; // 直近のファイル名
        return $results;
    }
    
    function shiftDateTime($dateTime, $interval){
        // 日付:$dateTime を $interval 秒後へずらした日付を返す
        // 日付は "yyyy-mm-dd hr:mn:sc" 形式
        // $interval は「秒数」
        // ## $interval が空だと 10 年前までの記録を修正可能
        $array = explode(" ", $dateTime);
        list($year, $month, $day) = explode("-", $array[0]);
        list($hour, $min, $sec) = explode(":", $array[1]);
        $date = mktime($hour, $min, $sec, $month, $day, $year);
        
        // $interval が空なら、いつでも訂正可能にするため２０年後の日時を返す
        // ## ２０年以上ずらすと PHP の仕様のためか過去の 1900 年代に戻ってしまう
        if (strlen($interval) == 0)
            $date = mktime($hour, $min, $sec, $month, $day, $year + 20);
        else
            $date += ($interval * 1); // 時刻を $interval 秒後にずらす
        
        $yyyy = date("Y", $date);
        
        //echo "interval($interval) $year --> $yyyy \n";
        
        $mm = date("m", $date);
        $dd = date("d", $date);
        $hr = date("H", $date);
        $mn = date("i", $date);
        $sc = date("s", $date);
        
        // この日時を過ぎていなければ直接訂正可能、過ぎていれば新しいページで上書き
        return "$yyyy-$mm-$dd $hr:$mn:$sc";;
    }
    
    function isEditableRecord($table, $field, $pid, $entryDate, $timeLimit){
        // entryDate + timeLimit（秒数）を越えていなければ 1 越えていれば 0 を返す
        // ## updateTime + timeLimit という考え方もあるが
        // ## entryDate を基準にする方が修正により厳密に対応でき
        // ## 編集後「timeLimit 越えなければ、完全にページ削除」できてしまうこともない
        // ## $timeLimit が "" だと 20 年前までの記録を修正可能 ##
        
        $datetime = shiftDateTime($entryDate, $timeLimit);
        $isEditable = (strcmp(timeStamp(), $datetime) < 0) ? 1 : 0;
        
        if ($isEditable){
            // 編集可能なレコードがあれば、その rowid を取得
            if (strcmp($table, "UniversalSection") == 0){
                $sql = "SELECT * FROM `$table` WHERE `patientId`='$pid' AND `entryDate`<='$entryDate' AND `field`='$field' AND (`freq` IS NULL OR `freq`<1) ORDER BY `entryDate` DESC,`updateTime` DESC";
            } else {
                $sql = "SELECT * FROM `$table` WHERE `patientId`='$pid' AND `entryDate`<='$entryDate' AND (`freq` IS NULL OR `freq`<1) ORDER BY `entryDate` DESC,`updateTime` DESC";
            }
            //echo "check target record:\n $sql \n";
            $result=mysql_query($sql);
            $row=mysql_fetch_array($result);
            if ($row && (strcmp($entryDate, $row['entryDate']) == 0)){
                echo " --> 編集可能時刻 $datetime 以内なので直接修正 OK\n";
                return "1:".$row['rowid'];
            } else {
                echo " --> 編集可能時刻以内の $entryDate ページがないので直接修正 NO\n";
                return "0:";
            }
        } else {
            echo " --> 編集可能時刻 $datetime を過ぎており直接修正 NO\n";
            return "0:";
        }
    }
	
   function setPageHeader($owner, $patientId, $entryDate){
        // $patientId, $entryDate, freq IS NULL のレコードが
        // あれば pageHeader 更新、なければ新たに追加
        $updateTime = timestamp();
        $st = "$updateTime ( $owner )"; // ### 漢字は化ける可能性あり
        // $st = "Recorded at ... $updateTime ( by $owner )";
        $sql = "SELECT * FROM `ProgressSection` WHERE `patientId`='$patientId' AND `entryDate`='$entryDate' AND (`freq` IS NULL OR `freq`<1)";
        //echo "$sql --- check pageHeader\n"; //###
        $result=mysql_query($sql);
        if ($row=mysql_fetch_array($result)){
            $rowid = $row['rowid'];
            $sql = "UPDATE `ProgressSection` SET `pageHeader`='$st' WHERE `rowid`='$rowid'";
        } else {
            $sql = "INSERT INTO `ProgressSection` (`patientId`,`pageHeader`,`entryDate`,`updateTime`,`owner`) VALUES ('$patientId','$st','$entryDate','$updateTime','$owner')";
        }
        echo "----- update pageHeader \n $sql \n"; //##
        $result=mysql_query($sql);
        
        return $st;
    }
    
    function getMenuItems($tag, $owner, $isAddressMenu){
        // MENU EDITOR 用メニュー・リストを返す (public と owner を merge したもの）
        // MENU EDITOR 用メニュー・リストを返す (owner のもののみ）
        // $tag $owner
        echo "##### getMenuItems #####\n"; //##
        
        // 以下に $owner ごとの CELL 属性が入っている
        $isGroupType = FALSE;
        $study = FALSE;
        if ($isAddressMenu){
            // 住所メニューの場合は tag が「品川区」などなので明示的に指定する必要あり
            // owner は関与せず
            $sql = "SELECT * FROM `FieldTable` WHERE `tag`='AddressSection.address' AND `direction`='CELL'";
        } else {
            $sql = "SELECT * FROM `FieldTable` WHERE `tag`='$tag' AND (`owner`='$owner' OR `owner`='public') AND `direction`='CELL'";
        }
        $result=mysql_query($sql);
        echo "$sql \n"; //###
        
        $hasOwner = FALSE;
        if ($row=mysql_fetch_array($result)){
            // _group_ type ### lib.js での定数宣言と整合性をとる必要あり
            if ($row['menuType'] * 1 == 3) $_isGroupType = TRUE;
            if ($row['study'] * 1 == 1) $_study = TRUE;
            if (strcmp($row['owner'], $owner) == 0){
                $isGroupType = $_isGroupType; // GROUP MENU タイプ
                $study = $_study; // 頻度学習をする
                $hasOwner = TRUE;
            } else if ($hasOwner == fALSE){
                // $owner のデータが設定されていない場合のみ設定
                $isGroupType = $_isGroupType; // GROUP MENU タイプ
                $study = $_study; // 頻度学習をする
            }
        }
        
        ///// FieldTable に格納されたデータを返す /////
        $array = array();
        if ($isGroupType){
            $sql = "SELECT * FROM `ProgressSection` WHERE `patientId`='GroupMenu' ORDER BY `freq` DESC";
            $result=mysql_query($sql);
            echo "$sql ========\n"; //##
            while ($row=mysql_fetch_array($result)){
                // GroupMenu の場合はパラメータを他のメニューに合わせる
                $ary = array();
                $ary['owner'] = $row['owner'];
                $ary['freq'] = $row['freq'];
                $menu = $ary['menu'] = $row['subject'];
                $ary['ProgressSection.subject'] = $row['subject']; // あえて重複
                $ary['ProgressSection.object'] = $row['object'];
                $ary['ProgressSection.examination'] = $row['examination'];
                $ary['ProgressSection.prescription'] = $row['prescription'];
                $ary['ProgressSection.disease'] = $row['disease'];
                $ary['ProgressSection.treatment'] = $row['treatment'];
                $ary['ProgressSection.assessment'] = $row['assessment'];
                $ary['ProgressSection.plan'] = $row['plan'];
                $ary['ProgressSection.note'] = $row['note'];
                
                // Public, Private の重複レコードをユニークにするためキー付き配列へ収納
                // owner 所有のレコードを優先的に拾い上げる
                if (strcmp($row['owner'], $owner) == 0){
                    // $owner のレコードなら無条件で追加
                    $menuItems[$menu] = $ary;
                } else if ($menuItems[$menu] == null){
                    // $owner のレコードがない場合のみ public のレコードを追加
                    if (strcmp($row['owner'], 'public') == 0)
                        $menuItems[$menu] = $ary;
                }
            }
        } else {
            // MenuTable の $tag に一致した内容を返す：owner は後で選別
            $sql = "SELECT * FROM `MenuTable` WHERE `tag`='$tag' ORDER BY `freq` DESC";
            $result=mysql_query($sql);
            echo "$sql ========\n"; //##
            while ($row=mysql_fetch_array($result)){
                $ary = array();
                $ary['owner'] = $row['owner'];
                $ary['tag'] = $row['tag'];
                $ary['value'] = $row['value'];
                $ary['public'] = $row['public'];
                //if ($row['owner'] == "public") $ary['public'] = "1";
                $ary['freq'] = $row['freq'];
                $menu = $ary['menu'] = $row['menu'];
                $template = $ary['template'] = $row['template'];
                
                // Public, Private の重複レコードをユニークにするためキー付き配列へ収納
                // owner 所有のレコードを優先的に拾い上げる
                if (strcmp($row['owner'], $owner) == 0){
                    // $owner のレコードなら無条件で追加
                    $menuItems[$menu][$template] = $ary;
                } else if ($menuItems[$menu][$template] == null){
                    // $owner のレコードがない場合のみ public のレコードを追加
                    if (strcmp($row['owner'], 'public') == 0)
                        $menuItems[$menu][$template] = $ary;
                }
            }
        }
        
        // キー付き配列だったものを普通の配列に戻す
        $results = array();
        if ($isGroupType){
            foreach ($menuItems as $menu=>$object){
                $results[] = $object;
            }
        } else {
            foreach ($menuItems as $menu=>$object){
                foreach ($object as $template=>$rec){
                    $results[] = $rec;
                    echo "$rec\n"; //##
                }
            }
        }
        
        return $results;
    }
    
    function getStandard($tag, $owner){
        // 基準値リストを返す (public と owner を merge したもの）
        echo "##### getStandard #####\n"; //##
        
        // MenuTable の $tag に一致した内容を返す：owner は後で選別
        $sql = "SELECT * FROM `MenuTable` WHERE `tag`='$tag' ORDER BY `menu`";
        $result=mysql_query($sql);
        echo "$sql ========\n"; //##
        
        $menuItems = array();
        while ($row=mysql_fetch_array($result)){
            $ary = array();
            $ary['owner'] = $row['owner'];
            $ary['value'] = $row['value'];
            $ary['unit'] = $row['template'];
            $menu = $ary['menu'] = $row['menu'];
            
            // Public, Private の重複レコードをユニークにするためキー付き配列へ収納
            // owner 所有のレコードを優先的に拾い上げる
            if (strcmp($row['owner'], $owner) == 0){
                // $owner のレコードなら無条件で追加
                $menuItems[$menu] = $ary;
            } else if ($menuItems[$menu] == null){
                // $owner のレコードがない場合のみ public のレコードを追加
                if (strcmp($row['owner'], $owner) != 0)
                    $menuItems[$menu] = $ary;
            }
        }
        
        return $menuItems;
    }
    
    function getHospitalInfo($hospitalId, $key){
        // 該当する診療行為（薬剤、処置名、など）を DB から取り出して返す
        $query = "SELECT `key`,`value` FROM `HospitalTable` WHERE `hospitalId`='$hospitalId' AND `key`='$key'";
        $result=mysql_query($query);
        
        if (mysql_num_rows ($result) > 0){
            $row=mysql_fetch_array($result);
            return $row['value'];
        }
        return "";
    }
    
    function hospitalId($owner){
        // $owner の所属する医療機関の hospitalId を返す
        $query = "SELECT `hospitalId` FROM `UserTable`
		WHERE `loginName`='$owner'";
        $result=mysql_query($query);
        
        if (mysql_num_rows ($result) > 0){
            $row=mysql_fetch_array($result);
            return $row['hospitalId'];
        }
        return "";
    }
    
    function hospitalInfo($owner){
        $hid = hospitalId($owner);
        $array['round'] = getHospitalInfo($hid, "まるめ係数");
        $array['ownRate'] = getHospitalInfo($hid, "自費係数");
        return $array;
    }
	
    function isPatientId($st){
        // $st が カルテID 形式でなければ FALSE を返す
        if (strlen($st) != 8) return FALSE;
        
        $month = substr($st, 0, 2);
        if ($month * 1 < 1) return FALSE;
        if ($month * 1 > 12) return FALSE;
        
        return TRUE;
    }
	
    function find($tag, $pid, $from, $to, $uniqueId, $key){
        // 条件にマッチした結果を返す
        $fromDateTime = substr($from,0,10)." 00:00:00";
        $toDateTime = substr($to,0,10)." 23:59:59";
        $tags = explode(".", $tag);
        $table = $tags[0];
        $field = $tags[1];
        $uniq = (strlen($uniqueId) > 0) ? TRUE : FALSE; // patientId 重複を避けるモード
        $pidArray = array();
        if (strcmp($table, "PatientTable") == 0){
            $pidst =  (strlen($pid) > 0) ? "`patientId`='$pid' AND" : "";
            $query = "SELECT * FROM `PatientTable`"
            ." WHERE $pidst"
            ." `entryDate`>='$fromDateTime' AND"
            ." `entryDate`<='$toDateTime' AND"
            ." `$field` LIKE '%$key%'"
            ." ORDER BY `entryDate` DESC, `updateTime` DESC";
            $result=mysql_query($query);
            echo "$query ===== \n";//###
            $array = array();
            $i = 0;
            while ($row=mysql_fetch_array($result)){
                // $rec[entryDate] = { 'patientId' = $pid, 'value' = $value } 形式で返す
                $rec = array();
                $_pid = $row['patientId'];
                if ((strlen($uniq) > 0) && $pidArray[$_pid]) continue;
                if (! isPatientId($_pid)) continue;
                
                $rec['entryDate'] = $row['entryDate'];
                $rec['patientId'] = $_pid;
                $namrow = nameSectionWithPatientId($_pid);
                $rec['name'] = $namrow['patientKanjiName'];
                $rec['value'] = $row[$field];
                // $row['entryDate'] だけでは、同じ entryDate の patient は
                // unique にしか $array に登録されないので、枝番号を追加する
                $date = $row['entryDate']." ".$i++;
                $array[$date] = $rec;
                $pidArray[$_pid] = TRUE;
            }
            return $array;
        } else if (strcmp($table, "UniversalSection") == 0){
            $fieldSearch = "";
            $keys = explode(" ", $key);
            $ct = count($keys);
            for ($i=0; $i < $ct; $i++){
                $ky = $keys[$i];
                $fieldSearch = " $fieldSearch(`dataString` LIKE '%$ky%') AND";
            }

            $pidst =  (strlen($pid) > 0) ? "`patientId`='$pid' AND" : "";
            $query = "SELECT * FROM `UniversalSection`"
			." WHERE $pidst"
			." `field`='$field' AND"
			." `entryDate`>='$fromDateTime' AND"
			." `entryDate`<='$toDateTime' AND"
            ." $fieldSearch"
			." (`freq` IS NULL OR `freq`<1) AND"
			." ORDER BY `entryDate` DESC, `updateTime` DESC";
            $result=mysql_query($query);
            echo "$query ===== \n";//###
            $array = array();
            $i = 0;
            while ($row=mysql_fetch_array($result)){
                // $rec[entryDate] = {'patientId'=$pid,'value'=$value} 形式で返す
                $rec = array();
                $_pid = $row['patientId'];
                if ((strlen($uniq) > 0) && $pidArray[$_pid]) continue;
                
                $rec['entryDate'] = $row['entryDate'];
                $rec['patientId'] = $row['patientId'];
                $namrow = nameSectionWithPatientId($_pid);
                $rec['name'] = $namrow['patientKanjiName'];
                $rec['value'] = $row['dataString'];
                // $row['entryDate'] だけでは、同じ entryDate の patient は
                // unique にしか $array に登録されないので、枝番号を追加する
                $date = $row['entryDate']." ".$i++;
                $array[$date] = $rec;
                $pidArray[$_pid] = TRUE;
            }
            return $array;
        } else {
            $fieldSearch = "";
            $keys = explode(" ", $key);
            $ct = count($keys);
            for ($i=0; $i < $ct; $i++){
                $ky = $keys[$i];
                $fieldSearch = "$fieldSearch (`$field` LIKE '%$ky%') AND";
            }
            
            $pidst =  (strlen($pid) > 0) ? "`patientId`='$pid' AND" : "";
            $query = "SELECT * FROM `$table`"
			." WHERE $pidst"
			." `entryDate`>='$fromDateTime' AND"
			." `entryDate`<='$toDateTime' AND"
            ." $fieldSearch"
			." (`freq` IS NULL OR `freq`<1)"
			." ORDER BY `entryDate` DESC, `updateTime` DESC";
            $result=mysql_query($query);
            echo "$query ===== \n";//###
            $array = array();
            while ($row=mysql_fetch_array($result)){
                // $rec[entryDate] = { 'patientId' = $pid, 'value' = $value } 形式で返す
                $rec = array();
                $_pid = $row['patientId'];
                if ((strlen($uniq) > 0) && $pidArray[$_pid]) continue;
                if (! isPatientId($_pid)) continue;
                
                $rec['entryDate'] = $row['entryDate'];
                $rec['patientId'] = $_pid;
                $namrow = nameSectionWithPatientId($_pid);
                $rec['name'] = $namrow['patientKanjiName'];
                $rec['value'] = $row[$field];
                // レコード識別のため patientId を追加する
                $date = $row['entryDate']." ".$_pid;
                $array[$date] = $rec;
                $pidArray[$_pid] = TRUE;
            }
            return $array;
        }
    }
    
    function layoutTags($owner){
        // $owner の LAOUT に含まれる table.field の配列を返す
        $tagArray = array();
        $tagArray["PatientTable.patientId"] = "カルテID"; // LAYOUT にないので追加
        $tagArray["ProgressSection.pageHeader"] = "PageHeader";
        
        $sql = "SELECT * FROM `FieldTable` WHERE `owner`='$owner' AND `direction`='CELL' ORDER BY `numbering`";
        $result=mysql_query($sql);
        echo "$sql \n"; //###
        
        while ($row=mysql_fetch_array($result)){
            $tagArray[$row['tag']] = $row['label'];
            //echo $row['tag']."->".$row['label']."\n"; //##
        }
        return $tagArray;
    }
    
    function encodeDoubleQuotation($value){
        $array = explode('"', $value);
        // " を ' に置換
        return join("'", $array);
    }
    
    function getArchiveValue($patientId, $table, $field){
        // $tableAndField 内の DB値のリストを返す
        $sql = "SELECT * FROM `$table` WHERE `patientId`='$patientId' ORDER BY `entryDate` DESC";
        $result=mysql_query($sql);
        echo "getArchiveValue: $sql \n"; //###
        
        $array = array();
        while ($row=mysql_fetch_array($result)){
            if ((strcmp($patientId != "GroupMenu") != 0) && (strcmp($table, "PatientTable") != 0) && $row['freq'] && ($row['freq'] > 0)) continue; // 削除されたレコードはスキップ
            
            $edate = $row['entryDate'];
            $udate = $row['updateTime'];
            $array2 = (count($array[$edate]) == 0) ? array() : $array[$edate];
            if (strcmp($table, "UniversalSection") == 0){
                $key = $row['field'];
                $value = $row['dataString'];
                if (strcmp($key, $field) == 0){
                    if (strlen($value) > 0){
                        // field にマッチした value が存在したら
                        $array2[$udate] = $value;
                        $array[$edate] = $array2;
                    }
                }
            } else {
                $value = $row[$field];
                if (strlen($value) > 0){
                    // field にマッチした value が存在したら
                    // ## $value に " が入っていると JSON にした後
                    // ## eval() する時にエラーになるので encode しておく
                    // ## JSON を eval() した後に decode を忘れぬこと
                    $value = encodeDoubleQuotation($value);
                    $array2[$udate] = $value;
                    $array[$edate] = $array2;
                }
            }
        }
        return $array;
    }
    function archive($patientId, $array){
        // $array 中の table に対するコンテンツを添えた JSON を返す
        $results = array();
        foreach ($array as $tag=>$kanjiName){
            $tags = explode(".", $tag);
            if (count($tags) > 1){
                $table = $tags[0];
                $field = $tags[1];
                
                $contents = getArchiveValue($patientId, $table, $field);
                $results[$tag] = $contents;
            }
        }
        return json_encode($results);
    }
    function archiveDirForToolMenu($owner, $folder){
        // $dir が無ければ作成
        $dir = rootDir()."Users";
        if (! file_exists($dir)){
            // $dir が無ければ作成
            echo "($dir) is not exist, so I'll make directory. \n"; //##
            mkdir($dir);
        }
        $dir = "$dir/$owner";
        if (! file_exists($dir)){
            // $dir が無ければ作成
            echo "($dir) is not exist, so I'll make directory. \n"; //##
            mkdir($dir);
        }
        $dir = "$dir/$folder";
        if (! file_exists($dir)){
            // $dir が無ければ作成
            echo "($dir) is not exist, so I'll make directory. \n"; //##
            mkdir($dir);
        }
        
        return $dir;
    }
    function archivedFile($patientId){
        // $dir が無ければ作成
        $dir = rootDir()."NOA_ARCHIVE";
        if (! file_exists($dir)){
            // $dir が無ければ作成
            echo "($dir) is not exist, so I'll make directory. \n"; //##
            mkdir($dir);
        }
        return "$dir/$patientId.txt";
    }
    
    function save($patientId, $buff){
        $filename = archivedFile($patientId);
        
        if (!$handle = fopen($filename, 'w')) {
            // $filenameを書き出しモードでオープン
            echo "Cannot open file ($filename)";
            return FALSE;
        }
        
        if (fwrite($handle, $buff) === FALSE) {
            // オープンしたファイルに$buffを書き込む
            echo "Cannot write to file ($filename)";
            return FALSE;
        } else {
            echo "Saved $patientId to file ($filename)";
            fclose($handle);
            return TRUE;
        }
    }
	
    function dirOfBackupFile($owner, $label){
        // バックアップ・ファイルの directory を返す
        $dir = rootDir()."Users/$owner";
        if (! file_exists($dir)){
            // $dir が無ければ作成
            echo "($dir) is not exist, so I'll make directory. \n"; //##
            mkdir($dir);
        }
        
        $dir = "$dir/CALLS";
        if (! file_exists($dir)){
            // $dir が無ければ作成
            echo "($dir) is not exist, so I'll make directory. \n"; //##
            mkdir($dir);
        }
        
        $dir = "$dir/backup";
        if (! file_exists($dir)){
            // $dir が無ければ作成
            echo "($dir) is not exist, so I'll make directory. \n"; //##
            mkdir($dir);
        }
        return $dir;
    }
    function saveBackup($owner, $label, $buff){
        $dir = dirOfBackupFile($owner, $label);
        
        date_default_timezone_set("Asia/Tokyo");
        $timeStamp = date("YmdHis",time());
        $path = "$dir/$timeStamp";
        if (!$handle = fopen($path, 'w')) {
            // $$path を書き出しモードでオープン
            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 isRemovedPage($row){
        // 削除されたページかどうかを返す
        // pageHeader に "EMOVED" の文字があれば削除されたページと判断
        // ## strpos() が確実に０以上になるよう "REMOVED" でなく "EMOVED"
        if ($row['freq'] > 0) return TRUE;
        return (strpos($row['pageHeader'], "EMOVED") > 0) ? TRUE : FALSE;
    }
	
    function recordsForKeys($patientId, $owner, $st){
        // kyes を含むすべてのレコードを返す
        $keys = explode(",", $st); // セパレータ "," はクライアントとの約束ごと
        $keyCount = count($keys);
        
        // keys は配列ではなくセパレータで区切られた文字列
        $sql = "SELECT * FROM `ProgressSection` WHERE `patientId`='$patientId' AND (`owner`='$owner' OR `owner`='public')  ORDER BY `entryDate` DESC";
        echo "$sql -----\n"; //##
        $result=mysql_query($sql);
        
        $array = array();
        while ($row=mysql_fetch_array($result)){
            if (isRemovedPage($row)) continue; // 削除されたレコードはスキップ
            
            $date = $row['entryDate'];
            $objc = $row['object'];
            $exam = $row['examination'];
            $ln = $objc.$exam; // object と examination 両方を検索対象にする
            for ($i=0; $i < $keyCount; $i++){
                $key = $keys[$i]."(";
                if (strpos($ln, $key) !== FALSE){
                    $array[$date] = $ln;
                    break;
                }
            }
        }
        
        return $array;
    }
    
    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 beforAndAfterDateTime($dateTime){
        // $dateTime の１時間前と１時間後の日時の入った配列を返す
        $date = new DateTime($dateTime); // "2013-02-12 17:51:04" を dateTime()に
        $date->sub(new DateInterval('PT60M')); // ６０分前の日時
        $beforeDate = $date->format("Y-m-d H:i:s");
        
        // NOA 時刻の６０分後を検索範囲とする：NOA でページ追加後６０分に FRONT で登録したとして
        $date = new DateTime($dateTime); // "2013-02-12 17:51:04" を dateTime()に
        $date->add(new DateInterval('PT60M')); // ６０分後の日時
        $afterDate = $date->format("Y-m-d H:i:s");
        
        $array = array();
        $array[] = $beforeDate;
        $array[] = $afterDate;
        return $array;
    }
    
	function rowOfPatientId($_pid){
        // テーブル中にすでに $_pid があれば 1 を、なければ 0 を返す
        $sql = "SELECT * FROM `PatientTable` WHERE `patientId`='$_pid'";
        $result=mysql_query($sql);
        $row=mysql_fetch_array($result);
        if (mysql_num_rows ($result) > 0)
            return $row;
        else
            return null;
    }
    
    function valForWebNOA($val){
        // $val 中の "<br>"(NOA2JSON で変換された) を "\n" に戻す操作を行っておく
        //    $array = explode("<BR/>", $val);
        $array = explode("<br>", $val);
        return join("\n", $array);
    }
    function valueForNOA($table, $field, $val){
        // CocoaNOA データを WebNOA データへ変換
        $tag = "$table.$field";
        if (strcmp($tag, "PatientTable.sex") == 0){
            if (strcmp($val, "f") == 0)
                return "女";
            else if (strcmp($val, "m") == 0)
                return "男";
        }
        else if (strcmp($tag, "PatientTable.birthDate") == 0){
            $array = explode(" ", $val);
            return join(" ", array_slice($array, 0, 1));
        }
        return $val;
    }
    function putRecord($patientId, $tag, $entryDate, $updateTime, $val, $owner){
        // 完全に一致するものがなければ、このレコードを挿入
        // $val 中の "<br>"(NOA2JSON で変換された) を "\n" に戻す操作を行っておく
        $val = valForWebNOA($val);
        $tags = explode(".", $tag);
        $table = $tags[0];
        $field = $tags[1];
        
        if (strcmp($table, "UniversalSection") == 0){
            $sql = "SELECT * FROM `$table`
            WHERE `patientId`='$patientId' AND `field`='$field'
            AND `entryDate`='$entryDate' AND `updateTime`='$updateTime'";
            $result=mysql_query($sql);
            if (mysql_num_rows ($result) > 0){ // 同じID・フィールド・日付・更新時のデータが存在した
                $row=mysql_fetch_array($result);
                if (strcmp($row['dataString'], $val) <> 0){ // データが異なった
                    $sql="UPDATE `$table` SET `field`='$field',`dataString`='$val'
                    WHERE `rowid`=".$row['rowid'];
                    echo "$sql \n"; // message
                    mysql_query($sql);
                }
            } else { // 同じID・フィールド・日付・更新時のデータが存在しなかった
                $sql = "INSERT INTO `$table`
                (`patientId`,`field`,`dataString`,`entryDate`,`updateTime`,`owner`)
                VALUES ('$patientId','$field','$val','$entryDate','$updateTime','$owner')";
                echo "$sql \n"; // message
                mysql_query($sql);
            }
        } else if (strcmp($table, "PatientTable") == 0){
            $sql = "SELECT * FROM `$table` WHERE `patientId`='$patientId'";
            $result=mysql_query($sql);
            $val = valueForNOA($table, $field, $val); // CocoaNOA データを WebNOA へ変換
            if (mysql_num_rows ($result) > 0){ // 同じ patientId のデータが存在した
                $row=mysql_fetch_array($result);
                if (strcmp($row[$field], $val) <> 0){ // データが異なった
                    // PatientTable のレコードは patientId ごとに唯一なので
                    // もし同じ patientId が存在した場合は最新のデータを優先する
                    if (strcmp($row['entryDate'], $entryDate) <= 0){
                        // 日付を比較して $entryDate より古いか同じものなら上書き
                        // entryDate も上書きすると後で別フィールドが比較できなくなってしまう
                        $sql="UPDATE `$table`
                        SET `$field`='$val',`updateTime`='$updateTime'
                        WHERE `rowid`=".$row['rowid'];
                        echo "$sql \n"; // message
                        mysql_query($sql);
                    }
                }
            } else { // 同じ patientId のデータが存在しなかった
                $sql = "INSERT INTO `$table`
                (`patientId`,`$field`,`entryDate`,`updateTime`)
                VALUES ('$patientId','$val','$entryDate','$updateTime')";
                echo "$sql \n"; // message
                mysql_query($sql);
            }
        } else {
            $sql = "SELECT * FROM `$table` WHERE `patientId`='$patientId'
            AND `entryDate`='$entryDate' AND `updateTime`='$updateTime'";
            echo "$sql \n"; // message
            
            $result=mysql_query($sql);
            if (mysql_num_rows ($result) > 0){ // 同じID・日付・更新時のデータが存在した
                $row=mysql_fetch_array($result);
                if (strcmp($row[$field], $val) <> 0){ // データが異なった
                    $sql="UPDATE `$table` SET `$field`='$val',`updateTime`='$updateTime' WHERE `rowid`=".$row['rowid'];
                    echo "$sql \n"; // message
                    mysql_query($sql);
                }
            } else { // 同じID・日付・更新時のデータが存在しなかった
                $sql = "INSERT INTO `$table`
                (`patientId`,`$field`,`entryDate`,`updateTime`,`owner`)
                VALUES ('$patientId','$val','$entryDate','$updateTime','$owner')";
                echo "$sql \n"; // message
                mysql_query($sql);
            }
        }
    }

    function isInScopeOf($from, $filename, $to){
        // $filename が $from と $to の範囲内なら true を返す
        
        // $from,$to: "2012-06-05 15:58:00" を "20120605" 形式にする
        $array = explode(" ", $from);
        $ymd = explode("-", $array[0]);
        $fromSt = join("", $ymd);
        
        $array = explode(" ", $to);
        $ymd = explode("-", $array[0]);
        $toSt = join("", $ymd);
        
        // $filename: "10135100_20120316091412_0.JPG" を "20120316" 形式にする
        // $filename: "_10135100_20120316091412.JPG" を "20120316" 形式にする
        $array = explode("_", $filename);
        if (strlen($array[0]) == 0){ // ファイル名先頭が "_" ではじまる
            $st = $array[2];
        } else { // ファイル名先頭に "_" がつかない
            $st = $array[1];
        }
        $fnSt = substr($st, 0, 8);
        
        echo "$filename -- $fromSt | $fnSt | $toSt \n";
        
        if ($fnSt * 1 < $fromSt * 1) return false;
        if ($toSt * 1 < $fnSt * 1) return false;
        echo "==> hit \n";
        
        return true;
    }
    
    function lvdForPatientId($patientId){
        // $patientId の最終受診日を返す lastVisitDate
        $sql = "SELECT * FROM `PatientTable` WHERE `patientId`='$patientId'";
        $result=mysql_query($sql);
        echo "$sql ========== <br>\n";
        
        while ($row=mysql_fetch_array($result)){
            $lvd = $row['lastVisitDate'];
            if ($lvd) return $lvd;
        }
        return "";
    }
    
    function getMessageMenu($owner){
        // メッセージを取得
        $sql = "SELECT * FROM `MenuTable` WHERE `tag`='MESSAGE_MENU' AND `owner`='$owner' ORDER BY `freq`";
        $result=mysql_query($sql);
        $array = array();
        while ($row=mysql_fetch_array($result)){
            $rec = array();
            $rec['menu'] = $row['menu'];
            $rec['freq'] = $row['freq'];
            $array[$row['menu']] = $rec;
        }
        return $array;
    }
    
    function getToolMenu($owner){
        // TOOL MENU 構造を返す
        $sql = "SELECT * FROM `FieldTable` WHERE `tag`='TOOL_MENU' AND `owner`='$owner' ORDER BY `numbering`";
        echo "--- GET_TOOL_MENU ---\n $sql \n"; //##
        $result=mysql_query($sql);
        
        $array = array();
        while ($row=mysql_fetch_array($result)){
            $rec = array();
            $rec['window'] = $row['buttonType'];
            $rec['menuType'] = $row['menuType'];
            $rec['fix'] = $row['menuAction'];
            $rec['subTitle'] = $row['fieldType'];
            $rec['disabled'] = $row['disabled'];
            $rec['editor'] = $row['editor'];
            $rec['id'] = $row['id'];
            $rec['url'] = $row['script'];
            $rec['label'] = $row['label'];
            $rec['icon'] = $row['fontFamily'];
            $array[] = $rec;
        }
        return $array;
    }
    
    function getCalls($owner){
        // call 一括処理をサーバから取り出す
        $sql = "SELECT * FROM `MenuTable` WHERE `owner`='$owner' AND `tag`='CALLS'";
        echo "$sql ========\n"; //###
        $result=mysql_query($sql);
        
        $records = array();
        while ($row=mysql_fetch_array($result)){
            $rec = array();
            $menu = $row['menu'];
            $rec['type'] = $row['freq'];
            $rec['value'] = $row['value'];
            $records[$menu] = $rec;
        }
        return $records;
    }
    
    function putCalls($args){
        // $args レコードの内容をサーバへ保存
        //$args = decodeObject($value);
        $owner = $args['owner'];
        $type = $args['type'];
        $menu = $args['name'];
        $calls = $args['calls'];
        $updateTime = timeStamp();
        
        if (! $calls || (strlen($calls) == 0)){
            // $calls が null なら削除動作になる
            $sql = "DELETE FROM `MenuTable` WHERE `owner`='$owner' AND `tag`='CALLS' AND `menu`='$menu'";
        } else {
            $sql = "SELECT * FROM `MenuTable` WHERE `owner`='$owner' AND `tag`='CALLS' AND `menu`='$menu' AND `freq`='$type'";
            $result=mysql_query($sql);
            
            if ($row=mysql_fetch_array($result)){
                $rowid = $row['rowid'];
                $sql = "UPDATE `MenuTable` SET `value`='$calls' WHERE `rowid`='$rowid'";
            } else {
                $sql = "INSERT INTO `MenuTable` ( `tag`,`menu`,`value`,`freq`,`updateTime`,`owner` ) VALUES ( 'CALLS','$menu','$calls','$type','$updateTime','$owner')";
            }
        }
        echo "$sql ========\n"; //###
        mysql_query($sql);
    }
    
    /////////////////////////////////////////////
    ///// 祝日リストの取得 
    function holidaySort($a, $b) {
        // 指定年の祝日リスト配列のソート
        if ($a['date'] == $b['date']) {
            return 0;
        }
        return ($a['date'] < $b['date']) ? -1 : 1;
    }
    function getHoliday($year, $country){
        // 祝日リストを取得：[{"date":"2014-03-21","title":"春分の日"},,] 型式
        // 参考：http://d.hatena.ne.jp/oka_bon/20111013/1318467804
        echo "getHoliday: $country <br>\n"; //##

        $ret = array();;
        if(empty($year)){
            $dateBegin = date( "Y-m-01" );
            $dateEnd   = date( "Y-m-t"  );
        }else{
            $dateBegin = date( "Y-01-01", mktime( 0, 0, 0,  1, 1, $year ) );
            $dateEnd   = date( "Y-12-t",  mktime( 0, 0, 0, 12, 1, $year ) );
        }
        $query = "start-min=" . $dateBegin . "&start-max=" . $dateEnd . "&max-results=100";
        switch($country){
            case 'ja':
                $feed = "http://www.google.com/calendar/feeds/japanese__ja@holiday.calendar.google.com/public/full" . "?" . $query;
                break;
            case 'us':
                $feed = "http://www.google.com/calendar/feeds/usa__ja@holiday.calendar.google.com/public/full" . "?" . $query;
                break;
            case 'uk':
                $feed = "http://www.google.com/calendar/feeds/uk__ja@holiday.calendar.google.com/public/full" . "?" . $query;
                break;
            case 'ch':
                $feed = "http://www.google.com/calendar/feeds/china__ja@holiday.calendar.google.com/public/full" . "?" . $query;
                break;
            case 'ph':
                $feed = "http://www.google.com/calendar/feeds/philippines__ja@holiday.calendar.google.com/public/full" . "?" . $query;
                break;
            default :
                $feed = "http://www.google.com/calendar/feeds/japanese__ja@holiday.calendar.google.com/public/full" . "?" . $query;
                break;
        }
        
        $xml = simplexml_load_file( $feed );
        if(!$xml){
            return $ret;
        }
        $ii = 0;
        foreach( $xml->entry as $entry ){
            $gd = $entry->children( "http://schemas.google.com/g/2005" );
            $attributes	= $gd->when->attributes();
            foreach( $attributes as $name => $value ){
                if( $name == "startTime" ){
                    $ret[$ii]['date'] = "".$value."";
                    $ret[$ii]['title'] = "".$entry->title."";
                    $ii++;
                    echo "$value ".$entry->title."<br>\n"; //##
                    
                    break;
                }
            }
        }
        usort($ret, "holidaySort");
        return $ret;
    }
    
    ///// 祝日リストの取得 
    /////////////////////////////////////////////
    
    /////////////////////////////////////////////
    ///// Chief Complaint Analizer
    
    function includeOf($subject, $key){
        // subject 欄から key を含む行を取り出して返す
        $rows = explode("\n", $subject);
        $count = count($rows);
        for ($num=0; $num < $count; $num++){
            $ln = $rows[$num];
            if (strlen($ln) == 0) continue;
            
            // ln 行に検索キーが含まれていなければスキップ
            $targetPos = strpos($ln, $key);
            if ($targetPos === FALSE) continue;
            
            // 検索キーが ( ) 内ならスキップ
            $pos = strpos($ln, "(");
            if (($pos !== FALSE) && ($pos < $targetPos)) continue; 
            
            return $ln;
        }
        return NULL;
    }
    
    function setDisase($obj, $disease){
        // $disease の各行の病名を $obj に挿入
        $rows = explode("\n", $disease);
        $count = count($rows);
        for ($num=0; $num < $count; $num++){
            $ln = $rows[$num];
            if (strlen($ln) == 0) continue;
            
            // "日付 病名" 型式から病名を取り出す
            $ary = explode(" ", $ln);
            if (count($ary) == 1) continue;
            
            $name = $ary[1];
            if (strlen($name) == 0) continue;
            
            // name が "120711" のことがあるので、これを除外
            if (is_numeric($name)) continue;
            
            $name = str_replace("膣", "腟", $name);
            $name = str_replace("頸", "頚", $name);
            
            // 病名を $obj に登録
            $freq = ($obj[$name]) ? ($obj[$name] * 1) + 1 : 1;
            $obj[$name] = $freq;
        }
        return $obj;
    }
    function setTreatment($obj, $treatment){
        // $treatment の各行の診療行為を $obj に挿入
        $rows = explode("\n", $treatment);
        $count = count($rows);
        for ($num=0; $num < $count; $num++){
            $ln = $rows[$num];
            if (strlen($ln) == 0) continue;
            
            // "日付 病名" 型式から病名を取り出す
            $ary = explode("]", $ln);
            if (count($ary) == 1) continue;
            
            $name = $ary[0]."]";
            
            if (strpos($name, "初診") !== false) continue;
            if (strpos($name, "再診") !== false) continue;
            if (strpos($name, "加算") !== false) continue;
            if (strpos($name, "薬加") !== false) continue;
            if (strpos($name, "判断") !== false) continue;
            if (strpos($name, "合計") !== false) continue;
            
            $name = str_replace("膣", "腟", $name);
            $name = str_replace("頸", "頚", $name);

            // 診療行為を $obj に登録
            $freq = ($obj[$name]) ? ($obj[$name] * 1) + 1 : 1;
            $obj[$name] = $freq;
        }
        return $obj;
    }

    function setPostItNull($patientId, $entryDate){
        // FrontTable の postIt に NULL をセットし UniversalSection の postIt を
        // 再検索させるようにする
        $from = substr($entryDate, 0, 10)." 00:00:00";
        $to= substr($entryDate, 0, 10)." 23:59:59";
        $sql = "UPDATE `FrontTable` SET `postIt`=NULL WHERE `patientId`='$patientId' AND `entryDate`>='$from' AND `entryDate`<='$to'";
        mysql_query($sql);
        echo "===\n $sql \n"; //##
    }
    
    

    $command = $_GET['command']; $command=htmlspecialchars($command);
    $value = $_GET['value']; $value=htmlspecialchars($value);
    $value = decodeSTRING($value);
    
    // DB を開いて該当レコードを読み込む
    // ### セキュリティーを保つには、以下のファイルを外からアクセスできない
    // ### directory に置き、以下の cfg.php の pass をそこへ変更
    require_once('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,"CHECK_DB") == 0){
        // FrontTable に指定した field がなければ追加する
        if (! hasField('NOA', 'FrontTable', 'reservedDate')){
            $sql = "ALTER TABLE `FrontTable` ADD `reservedDate` TIMESTAMP AFTER `checkOutTime`";
            echo "CHECK_DB: $sql ======\n"; //##
            $result = mysql_query($sql);
        }
        // FrontTable に指定した field がなければ追加する
        if (! hasField('NOA', 'FrontTable', 'postIt')){
            $sql = "ALTER TABLE `FrontTable` ADD `postIt` INT AFTER `plan`";
            echo "CHECK_DB: $sql ======\n"; //##
            $result = mysql_query($sql);
        }
        // PriceList に指定した field がなければ追加する
        if (! hasField('NOA', 'PriceList', 'disease')){
            $sql = "ALTER TABLE `PriceList` ADD `disease` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL AFTER `effect`";
            echo "CHECK_DB: $sql ======\n"; //##
            $result = mysql_query($sql);
        }
    } else if (strcmp($command,"PUT_FRONT_BOOKING") == 0){
        // patientId, reservedDate のレコードの entryDate を指定日時に変更する
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $reservedDate = $args['reservedDate'];
        $updateTime = timestamp();
        // 指定された entryDate が空なら 現在時刻を entryDate とする
        $entryDate = $args['entryDate'];
        if (strlen($entryDate) == 0) $entryDate = timestamp();

        $sql = "UPDATE `FrontTable` SET `entryDate`='$entryDate', `updateTime`='$updateTime' WHERE `patientId`='$patientId' AND `reservedDate`='$reservedDate'";
        echo "$sql ===== \n"; //##
        $result=mysql_query($sql);

        echo "<SEPARATOR>";
        if ($result) {
            putTimeStamp(); // FrontTable が更新されたことを記録
            echo "entryDate を $entryDate に変更しました";
        } else {
            echo "entryDate は変更できませんでした（予約患者ではない？）";
        }
    } else if (strcmp($command,"PUT_FRONT_END_TIME") == 0){
        // FRONT の patientId, entryDate レコードの 診療終了時刻 endTime を変更
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $entryDate = $args['entryDate'];
        $endTime = $args['endTime'];
        $updateTime = timestamp();
        
        if ($endTime == NULL){ // 診療終了時刻を空にする
            // $endTime = "" は $endTime = NULL と解釈される
            $sql = "UPDATE `FrontTable` SET `endTime`= NULL, `updateTime`='$updateTime' WHERE `patientId`='$patientId' AND `entryDate`='$entryDate'";
        } else if (strlen($endTime) > 10){ // 診療終了時刻を $endTime にする
            $sql = "UPDATE `FrontTable` SET `endTime`='$endTime', `updateTime`='$updateTime' WHERE `patientId`='$patientId' AND `entryDate`='$entryDate'";
        } else { // $patientId の当日最終レコードの診療終了時刻を $updateTime にする
            // entryDate が $dateTime と同じ年月日のデータを検索
            // $entryDate は NOA の受診日時だが FRONT の entryDate とは時刻が微妙に異なる
            $date = substr($entryDate, 0, 10);
            $sql = "SELECT * FROM `FrontTable` WHERE `patientId`='$patientId' AND `entryDate`>'$date 00:00:00' AND `entryDate`<'$date 24:00:00' ORDER BY `entryDate` DESC";
            echo "PUT_FRONT_END_TIME:\n $sql \n"; //##
            $result = mysql_query($sql);
            
            // patientId 当日最終レコードの endTime:診療終了時刻 にタイムスタンプ刻印
            echo "<SEPARATOR>";
            if ($row=mysql_fetch_array($result)){
                // 同日再診の場合もあるので、当日最後のレコードのみ endTime にタイムスタンプ
                $rowid = $row['rowid'];
                $sql = "UPDATE `FrontTable` SET `endTime`= '$updateTime', `updateTime`='$updateTime' WHERE `rowid`='$rowid'";
                echo "$sql \n"; //##
                $result = mysql_query($sql);
            }
            exit;
        }
        echo "$sql ===== \n"; //##
        $result=mysql_query($sql);
        
        echo "<SEPARATOR>";
    } else if (strcmp($command,"LOGIN") == 0){
        $args = decodeObject($value);
        $loginName = $args['loginName'];
        $passwd = $args['passwd'];
        
        echo "logname($loginName) pwd($passwd)\n"; //return; //##
        
        if (strlen($loginName) == 0){
            echo "<SEPARATOR>";
            echo "ERROR: userName が入っていません";
            return;
        } else if (strlen($passwd) == 0){
            echo "<SEPARATOR>";
            echo "ERROR: password が入っていません";
            return;
        } else if (($row = getUser($loginName)) == null){
            // <SEPARATOR> がないなら error を示す
            echo "<SEPARATOR>";
            echo "ERROR: $loginName は登録されたユーザではありません";
            return;
        }
        
        if (strlen($row['identifier']) == 0){
            // <SEPARATOR> の後が何もないなら passwd が設定されていないので
            // passwd を入力させる
            echo "<SEPARATOR>";
        } else if (strcmp($row['identifier'], md5($passwd)) == 0){
            // 暗号化してから DB 値と比較する
            // <SEPARATOR> の後に文字があれば成功を示す
            $array = getHospitalNames(); // $array[hospitalName] = hospitalId
            $row['hospitalTable'] = $array;
            echo "<SEPARATOR>";
            echo json_encode($row);
        } else {
            echo "<SEPARATOR>";
            echo "ERROR: password が違っています";
        }
    } else if (strcmp($command,"PUT_PASSWD") == 0){
        // パスワードを設定・保存
        $args = decodeObject($value);
        $loginName = $args['loginName'];
        $passwd = $args['passwd'];
        
        $sql = "SELECT * FROM `UserTable` WHERE `loginName`='$loginName'";
        echo "$sql ===== \n"; //##
        $result=mysql_query($sql);
        if (mysql_num_rows ($result) > 0){
            $pwd = md5($passwd); // passwd を暗号化する
            $updateTime = timestamp();
            $sql = "UPDATE `UserTable`
			SET `identifier`='$pwd', `updateTime`='$updateTime'
			WHERE `loginName`='$loginName'";
            echo "$sql -----\n";
            $result=mysql_query($sql);
            echo "<SEPARATOR>";
            echo "パスワードが設定されました\n";
        } else {
            echo "<SEPARATOR>";
            echo "ERROR *** パスワードが設定できませんでした\n";
        }
    } else if (strcmp($command,"GET_FRONT_ACCEPTANCE") == 0){
        // NOA の pollingWORKER から呼ばれる
        $args = decodeObject($value);
        $dateTime = $args['dateTime']; // 以前チェックされた日付：today() が入っている
        $date = substr($dateTime, 0, 10);
        
        // タイムスタンプが更新されているかどうかをチェック
        $st = getTimeStamp($dateTime); // "same","empty","前回の更新日時" が返される
        if (strcmp($st, "same") == 0){
            echo "<SEPARATOR>";
            return;
        }
        
        // entryDate が $dateTime と同じデータを検索
        $sql = "SELECT * FROM `FrontTable` WHERE `entryDate`>'$date 00:00:00' ORDER BY `entryDate` DESC";
        echo "GET_FRONT_ACCEPTANCE:\n $sql \n"; //##
        $result=mysql_query($sql);
        
        $array = array();
        while ($row=mysql_fetch_array($result)){
            $rec = array();
			$rec['entryDate'] = $row['entryDate'];
			$rec['patientId'] = $row['patientId'];
			$rec['anotherId'] = $row['anotherId'];
			$rec['kanjiName'] = $row['kanjiName'];
			$rec['plan'] = $row['plan'];
			$rec['updateTime'] = $row['updateTime'];
			$rec['endTime'] = $row['endTime'];
            // waitingList に必要な項目
            $rec['insFee'] = $row['insFee'];
            $rec['ownFee'] = $row['ownFee'];
            $rec['reservedDate'] = $row['reservedDate'];
            $rec['reserved'] = ($row['entryDate'] > $row['updateTime']) ? "1" : "0";
            $patientId = trim($row['patientId']); // patientId に空白がついていることあり
            $dir = rootDir()."NOA_ARCHIVE/$patientId/Insurance";
            $obj = insScanDate($patientId, $dir);
            $rec['scanDataPath'] = $obj["path"];
            $rec['scanDateTime'] = $obj["filename"];
            $rec['postItColor'] = postItColor($patientId, $row['entryDate']);
            $recs[$dateAndId] = $rec;
            $array[] = $rec;
        }
        $records['records'] = $array;
        
        // メッセージの入ったレコードをサーチ
        $sql = "SELECT * FROM `FrontTable` WHERE `patientId`='MESSAGE'";
        $result=mysql_query($sql);
        echo "GET_MESSAGE:\n"; //##
        
        $array = 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'];
            $array[] = $rec;
        }
        $records['message'] = $array;
        
        // entryDate が $dateTime と同じ年月日のレコードの配列を返す
        echo "<SEPARATOR>";
        echo json_encode($records);
    } else if (strcmp($command,"GET_USER_TABLE") == 0){
        // UserTable の内容を返す
        $args = decodeObject($value);
        $loginName = $args['logName'];
        
        $row = getUser($loginName);
        echo "<SEPARATOR>";
        echo json_encode($row);
    } else if (strcmp($command,"GET_TOOL_MENU") == 0){
        // TOOL MENU の内容を検索
        $args = decodeObject($value);
        $owner = $args['owner'];
        
        $array = getToolMenu($owner);

        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"REMOVE_TOOL_MENU") == 0){
        //  ツール・メニューの項目を削除
        $args = decodeObject($value);
        $owner = $args['owner'];
        $id = $args['id'];
        $label = $args['label'];
        $tag = "TOOL_MENU";
        
        if ($label){
            $sql = "DELETE FROM `FieldTable` WHERE `tag`='$tag' AND `owner`='$owner' AND `id`='$id' AND `label`='$label'";
        } else {
            $sql = "DELETE FROM `FieldTable` WHERE `tag`='$tag' AND `owner`='$owner'";
        }
        echo "----- $sql \n"; //##
        $result=mysql_query($sql);
        
        echo "<SEPARATOR>";
        if ($label)
            echo "$label を削除しました";
        else
            echo "メニュー構造を工場出荷状態に戻しました";
    } else if (strcmp($command,"REMOVE_TAG_LABEL") == 0){
        // LAYOUT を工場出荷状態に戻す
        $args = decodeObject($value);
        $owner = $args['owner'];
        $direction = "CELL";
        
        $sql = "DELETE FROM `FieldTable` WHERE `owner`='$owner' AND `direction`='$direction'";
        echo "----- $sql \n"; //##
        $result=mysql_query($sql);
        
        echo "<SEPARATOR>";
        echo "レイアウトを工場出荷状態に戻しました";
    } else if (strcmp($command,"GET_HOSPITAL_INFO") == 0){
        $args = decodeObject($value);
        // hospitalId は UserTable には２つ以上持っている場合があるので外部から与える
        $hospitalId = $args['hospitalId'];
        $owner = $args['owner'];

        $array = getHospitalTable($hospitalId);
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"DUMP_PAGES") == 0){
        // 全ページを印刷する前に全ページのデータを local file へ書き出す
        $args = decodeObject($value);
        $owner = $args['owner'];
        $patientId = $args['patientId'];
        $dateTime = $args['currentDate']; 
        $path = $args['path']; 
        
        $results = array();
        $results['patientTable'] = getPatientTable($owner, $patientId);
        $results['nameSection'] = getNameSection($owner, $patientId);
        $results['progressSection'] = getProgressSection($owner, $patientId);
        //$results['frontTable'] = getFrontTable($owner, $patientId);

        $results['entryDate'] = $dateTime;
        $results['addressSection'] = getAddressSection($owner, $patientId, $dateTime);
        $results['basicSection'] = getBasicSection($owner, $patientId, $dateTime);
        $results['maritalSection'] = getMaritalSection($owner, $patientId, $dateTime);
        $results['universalSection'] = getUniversalSection($owner, $patientId, $dateTime);
        $results['healthInsurance'] = getHealthInsurance($owner, $patientId, $dateTime);
        $results['publicInsurance'] = getPublicInsurance($owner, $patientId, $dateTime);

        // 印刷モードの場合は結果をテンポラリーファイルに書き出す
        echo "<SEPARATOR>";
        if (file_put_contents($path, json_encode($results)))
            echo ""; // 成功したら空文字列を返す
        else
            echo "$path への書き出しに失敗しました";
    } else if (strcmp($command,"GET_PAGES") == 0){
        // カルテの全情報をサーバへリクエスト：受診者カルテが開かれた時に呼ばれる
        // ##### 当面は全情報ではなく ProgressSection のみ #####
        $args = decodeObject($value);
        $owner = $args['owner'];
        $patientId = $args['patientId'];
        
        $results = array();
        $results['patientTable'] = getPatientTable($owner, $patientId);
        $results['nameSection'] = getNameSection($owner, $patientId);
        $results['progressSection'] = getProgressSection($owner, $patientId);
        $results['frontTable'] = getFrontTable($owner, $patientId);
        $results['postIt'] = getPostIt($owner, $patientId);
        
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"GET_PAGE") == 0){
        // dateTime の情報をサーバへリクエスト
        $args = decodeObject($value);
        $owner = $args['owner'];
        $patientId = $args['patientId'];
        $dateTime = $args['dateTime'];
        
        $results = array();
        $results['entryDate'] = $dateTime;
        // nameSection は GET_PAGES でも取得しているが dateTime のレコードで上書き
        $results['nameSection'] = getNameSection($owner, $patientId, $dateTime);
        $results['addressSection'] = getAddressSection($owner, $patientId, $dateTime);
        $results['basicSection'] = getBasicSection($owner, $patientId, $dateTime);
        $results['maritalSection'] = getMaritalSection($owner, $patientId, $dateTime);
        $results['universalSection'] = getUniversalSection($owner, $patientId, $dateTime);
        $results['healthInsurance'] = getHealthInsurance($owner, $patientId, $dateTime);
        $results['publicInsurance'] = getPublicInsurance($owner, $patientId, $dateTime);
        
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"PUT_PAGE") == 0){
        // value に含まれる "tagname"="value" で DB を更新
        // IN: patientId entryDate owner [tag:value,tag:value,,]
        // OUT: debug 用メッセージのみで、特になし
        $args = decodeObject($value);
        $owner = $args['owner'];
        $patientId = $args['patientId'];
        // この entryDate 以前のものを境として「修正」か「追加」かを決定する
        $entryDate = $args['entryDate'];
        // entryDate から timeLimit秒 過ぎるまでは直接修正可能
        // それを過ぎると新しいページを追加し上書きする形になる
        $timeLimit = $args['timeLimit'];
        $updateTime = timestamp();
        
        // "ProgressSection.Subject"="some thing" の配列をスキャンして
        // $sections['ProgressSection']['Subject']='腹痛';
        // $sections['ProgressSection']['Object']='特記所見なし'';
        // のような Section Table の配列として記憶
        $sections = array(); // Section Table を入れる配列
        $updateValues = array(); // 更新リクエストを入れる配列
        foreach ($args as $key=>$val){
            if (strcmp($key, "owner") == 0) continue; // tag 以外は無視
            if (strcmp($key, "patientId") == 0) continue; // tag 以外は無視
            if (strcmp($key, "entryDate") == 0) continue; // tag 以外は無視
            if (strcmp($key, "timeLimit") == 0) continue; // tag 以外は無視
            
            echo("$key($val)\n"); //##
            
            // 上記以外は "HealthInsurance.bangou" 形式の tag のはず
            $ary = explode(".", $key);
            $table = $ary[0]; // table = "HealthInsurance"
            if (count($ary) > 1){
                $field = $ary[1]; // field = "bangou"
                
                //echo "--- $table $field($val) \n";
                
                // $val が null の場合、処理時に認識されないので別途 $updateValues で記憶
                $sections[$table][$field] = $val;
                $updateValues[$table][$field] = "hasValue";
            } else {
                //echo "--- $table($val) \n";
                // "HealthInsurance" のように field 指定がされていない場合は「削除」を表す
                $sections[$table] = null;
            }
        }
        
        // $sections 中のテーブルごとに DB 処理
        foreach ($sections as $sectionName=>$fieldArray){
            echo "=== PUT_PAGE：$sectionName $fieldArray \n"; //##
            if ($fieldArray == null){
                // "PublicInsurance:" のように　table 指定だけで
                // field 指定がされていなければそのテーブルの該当レコードを削除
                // ## page そのものがなくなるので pageHeader の更新は不要
                $sql = "DELETE FROM `$sectionName` WHERE `patientId`='$patientId' AND `entryDate`='$entryDate'";
                mysql_query($sql); // $sql 実行 ####
                echo "===\n $sql \n"; //##
            } else if  (strcmp($sectionName, "PatientTable") == 0){
                // PatientTable の場合は別処理
                $farray = array();
                foreach ($fieldArray as $fieldName=>$value){
                    $farray[] = "`$fieldName`='$value'";
                }
                $fst = join(",", $farray);
                $sql = "UPDATE `PatientTable` SET $fst,`updateTime`='$updateTime' WHERE `patientId`='$patientId'";
                mysql_query($sql); // $sql 実行 ####
                echo "===\n $sql \n"; //##
            } else if  (strcmp($sectionName, "FrontTable") == 0){
                // FrontTable について
                // $patientId,($entryDate の年月日部分) に一致するレコードを探す
                // $entryDate の１時間前と１時間後の日時の入った配列を返す
                $array = beforAndAfterDateTime($entryDate);
                $beginDate = $array[0];
                $endDate = $array[1];
                $sql = "SELECT * FROM `FrontTable` WHERE `patientId`='$patientId' AND `entryDate`>='$beginDate' AND `entryDate`<='$endDate'";
                echo "===\n $sql \n"; //##
                $result=mysql_query($sql);
                // レコードがあれば　$fieldArray 内のものをアップデート
                if (mysql_num_rows ($result) > 0){
                    // 該当するレコードの rowid をピックアップ
                    $row=mysql_fetch_array($result);
                    $rowid = $row['rowid'];
                    
                    // field 名のカンマ区切り文字列を作成
                    $farray = array();
                    foreach ($fieldArray as $fieldName=>$value){
                        $farray[] = "`$fieldName`='$value'";
                    }
                    $fst = join(",", $farray);
                    
                    // fieldArray に該当するデータをアップデート
                    $sql = "UPDATE `FrontTable` SET $fst,`updateTime`='$updateTime' WHERE `rowid`='$rowid'";
                    mysql_query($sql); // $sql 実行 ####
                    echo "===\n $sql \n"; //##
                    putTimeStamp(); // FRONT 画面を更新
                }
            } else if  (strcmp($sectionName, "UniversalSection") == 0){
                foreach ($fieldArray as $fieldName=>$value){
                    //　$status：entryDate + timeLimit（秒数）を越えていなければ 1 越えていれば 0
                    $status = isEditableRecord($sectionName, $fieldName,
                                               $patientId, $entryDate, $timeLimit);
                    
                    $array = explode(":", $status); // $status = "1:rowid" 形式
                    $rowid = (count($array) > 1) ? $array[1] : null;
                    if ($array[0] * 1 > 0){ // 当日のページを UPDATE
                        // ## rowid でなく patientId,entryDate で UPDATE すると
                        // ## 該当するほかの updateTime のものも全て変更されてしまう
                        $sql = "UPDATE `$sectionName` SET `field`='$fieldName',`dataString`='$value',`updateTime`='$updateTime',`owner`='$owner' WHERE `rowid`='$rowid'";
                        mysql_query($sql); // $sql 実行 ####
                        echo "===\n $sql \n"; //##
                    } else {
                        // 在来の当日ページがあれば削除マーク(freq=1)をつける
                        $sql = "UPDATE `$sectionName` SET `freq`='1',`updateTime`='$updateTime',`owner`='$owner' WHERE `patientId`='$patientId' AND `field`='$fieldName' AND `entryDate`='$entryDate' AND (`freq` IS NULL OR `freq`<1)";
                        echo "===\n $sql \n"; //##
                        $result=mysql_query($sql);
                        
                        // 当日のページを作成して追加
                        $updateTime = timestamp(); // 上と同じ updateTime を使わない
                        $sql = "INSERT INTO `$sectionName` (`patientId`,`type`,`field`,`dataString`,`entryDate`,`updateTime`,`freq`,`owner`) VALUES ('$patientId','0','$fieldName','$value','$entryDate','$updateTime','0','$owner')";
                        mysql_query($sql); // $sql 実行 ####
                        echo "===\n $sql \n"; //##
                    }
                }
            } else {
                //　$status：entryDate + timeLimit（秒数）を越えていなければ 1 越えていれば 0
                $status = isEditableRecord($sectionName, "", $patientId,
                                           $entryDate, $timeLimit);
                echo "--- status:$status \n"; //##
                $array = explode(":", $status); // $status = "1:rowid" 形式
                if ($array[0] * 1 > 0){ // 当日のページを UPDATE
                    $ary = array();
                    foreach ($fieldArray as $fieldName=>$value){
                        $ary[] = "`$fieldName`='$value'";
                    }
                    if ($sectionName == "ProgressSection"){
                        $pageHeader = "$updateTime ( $owner )"; // 漢字は化けることあり
                        $args['ProgressSection.pageHeader'] = $pageHeader; // 戻り値に追加
                        $ary[] = "`pageHeader`='$pageHeader'";
                    }
                    $fst = join(",", $ary);
                    // ## rowid でなく patientId,entryDate で UPDATE すると
                    // ## 該当するほかの updateTime のものも全て変更されてしまう
                    $rowid = (count($array) > 1) ? $array[1] : null;
                    if ($rowid == null){
                        echo "*** rowid is NULL \n"; //##
                    } else {
                        $sql = "UPDATE `$sectionName` SET $fst,`updateTime`='$updateTime',`owner`='$owner' WHERE `rowid`='$rowid'";
                        mysql_query($sql); // $sql 実行 ####
                        echo "===\n $sql \n"; //##
                    }
                } else {
                    // 削除マークをつける前に、在来のレコードを取得しておく
                    $sql = "SELECT * FROM `$sectionName` WHERE `patientId`='$patientId' AND `entryDate`='$entryDate' AND (`freq` IS NULL OR `freq`<1)";
                    echo "===\n $sql \n"; //##
                    $result=mysql_query($sql);
                    
                    if ($old_row=mysql_fetch_array($result)){
                        // 在来の当日ページに削除マーク(freq=1)をつけ updateTime はそのまま
                        // ##### 削除マークをつけて残し修正前ページを再現可能とする #####
                        $rowid = $old_row['rowid'];
                        $sql = "UPDATE `$sectionName` SET `freq`='1',`owner`='$owner' WHERE `rowid`='$rowid'";
                        echo "=== ADD DELETE MARK \n $sql \n"; //##
                        $result=mysql_query($sql); 
                                                
                        // 在来レコードを変更データで上書きした新レコードを生成
                        $farray = array();
                        $varray = array();
                        foreach ($old_row as $fieldName=>$value){
                            if (is_numeric($fieldName)) continue;
                            if (strcmp($fieldName, 'patientId') == 0) continue;
                            if (strcmp($fieldName, 'pageHeader') == 0) continue;
                            if (strcmp($fieldName, 'entryDate') == 0) continue;
                            if (strcmp($fieldName, 'updateTime') == 0) continue;
                            if (strcmp($fieldName, 'owner') == 0) continue;
                            if (strcmp($fieldName, 'rowid') == 0) continue;
                            
                            if ($fieldArray[$fieldName] === NULL) // 変更データがなかった
                                $val = $old_row[$fieldName];
                            else // 変更データがあった
                                $val = $fieldArray[$fieldName];
                            $farray[] = "`$fieldName`";
                            $varray[] = "'$val'";
                        }
                        if ($sectionName == "ProgressSection"){
                            $pageHeader = "$updateTime ( $owner )"; // 漢字は化けることあり
                            $args['ProgressSection.pageHeader'] = $pageHeader; // 戻り値に追加
                            $farray[] = "`pageHeader`";
                            $varray[] = "'$pageHeader'";
                        }
                        $fst = join(",", $farray);
                        $vst = join(",", $varray);
                        $sql = "INSERT INTO `$sectionName` ($fst,`patientId`,`entryDate`,`updateTime`,`owner`) VALUES ($vst,'$patientId','$entryDate', '$updateTime','$owner')";
                        mysql_query($sql); // $sql 実行 ####
                        echo "===\n $sql \n"; //##
                    } else {
                        $farray = array();
                        $varray = array();
                        if ($sectionName == "ProgressSection"){
                            // 指定された日のページがなかったので、新規ページを追加
                            $pageHeader = "$updateTime ( $owner )"; // 漢字は化けることあり
                            $fieldArray['pageHeader'] = $pageHeader; // 戻り値に追加
                            foreach ($fieldArray as $fieldName=>$value){
                                $farray[] = "`$fieldName`";
                                $varray[] = "'$value'";
                            }
                            $fst = join(",", $farray);
                            $vst = join(",", $varray);
                            $sql = "INSERT INTO `ProgressSection` ($fst,`patientId`,`entryDate`,`updateTime`,`owner`) VALUES ($vst,'$patientId','$entryDate', '$updateTime','$owner')";
                        } else {
                            // 在来レコードを変更データで上書きした新レコードを生成
                            foreach ($fieldArray as $fieldName=>$value){
                                $farray[] = "`$fieldName`";
                                $varray[] = "'$value'";
                            }
                            $fst = join(",", $farray);
                            $vst = join(",", $varray);
                            $sql = "INSERT INTO `$sectionName` ($fst,`patientId`,`entryDate`,`updateTime`,`owner`) VALUES ($vst,'$patientId','$entryDate', '$updateTime','$owner')";
                        }
                        mysql_query($sql); // $sql 実行 ####
                        echo "===\n $sql \n"; //##
                    }
                }
            }
        }
        
        // lastVisitDate(最終受診日)を PatientTable に記録する
        $sql = "UPDATE `PatientTable` SET `lastVisitDate`='$entryDate',`updateTime`='$updateTime' WHERE `patientId`='$patientId'";
        //echo "=== lastVistDate を更新\n $sql \n"; //##
        mysql_query($sql);
        
        echo "=========== \n";
        echo "<SEPARATOR>";
        echo json_encode($args); // 更新ページヘッダーが追加されている
    } else if (strcmp($command,"REMOVE_PAGE") == 0){
        // 当日のページを全部削除
        // IN: patientId entryDate owner
        // OUT: 終了したら "<SEPARATOR>" -- 余り意味がないがとりあえず
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $entryDate = $args['entryDate'];
        $timeLimit = $args['timeLimit'];
        $owner = $args['owner'];
        
        // timeLimit 以内の ProgressSection レコードの有無をチェック
        $status = isEditableRecord("ProgressSection", "", $patientId, $entryDate, $timeLimit);
        $where = "`patientId`='$patientId' AND `entryDate`='$entryDate'";
        $array = explode(":", $status);
        if ($array[0] * 1 > 0){
            // ProgressSection の更新が編集可能制限時間 timeLimit 以内だった
            // entryDate のレコード全てを削除
            $sql = "DELETE FROM `AddressSection` WHERE $where";
            echo "===\n $sql \n";
            mysql_query($sql);
            $sql = "DELETE FROM `BasicSection` WHERE $where";
            echo "===\n $sql \n";
            mysql_query($sql);
            $sql = "DELETE FROM `HealthInsurance` WHERE $where";
            echo "===\n $sql \n";
            mysql_query($sql);
            $sql = "DELETE FROM `MalitalSection` WHERE $where";
            echo "===\n $sql \n";
            mysql_query($sql);
            $sql = "DELETE FROM `NameSection` WHERE $where";
            echo "===\n $sql \n";
            mysql_query($sql);
            $sql = "DELETE FROM `ProgressSection` WHERE $where";
            echo "===\n $sql \n";
            mysql_query($sql);
            $sql = "DELETE FROM `PublicInsurance` WHERE $where";
            echo "===\n $sql \n";
            mysql_query($sql);
            $sql = "DELETE FROM `UniversalSection` WHERE $where";
            echo "===\n $sql \n";
            mysql_query($sql);
        } else {
            // 編集可能制限時間 timeLimit 以上経過しているのでレコード削除不可
            // すべてのセクションの同じ entryDate のレコードを対象に ######
            // freq に削除マークとして 1 を入れる
            $sql = "UPDATE `ProgressSection` SET `freq`='1',`updateTime`='$updateTime' WHERE $where";
            echo "===\n $sql \n";
            mysql_query($sql);
        }
        $array['patientId'] = $patientId;
        echo "<SEPARATOR>";
        echo json_encode($arroy);
    } else if (strcmp($command,"GET_POSTIT") == 0){
        // カルテの全情報をサーバへリクエスト：受診者カルテが開かれた時に呼ばれる
        // ##### 当面は全情報ではなく ProgressSection のみ #####
        $args = decodeObject($value);
        $owner = $args['owner'];
        $patientId = $args['patientId'];
        $records = getPostIt($owner, $patientId);
        
        echo "<SEPARATOR>";
        echo json_encode($records);
    } else if (strcmp($command,"GET_PATIENTS") == 0){
        // カルテID、氏名、ふりがな などでカルテを検索
        $args = decodeObject($value);
        $key = $args['key'];
        $val = $args['val'];
        echo "key($key) val($val) \n"; //return; //###
        
        if (strcmp($key, "id") == 0){
            // カルテID による検索
            $sql = "SELECT * FROM `PatientTable` WHERE `patientId` LIKE '$val%' ORDER BY `patientId`";
            $result=mysql_query($sql);
            echo "$sql \n"; //return; //###
            $records = array();
            while ($row=mysql_fetch_array($result)){
                $nameRow = nameSectionWithPatientId($row['patientId']);
                $rec = array();
                $rec['patientId'] = $row['patientId'];
                $rec['anotherId'] = $row['anotherId'];
                $rec['receiptId'] = $row['receiptId'];
                $rec['sex'] = $row['sex'];
                $rec['unpaid'] = $row['unpaid'];
                $rec['birthDate'] = $row['birthDate'];
                $rec['deathDate'] = $row['deathDate'];
                $rec['lastVisitDate'] = $row['lastVisitDate'];
                $rec['updateTime'] = $row['updateTime'];
                $rec['patientKanjiName'] = $nameRow['patientKanjiName'];
                $rec['patientKanaName'] = $nameRow['patientKanaName'];
                $rec['patientRomajiName'] = $nameRow['patientRomajiName'];
                $records[] = $rec;
            }
            echo "<SEPARATOR>";
            echo json_encode($records);
        } else if (strcmp($key, "anotherId") == 0){ // anotherId による検索
            $sql = "SELECT * FROM `PatientTable` WHERE `anotherId` LIKE '$val%' ORDER BY `anotherId`";
            $result=mysql_query($sql);
            echo "$sql \n"; //###
            $records = array();
            while ($row=mysql_fetch_array($result)){
                $nameRow = nameSectionWithPatientId($row['patientId']);
                $rec = array();
                $rec['patientId'] = $row['patientId'];
                $rec['anotherId'] = $row['anotherId'];
                $rec['receiptId'] = $row['receiptId'];
                $rec['sex'] = $row['sex'];
                $rec['unpaid'] = $row['unpaid'];
                $rec['birthDate'] = $row['birthDate'];
                $rec['deathDate'] = $row['deathDate'];
                $rec['lastVisitDate'] = $row['lastVisitDate'];
                $rec['patientKanjiName'] = $nameRow['patientKanjiName'];
                $rec['patientRomajiName'] = $nameRow['patientRomajiName'];
                $records[] = $rec;
            }
            // 重複した patientId のものをユニークにする
            $rec = array();
            while (list($pid, $ary) = each ($records)) $rec[] = $ary;
            echo "<SEPARATOR>";
            echo json_encode($rec);
        } else if (strcmp($key, "roma") == 0){ // ローマ字による検索
            $sql = "SELECT * FROM `NameSection` WHERE `patientRomajiName` LIKE '%$val%' ORDER BY `patientId`";
            $result=mysql_query($sql);
            echo "$sql \n"; //###
            $records = array();
            while ($row=mysql_fetch_array($result)){
                $rec = array();
                $rec['patientKanjiName'] = $row['patientKanjiName'];
                $rec['patientRomajiName'] = $row['patientRomajiName'];
                $prow = patientTableWithPatientId($row['patientId']);
                $rec['patientId'] = $prow['patientId'];
                $rec['anotherId'] = $prow['anotherId'];
                $rec['receiptId'] = $prow['receiptId'];
                $rec['sex'] = $prow['sex'];
                $rec['unpaid'] = $prow['unpaid'];
                $rec['birthDate'] = $prow['birthDate'];
                $rec['deathDate'] = $prow['deathDate'];
                $rec['lastVisitDate'] = $prow['lastVisitDate'];
                $records[$row['patientId']] = $rec;
            }
            // 重複した patientId のものをユニークにする
            $rec = array();
            while (list($pid, $ary) = each ($records)) $rec[] = $ary;
            echo "<SEPARATOR>";
            echo json_encode($rec);
        } else { // 漢字または仮名による検索
            // 姓名の間に空白がある場合、スペースが半角でも全角でも検索する
            $array = explode(" ", $val); // 半角スペースが存在するか
            if (count($array) == 1)
                $array = explode("　", $val); // 全角スペースが存在するか
            if (count($array) > 1){
                $sei = $array[0];
                $mei = $array[1];
                $sql = "SELECT * FROM `NameSection` WHERE (`patientKanjiName` LIKE '%$sei%' AND `patientKanjiName` LIKE '%$mei%') OR (`patientKanaName` LIKE '%$sei%' AND `patientKanaName` LIKE '%$mei%') ORDER BY `patientId`";
            } else {
                $sql = "SELECT * FROM `NameSection` WHERE (`patientKanjiName` LIKE '%$val%') OR (`patientKanaName` LIKE '%$val%') ORDER BY `patientId`";
            }
            
            $result=mysql_query($sql);
            echo "$sql \n"; //###
            $records = array();
            while ($row=mysql_fetch_array($result)){
                $rec['patientKanjiName'] = $row['patientKanjiName'];
                $rec['patientRomajiName'] = $row['patientRomajiName'];
                $prow = patientTableWithPatientId($row['patientId']);
                $rec['patientId'] = $prow['patientId'];
                $rec['anotherId'] = $prow['anotherId'];
                $rec['receiptId'] = $prow['receiptId'];
                $rec['sex'] = $prow['sex'];
                $rec['unpaid'] = $prow['unpaid'];
                $rec['birthDate'] = $prow['birthDate'];
                $rec['deathDate'] = $prow['deathDate'];
                $rec['lastVisitDate'] = $prow['lastVisitDate'];
                $records[$row['patientId']] = $rec;
            }
            // 重複した patientId のものをユニークにする
            $rec = array();
            while (list($pid, $ary) = each ($records)) $rec[] = $ary;
            echo "<SEPARATOR>";
            echo json_encode($rec);
        }
    } else if (strcmp($command,"GET_ACCESS_LOG") == 0){
        // owner のアクセス・ログを取り出し返す
        $args = decodeObject($value);
        $owner = $args['owner'];
        $reverse = $args['reverse'];
        
        $results = getAccessLog($owner, $reverse);
        
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"REMOVE_ACCESS_LOG") == 0){
        $args = decodeObject($value);
        $owner = $args['owner'];
        $patientId = $args['patientId'];
        
        $results = removeAccessLog($patientId, $owner);
        
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"GET_MENU") == 0){
        // tag, onwer に該当するメニュー・リストを返す
        $args = decodeObject($value); // client 側との約束ごと
        $array = getMenuItems($args['tag'], $args['owner'], $args['isAddressMenu']);
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"PUT_MENU") == 0){
        // tag, onwer に該当するメニュー・リストを DB へ保存
        // address.js form.js で使う
        // IN: tag owner menuItem val menuAction freq
        // OUT: array["menuAcion"]=val, array[menuItem]="freq:val",,,
        $args = decodeObject($value);
        $tag = $args['tag'];
        $owner = $args['owner'];
        $menuItem = $args['menuItem'];
        $freq = $args['freq'];
        $val = $args['val'];
        $dateTime = timeStamp();
        
        if (strlen($menuItem)){
            // MenuTable をアップデート
            // ### tag(メニュー名称)は他人とダブルことはできない
            $sql = "SELECT * FROM `MenuTable` WHERE `tag`='$tag' AND `menu`='$menuItem' AND `template` IS NULL  AND `owner`='$owner'";
            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 (strlen($freq) == 0) $freq = $row['freq'] + 1; // 頻度インクリメント
                $_val = (strlen($val) > 0) ? ",`value`='$val'" : "";
                
                $sql = "UPDATE `MenuTable` SET `freq`='$freq',`updateTime`='$dateTime' $_val WHERE `tag`='$tag' AND `menu`='$menuItem' AND `template` IS NULL  AND `owner`='$owner'";
            } else { // 同じ menuItem が存在しなかった
                if (strlen($freq) == 0) $freq = 0;
                $sql = "INSERT INTO `MenuTable` ( `tag`,`freq`,`menu`,`value`,`updateTime`,`owner` ) VALUES ( '$tag','$freq','$menuItem','$val','$dateTime','$owner')";
            }
            echo "$sql ========\n"; //###
            mysql_query($sql);
        }
        
        // 変更結果を返す
        $array = getMenuItems($tag, $owner);
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"REMOVE_MENU") == 0){
        // メニューを削除
        // form.js templateMenu.js で使う
        $args = decodeObject($value);
        $owner = $args['owner'];
        $tag = $args['tag'];
        
        $menu = $args['menuItem'];
        $menu = decodeSTRING($menu);
        
        $template = $args['template'];
        if (strlen($template) == 0){
            $templateSt = "`template` IS NULL";
        } else {
            $template = decodeSTRING($template);
            $templateSt = "`template`='$template'";
        }
        
        $sql = "DELETE FROM `MenuTable` WHERE `tag`='$tag' AND `owner`='$owner' AND  `menu`='$menu' AND $templateSt";
        echo "$sql ========\n"; //###
        mysql_query($sql);
        
        // 変更結果を返す
        $array = getMenuItems($tag, $owner);
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"PUT_PUBLIC_MENU") == 0){
        // public menu の表示・非表示を設定
        // cellPreference.js で使う
        $args = decodeObject($value);
        $owner = $args['owner'];
        $tag = $args['tag'];
        $publicMenus = $args['publicMenus']; // {"主婦":true,"会社員":false,,,} 型式
        $isGroupMenu = ($publicMenus['GroupMenu']) ? TRUE : FALSE;
        $dateTime = timeStamp();
        
        foreach ($publicMenus as $menu=>$status){
            // GroupMenu であることを伝えるだけのためのレコードはスキップ
            if (strcmp($menu, 'GroupMenu') == 0) continue;
            
            // $owner,$tag,$menu の $satatus 0:表示 1:非表示 を public 属性にセット
            if ($status * 1 > 0){ // public 表示
                // public menu を打ち消す $owner レコードを削除
                if ($isGroupMenu){
                    $sql = "DELETE FROM `ProgressSection` WHERE `patientId`='GroupMenu' AND `owner`='$owner' AND  `subject`='$menu'";
                } else {
                    $sql = "DELETE FROM `MenuTable` WHERE `tag`='$tag' AND `owner`='$owner' AND  `menu`='$menu'";
                }
                echo "$sql ========\n"; //###
                mysql_query($sql);
            } else { // public 非表示
                if ($isGroupMenu){
                    // public menu を打消すため 
                    // $owner,$tag,$menu で public=2 のレコードを挿入
                    $sql = "SELECT * FROM `ProgressSection` WHERE `owner`='$owner' AND `patientId`='GroupMenu' AND `subject`='$menu'";
                    echo "$sql ========\n"; //###
                    $result=mysql_query($sql);
                    
                    if (mysql_num_rows ($result) > 0){	// 同じ menu が存在した
                        $row=mysql_fetch_array($result);
                        $rowid = $row['rowid'];
                        // $status のみ更新（1 は過去に使われているので 2 を設定）
                        $sql = "UPDATE `ProgressSection` SET `pageHeader`='2',`updateTime`='$dateTime' WHERE `rowid`='$rowid'";
                    } else { // 同じ menu が存在しなかった
                        $sql = "INSERT INTO `ProgressSection` ( `patientId`,`subject`,`pageHeader`,`updateTime`,`owner` ) VALUES ( 'GroupMenu','$menu','2','$dateTime','$owner')";
                    }
                } else {
                    // public menu を打消すため 
                    // $owner,$tag,$menu で public=2 のレコードを挿入
                    $sql = "SELECT * FROM `MenuTable` WHERE `owner`='$owner' AND `tag`='$tag' AND `menu`='$menu' AND `template` IS NULL";
                    echo "$sql ========\n"; //###
                    $result=mysql_query($sql);
                    
                    if (mysql_num_rows ($result) > 0){	// 同じ menu が存在した
                        $row=mysql_fetch_array($result);
                        $rowid = $row['rowid'];
                        // $status のみ更新（1 は過去に使われているので 2 を設定）
                        $sql = "UPDATE `MenuTable` SET `public`='2',`updateTime`='$dateTime' WHERE `rowid`='$rowid'";
                    } else { // 同じ menu が存在しなかった
                        $sql = "INSERT INTO `MenuTable` ( `tag`,`freq`,`menu`,`public`,`updateTime`,`owner` ) VALUES ( '$tag','0','$menu','2','$dateTime','$owner')";
                    }
                }
                echo "$sql ========\n"; //###
                mysql_query($sql);
            }
        }
        
        // 変更結果を返す
        $array = getMenuItems($tag, $owner);
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"GET_GROUP_MENU") == 0){
        $args = decodeObject($value);
        $owner = $args['owner'];
        
        $sql = "SELECT * FROM `ProgressSection` WHERE `patientId`='GroupMenu' AND (`owner`='$owner' OR `owner`='public') ORDER BY `freq` DESC";
        echo "$sql ========\n"; //###
        $result=mysql_query($sql);
        
        $menuItems = array();
        while ($row=mysql_fetch_array($result)){
            $ary = array();
            $ary['owner'] = $row['owner'];
            $ary['freq'] = $row['freq'];
            $menu = $ary['menu'] = $row['subject'];
            $ary['public'] = $row['pageHeader']; // 共有メニューに使われる
            $ary['ProgressSection.subject'] = $row['subject']; // あえて重複
            $ary['ProgressSection.object'] = $row['object'];
            $ary['ProgressSection.examination'] = $row['examination'];
            $ary['ProgressSection.prescription'] = $row['prescription'];
            $ary['ProgressSection.disease'] = $row['disease'];
            $ary['ProgressSection.treatment'] = $row['treatment'];
            $ary['ProgressSection.assessment'] = $row['assessment'];
            $ary['ProgressSection.plan'] = $row['plan'];
            $ary['ProgressSection.note'] = $row['note'];
            // owner のものを優先的に取り込む：owner のものが無ければ public を取り込む
            if (!$menuItems[$menu] || (strcmp($row['owner'],$owner) == 0))
                $menuItems[$menu] = $ary;
        }
        echo "<SEPARATOR>";
        echo json_encode($menuItems);
    } else if (strcmp($command,"PUT_GROUP_MENU") == 0){
        // とりあえずは GROUP MENU の頻度更新のみ
        $args = decodeObject($value);
        $owner = $args['owner'];
        $freq = $args['freq'];
        $menuItem = decodeSTRING($args['menuItem']);
        $subject = decodeSTRING($args['ProgressSection.subject']);
        $object = decodeSTRING($args['ProgressSection.object']);
        $assessment = decodeSTRING($args['ProgressSection.assessment']);
        $plan = decodeSTRING($args['ProgressSection.plan']);
        $disease= decodeSTRING($args['ProgressSection.disease']);
        $examination = decodeSTRING($args['ProgressSection.examination']);
        $prescription = decodeSTRING($args['ProgressSection.prescription']);
        $treatment = decodeSTRING($args['ProgressSection.treatment']);
        $note = $args['ProgressSection.note'];
        $updateTime = timestamp();
        
        if (strcmp($freq, "-1") == 0){
            // $freq が 負数 ならその $menuItem の削除命令となる
            $sql = "DELETE FROM `ProgressSection` WHERE `patientId`='GroupMenu' AND `subject`='$menuItem' AND `owner`='$owner'";
            echo "$sql ========\n"; //###
            $result=mysql_query($sql);
            echo "<SEPARATOR>";
            echo "groupMenu: $menuItem are removed...";
        } else {
            $sql = "SELECT * FROM `ProgressSection` WHERE `patientId`='GroupMenu' AND `subject`='$menuItem' AND `owner`='$owner'";
            echo "$sql ========\n"; //###
            $result=mysql_query($sql);
            
            // 該当するデータがあれば更新、なければ追加
            if ($row=mysql_fetch_array($result)){
                if (strlen($freq) == 0) {
                    // $freq == "" なら頻度のインクリメントのみ行う
                    $freq = $row['freq'] + 1; // 頻度インクリメント
                    $sql = "UPDATE `ProgressSection`
                    SET `freq`='$freq',`updateTime`='$updateTime'
                    WHERE `patientId`='GroupMenu' AND `subject`='$menuItem' AND `owner`='$owner'";
                } else {
                    $sql = "UPDATE `ProgressSection` SET
                    `object`='$object'
                    ,`examination`='$examination'
                    ,`prescription`='$prescription'
                    ,`disease`='$disease'
                    ,`treatment`='$treatment'
                    ,`assessment`='$assessment'
                    ,`plan`='$plan'
                    ,`note`='$note'
                    ,`freq`='$freq'
                    ,`updateTime`='$updateTime'
                    WHERE `patientId`='GroupMenu' AND `subject`='$menuItem' AND `owner`='$owner'";
                }
            } else {
                $sql = "INSERT INTO `ProgressSection`
                ( `patientId`,`subject`,`object`,`examination`,`prescription`,`disease`
                 ,`treatment`,`assessment`,`plan`,`note`,`freq`,`updateTime`,`owner`)
                VALUES ( 'GroupMenu','$subject','$object','$examination','$prescription','$disease','$treatment','$assessment','$plan','$note','$freq','$updateTime','$owner')";
            }
            
            echo "$sql ========\n\n"; //###
            mysql_query($sql);
            echo "<SEPARATOR>";
            echo $freq;
        }
    } else if (strcmp($command,"PUT_MENU_TEMPLATE") == 0){
        // tag, onwer に該当するメニュー・リストを DB へ保存
        // address.js form.js で使う
        $args = decodeObject($value);
        $tag = $args['tag'];
        $owner = $args['owner'];
        $menuItem = $args['menuItem'];
        $menuItem = decodeSTRING($menuItem);
        $tempName = $args['tempName'];
        $tempName = decodeSTRING($tempName);
        $freq = $args['freq'];
        $val = $args['val'];
        $dateTime = timeStamp();
        
        if (strlen($menuItem)){
            // MenuTable をアップデート
            // ### tag(メニュー名称)は他人とダブルことはできない
            $sql = "SELECT * FROM `MenuTable` WHERE `tag`='$tag' AND `menu`='$menuItem' AND `template`='$tempName' AND `owner`='$owner'";
            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 (strlen($freq) == 0) $freq = $row['freq'] + 1; // 頻度インクリメント
                $_val = (strlen($val) > 0) ? ",`value`='$val'" : "";
                
                $sql = "UPDATE `MenuTable` SET `freq`='$freq',`updateTime`='$dateTime' $_val WHERE `rowid`='$rowid'";
            } else { // 同じ menuItem が存在しなかった
                if (strlen($freq) == 0) $freq = 0;
                $sql = "INSERT INTO `MenuTable` ( `tag`,`freq`,`menu`,`template`,`value`,`updateTime`,`owner` ) VALUES ( '$tag','$freq','$menuItem','$tempName','$val','$dateTime','$owner')";
            }
            echo "$sql ========\n"; //###
            mysql_query($sql);
        }
        
        // 変更結果を返す
        $array = getMenuItems($tag, $owner);
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"GET_MENU_TEMPLATE") == 0){
        // テンプレート・メニューを DB から取得
        $args = decodeObject($value);
        $owner = $args['owner'];
        $tag = 'GROUP_TEMPLATE';
        
        $menuItems = getMenuItems($tag, $owner, FALSE);
        echo "<SEPARATOR>";
        echo json_encode($menuItems);
    } else if (strcmp($command,"REMOVE_MENU_TEMPLATE") == 0){
        // テンプレート・メニューを削除
        // form.js で使う
        $args = decodeObject($value);
        $owner = $args['owner'];
        $tag = $args['tag'];
        $menu = $args['menuItem'];
        $template = $args['tempName'];
        
        $sql = "DELETE FROM `MenuTable` WHERE `tag`='$tag' AND `owner`='$owner' AND  `menu`='$menu' AND `template`='$template'";
        echo "$sql ========\n"; //###
        mysql_query($sql);
        
        // 変更結果を返す
        $array = getMenuItems($tag, $owner);
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"PUT_STANDARD") == 0){
        // tag, onwer に該当するメニュー・リストを DB へ保存
        // address.js form.js で使う
        // IN: tag owner menuItem val menuAction freq
        // OUT: array["menuAcion"]=val, array[menuItem]="freq:val",,,
        $args = decodeObject($value);
        $tag = "STANDARD";
        $owner = $args['owner'];
        $item = $args['item'];
        $val = $args['value'];
        $dateTime = timeStamp();
        
        if (strlen($item)){
            if ($val){
                // MenuTable をアップデート
                // ### tag(メニュー名称)は他人とダブルことはできない
                $sql = "SELECT * FROM `MenuTable` WHERE `tag`='$tag' AND `menu`='$item' AND `owner`='$owner'";
                echo "$sql ========\n"; //###
                $result=mysql_query($sql);
                if (mysql_num_rows ($result) > 0){	// 同じ menuItem が存在した
                    $row=mysql_fetch_array($result);
                    $rowid = $row['rowid'];
                    // menuItem は同じなので freq のみ更新
                    $sql = "UPDATE `MenuTable` SET `value`='$val',`updateTime`='$dateTime' WHERE `rowid`='$rowid'";
                } else { // 同じ item が存在しなかった
                    $sql = "INSERT INTO `MenuTable` ( `tag`,`menu`,`value`,`updateTime`,`owner` ) VALUES ( '$tag','$item','$val','$dateTime','$owner')";
                }
            } else {
                // $val が指定されていなければこのレコードを削除
                $sql = "DELETE FROM `MenuTable` WHERE `tag`='$tag' AND `menu`='$item' AND `owner`='$owner'";
            }
            echo "$sql ========\n"; //###
            mysql_query($sql);
        }
        
        // 変更結果を返す
        $array = getStandard($tag, $owner);
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"GET_STANDARD") == 0){
        $args = decodeObject($value);
        $tag = "STANDARD";
        $owner = $args['owner'];
        
        $array = getStandard($tag, $owner);
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"GET_PRICE_LIST") == 0){
        // PriceList の code, name に該当するレコードを返す
        $args = decodeObject($value);
        $code = $args['code'];
        $name = $args['name'];
        $sql = "SELECT * FROM `PriceList` WHERE `code`='$code' AND `name`='$name'";
        echo "$sql ========\n"; //###
        $result = mysql_query($sql);
        
        echo "<SEPARATOR>";
        if ($row=mysql_fetch_array($result)){
            $record = array();
            foreach ($row as $fieldName=>$value){
                if (is_numeric($fieldName)) continue;
                $record[$fieldName] = $value;
            }
            echo json_encode($record);
            break;
        }
    } else if (strcmp($command,"PUT_DISEASE_TO_PRICELIST") == 0){
        // $name に対応する $disease を保存
        $args = decodeObject($value);
        $name = $args['name'];
        $disease = $args['disease'];
        $now = timeStamp();
        
        $sql = "SELECT * FROM `PriceList` WHERE `name`='$name'";
        $result = mysql_query($sql);
        if (mysql_num_rows ($result) > 0){
            $row=mysql_fetch_array($result);
            $rowid = $row['rowid'];
            $sql = "UPDATE `PriceList` SET `disease`='$disease',`updateTime`='$now' WHERE `rowid`='$rowid'";
            mysql_query($sql);
        } else {
            // 既存の name が見つからないことはないはず
            $sql = "PUT_DISEASE_TO_PRICELIST: $name not found.";
        }
        
        // すべてのチェックリストを検索し 病名チェックリストを返す
        $sql = "SELECT * FROM `PriceList` ORDER BY `alias`";
        $result = mysql_query($sql);
        echo "$sql \n"; // ##
        
        $results = array();
        while ($row = mysql_fetch_array($result)){
            $name = $row['name'];
            $disease = $row['disease'];
            if ($disease){
                $rec = array();
                $rec['code'] = $row['code'];
                $rec['disease'] = $disease;
                $results[$name] = $rec;
            }
        }
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"GET_DISEASE_FROM_PRICELIST") == 0){
        // PriceList の name に対応する disease をサーバへリクエスト
        $args = decodeObject($value);
        $name = $args['name'];

        if ($name && (strlen($name) > 0)){ // $name に対応するものだけを検索
            $sql = "SELECT * FROM `PriceList` WHERE `name`='$name'";
            $result = mysql_query($sql);
            echo "$sql \n"; // ##
            
            echo "<SEPARATOR>";
            if ($row = mysql_fetch_array($result)){
                echo $row['disease'];
            }
        } else { // すべてのチェックリストを検索
            $sql = "SELECT * FROM `PriceList` ORDER BY `alias`";
            $result = mysql_query($sql);
            echo "$sql \n"; // ##
            
            $results = array();
            while ($row = mysql_fetch_array($result)){
                $name = $row['name'];
                $disease = $row['disease'];
                if ($disease){
                    $rec = array();
                    $rec['code'] = $row['code'];
                    $rec['disease'] = $disease;
                    $results[$name] = $rec;
                }
            }
            echo "<SEPARATOR>";
            echo json_encode($results);
        }
    } else if (strcmp($command,"REMOVE_DISEASE_FROM_PRICELIST") == 0){
        // PriceList の name に対応する disease を削除
        $args = decodeObject($value);
        $name = $args['name'];
        $now = timeStamp();
        
        $sql = "UPDATE `PriceList` SET `disease`='',`updateTime`='$now' WHERE `name`='$name'";
        mysql_query($sql);
        echo "$sql \n"; // ##

        echo "<SEPARATOR>";
    } else if (strcmp($command,"GET_DISEASE_FROM_HOSTORY") == 0){
        // 過去１年間の全カルテ履歴から name とともに使われた病名を探して返す
        $args = decodeObject($value);
        $name = $args['name']; // 診療行為名
        $fromDate = $args['fromDate'];
        
        $sql = "SELECT * FROM `ProgressSection` WHERE `entryDate`>'$fromDate' AND `treatment`LIKE'%$name%' AND (`freq` IS NULL OR `freq`<1)";
        $result = mysql_query($sql);
        echo "$sql \n"; // ##
        
        $results = array();
        while ($row = mysql_fetch_array($result)){
            if ($row['disease']){
                $ln = trim($row['disease']); // 病名欄の内容
                if (strlen($ln) > 0)
                    $results[] = $ln; 
            }
        }
        
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"PUT_ARCHIVE") == 0){
        // $patientId のデータをアーカイブし保存
        $args = decodeObject($value);
        $owner = $args['owner'];
        $patientId = $args['patientId'];
        
        // $owner のレイアウトに存在する tag の配列を得る
        $tagArray = layoutTags($owner);
        
        // $patientId のカルテをアーカイブ
        $buff = archive($patientId, $tagArray);
        if (save($patientId, $buff)){
            echo "<SEPARATOR>";
            echo $buff;
        } else
            echo "$patientId cannot save";
    } else if (strcmp($command,"PUT_VIN_FILTER") == 0){
        $args = decodeObject($value);
        $tag = 'VIN_FILTER';
        $key = $args['key'];
        $val = $args['value'];
        $dateTime = $args['dateTime'];
        
        if (strlen($val) == 0){ // val が空なら削除
            $sql = "DELETE FROM `MenuTable` WHERE `tag`='$tag' AND `menu`='$key'";
        } else {
            $sql = "SELECT * FROM `MenuTable` WHERE `tag`='$tag' AND `menu`='$key'";
            $result = mysql_query($sql);
            echo "$sql \n"; // message
            
            if ($row = mysql_fetch_array($result)){
                $rowid = $row['rowid'];
                $sql = "UPDATE `MenuTable` SET `value`='$val',`updateTime`='$dateTime' WHERE `rowid`='$rowid'";
            } else { // 同じ menu が存在しなかった
                $sql = "INSERT INTO `MenuTable` ( `tag`,`menu`,`value`,`updateTime`) VALUES ( '$tag','$key','$val','$dateTime')";
            }
        }
        $result = mysql_query($sql);
        echo "$sql \n"; // message
        
        echo "<SEPARATOR>";
    } else if (strcmp($command,"GET_VIN_FILTER") == 0){
        // VIN 用フィルターを取り出す
        $sql = "SELECT * FROM `MenuTable` WHERE `tag`='VIN_FILTER'";
        $result = mysql_query($sql);
        echo "$sql \n"; // message
        
        $results = array();
        while ($row = mysql_fetch_array($result)){
            $key = $row['menu'];
            $results[$key] = $row['value'];
        }
        
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"GET_ARCHIVE") == 0){
        // tag=table.field のリストに対応するコンテンツを DB から get し JSON 形式で返す
        $args = decodeObject($value); // client 側との約束ごと
        $patientId = $args['patientId'];
        $filename = archivedFile($patientId); // $patientId に対応するアーカイブファイル
        
        echo "GET_ARCHIVE filename ($filename)\n";
        
        $handle = @fopen($filename, "r");
        if ($handle) {
            echo "<SEPARATOR>";
            while (!feof($handle)) {
                $buffer = fgets($handle, 4096);
                // ## ブラウザーの設定により好みのコードに変更可
                //$buffer = mb_convert_encoding($buffer, "SJIS", "UTF-8");
                echo "$buffer";
            }
            fclose($handle);
        }
        else
            echo "ERROR: *** $patientId のデータはみつかりません";
    } else if (strcmp($command,"MERGE_ARCHIVE") == 0){
        // アーカイブ・データを DB へマージ
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $owner = $args['owner'];
        $tag = $args['tag'];
        $entryDate = $args['entryDate'];
        $updateTime = $args['updateTime'];
        $val = $args['val'];
        
        echo "<SEPARATOR>";
        putRecord($patientId, $tag, $entryDate, $updateTime, $val, $owner);
    } else if (strcmp($command,"GET_BOOKING") == 0){
        // dateTime 以後の patientId の受診日を返す
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $dateTime = $args['dateTime'];
        
        // 予約日をピックアップ
        $sql = "SELECT * FROM `FrontTable` WHERE `patientId`='$patientId' AND `entryDate`>'$dateTime' ORDER BY `entryDate` DESC";
        echo "====== GET_BOOKING\n $sql \n";//###
        $result=mysql_query($sql);
        
        $results = array();
        while ($row=mysql_fetch_array($result)){
            $results[] = $row['entryDate'];
        }
        
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"KICK_WINDOW") == 0){
        $args = decodeObject($value);
        echo "KICK_WINDOW: $value \n"; //##
        
		echo "<SEPARATOR>";
		echo json_encode($args);
    } else if (strcmp($command,"DO_MULTI_THREAD") == 0){
        $args = decodeObject($value);
        echo "DO_MULTI_THREAD: $value \n"; //##
        
		echo "<SEPARATOR>";
		echo json_encode($args);
    } else if (strcmp($command,"FIND") == 0){
        // 条件検索: ChartFinder から使われる
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $from = $args['from']; // 検索開始対象年月日
        $to = $args['to']; // 検索終了対象年月日
        $unique = $args['unique']; // 同じ patientId の複数レコード回答を許可・不許可
      
        foreach ($args as $key=>$value){
            echo "$key -- $value \n"; //##
            if ($key == 'patientId') continue;
            else if ($key == 'from') continue;
            else if ($key == 'to') continue; 
            else if ($key == 'unique') continue; 
            else {
                $array = find($key, $patientId, $from, $to, $unique, $value);
                if (!$results){
                    $results = $array;
                } else {
                    // $array と patientId,entryDate が一致したものだけを $results に残す
                    $ary = array();
                    foreach ($results as $dateAndPid=>$record){
                        if ($array[$dateAndPid]) 
                            $ary[$dateAndPid] = $results[$dateAndPid];
                    }
                    $results = $ary;
                }
            }
        }
        
        // 検索結果 を JSON 形式で返す
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"GET_SEARCH_TABLE") == 0){
        $args = decodeObject($value);
        $keys = $args['keys']; // {"patientId":"entryDate":"",,,}
        $owner = $args['owner'];
        
        $results = array();
        foreach ($keys as $patientId=>$dateTime){
            $rec = array();
            $rec['postItColor'] = postItColor($patientId, $dateTime);
            $rec['patientTable'] = getPatientTable($owner, $patientId);
            $rec['nameSection'] = getNameSection($owner, $patientId, $dateTime);
            $rec['addressSection'] = getAddressSection($owner, $patientId, $dateTime);
            $rec['basicSection'] = getBasicSection($owner, $patientId, $dateTime);
            $rec['maritalSection'] = getMaritalSection($owner, $patientId, $dateTime);
            $rec['universalSection'] = getUniversalSection($owner, $patientId, $dateTime);
            $rec['healthInsurance'] = getHealthInsurance($owner, $patientId, $dateTime);
            $rec['publicInsurance'] = getPublicInsurance($owner, $patientId, $dateTime);
            $rec['progressSection'] = getProgressSection($owner, $patientId);
            $results[$patientId] = $rec;
        }
        
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"GET_VALUE_API") == 0){
        // 現在開かれているカルテから tag に該当するデータを返す
        $args = decodeObject($value);
        $owner = $args['owner'];
        $patientId = $args['patientId'];
        $entryDate = $args['currentDate'];
        $hospitalId = $args['hospitalId'];
        $st = $args['tags']; // "table.field,table.field,,," 型式
        $tags = explode(",", $st);
        
        $records = array();
        foreach ($tags as $tag) {
            $array = explode(".", $tag);
            $table = $array[0];
            $field = (count($array) > 1) ? $array[1] : "";
            
            // ### 他オーナーのものを含め探す：DocMaker 名前を受付で入力した場合など
            // ### ProgressSection のみ $owner 指定で探す
            if (strcmp($table, "HospitalTable") == 0){
                $sql = "SELECT * FROM `HospitalTable` WHERE `hospitalId`='$hospitalId' AND `key`='$field'";
                echo "$sql ========\n"; //###
                $result=mysql_query($sql);
                
                $row=mysql_fetch_array($result);
                $rec = array();
                $rec['entryDate'] = $row['entryDate'];
                $rec['owner'] = $row['owner'];
                $rec['value'] = $row['value'];
            } else if (strcmp($table, "PatientTable") == 0){
                $sql = "SELECT * FROM `PatientTable` WHERE `patientId`='$patientId'";
                echo "$sql ========\n"; //###
                $result=mysql_query($sql);
                
                while ($row=mysql_fetch_array($result)){
                    $rec = array();
                    $rec['entryDate'] = $row['entryDate'];
                    $rec['owner'] = $row['owner'];
                    $rec['value'] = $row[$field];
                    if (strlen($rec['value']) > 0) break;
                }
            } else if (strcmp($table, "ProgressSection") == 0){
                $sql = "SELECT * FROM `ProgressSection` WHERE `patientId`='$patientId' AND `entryDate`<='$entryDate' AND `owner`='$owner' AND (`freq` IS NULL OR `freq`<1) ORDER BY `entryDate` DESC";
                echo "$sql ========\n"; //###
                $result=mysql_query($sql);
                
                while ($row=mysql_fetch_array($result)){
                    $rec = array();
                    $rec['entryDate'] = $row['entryDate'];
                    $rec['owner'] = $row['owner'];
                    $rec['value'] = $row[$field];
                    if (strlen($rec['value']) > 0) break;
                }
            } else if (strcmp($table, "UniversalSection") == 0){
                // UniversalSection の全てのレコードを返す
                $sql = "SELECT * FROM `UniversalSection` WHERE `patientId`='$patientId' AND `entryDate`<='$entryDate' AND (`freq` IS NULL OR `freq`<1) ORDER BY `entryDate` DESC, `updateTime` DESC";
                echo "$sql -----\n"; //###
                $result=mysql_query($sql);
                
                while ($row=mysql_fetch_array($result)){
                    if (strcmp($row['field'], '_REMINDER_') == 0) continue;
                    if (strcmp($row['field'], $field) != 0) continue;
                    
                    $rec = array();
                    $rec['entryDate'] = $row['entryDate'];
                    $rec['owner'] = $row['owner'];
                    $rec['value'] = $row['dataString'];
                    if (strlen($rec['value']) > 0) break;
                }
            } else {
                // 他オーナーのものを含め探す：DocMaker 名前を受付で入力した場合など
                $sql = "SELECT * FROM `$table` WHERE `patientId`='$patientId' AND `entryDate`<='$entryDate' AND (`freq` IS NULL OR `freq`<1) ORDER BY `entryDate` DESC";
                echo "$sql ========\n"; //###
                $result=mysql_query($sql);
                while ($row=mysql_fetch_array($result)){
                    $rec = array();
                    $rec['entryDate'] = $row['entryDate'];
                    $rec['owner'] = $row['owner'];
                    $rec['value'] = $row[$field];
                    if (strlen($rec['value']) > 0) break;
                }
            }
            
            echo $rec['entryDate']."(".$rec['owner'].")".$rec[$field]."\n"; //##
            $records[$tag] = $rec;
        }
        
        echo "<SEPARATOR>";
        echo json_encode($records);
    } else if (strcmp($command,"GET_CONDITIONAL_PATIENT") == 0){
        // lvdSearch/NOAManager から呼ばれる
        $args = decodeObject($value);
        $from = $args['fromDate'];
        $to = $args['toDate'];
        
        $sql = "SELECT * FROM `PatientTable` WHERE `lastVisitDate` > '$from' AND `lastVisitDate` < '$to' ORDER BY `lastVisitDate`";
        $result=mysql_query($sql);
        echo "$sql ========== <br>\n";
        
        $records = array();
        $count = 0;
        while ($row=mysql_fetch_array($result)){
            $pid = $row['patientId'];
            $lvd = $row['lastVisitDate'];
            
            // $pid のカルテについて指定期間以後に受診しているものはスキップ
            $sql2 = "SELECT * FROM `ProgressSection` WHERE `patientId`=$pid AND `entryDate` > '$to'";
            $result2=mysql_query($sql2);
            if ($row2=mysql_fetch_array($result2)){
                echo " $pid $lvd -> entryDate: ".$row2['entryDate']." <br>\n";
                continue;
            }
            
            echo "$pid $lvd <br>\n";
            
            $rec = array();
            $namrow = nameSectionWithPatientId($pid);
            $rec['patientId'] = $pid;
            $rec['name'] = $namrow['patientKanjiName'];
            $rec['lvd'] = $lvd;
            $records[$lvd] = $rec;
            $count++;
        }
        
        echo "<SEPARATOR>";
        echo json_encode($records);
    } else if (strcmp($command,"GET_HEALTHINSURANCE_WITH_KEY") == 0){
        // 保険者番号に一致する保険者名・電話番号を検索
        // args = $value："HealthInsurance.ownerNumber_|_保険者番号"
        // $value に相当するデータを返す
        $args = decodeObject($value);
        $ownerNumber = $args['HealthInsurance.ownerNumber'];
        
        // HealthInsurance の ownerNumber が value に該当するレコードを探し
        // その "保険者名, 電話番号, 種別" を返す
        $sql = "SELECT * FROM `HealthInsurance` WHERE `ownerNumber` LIKE '$ownerNumber%' ORDER BY `updateTime` DESC";
        $result=mysql_query($sql);
        $row=mysql_fetch_array($result);
        $array = array();
        if ($row){
            $array['ownerNumber'] = $row['ownerNumber'];
            $array['ownerName'] = $row['ownerName'];
            $array['ownerPhone'] = $row['ownerPhone'];
            $array['shubetsu'] = $row['shubetsu'];
        } else {
            // 一致する 保険者番号 のレコードが見つからなかった
            $array['ownerNumber'] = $value;
            $array['ownerName'] = "";
            $array['ownerPhone'] = "";
            $array['shubetsu'] = "";
            $array[''] = "HealthInsurance.ownerNumber<SEP>$value";
            $array[''] = "HealthInsurance.ownerName<SEP>";
            $array[''] = "HealthInsurance.ownerPhone<SEP>";
            $array[''] = "HealthInsurance.shubetsu<SEP>";
        }
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"GET_INS_IMAGE") == 0){
        // patientId, currentDate に相当する保険証画像イメージがあればその URLリスト を返す
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $filename = $args['filename'];
        
        // ##### $dir は HTTP ではなく FILE-SYSTEM の PATH を示す #####
        $dir = rootDir()."NOA_ARCHIVE/$patientId/Insurance/";
        
        if (strlen($filename) > 0){
            echo "<SEPARATOR>";
            echo "$dir$filename";
        } else {
            $results = getDir($dir);
            echo "<SEPARATOR>";
            echo json_encode($results);
        }
    } else if (strcmp($command,"REMOVE_INS_IMAGE") == 0){
        //　patientId の filename を削除
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $filename = $args['filename'];
        
        $dir = rootDir()."NOA_ARCHIVE/$patientId/Insurance/";

        $oldPath = "$dir/$filename";
        $newPath = "$dir/_$filename";
        
        // ファイル名の頭に削除マーク "_" を付ける
        rename($oldPath, $newPath);
		echo "<SEPARATOR>";
		echo "$filename は削除されました";
    } else if (strcmp($command,"REMOVE_INS_IMAGES") == 0){
        // filenames のファイルをまとめて削除
        // files = '03234200_20131001161552.JPG,_03234200_20131001091325_0.JPG' 型式
        $args = decodeObject($value);
        $files = $args['files'];
        $array = explode(',', $files);
        
        echo "files: $files \n"; //##
        echo "array: $array \n"; //##

        for ($i=0,$ct=count($array); $i < $ct; $i++){
            $st = $array[$i]; // '03234200_20131001161552.JPG' 型式
            if (strcmp(substr($st, 0, 1), '_') == 0){
                // 削除済みのファイル '_03234200_20131001161552.JPG' 型式
                $ary = explode('_', $st);
                $patientId = $ary[1];
                
                $oldFile = rootDir()."NOA_ARCHIVE/$patientId/Insurance/$st";
                echo "unlink $oldFile \n"; //##
                unlink($oldFile);
            } else {
                $ary = explode('_', $st);
                $patientId = $ary[0];
                
                // ファイル名の頭に削除マーク "_" を付ける
                $oldFile = rootDir()."NOA_ARCHIVE/$patientId/Insurance/$st";
                echo "rename $oldFile \n"; //##
                $newFile = rootDir()."NOA_ARCHIVE/$patientId/Insurance/_$st";
                rename($oldFile, $newFile);
            }
        }
        echo "<SEPARATOR>";
        echo "$filename は削除されました";
    } else if (strcmp($command,"GET_USER_LIST") == 0){
        // ユーザのリストを返す
        $sql = "SELECT * FROM `UserTable`";
        echo "$sql \n"; //##
        $result=mysql_query($sql);
        
        $array = array();
        while ($row=mysql_fetch_array($result)){
            $logname = $row['loginName'];
            $array[$logname] = $row['kanjiName'];
            echo "$logname -> ".$row['kanjiName']."\n"; //##
        }

        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"GET_RECORDS_FOR_KEYS") == 0){
        // $keys に含まれるキー群を含むすべての ProgressSection レコードを返す
        $args = decodeObject($value);
        // client 側との約束ごと
        $pid = $args['patientId'];
        $owner = $args['owner'];
        $keys = $args['keys']; // separator で区切られたラベル名群の文字列
        echo "pid($pid) owner($owner) keys($keys)\n"; //return; //###
        
        $records = recordsForKeys($pid, $owner, $keys);
        echo "<SEPARATOR>";
        echo json_encode($records);
    } else if (strcmp($command,"PUT_REMINDER") == 0){
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $owner = $args['owner'];
        $type = $args['type'];
        $val = $args['dataString'];
        $now = timeStamp();
        
        if (strlen($val) == 0){
            $sql = "DELETE FROM `UniversalSection` WHERE `patientId`='$patientId' AND `field`='_REMINDER_' AND `type`='$type' AND `owner`='$owner'";
            echo "===\n $sql \n";
            mysql_query($sql);
            echo "<SEPARATOR>";
            return;
        }
        
        $sql = "SELECT * FROM `UniversalSection`
        WHERE `patientId`='$patientId' AND `field`='_REMINDER_'
        AND `type`='$type' AND `owner`='$owner'";
        echo "===\n $sql \n"; //##
        $result=mysql_query($sql);
        
        if (mysql_num_rows ($result) > 0){
            // dataString を更新
            $row=mysql_fetch_array($result);
            $rowid = $row['rowid'];
            
            $sql = "UPDATE `UniversalSection`
            SET `dataString`='$val'
            ,`updateTime`='$now'
            WHERE `rowid`='$rowid'";
        } else {
            $sql = "INSERT INTO `UniversalSection`
            (`patientId`,`field`,`dataString`,`type`
             ,`entryDate`,`updateTime`,`owner`)
            VALUES ('$patientId','_REMINDER_','$val','$type'
                    ,'$now','$now','$owner')";
        }
        echo "===\n $sql \n";
        mysql_query($sql);
        echo "<SEPARATOR>";
    } else if (strcmp($command,"GET_REMINDER") == 0){
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $owner = $args['owner'];
        $type = $args['type'];
        
        if (strlen($patientId) == 0){
            $sql = "SELECT * FROM `UniversalSection` WHERE `field`='_REMINDER_' AND `type`='$type' AND `owner`='$owner' ORDER BY `updateTime` DESC";
        } else {
            $sql = "SELECT * FROM `UniversalSection` WHERE `field`='_REMINDER_' AND `patientId`='$patientId' AND `type`='$type' AND `owner`='$owner' ORDER BY `updateTime` DESC";
        }
        echo "$sql ------------ \n"; //###
        
        mysql_query($sql);
        $result=mysql_query($sql);
        $records = array();
        while ($row=mysql_fetch_array($result)){
            $rec = array();
            $rec['patientId'] = $row['patientId'];
            $rec['updateTime'] = $row['updateTime'];
            $rec['dataString'] = $row['dataString'];
            $nameRow = nameSectionWithPatientId($row['patientId']);
            $rec['patientKanjiName'] = $nameRow['patientKanjiName'];
            $records[] = $rec;
        }
        echo "<SEPARATOR>";
        echo json_encode($records);
    } else if (strcmp($command,"PUT_NEW_PATIENT") == 0){
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $anotherId = $args['anotherId'];
        $receiptId = $args['receiptId'];
        $entryDate = $args['entryDate'];
        $owner = $args['owner'];
        $birthDate = $args['birthDate'];
        $deathDate = "";
        $sex = $args['sex'];
        $kanjiName = $args['kanjiName'];
        $kanaName = $args['kanaName'];
        $romajiName = $args['romajiName'];
        
        $row = rowOfPatientId($patientId);
        if ($row){
            echo "<SEPARATOR>";
            echo "ERROR *** $patientId はすでに登録されています";
        } else if ($patientId <> "") {
            $sql = "INSERT INTO `PatientTable` (`patientId`,`anotherId`,`receiptId`
            ,`sex`,`birthDate` ,`deathDate` ,`entryDate`)
            VALUES ('$patientId','$anotherId','$receiptId','$sex'
                    ,'$birthDate','$deathDate','$entryDate');";
            echo "SQL:\n $sql ----\n"; //##
            mysql_query($sql);
            $sql = "INSERT INTO `NameSection` (`patientId`
            ,`patientKanjiName`,`patientKanaName`,`patientRomajiName`
            ,`entryDate`,`updateTime`,`owner`)
            VALUES ('$patientId'
                    ,'$kanjiName', '$kanaName', '$romajiName',
                    '$entryDate','".timeStamp()."','$owner');";
            echo "SQL:\n $sql ----\n"; //##
            mysql_query($sql);
            
            echo "<SEPARATOR>";
            echo "$patientId $kanjiName を登録しました";
        }
    } else if (strcmp($command,"GET_ARCHIVE_FILE") == 0){
        // JSON 形式で保存された配列データを読み出す
        // ##### PUT_ARCHIVE_FILE は postServer.php で実施 #####
        $args = decodeObject($value);
        $owner = $args['owner']; // 先頭に owner が埋め込まれている
        $folder = $args['folder'];
        $filename = $args['filename']; // "foo/bar" 形式のことあり
        echo "dir: $folder/$filename \n"; //##
        
        $path = archiveDirForToolMenu($owner, "$folder/$filename");
        echo "path: $path \n"; //##
        
		echo "<SEPARATOR>";
        $json = file_get_contents($path);
        echo $json;
    } else if (strcmp($command,"GET_ARCHIVE_FILES") == 0){
        // TOOL MENU や LAYOUT のアーカイブを取得
        $args = decodeObject($value);
        $owner = $args['owner']; // 先頭に owner が埋め込まれている
        $folder = $args['folder'];
        $filename = $args['filename']; // "foo/bar" 形式のことあり
        $dir = archiveDirForToolMenu($owner, "$folder/$filename");
        
        $results = getDir($dir);
        //rsort($results); // 逆順にソート
		echo "<SEPARATOR>";
		echo json_encode($results);
    } else if (strcmp($command,"REMOVE_ARCHIVE_FILE") == 0){
        $args = decodeObject($value);
        $owner = $args['owner']; 
        $folder = $args['folder'];
        $filename = $args['filename']; // "foo/bar" 形式のことあり
        
        $path = archiveDirForToolMenu($owner, "$folder/$filename");
        $lastPath = basename($path); // $path の最後のファイル名
        $dir = dirname($path); // $lastPath の親 dir
        $oldPath = "$dir/$lastPath";
        $newPath = "$dir/_$lastPath";
        
        // ファイル名の頭に削除マーク "_" を付ける
        rename($oldPath, $newPath);
        
		echo "<SEPARATOR>";
		echo "$filename を削除しました";
    } else if (strcmp($command,"SET_CELL_ATTRIBUTES") == 0){
        // CELL 属性を保存
        $args = decodeObject($value);
        
        // === Ror FieldTable ===
        $owner = $args['owner'];
        $id = $args['id']; // _progress, _basic, _insurance：LAYOUT 編集で扱う
        $tag = $args['tag'];
        $buttonType = $args['buttonType'];
        $fieldType = $args['fieldType'];
        $menuType = $args['menuType'];
        $menuAction = $args['menuAction'];
        $label = $args['label'];
        $hitAndRun = $args['hitAndRun']; // 表示・非表示：LAYOUT 編集で扱う
        $numbering = $args['numbering']; // CELL の表示順：LAYOUT 編集で扱う
        $study = $args['study'];
        $fontSize = $args['fontSize'];
        $fontFamily = $args['fontFamily'];
        $color = $args['color'];
        $bgcolor = $args['bgcolor'];
        $direction = 'CELL';
        $disabled = $args['disabled'];
        $script = $args['script'];
        $editor = $args['editor'];
		
        // === For ProgressSection ===
        $subject = $args['ProgressSection.subject'];
        $object = $args['ProgressSection.object'];
        $examination = $args['ProgressSection.examination'];
        $prescription = $args['ProgressSection.prescription'];
        $disease = $args['ProgressSection.disease'];
        $treatment = $args['ProgressSection.treatment'];
        $assessment = $args['ProgressSection.assessment'];
        $plan = $args['ProgressSection.plan'];
        $updateTime = timestamp();
        
        // FieldTable をアップデート
        $sql = "SELECT * FROM `FieldTable` WHERE `tag`='$tag' AND `direction`='CELL' AND `owner`='$owner'";
        echo "$sql ========\n"; //###
        $result=mysql_query($sql);
        
        // 該当するデータがあれば更新、なければ追加
        if (mysql_num_rows ($result) > 0){
            $row=mysql_fetch_array($result);
            $rowid = $row['rowid'];
            $sql = "UPDATE `FieldTable` SET
            `buttonType`='$buttonType'
            ,`fieldType`='$fieldType'
            ,`menuType`='$menuType'
            ,`menuAction`='$menuAction'
            ,`label`='$label'
            ,`numbering`='$numbering'
            ,`study`='$study'
            ,`fontSize`='$fontSize'
            ,`fontFamily`='$fontFamily'
            ,`color`='$color'
            ,`bgcolor`='$bgcolor'
            ,`direction`='CELL'
            ,`disabled`='$disabled'
            ,`id`='$id'
            ,`script`='$script'
            ,`editor`='$editor'
            ,`updateTime`='$updateTime'
            WHERE `rowid`='$rowid'";
        } else {
            $sql = "INSERT INTO `FieldTable`
            ( `tag`,`buttonType`,`fieldType`,`menuType`,`menuAction`,`label`,`numbering`,`study`,`fontSize`,`fontFamily`,`color`,`bgcolor`,`direction`,`disabled`,`script`,`editor`,`id`,`updateTime`,`owner`)
            VALUES ( '$tag',0,'$fieldType','$menuType','$menuAction','$label','$numbering','$study','$fontSize'
                    ,'$fontFamily','$color','$bgcolor','CELL','$disabled','$script'
                    ,'$editor','$id','$updateTime','$owner')";
        }
        echo "$sql ========\n\n"; //###
        mysql_query($sql);
        
        if ($subject){ // GROUP MENU があれば
            // ProgressSection をアップデート：GROUP MENU 用
            $sql = "SELECT `subject` FROM `ProgressSection` WHERE `patientId`='GroupMenu' AND `subject`='$subject' AND `owner`='$owner'";
            echo "$sql ========\n"; //###
            $result=mysql_query($sql);
            
            // 該当するデータがあれば更新、なければ追加
            if (mysql_num_rows ($result) > 0){
                $sql = "UPDATE `ProgressSection` SET
                `object`='$object'
                ,`examination`='$examination'
                ,`prescription`='$prescription'
                ,`disease`='$disease'
                ,`treatment`='$treatment'
                ,`assessment`='$assessment'
                ,`plan`='$plan'
                ,`updateTime`='$updateTime'
                WHERE `patientId`='GroupMenu' AND `subject`='$subject' AND `owner`='$owner'";
            } else {
                $sql = "INSERT INTO `ProgressSection`
                ( `patientId`,`subject`,`object`,`examination`,`prescription`,`disease`
                 ,`treatment`,`assessment`,`plan`,`freq`,`updateTime`,`owner`)
                VALUES ( 'GroupMenu',’$subject’,'$object','$examination','$prescription','$disease','$treatment','$assessment','$plan','$freq','$updateTime','$owner')";
            }
            echo "$sql ========\n\n"; //###
            mysql_query($sql);
        }
        
        // 変更結果を返す
        echo "<SEPARATOR>";
        echo "SET_CELL_ATTRIBUTES: $tag のデータは更新されました";
    } else if (strcmp($command,"GET_CORRECTION_HISTORY") == 0){
        // 修正履歴を返す：correctionHistory.js で使われる
        $args = decodeObject($value);
        $owner = $args['owner'];
        $patientId = $args['patientId'];
        $entryDate = $args['entryDate'];
        
        $sql = "SELECT * FROM `ProgressSection` WHERE `owner`='$owner' AND `patientId`='$patientId' AND `entryDate`='$entryDate' ORDER BY `updateTime` DESC";
        $result=mysql_query($sql);
        echo "sql: $sql \n"; //##
        
        $results = array();
        while ($row = mysql_fetch_array($result)){
            $rec = array();
            $rec['ProgressSection.entryDate'] = $row['entryDate']; // dateTime 取得に必要
            $rec['ProgressSection.updateTime'] = $row['updateTime']; // 修正日時ポップアップに必要
            $rec['ProgressSection.pageHeader'] = $row['pageHeader'];
            $rec['ProgressSection.freq'] = $row['freq'];
            $rec['ProgressSection.subject'] = $row['subject'];
            $rec['ProgressSection.object'] = $row['object'];
            $rec['ProgressSection.examination'] = $row['examination'];
            $rec['ProgressSection.prescription'] = $row['prescription'];
            $rec['ProgressSection.disease'] = $row['disease'];
            $rec['ProgressSection.treatment'] = $row['treatment'];
            $rec['ProgressSection.assessment'] = $row['assessment'];
            $rec['ProgressSection.plan'] = $row['plan'];
            
            $results[] = $rec;
        }
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"PUT_POST_IT") == 0){
        // 付箋を登録/削除
        // $val が "" の場合、レコードは削除される
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $entryDate = $args['entryDate'];
        $array = beforAndAfterDateTime($entryDate);
        $beginDate = $array[0];
        $endDate = $array[1];
        $field = "postIt";
        $type = $args['type'];
        $color = $args['color'];
        $val = $args['val'];
        $owner = $args['owner'];
        
        // timeLimit 以内の ProgressSection レコードの有無をチェック
        if (strlen($val) == 0){
            // val が空の場合は entryDate のレコードを実際に削除
            // PostIt パネルで「削除」にチェックを入れただけなら type が expired になるだけ
            $sql = "DELETE FROM `UniversalSection` WHERE `patientId`='$patientId' AND `entryDate`>='$beginDate' AND `entryDate`<='$endDate' AND `field`='$field' AND `owner`='$owner'";
            mysql_query($sql);
            echo "===\n $sql \n"; //##

            // FrontTable の postIt に NULL をセットし UniversalSection の postIt を
            // 再検索させるようにする
            setPostItNull($patientId, $entryDate);
            
            echo "<SEPARATOR>";
        } else {
            $sql = "SELECT * FROM `UniversalSection` WHERE `patientId`='$patientId' AND `field`='$field' AND `entryDate`>='$beginDate' AND `entryDate`<='$endDate' ORDER BY `entryDate` DESC";
            echo "===\n $sql \n"; //##
            $result=mysql_query($sql);
            $now = timestamp();
            
            if (mysql_num_rows ($result) > 0){
                // dataString を更新
                $row=mysql_fetch_array($result);
                $rowid = $row['rowid'];
                
                $sql = "UPDATE `UniversalSection`
                SET `dataString`='$val'
                ,`type`='$type'
                ,`dataObject`='$color'
                ,`owner`='$owner'
                ,`updateTime`='$now'
                WHERE `rowid`='$rowid'";
                echo "===\n $sql \n";
                mysql_query($sql);
            } else {
                $sql = "INSERT INTO `UniversalSection`
                (`patientId`,`field`,`dataString`,`dataObject`,`type`
                 ,`entryDate`,`updateTime`,`owner`)
                VALUES ('$patientId','$field','$val','$color','$type'
                        ,'$entryDate','$now','$owner')";
                mysql_query($sql);
                echo "===\n $sql \n"; //##
            }
            
            // FrontTable の postIt に NULL をセットし UniversalSection の postIt を
            // 再検索させるようにする
            setPostItNull($patientId, $entryDate);
            
            $array = getPostIt($owner, $patientId);
            echo "<SEPARATOR>";
            echo json_encode($array);
        }
    } else if (strcmp($command,"GET_VIEWER") == 0){
        // vierwer@FRONT から呼ばれる
        // owner は無関係で読み出す
        // $patientId $dateTime のデータを返す
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $date = $args['dateTime']; // FRONT 登録時間なので NOA より少し前のはず
        $maxDate = substr($date, 0, 10)." 24:00:00"; // ここから前をスキャン
        $rescords = array();
        
        // ProgressSection ===============================
        // 最新のレコードから古いものへとスキャンしながら各フィールドの値を取り込んでゆく
        $sql = "SELECT * FROM `ProgressSection` WHERE `patientId`='$patientId' AND `entryDate`<'$maxDate' AND (`freq` IS NULL OR `freq`<1) ORDER BY `entryDate` DESC, `updateTime` DESC";
        echo "scanTable-> $sql \n"; //###
        
        $result = mysql_query($sql);
        while ($row = mysql_fetch_array($result)){
            if (! $subject) $subject = $row['subject'];
            if (! $object) $object = $row['object'];
            if (! $examination) $examination = $row['examination'];
            if (! $prescription) $prescription = $row['prescription'];
            if (! $disease) $disease = $row['disease'];
            if (! $treatment) $treatment = $row['treatment'];
            if (! $assessment) $assessment= $row['assessment'];
            if (! $plan) $plan = $row['plan'];
            
            // 全てのフィールドが満たされたらループを抜ける
            if ($subject && $object && $examination && $prescription && $disease && $treatment && $assessment && $plan) break;
        }
        $rescords['ProgressSection.entryDate'] = $args['dateTime'];
        $rescords['ProgressSection.subject'] = $subject;
        $rescords['ProgressSection.object'] = $object;
        $rescords['ProgressSection.examination'] = $examination;
        $rescords['ProgressSection.prescription'] = $prescription;
        $rescords['ProgressSection.disease'] = $disease;
        $rescords['ProgressSection.treatment'] = $treatment;
        $rescords['ProgressSection.assessment'] = $assessment;
        $rescords['ProgressSection.plan'] = $plan;
        
        // AddressSection ===============================
        $sql = "SELECT * FROM `AddressSection` WHERE `patientId`='$patientId' AND `entryDate`<'$maxDate' ORDER BY `entryDate` DESC, `updateTime` DESC";
        echo "scanTable-> $sql \n"; //###
        $result = mysql_query($sql);
        
        // AddressSection などで使われている変数名を使わないこと
        while ($row = mysql_fetch_array($result)){
            if (! $p_address) $p_address = $row['address'];
            if (! $p_phone) $p_phone = $row['phone'];
            if (! $p_email) $p_email = $row['email'];
            
            // 全てのフィールドが満たされたらループを抜ける
            if ($p_address && $p_phone) break;
        }
        $rescords['AddressSection.address'] = $p_address;
        $rescords['AddressSection.phone'] = $p_phone;
        $rescords['AddressSection.email'] = $p_email;
        
        // HealthInsurance ===============================
        $sql = "SELECT * FROM `healthInsurance` WHERE `patientId`='$patientId' AND `entryDate`<'$maxDate' ORDER BY `entryDate` DESC, `updateTime` DESC";
        echo "scanTable-> $sql \n"; //###
        
        $result = mysql_query($sql);
        while ($row = mysql_fetch_array($result)){
            if (! $ownerName) $ownerName = $row['ownerName'];
            if (! $ownerNumber) $ownerNumber = $row['ownerNumber'];
            if (! $ownerPhone) $ownerPhone = $row['ownerPhone'];
            if (! $shubetsu) $shubetsu = $row['shubetsu'];
            if (! $kubun) $kubun = $row['kubun'];
            if (! $kigou) $kigou = $row['kigou'];
            if (! $bangou) $bangou = $row['bangou'];
            if (! $continuedDiseases) $continuedDiseases = $row['continuedDiseases'];
            if (! $paymentRatio) $paymentRatio = $row['paymentRatio'];
            if (! $discountRatio) $discountRatio = $row['discountRatio'];
            if (! $confirmation) $confirmation = $row['confirmation'];
            if (! $startDate) $startDate = $row['startDate'];
            if (! $expiredDate) $expiredDate = $row['expiredDate'];
            
            // 全てのフィールドが満たされたらループを抜ける
            if ($ownerName && $ownerNumber && $ownerPhone && $shubetsu && $kubun && $kigou && $bangou && $continuedDiseases && $paymentRatio && $discountRatio && $confirmation && $startDate && $expiredDate) break;
        }
        $rescords['HealthInsurance.ownerName'] = $ownerName;
        $rescords['HealthInsurance.ownerNumber'] = $ownerNumber;
        $rescords['HealthInsurance.ownerPhone'] = $ownerPhone;
        $rescords['HealthInsurance.shubetsu'] = $shubetsu;
        $rescords['HealthInsurance.kubun'] = $kubun;
        $rescords['HealthInsurance.kigou'] = $kigou;
        $rescords['HealthInsurance.bangou'] = $bangou;
        $rescords['HealthInsurance.continuedDiseases'] = $continuedDiseases;
        $rescords['HealthInsurance.paymentRatio'] = $paymentRatio;
        $rescords['HealthInsurance.discountRatio'] = $discountRatio;
        $rescords['HealthInsurance.confirmation'] = $confirmation;
        $rescords['HealthInsurance.startDate'] = $startDate;
        $rescords['HealthInsurance.expiredDate'] = $expiredDate;
        
        // PublicInsurance ===============================
        $sql = "SELECT * FROM `PublicInsurance` WHERE `patientId`='$patientId' AND `entryDate`<'$maxDate' ORDER BY `entryDate` DESC, `updateTime` DESC";
        echo "scanTable-> $sql \n"; //###
        $result = mysql_query($sql);
        
        // HealthInsurance などで使われている変数名を使わないこと
        while ($row = mysql_fetch_array($result)){
            if (! $p_ownerName) $p_ownerName = $row['ownerName'];
            if (! $p_ownerNumber) $p_ownerNumber = $row['ownerNumber'];
            if (! $p_recipientNumber) $p_recipientNumber = $row['recipientNumber'];
            if (! $p_shubetsu) $p_shubetsu = $row['shubetsu'];
            if (! $p_paymentRatio) $p_paymentRatio = $row['paymentRatio'];
            if (! $p_payment) $p_payment = $row['payment'];
            if (! $p_startDate) $p_startDate = $row['startDate'];
            if (! $p_expiredDate) $p_expiredDate = $row['expiredDate'];
            
            // 全てのフィールドが満たされたらループを抜ける
            if ($p_ownerName && $p_ownerNumber && $p_recipientNumber && $p_shubetsu && $p_paymentRatio && $p_payment && $p_startDate && $p_expiredDate) break;
        }
        $rescords['PublicInsurance.ownerName'] = $p_ownerName;
        $rescords['PublicInsurance.ownerNumber'] = $p_ownerNumber;
        $rescords['PublicInsurance.recipientNumber'] = $p_recipientNumber;
        $rescords['PublicInsurance.shubetsu'] = $p_shubetsu;
        $rescords['PublicInsurance.paymentRatio'] = $p_paymentRatio;
        $rescords['PublicInsurance.payment'] = $p_payment;
        $rescords['PublicInsurance.startDate'] = $p_startDate;
        $rescords['PublicInsurance.expiredDate'] = $p_expiredDate;
        
        echo "<SEPARATOR>";
        echo json_encode($rescords);
    } else if (strcmp($command,"GET_CONDITIONAL_INS_FILES") == 0){
        // fileCleaner/NOAManager から呼ばれる
        $args = decodeObject($value);
        $from = $args['fromDate'];
        $to = $args['toDate'];
        
        $sql = "SELECT * FROM `PatientTable` ORDER BY `patientId`";
        $result=mysql_query($sql);
        echo "$sql ========== <br>\n";
        
        $records = array();
        while ($row=mysql_fetch_array($result)){
            $patientId = $row['patientId'];
            //echo "$patientId --\n";
            
            $dir = rootDir()."NOA_ARCHIVE/$patientId/Insurance";
            $files = scandir($dir);
            
            $array = array();
            for ($i=$num=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;
                
                if (! isInScopeOf($from, $filename, $to)) continue;
                
                echo "HIT $filename \n";
                
                $array[] = $filename; // filename="03234202_20120113165123.JPG" 形式
                $num++;
            }
            if ($num == 0) continue; // 保険証画像がなければスキップ
            
            $rec = array();
            $rec['pid'] = $patientId;
            $namrow = nameSectionWithPatientId($patientId);
            $rec['name'] = $namrow['patientKanjiName'];
            $rec['files'] = $array;
            $rec['lvd'] = lvdForPatientId($patientId);
            
            $records[$patientId] = $rec;
        }
        
        echo "========  \n";
        
        echo "<SEPARATOR>";
        echo json_encode($records);
    } else if (strcmp($command,"GET_TABLE_RECORDS") == 0){
        // patientId
        // 各テーブルごとの patientId のレコード数を返す
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        
        echo "<SEPARATOR>";
        $results = array();
        $results["patientId"] = $patientId;
        $sum = 0;
        
        $sql = "SELECT * FROM `NameSection` WHERE `patientId`='$patientId'";
        $result=mysql_query($sql);
        $count = mysql_num_rows($result); $sum += $count;
        $results["NameSection"] = $count;
        $sql = "SELECT * FROM `AddressSection` WHERE `patientId`='$patientId'";
        $result=mysql_query($sql);
        $count = mysql_num_rows($result); $sum += $count;
        $results["AddressSection"] = $count;
        $sql = "SELECT * FROM `BasicSection` WHERE `patientId`='$patientId'";
        $result=mysql_query($sql);
        $count = mysql_num_rows($result); $sum += $count;
        $results["BasicSection"] = $count;
        $sql = "SELECT * FROM `MalitalSection` WHERE `patientId`='$patientId'";
        $result=mysql_query($sql);
        $count = mysql_num_rows($result); $sum += $count;
        $results["MalitalSection"] = $count;
        $sql = "SELECT * FROM `HealthInsurance` WHERE `patientId`='$patientId'";
        $result=mysql_query($sql);
        $count = mysql_num_rows($result); $sum += $count;
        $results["HealthInsurance"] = $count;
        $sql = "SELECT * FROM `PublicInsurance` WHERE `patientId`='$patientId'";
        $result=mysql_query($sql);
        $count = mysql_num_rows($result); $sum += $count;
        $results["PublicInsurance"] = $count;
        $sql = "SELECT * FROM `ProgressSection` WHERE `patientId`='$patientId'";
        $result=mysql_query($sql);
        $count = mysql_num_rows($result); $sum += $count;
        $results["ProgressSection"] = $count;
        $sql = "SELECT * FROM `UniversalSection` WHERE `patientId`='$patientId'";
        $result=mysql_query($sql);
        $count = mysql_num_rows($result); $sum += $count;
        $results["UniversalSection"] = $count;
        $sql = "SELECT * FROM `PatientTable` WHERE `patientId`='$patientId'";
        $result=mysql_query($sql);
        $count = mysql_num_rows($result); $sum += $count;
        $results["PatientTable"] = $count;
        $results["sum"] = $sum;
        
        echo json_encode($results);
    } else if (strcmp($command,"REMOVE_TABLE_RECORDS") == 0){
        // patientId, table のレコードをすべて削除
        $args = decodeObject($value);
        // client 側との約束ごと
        $table = $args['table'];
        $patientId = $args['patientId'];
        
        if (strcmp($table, "ALL") == 0){
            $sql = "DELETE FROM `NameSection` WHERE `patientId`='$patientId'";
            echo "$sql ----\n"; //##
            mysql_query($sql);
            $sql = "DELETE FROM `AddressSection` WHERE `patientId`='$patientId'";
            echo "$sql ----\n"; //##
            mysql_query($sql);
            $sql = "DELETE FROM `BasicSection` WHERE `patientId`='$patientId'";
            echo "$sql ----\n"; //##
            mysql_query($sql);
            $sql = "DELETE FROM `MalitalSection` WHERE `patientId`='$patientId'";
            echo "$sql ----\n"; //##
            mysql_query($sql);
            $sql = "DELETE FROM `HealthInsurance` WHERE `patientId`='$patientId'";
            echo "$sql ----\n"; //##
            mysql_query($sql);
            $sql = "DELETE FROM `PublicInsurance` WHERE `patientId`='$patientId'";
            echo "$sql ----\n"; //##
            mysql_query($sql);
            $sql = "DELETE FROM `ProgressSection` WHERE `patientId`='$patientId'";
            echo "$sql ----\n"; //##
            mysql_query($sql);
            $sql = "DELETE FROM `UniversalSection` WHERE `patientId`='$patientId'";
            echo "$sql ----\n"; //##
            mysql_query($sql);
            $sql = "DELETE FROM `PatientTable` WHERE `patientId`='$patientId'";
            echo "$sql ----\n"; //##
            mysql_query($sql);
        } else {
            $sql = "DELETE FROM `$table` WHERE `patientId`='$patientId'";
            echo "$sql ----\n"; //##
            mysql_query($sql);
            $sql = "SELECT * FROM `$table` WHERE `patientId`='$patientId'";
            echo "$sql ----\n"; //##
            $result=mysql_query($sql);
        }
        
        echo "<SEPARATOR>";
        echo $patientId;
    } else if (strcmp($command,"GET_MESSAGE_AND_MENU") == 0){
        // $owner のメッセンジャー用メッセージ・メニューとユーザ・リストを返す
        $args = decodeObject($value);
        $owner = $args['owner'];
        
        // メッセージ・メニューを取得
        $records['messageMenu'] = getMessageMenu($owner);
        
        // ユーザ・リストを取得
        $sql = "SELECT * FROM `UserTable`";
        echo "$sql \n"; //##
        $array = array();
        $result=mysql_query($sql);
        while ($row=mysql_fetch_array($result)){
            $logname = $row['loginName'];
            $array[$logname] = $row['kanjiName'];
        }
        $records['userList'] = $array;
        
        echo "<SEPARATOR>";
        echo json_encode($records);
    } else if (strcmp($command,"PUT_MESSAGE") == 0){
        // receiver へメッセージを伝える
        $args = decodeObject($value);
        $owner = $args['sender'];
        $receiver = $args['receiver'];
        $message = $args['message'];
        $docId = $args['docId'];
        $updateTime = timestamp();
        echo "$value ------------ \n"; //###
        
        if (strlen($docId) > 0){
            // documentId が指定されているので、そのレコードを更新
            $sql = "SELECT * FROM `FrontTable` WHERE `rowid`='$docId'";
            $result=mysql_query($sql);
            
            $row=mysql_fetch_array($result);
            if ($row && (strcmp($row['patientId'],'MESSAGE') == 0)){ // MESSAGE が存在した
                $sql = "UPDATE `FrontTable` SET `plan`='$message',`mishuu`='$receiver',`owner`='$owner',`updateTime`='$updateTime' WHERE `rowid`='$docId'";
            }
        } else {
            // documentId が指定されていないので新規レコードを追加
            $sql = "INSERT INTO `FrontTable` (`patientId`,`owner`,`mishuu`,`plan`,`updateTime`) VALUES ('MESSAGE',  '$owner','$receiver','$message','$updateTime')";
        }
        echo "$sql ------------ \n"; //###
        mysql_query($sql);
        
        // timeStamp を記憶する
        putTimeStamp();
        
        // 更新されたメッセージ・メニューを返す
        echo "<SEPARATOR>";
        echo "$message を送信しました";
    } else if (strcmp($command,"REMOVE_MESSAGE") == 0){
        // owner からのメッセージを削除
        $args = decodeObject($value);
        $owner = $args['owner'];
        $rowid = $args['docId'];
        
        $sql = "DELETE FROM `FrontTable` WHERE `rowid`='$rowid'";
        echo "$sql ========\n"; //###
        mysql_query($sql);
        
        // 更新されたメッセージ・メニューを返す
        echo "<SEPARATOR>";
        echo "メッセージを削除しました";
    } else if (strcmp($command,"PUT_CALLS") == 0){
        // call 一括処理をサーバへ記憶
        $args = decodeObject($value);
        putCalls($args);
        
        echo "<SEPARATOR>";
        echo "call を保存しました";
    } else if (strcmp($command,"PUT_CALLS_ARRAY") == 0){
        // call の配列を DB のレコードと置換
        $array = decodeObject($value);
        $args = $array[0];
        $owner = $args['owner'];
        
        // DB からすべての CALL レコードを削除
        $sql = "DELETE FROM `MenuTable` WHERE `owner`='$owner' AND `tag`='CALLS'";
        echo "$sql ========\n"; //###
        mysql_query($sql);

        // 受け取ったすべての CALL レコードを DB へ保存
        $ct = count($array);
        for ($i=0; $i < $ct; $i++){
            $args = $array[$i];
            putCalls($args);
        }
        
        echo "<SEPARATOR>";
        echo "call を保存しました";
    } else if (strcmp($command,"GET_CALLS") == 0){
        // call 一括処理をサーバから取り出す
        $args = decodeObject($value);
        $owner = $args['owner'];

        $records = getCalls($owner);
        
        echo "<SEPARATOR>";
        echo json_encode($records);
    } else if (strcmp($command,"PUT_CALLS_BACKUP") == 0){
        // call のバックアップを保存
        $args = decodeObject($value);
        $owner = $args['_OWNER_']; // owner 埋込でないと正しく解凍されない
        
        if (saveBackup($owner, "CALLS", $value)){
            echo "<SEPARATOR>";
            echo "CALL のバックアップを保存しました";
        } else
            echo "PUT_CALLS_BACKUP ... failed";
    } else if (strcmp($command,"GET_CALLS_BACKUP") == 0){
        $args = decodeObject($value);
        $owner = $args['owner'];
        $filename = $args['filename'];

        $dir = dirOfBackupFile($owner, "CALLS");

        if ($filename){
            $path = "$dir/$filename";
            echo "<SEPARATOR>";
            $noaString = file_get_contents($path);
            echo $noaString;
        } else {
            // dir 内のフィアル名の配列を返す
            $results = getDir($dir);
            echo "<SEPARATOR>";
            echo json_encode($results);
        }
    } else if (strcmp($command,"REMOVE_CALLS_BACKUP") == 0){
        $args = decodeObject($value);
        $owner = $args['owner'];
        $filename = $args['value'];
        
        $dir = dirOfBackupFile($owner, "CALLS");
        $oldPath = "$dir/$filename";
        $newPath = "$dir/_$filename";

        // ファイル名の頭に削除マーク "_" を付ける
        rename($oldPath, $newPath);
		echo "<SEPARATOR>";
		echo "$filename は削除されました";
    } else if (strcmp($command,"GET_PRESCRIPTION_HISTORY") == 0){
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        
        $sql = "SELECT * FROM `ProgressSection` WHERE `patientId`='$patientId' AND (`freq` IS NULL OR `freq`<1) ORDER BY `entryDate` DESC, `updateTime` DESC";
        echo "$sql ========\n"; //###
        $result=mysql_query($sql);
        
        $records = array();
        while ($row=mysql_fetch_array($result)){
            $prs = trim($row['prescription']);
            if (!$prs || (strlen($prs) == 0)) continue;

            $rec = array();
            $rec['owner'] = $row['owner'];
            $rec['prescription'] = $prs;
            
            $entryDate = $row['entryDate'];
            $records[$entryDate] = $rec;
        }
        
        echo "<SEPARATOR>";
        echo json_encode($records);
    } else if (strcmp($command,"GET_LAYOUT") == 0){
        // $owner の NOA レイアウトを返す
        $args = decodeObject($value);
        $owner = $args['owner'];
        
        $sql = "SELECT * FROM `FieldTable` WHERE `owner`='$owner' AND `direction`='CELL' ORDER BY `numbering`";
        $result=mysql_query($sql);
        echo "$sql \n"; //###
        
        $recs = array();
        while ($row=mysql_fetch_array($result)){
            $rec = array();
            $rec['tag'] = $row['tag']; // 必要
            $rec['buttonType'] = $row['buttonType'];
            $rec['menuType'] = $row['menuType'];
            $rec['menuAction'] = $row['menuAction'];
            $rec['hitAndRun'] = $row['hitAndRun'];
            $rec['fieldType'] = $row['fieldType'];
            // direction は「FieldTable 検索専用キー: CELL」固定なので使わない
            $rec['disabled'] = $row['disabled'];
            $rec['editor'] = $row['editor'];
            $rec['id'] = $row['id'];
            $rec['script'] = $row['script'];
            $rec['bgcolor'] = $row['bgcolor'];
            $rec['label'] = $row['label'];
            $rec['numbering'] = $row['numbering']; // LAYOUT で使う
            $rec['study'] = $row['study'];
            $rec['fontSize'] = $row['fontSize'];
            $rec['fontFamily'] = $row['fontFamily'];
            $rec['color'] = $row['color'];
            $tag = $row['tag'];
            $recs[] = $rec;
        }
        echo "<SEPARATOR>";
        echo json_encode($recs);
    } else if (strcmp($command,"STARTUP_NOA") == 0){
        $args = decodeObject($value);
        $owner = $args['owner'];
        $hospitalId = $args['hospitalId'];
        $results = array();
        
        // DB をチェック：欠けているフィールドなどあれば追加
        checkDB();
        
        // LAYOUT を取得
        $sql = "SELECT * FROM `FieldTable` WHERE `owner`='$owner' AND `direction`='CELL' ORDER BY `numbering`";
        $result=mysql_query($sql);
        echo "$sql \n"; //###
        
        $layout = array();
        while ($row=mysql_fetch_array($result)){
            $rec = array();
            $rec['tag'] = $row['tag']; // 必要
            $rec['buttonType'] = $row['buttonType'];
            $rec['menuType'] = $row['menuType'];
            $rec['menuAction'] = $row['menuAction'];
            $rec['hitAndRun'] = $row['hitAndRun'];
            $rec['fieldType'] = $row['fieldType'];
            // direction は「FieldTable 検索専用キー: CELL」固定なので使わない
            $rec['disabled'] = $row['disabled'];
            $rec['editor'] = $row['editor'];
            $rec['id'] = $row['id'];
            $rec['script'] = $row['script'];
            $rec['bgcolor'] = $row['bgcolor'];
            $rec['label'] = $row['label'];
            $rec['numbering'] = $row['numbering']; // LAYOUT で使う
            $rec['study'] = $row['study'];
            $rec['fontSize'] = $row['fontSize'];
            $rec['fontFamily'] = $row['fontFamily'];
            $rec['color'] = $row['color'];
            $tag = $row['tag'];
            $layout[] = $rec;
        }
        $results['layout'] = $layout;
        
        // TOOL MENU 構造を取得
        $results['toolMenus'] = getToolMenu($owner);
        
        // HospitalTable 情報を取得
        $results['hospitalInfo'] = getHospitalTable($hospitalId);
        
        // 一括処理設定があれば取得
        $results['calls'] =  getCalls($owner);
        
        // 基準値を取得
        $results['standard']  = getStandard("STANDARD", $owner);
        
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"GET_HORIDAY") == 0){
        // 祝日リストを返す：[{"date":"2014-03-21","title":"春分の日"},,] 型式
        $args = decodeObject($value);
        $year = $args['year'];
        
        echo "year:$year <br>\n"; //##

        $results = getHoliday($year, 'ja');
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"REMOVE_RECORDS_FOR_TAG") == 0){
        // UniversalSection から owner, tag の全レコードを削除
        $args = decodeObject($value);
        $owner = $args['owner'];
        $tag = $args['tag'];
        $array = explode(".", $tag);
        $field = $array[1];
        
        // LAYOUT テーブルから owner, tag のレコードを削除
        $sql = "DELETE FROM `FieldTable` WHERE `tag`='$tag' AND `owner`='$owner' AND `direction`='CELL'";
        echo "----- $sql \n"; //##
        $result=mysql_query($sql);
        
        // UniversalSection から owner, field のレコードを削除
        $sql = "DELETE FROM `UniversalSection` WHERE `field`='$field' AND `owner`='$owner'";
        echo "----- $sql \n"; //##
        $result=mysql_query($sql);
        
        echo "<SEPARATOR>";
        echo "UniversalSection から $owner, $field のデータ全てを削除しました";
    } else if (strcmp($command,"GET_ANARIZE") == 0){
        // 主訴欄に key を含むものを検索して返す
        $args = decodeObject($value);
        $owner = $args['owner'];
        $key = $args['key'];
        $sql = "SELECT * FROM `ProgressSection` WHERE `owner`='$owner' AND `subject` LIKE '%$key%' AND (`freq` IS NULL OR `freq`<1) ";
        echo "===\n $sql \n"; //##
        $result=mysql_query($sql);
        
        $diseases = array();
        $treatments = array();
        while ($row=mysql_fetch_array($result)){
            // $key を含む $subject のみを抽出
            $subject = includeOf($row['subject'], $key);
            if ($subject == NULL) continue;
            
            $diseases = setDisase($diseases, $row['disease']);
            $treatments = setTreatment($treatments, $row['treatment']);
        }
        arsort($diseases);
        arsort($treatments);
        
        $results = array();
        $results['disease'] = $diseases;
        $results['treatment'] = $treatments;
        echo "<SEPARATOR>";
        echo json_encode($results);
    } else if (strcmp($command,"TEST") == 0){
        // ### for TEST ###
        $args = decodeObject($value);
        $patientId = $args['patientId'];
        $entryDate = $args['entryDate'];
        
        $colorNum = postItColor($patientId, $entryDate);
        echo "<SEPARATOR>";
        echo "colorNum($colorNum) <br>\n";
    } else {
        echo "*** unknown command: $command ***";
    }
    
?>

