<?php
	
    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;
                    }
                    //echo "$key{".$obj[$key]."}\n"; //##
                }
            }
        }
        return $obj;
    }
	
    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);
        return $val;
    }
    
    function timestamp(){
        // 現在のタイムスタンプを返す updateTime に使う
        return date("Y-m-d H:i:s",time());
    }
    
    function hasDB($_dbname){
        // $db_name があれば TRUE を、なければ FALSE を返す
        $sql="SHOW TABLES FROM $_dbname";
        echo "$sql <br>"; //##
        
        $result = mysql_query($sql);
        while ($row = mysql_fetch_row($result)) {
            echo "hasDB -- true <br>";
            return TRUE;
        }
        echo "hasDB -- false <br>";
        return FALSE;
    }
    
    function hasTable($_dbname, $_tablename){
        // $db_name 中に $_tablename があれば TRUE を、なければ FALSE を返す
        $sql="SHOW TABLES FROM $_dbname";
        $result = mysql_query($sql);
        while ($row = mysql_fetch_row($result)) {
            if ($row[0]==$_tablename) return TRUE;
        }
        return FALSE;
    }
    
    function hasField($_dbname, $_tablename, $_fieldname){
        // $db_name 中に $_tablename があれば 1 を、なければ 0 を返す
        $result = mysql_query("SHOW COLUMNS FROM $_tablename");
        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();
        return FALSE;
    }
    
    function checkDB($_dbname){
        // NOA DB が存在するかチェックし存在しなければ生成
        if (hasDB($_dbname)){
            echo "checkDB -- true ";
            return TRUE;
        } else {
            // NOA DB が存在しなければ作る
            $sql="CREATE DATABASE $_dbname";
            echo "$sql \n"; //##
            $result = mysql_query($sql);
            
            return $result;
        }
    }
    
    function createTableIfNeeded($_dbname){
        // TABLE が存在しなければ生成
        if (! hasTable($_dbname, "AddressSection")){
            $sql="CREATE TABLE `AddressSection` (
            `patientId` VARCHAR( 32 ) NOT NULL ,
            `type` VARCHAR( 15 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `zip` VARCHAR( 15 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `address` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `phone` VARCHAR( 127 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `fax` VARCHAR( 127 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `email` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `memo` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `entryDate` TIMESTAMP NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `freq` INT NULL ,
            `owner` VARCHAR( 32 ) NULL ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "BasicSection")){
            $sql="CREATE TABLE `BasicSection` (
            `patientId` VARCHAR( 32 ) NOT NULL ,
            `allergy` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `drinking` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `smoking` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `bloodtype` VARCHAR(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `history` VARCHAR( 512 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `job` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `entryDate` TIMESTAMP NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `freq` INT NULL ,
            `owner` VARCHAR( 32 ) NULL ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "FieldTable")){
            $sql="CREATE TABLE `FieldTable` (
            `owner` VARCHAR( 32 ) NOT NULL ,
            `tag` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `buttonType` INT NULL ,
            `menuType` INT NULL ,
            `menuAction` INT NULL ,
            `hitAndRun` INT NULL ,
            `fieldType` INT NULL ,
            `direction` VARCHAR( 8 ) NULL ,
            `disabled` INT NULL ,
            `editor` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `id` VARCHAR( 32 ) NOT NULL ,
            `script` VARCHAR( 512 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `bgcolor` VARCHAR( 8 ) NULL ,
            `label` VARCHAR( 16 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `numbering` INT NULL ,
            `study` INT NULL ,
            `fontSize` INT NULL ,
            `fontFamily` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `color` VARCHAR( 8 ) NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "FrontTable")){
            $sql="CREATE TABLE `FrontTable` (
            `userCode` INT UNSIGNED NULL ,
            `groupCode` INT UNSIGNED NULL ,
            `inOut` VARCHAR( 10 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `newPatient` VARCHAR( 10 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `point` FLOAT NULL ,
            `insFee` INT NULL ,
            `ownFee` INT NULL ,
            `mishuu` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `receive` INT NULL ,
            `patientId` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
            `anotherId` VARCHAR( 20 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
            `kanjiName` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `plan` VARCHAR( 512 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `beginTime` TIMESTAMP NULL ,
            `endTime` TIMESTAMP NULL ,
            `checkOutTime` TIMESTAMP NULL ,
            `entryDate` TIMESTAMP NOT NULL ,
            `updateTime` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ,
            `owner` VARCHAR( 32 ) NOT NULL ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "HealthInsurance")){
            $sql="CREATE TABLE `HealthInsurance` (
            `patientId` VARCHAR( 32 ) NOT NULL ,
            `ownerName` VARCHAR( 127 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `ownerNumber` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `ownerPhone` VARCHAR( 127 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `shubetsu` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `kubun` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `kigou` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `bangou` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `continuedDiseases` VARCHAR( 127 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `paymentRatio` INT NULL ,
            `discountRatio` INT NULL ,
            `confirmation` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `startDate` DATE NULL ,
            `expiredDate` DATE NULL ,
            `entryDate` TIMESTAMP NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `freq` INT NULL ,
            `owner` VARCHAR( 32 ) NULL ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "HospitalTable")){
            $sql="CREATE TABLE `HospitalTable` (
            `hospitalId` VARCHAR(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
            `key` VARCHAR(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `value` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `entryDate` TIMESTAMP NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `owner` VARCHAR( 32 ) NOT NULL ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "MalitalSection")){
            $sql="CREATE TABLE `MalitalSection` (
            `patientId` VARCHAR( 32 ) NOT NULL ,
            `type` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `partner` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `partnersJob` VARCHAR(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `partnersOffice` VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `memo` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `startDate` DATE NULL ,
            `expiredDate` DATE NULL ,
            `entryDate` TIMESTAMP NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `freq` INT NULL ,
            `owner` VARCHAR( 32 ) NULL ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "MenuTable")){
            $sql="CREATE TABLE `MenuTable` (
            `owner` VARCHAR( 32 ) NOT NULL ,
            `tag` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `menu` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `value` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `public` INT NULL ,
            `freq` INT NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "MoneyTable")){
            $sql="CREATE TABLE `MoneyTable` (
            `entryDate` TIMESTAMP NULL ,
            `value1` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `value2` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `staff1` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `staff2` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `income` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `payment` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `memo` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `owner` VARCHAR( 32 ) NULL ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "NameSection")){
            $sql="CREATE TABLE `NameSection` (
            `patientId` VARCHAR( 32 ) NOT NULL ,
            `patientKanjiName` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `patientKanaName` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `patientRomajiName` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `entryDate` TIMESTAMP NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `freq` INT NULL ,
            `owner` VARCHAR( 32 ) NULL ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "PatientTable")){
            $sql="CREATE TABLE `PatientTable` (
            `patientId` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
            `anotherId` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
            `receiptId` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
            `sex` VARCHAR( 8 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `unpaid` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `birthDate` DATE NOT NULL ,
            `deathDate` TIMESTAMP NULL ,
            `lastVisitDate` TIMESTAMP NULL ,
            `entryDate` TIMESTAMP NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "PriceList")){
            $sql="CREATE TABLE `PriceList` (
            `code` VARCHAR( 32 ) NULL ,
            `requestCode` VARCHAR( 16 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `alias` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
            `name` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `generic` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `point` FLOAT NULL ,
            `unitName` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `handan` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `min` FLOAT NULL ,
            `standard` FLOAT NULL ,
            `max` FLOAT NULL ,
            `width` FLOAT NULL ,
            `effectCode` VARCHAR( 16 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `effect` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `memo` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `enforceDate` DATE NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "PriceListGlobal")){
            $sql="CREATE TABLE `PriceListGlobal` (
            `code` VARCHAR( 8 ) NULL ,
            `classCode` VARCHAR( 4 ) NULL ,
            `requestCode` VARCHAR( 16 ) NULL ,
            `name` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `point` FLOAT NULL ,
            `unitCode` VARCHAR( 16 ) NULL ,
            `handanCode` VARCHAR( 8 ) NULL ,
            `unitName` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `effectCode` VARCHAR( 16 ) NULL ,
            `enforceDate` DATE NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "$sql v\n"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "ProgressSection")){
            $sql="CREATE TABLE `ProgressSection` (
            `patientId` VARCHAR( 32 ) NOT NULL ,
            `pageHeader` VARCHAR( 64 ) NOT NULL ,
            `subject` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `object` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `examination` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `prescription` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `disease` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `treatment` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `assessment` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `plan` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `freq` INT NULL ,
            `entryDate` TIMESTAMP NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `owner` VARCHAR( 32 ) NULL ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "PublicInsurance")){
            $sql="CREATE TABLE `PublicInsurance` (
            `patientId` VARCHAR( 32 ) NOT NULL ,
            `ownerName` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `ownerNumber` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `recipientNumber` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `shubetsu` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `paymentRatio` VARCHAR( 5 ) NULL ,
            `payment` VARCHAR( 8 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `startDate` DATE NULL ,
            `expiredDate` DATE NULL ,
            `entryDate` TIMESTAMP NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `freq` INT NULL ,
            `owner` VARCHAR( 32 ) NULL ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "UniversalSection")){
            $sql="CREATE TABLE `UniversalSection` (
            `patientId` VARCHAR( 32 ) NOT NULL ,
            `field` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `type` INT NULL ,
            `dataString` VARCHAR( 512 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `dataObject` VARCHAR( 512 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `entryDate` TIMESTAMP NULL ,
            `updateTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `freq` INT NULL ,
            `owner` VARCHAR( 32 ) NULL ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
        if (! hasTable($_dbname, "UserTable")){
            $sql="CREATE TABLE `UserTable` (
            `userCode` VARCHAR(8) CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
            `sectionCode` VARCHAR(8) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `groupCode` VARCHAR(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `loginName` VARCHAR(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `kanjiName` VARCHAR(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `identifier` VARCHAR(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `hospitalId` VARCHAR(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `memo` VARCHAR(512) CHARACTER SET utf8 COLLATE utf8_general_ci NULL ,
            `entryDate` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
            `updateTime` TIMESTAMP NULL ,
            `owner` VARCHAR( 32 ) NOT NULL ,
            `rowid` DOUBLE NOT NULL AUTO_INCREMENT PRIMARY KEY
            )";
            echo "<p>$sql </p>"; //##
            mysql_query($sql);
        }
    }

    function hospitalIdTable($hid){
        // hospitalId の配列を返す
        if (strlen($hid) > 0)
            $sql = "SELECT * FROM `HospitalTable` WHERE `hospitalId`='$hid' ORDER BY `hospitalId`";
            else
                $sql = "SELECT * FROM `HospitalTable` ORDER BY `hospitalId`";
        echo "$sql =====\n";
        $records = array();
        $result=mysql_query($sql);
        while ($row=mysql_fetch_array($result)){
            $rec = array();
            $rec['hospitalId'] = $row['hospitalId'];
            $rec['key'] = $row['key'];
            $rec['value'] = $row['value'];
            $rec['entryDate'] = $row['entryDate'];
            $rec['updateTime'] = $row['updateTime'];
            $rec['owner'] = $row['owner'];
            $records[] = $rec;
        }
        return $records;
    }
	
    function hasSameId($fieldValue, $hid){
        // $fieldValue:"0234 8677 0323" に $hid:"8623" が含まるかどうかをチェック
        $ary = explode(" ", $fieldValue);
        for ($i=0,$ct=count($ary); $i < $ct; $i++){
            if (strcmp($ary[$i], $hid) == 0) return TRUE;
        }
        return FALSE;
    }
    function getUsersOf($hid){
        // hospitalId フィールドに $hid を含むものを検索
        $sql = "SELECT * FROM `UserTable` WHERE `hospitalId` like '%$hid%'";
        echo "getUsersOf ========\n $sql \n"; //##
        $result=mysql_query($sql);
        $array = array();
        while ($row=mysql_fetch_array($result)){
            if (hasSameId($row['hospitalId'], $hid)){
                $array[] = $row;
            }
        }
        return $array;
    }
	
    function getUserForKanjiName($hid, $name, $isNew){
        if ($isNew){
            $sql = "SELECT * FROM `UserTable` WHERE `kanjiName`='$name'";
            echo "========\n $sql \n"; //##
            $result=mysql_query($sql);
            $row=mysql_fetch_array($result);
            return $row;
        } else {
            $sql = "SELECT * FROM `UserTable` WHERE `hospitalId` like '%$hid%' AND `kanjiName`='$name'";
            echo "========\n $sql \n"; //##
            $result=mysql_query($sql);
            while ($row=mysql_fetch_array($result)){
                if (hasSameId($row['hospitalId'], $hid)) 
                    return $row;
            }
            return null;
        }
    }
	
    function newHospId($oldId, $newId){
        // 複数施設に属することができるよう hospitalId は空白で区切り複数記述できる
        // $oldId:"0123 2634 2588" に $newId:"0816" が存在しなければ追加したものを返す
        $array = explode(" ", $oldId);
        for ($i=0,$ct=count($array); $i < $ct; $i++){
            $id = $array[$i];
            if ($id == $newId) return $oldId; // すでに $newId が登録されていた
        }
        return "$oldId $newId"; // $newId を追加したものを返す
    }
	
    function putUser($record){
        // ユーザを登録：複数施設に所属してもユーザは唯一しか存在しない
        // 従って userCode は不要なので、定義されているが使用しない
        $owner = $record['owner'];
        $ucode = $record['userCode'];
        $scode = $record['sectionCode'];
        $gcode = $record['groupCode'];
        $name = $record['kanjiName'];
        $identifier = $record['identifier'];
        $loginName = $record['loginName'];
        $hid = $record['hospitalId'];
        $memo = $record['memo'];
        $updateTime = date("Y-m-d H:i:s",time()); // DB が未対応なので必要
        
        $sql = "SELECT * FROM `UserTable` WHERE `loginName`='$loginName'";
        echo "========\n $sql \n"; //###
        $result=mysql_query($sql);
        
        $row=mysql_fetch_array($result);
        if ($row){ // 同じ loginName が存在した
            $hospitalId = newHospId($row['hospitalId'], $hid);
            $rowid = $row['rowid'];
            $sql = "UPDATE `UserTable` SET `userCode`='$ucode',`sectionCode`='$scode',`groupCode`='$gcode',`kanjiName`='$name',`identifier`='$identifier',`hospitalId`='$hospitalId',`memo`='$memo',`updateTime`='$updateTime' WHERE `rowid`='$rowid'";
        }
        else { // 同じ loginName が存在しなかった
            $sql = "INSERT INTO `UserTable` (`userCode`,`sectionCode`,`groupCode`,`loginName`,`kanjiName` ,`identifier`,`hospitalId`,`memo`,`entryDate`,`updateTime`,`owner`) VALUES ('$ucode','$scode','$gcode','$loginName','$name','$identifier','$hid','$memo','$updateTime','$updateTime','$owner')";
        }
        echo "========\n $sql \n"; //###
        mysql_query($sql);
    }

    function valueWithout($st, $hospitalId){
        // st:"0323 4200 8612" から patientId:"4200" を削除して返す
        $results = array();
        $array = explode(" ", $st);
        for ($i=0,$ct=count($array); $i < $ct; $i++){
            if (strcmp($hospitalId, $array[$i]) == 0) continue;
            $results[] = $array[$i];
        }
        return join(" ", $results);
    }
    
	function removeUserHospitalId($hospitalId, $loginName){
        // $hospitalId と $loginName を持つ user record から $hospitalId を削除
        
        if ($loginName){
            // hospitalId と loginName を持つユーザ・レコードを検索
            $sql = "SELECT * FROM `UserTable` WHERE `hospitalId`like'%$hospitalId%' AND `loginName`='$loginName'";
        } else {
            // hospitalId を持つユーザ・レコードを検索
            $sql = "SELECT * FROM `UserTable` WHERE `hospitalId`like'%$hospitalId%'";
        }
        echo "========\n $sql \n"; //###
        $result=mysql_query($sql);
        
        while ($row=mysql_fetch_array($result)){
            $rowid = $row['rowid'];
            if (strcmp($row['hospitalId'], $hospitalId) == 0){
                // hospitalId 唯一しか持たない user はレコードごと削除
                $sql = "DELETE FROM `UserTable` WHERE `rowid`='$rowid'";
            } else {
                // hospitalId を複数持つレコードから hospitalId ひとつのみ削除
                $val = valueWithout($row['hospitalId'], $hospitalId);
                $updateTime = date("Y-m-d H:i:s",time());
                $sql = "UPDATE `UserTable` SET `hospitalId`='$val',`updateTime`='$updateTime' WHERE `rowid`='$rowid'";
            }
            echo "========\n $sql \n"; //###
            mysql_query($sql);
        }
    }

    function pathWith($owner, $tableType, $filename){
        // アーカイブ・ファイルの収納先の path を設定して返す
        // $tableType が "./MENU.txt" 形式なら、そのままを path と解釈
        if (substr($tableType, 0, 2) == "./")
            return $tableType;
        
        $dir = "../Users";
        if (! file_exists($dir)) mkdir($dir, 0777);
        
        $dir = "$dir/$owner";
        if (! file_exists($dir)) mkdir($dir, 0777);
        
        // FOLDER
        if (strcmp($tableType, "MENU") == 0)
            $dir = "$dir/MENU_SOURCE";
        else if (strcmp($tableType, "FIELD") == 0)
            $dir = "$dir/FIELD_SOURCE";
        else if (strcmp($tableType, "GROUP") == 0)
            $dir = "$dir/GROUP";
        else if (strcmp($tableType, "PRICE") == 0)
            $dir = "../Users/PRICE_SOURCE";
        else
            return ""; // Irregurar $tabletype
        if (! file_exists($dir)) mkdir($dir, 0777);
        
        if ($filename){
            return "$dir/$filename";
        } else {
            // $filename が省略されている場合は バックアップファイル
            $now = date("YmdHi",time());
            return "$dir/$now$tableType.txt"; // 201112080835MENU.txt 形式
        }
    }
    
    function recordOfGlobal($requestCode){
        // $requestCode のレコードを PriceListGlobal から取り出して返す
        $sql = "SELECT * FROM `PriceListGlobal` WHERE `requestCode`='$requestCode'";
        //echo "=== recordOfGlobal =====\n $sql \n";
        $result=mysql_query($sql);
        
        if (mysql_num_rows ($result) > 0){
            $row=mysql_fetch_array($result);
            return $row;
        } else
            return null;
    }

	function overWriteToPriceList($rec){
        // $rec の必要な内容を PriceList の該当レコードへ書き込む
        if (!$rec) return;
        
        $requestCode = $rec['requestCode'];
        $name = $rec['name'];
        $point = $rec['point'];
        $updateTime = timeStamp();
        $unitName = $rec['unitName'];
        $_unit = ($unitName) ? ",`unitName`='$unitName'" : "";
        $effectCode = $rec['effectCode'];
        $_effect = ($effectCode) ? ",`effectCode`='$effectCode'" : "";
        $handan = handanWithCode($rec['handanCode']);
        $_handan = ($handan) ? ",`handan`='$handan'" : "";
        
        $sql = "UPDATE `PriceList` SET `name`='$name',`point`='$point' $_unit $_effect $_handan,`updateTime`='$updateTime' WHERE `requestCode`='$requestCode'";
        
        echo "=== overWriteToPriceList =====\n $sql \n";
        mysql_query($sql);
    }

    function decodeMenu($val){
        // menuTable の value 中の "^" を '"' へ "&lt;br/&gt;" を改行へ decode
        $array = explode("^", $val);
        $val = implode('\"', $array);
        $array = explode("&lt;br/&gt;", $val);
        $val = implode('\n', $array);
        return $val;
    }
    



    
    
    $command = $_GET['command']; $command=htmlspecialchars($command);
    $value = $_GET['value']; $value=htmlspecialchars($value);
    $value = decodeSTRING($value);
    
    // DB を開いて該当レコードを読み込む
    // ### セキュリティーを保つには、以下のファイルを外からアクセスできない
    // ### directory に置き、以下の cfg.php の pass をそこへ変更
    require_once('../XNOA/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,"CREATE_TABLE_IF_NEEDED") == 0){
        // NOA の各テーブルをチェックし存在しなければ生成する
        // テーブル生成する場合はメッセージを echo
        echo "<SEPARATOR>";
        // 全てのテーブルがすでに存在すれば、以後何のメッセージも発生しない
        createTableIfNeeded($db['dbname']);
    } else if (strcmp($command,"CHECK_DB") == 0){
        // NOA DB が存在するかチェック
        if (checkDB($db['dbname']) == FALSE)
            echo "<SEPARATOR>".$db['dbname']." が構築されていません";
        else
            echo "<SEPARATOR>";
    } else if (strcmp($command,"GET_HOSPITAL_TABLE") == 0){
        // $target
        $array = hospitalIdTable($target);
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"PUT_HOSPITAL_TABLE") == 0){ 
        $args = decodeObject($value);
        $hid = $args['hospitalId'];
        $owner = $args['owner'];
        
        // client 側で再読込みするので結果の返送不要：従ってここではデバッグ用ログを返送
        echo "<SEPARATOR>";
        foreach ($args as $key=>$value){
            if (strcmp($key, 'hospitalId') == 0) continue;
            if (strcmp($key, 'owner') == 0) continue;
            
            if (strlen($value) == 0){
                $sql = "DELETE FROM `HospitalTable` WHERE `key`='$key'";
                echo "$sql ==========\n";
                mysql_query($sql);
           } else {
                $sql = "SELECT * FROM `HospitalTable` WHERE `hospitalId`='$hid' AND `key`='$key'";
                $result=mysql_query($sql);
               
                $updateTime = date("Y-m-d H:i:s",time());
                if (mysql_num_rows ($result) > 0){
                    $sql = "UPDATE `HospitalTable` SET `value`='$value',`updateTime`='$updateTime' WHERE `hospitalId`='$hid' AND `key`='$key'";
                } else {
                    $sql = "INSERT INTO `HospitalTable` (`hospitalId`,`key`,`value`,`entryDate`,`updateTime`,`owner`) VALUES ('$hid','$key','$value','$updateTime','$updateTime','$owner')";
                }
                echo "$sql ==========\n";
                mysql_query($sql);
            }
        }
    } else if (strcmp($command,"REMOVE_HOSPITAL") == 0){
        // $target $owner
        $array = decodeObject($value);
        $hospitalId = $array['hospitalId'];
        
        // 指定された hospitalId のレコードを削除
        $sql = "DELETE FROM `HospitalTable` WHERE `hospitalId`='$hospitalId'";
        echo "$sql ==========\n";
        mysql_query($sql);
        
        // ユーザ・レコードの hospitalId フィールドから $hospitalId の部分のみを削除
        // もし hospitalId が複数の $hospitalId を持たないならユーザ・レコード自体を削除
        removeUserHospitalId($hospitalId, "");
        
        // 削除処理された後の hospitalId の配列を返す
        $array = hospitalIdTable($hospitalId);
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"GET_USERS") == 0){
        // $target
        // hospitalInfo:$target に所属するスタッフのレコードを返す
        $array = decodeObject($value);
        $hospitalId = $array['hospitalId'];
        
        $row = getUsersOf($hospitalId);
        echo "<SEPARATOR>";
        echo json_encode($row);
    } else if (strcmp($command,"GET_USER") == 0){
        // $target $value
        // hospitalInfo:$target に所属するスタッフのレコードを返す
        $array = decodeObject($value);
        $hospitalId = $array['hospitalId'];
        $kanjiName = $array['kanjiName'];
        $isNew = $array['isNew'];
        
        $rec = array();
        $row = getUserForKanjiName($hospitalId, $kanjiName, $isNew);
        if ($row){
            $rec['userCode'] = $row['userCode'];
            $rec['sectionCode'] = $row['sectionCode'];
            $rec['groupCode'] = $row['groupCode'];
            $rec['identifier'] = $row['identifier'];
            $rec['loginName'] = $row['loginName'];
            $rec['kanjiName'] = $row['kanjiName'];
            $rec['hospitalId'] = $row['hospitalId'];
            $rec['memo'] = $row['memo'];
            $rec['entryDate'] = $row['entryDate'];
            $rec['updateTime'] = $row['updateTime'];
            $rec['owner'] = $row['owner'];
        } else {
            $rec['kanjiName'] = $kanjiName;
        }
        //echo "kanjiName(".$row['kanjiName'].")"; //##
        
        echo "<SEPARATOR>";
        echo json_encode($rec);
    } else if (strcmp($command,"PUT_USER") == 0){
        $array = decodeObject($value);
        $kanjiName = $array['kanjiName'];

        putUser($array);

        echo "<SEPARATOR>$kanjiName を登録しました";
    } else if (strcmp($command,"REMOVE_USER") == 0){
        $array = decodeObject($value);
        $hospitalId = $array['hospitalId'];
        $loginName = $array['loginName'];
        
        // $loginName のレコードから hospitalId のデータを削除
        // 該当 hospitalId を一つのみ持つユーザはレコードごと削除
        removeUserHospitalId($hospitalId, $loginName);
        
        // 更新されたユーザリストを返す
        $row = getUsersOf($hospitalId);
        echo "<SEPARATOR>";
        echo json_encode($row);
    } else if (strcmp($command,"GET_ARCHIVED_LIST") == 0){
        $args = decodeObject($value);
        $owner = $args['owner'];
        $folder = $args['folder'];
        
        $path = "../Users/$owner/$folder/";
        $files = scandir($path, 1); // 1:降順に取り出す
        
        $array = array();
        for ($i=0,$ct=count($files); $i < $ct; $i++){
            $file = $files[$i];
            $aPath = "$path/$file";
            
            // $aPath を調べて directory なら除外
            if (is_dir($aPath)) continue;
            
            $array[] = $file;
        }
        
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"GET_TABLE_SOURCE") == 0){
        // tag とそこに従属するメニュー項目を入れたオブジェクトを返す
        // args: $owner
        $args = decodeObject($value);
        // client 側との約束ごと
        $owner = $args['owner'];
        $table = $args['table'];
        $order = $args['order'];
        if (strcmp($table, "PriceList") == 0){
            $sql = "SELECT * FROM `$table`
            ORDER BY $order";
        } else if (strcmp($table, "ProgressSection") == 0){
            $sql = "SELECT * FROM `$table`
            WHERE `owner`='$owner' AND `patientId`='GroupMenu'
            ORDER BY $order";
        } else {
            $sql = "SELECT * FROM `$table`
            WHERE `owner`='$owner'
            ORDER BY $order";
        }
        echo "$sql ==========\n";
        $array = array();
        $result=mysql_query($sql);
        while ($row=mysql_fetch_array($result)){
            $array[] = $row;
        }
        echo "<SEPARATOR>";
        // [{"owner":"ohashi","tag":"BasicSection.allergy",,},{,,},,] を返す
        echo json_encode($array);
    } else if (strcmp($command,"GET_GLOBAL_PRICE") == 0){
        $args = decodeObject($value);
        $code = $args['code'];
        $classCode = $args['classCode'];
        $effectCode = $args['effectCode'];
        $name = $args['name'];
        $handanCode = $args['handan'];
        if (strcmp($code, "*") == 0){
            // ワイルドカード：全レコードを表示
            $sql = "SELECT * FROM `PriceListGlobal` ORDER BY `code`,`name`";
        } else {
            $_code = (strlen($code))
            ? "`code` LIKE '$code%' AND " : "";
            
            $_class = (strlen($classCode))
            ? "`classCode`='$classCode' AND " : "";
            
            $_effect = (strlen($effectCode))
            ? "`effectCode` LIKE '$effectCode%' AND " : "";
            
            $_handan = (strlen($handanCode))
            ? "`handanCode` LIKE '$handanCode%' AND " : "";
            
            $sql = "SELECT * FROM `PriceListGlobal` WHERE $_code $_class $_effect $_handan `name` LIKE '%$name%' ORDER BY `code`,`name`";
        }
        
        echo "$sql ------\n";
        $result=mysql_query($sql);
        
        echo "<SEPARATOR>[";
        while ($row=mysql_fetch_array($result)){
            $array = array();
            $array['code'] = $row['code'];
            $array['classCode'] = $row['classCode'];
            $array['requestCode'] = $row['requestCode'];
            $array['name'] = $row['name'];
            $array['point'] = $row['point'];
            $array['unitCode'] = $row['unitCode'];
            $array['unitName'] = $row['unitName'];
            $array['handanCode'] = $row['handanCode'];
            $array['effectCode'] = $row['effectCode'];
            $array['enforceDate'] = $row['enforceDate'];
            // 全体を json_encode() 使用とすると巨大データでコケるので
            // レコードを一行ずつ encode する
            echo json_encode($array).",";
        }
        echo "{}]";
    } else if (strcmp($command,"PUT_PRICE_LIST") == 0){
        // レコードを挿入する
        $args = decodeObject($value);
        $code = $args['code'];
        $requestCode = $args['requestCode'];
        $alias = $args['alias'];
        $name = $args['name'];
        $generic = $args['generic'];
        $point = $args['point'];
        $unitName = $args['unitName'];
        $handan = $args['handan'];
        $min = $args['min'];
        $standard = $args['standard'];
        $max = $args['max'];
        $width = $args['width'];
        $effectCode = $args['effectCode'];
        $effect = $args['effect'];
        $memo = $args['memo'];
        $enforceDate = $args['enforceDate'];
        $updateTime = date("Y-m-d H:i:s",time());
        
        $sql = "SELECT * FROM `PriceList` WHERE `code`='$code' AND `alias`='$alias'";
        echo "$sql ------\n";
        $result=mysql_query($sql);
        
        if (mysql_num_rows ($result) == 0){	// 同じ項目が存在しなかった
            $sql = "INSERT INTO `PriceList`
            (`code`,`requestCode`,`alias`,`name`,`generic`,`point`,`unitName`
             ,`handan`,`min`,`standard`,`max`,`width`,`effectCode`
             ,`effect`,`memo`,`enforceDate`,`updateTime`)
            VALUES (
                    '$code','$requestCode','$alias','$name','$generic','$point','$unitName'
                    ,'$nandan','$min','$standard','$max','$width','$effectCode'
                    ,'$effect','$memo','$enforceDate','$updateTime')";
        } else {
            $sql = "UPDATE `PriceList`
            SET `code`='$code'
            ,`requestCode`='$requestCode'
            ,`name`='$name'
            ,`generic`='$generic'
            ,`point`='$point'
            ,`unitName`='$unitName'
            ,`handan`='$handan'
            ,`min`='$min'
            ,`standard`='$standard'
            ,`max`='$max'
            ,`effectCode`='$effectCode'
            ,`effect`='$effect'
            ,`memo`='$memo'
            ,`enforceDate`='$enforceDate'
            ,`updateTime`='$updateTime'
            WHERE `alias`='$alias'";
        }
        echo "$sql ----\n";
        mysql_query($sql);
        echo "<SEPARATOR>";
        echo $value;
    } else if (strcmp($command,"GET_ARCHICE") == 0){
        $args = decodeObject($value);
        // client 側との約束ごと
        //$owner = get_current_user(); // PHP の関数
        $owner = $args['owner'];
        $tableType = $args['tableType'];
        $filename = $args['filename'];
        if (strpos($filename, '.') == 0){
            $path = $filename;
        } else {
            $path = pathWith($owner, $tableType, $filename);
            
            if (strlen($path) == 0){
                echo "Irregular target($path) \n";
                
                return; // Irregular $target
            }
        }
        echo "GET_ARCHICE($path) \n";
        
        if (file_exists($path)){ // PHP の関数
            if ($handle = fopen($path, 'r')) {
                // オープンしたファイルを読込む
                echo "<SEPARATOR>";
                if ($handle) {
                    while (!feof($handle)) {
                        $st = fgets($handle);
                        $st = mb_convert_encoding($st, "UTF-8", "UTF-8,SJIS,EUC-JP");
                        
                        echo "$st";
                    }
                }
                fclose($handle);
                return;
            } else
                echo "ERROR *** ($path) Cannot open \n";
        } else
            echo "ERROR *** ($path) not exist \n";
    } else if (strcmp($command,"PUT_MENU") == 0){
        $args = decodeObject($value);
        // client 側との約束ごと
        $owner = $args['owner'];
        $tag = $args['tag'];
        $menu = $args['menu'];
        $value = $args['value'];
        $public = $args['public'];
        $freq = $args['freq'];
        $updateTime = timeStamp();
        
        $sql = "SELECT * FROM `MenuTable` WHERE `tag`='$tag' AND `menu`='$menu' AND `owner`='$owner'";
        echo "$sql ==========\n";
        $result=mysql_query($sql);
        
        if (mysql_num_rows ($result) > 0){
            $sql = "UPDATE `MenuTable`
            SET `owner`='$owner',`value`='$value',`public`='$public'
            ,`freq`='$freq',`updateTime`='$updateTime'
            WHERE `tag`='$tag' AND `menu`='$menu'";
        } else {
            $sql = "INSERT INTO `MenuTable`
            (`owner`,`tag`,`menu`,`value`,`public`,`freq`,`updateTime`)
            VALUES ('$owner','$tag','$menu','$value','$public','$freq'
                    ,'$updateTime')";
        }
        echo "$sql ==========\n";
        $result=mysql_query($sql);
        echo "<SEPARATOR>";
    } else if (strcmp($command,"MERGE_MENU") == 0){
        // メニュー項目を DB のものとマージ
        $args = decodeObject($value);
        $owner = $args['owner'];
        $tag = $args['tag'];
        $menu = $args['menu'];
        $val = $args['value'];
        $public = $args['public'];
        $freq = $args['freq'];
        $updateTime = date("Y-m-d H:i:s",time());
        
        $sql = "SELECT * FROM `MenuTable`
        WHERE `tag`='$tag' AND `menu`='$menu' AND `owner`='$owner'";
        //echo "$sql ===\n\n";
        
        $result=mysql_query($sql);
        echo "<SEPARATOR>";
        if (mysql_num_rows ($result) == 0){	// 同じメニュー項目が存在しなかった
            $sql = "INSERT INTO `MenuTable` (
            `tag`,`freq`,`menu`,`value`,`public`,`updateTime`,`owner`
            ) VALUES (
                      '$tag','$freq','$menu','$val','$public','$updateTime','$owner')";
            echo "$sql ===\n\n";
            mysql_query($sql);
        } else
            echo "$tag AND $menu AND $owner ... はすでに存在します";
		
    } else if (strcmp($command,"MERGE_FIELD") == 0){
        // フィールド項目を DB のものとマージ
        $args = decodeObject($value);
        $owner = $args['owner'];
        $tag = $args['tag'];
        $buttonType = $args['buttonType'];
        $menuType = $args['menuType'];
        $menuAction = $args['menuAction'];
        $hitAndRun = $args['hitAndRun'];
        $fieldType = $args['fieldType'];
        $direction = $args['direction'];
        $disabled = $args['disabled'];
        $editor = $args['editor'];
        $id = $args['id'];
        
        // script は " が object2json により ^ で置換されている場合があるので、その場合は元へ戻す
        $ary = explode("^", $args['script']);
        if (count($ary) > 1)
            $script = join('"', $ary);
        else
            $script =  $args['script'];
        
        $bgcolor = $args['bgcolor'];
        $label = $args['label'];
        $numbering = $args['numbering'];
        $study = $args['study'];
        $fontSize = $args['fontSize'];
        $color = $args['color'];
        $fontFamily = $args['fontFamily'];
        $updateTime = timeStamp();
        
        $sql = "SELECT * FROM `FieldTable`
        WHERE `tag`='$tag' AND `id`='$id' AND `owner`='$owner'";
        //echo "$sql ------\n";
        
        $result=mysql_query($sql);
        echo "<SEPARATOR>";
        if (mysql_num_rows ($result) == 0){	// $tag が存在しなかった
            $sql = "INSERT INTO `FieldTable`
            (`owner`,`tag`,`buttonType`,`menuType`,`menuAction`,`hitAndRun`
             ,`fieldType`,`direction`,`disabled`,`editor`,`id`
             ,`script`,`bgcolor`,`label`,`numbering`,`study`
             ,`fontSize`,`fontFamily`,`color`,`updateTime`) VALUES (
                                                                    '$owner','$tag','$buttonType','$menuType','$menuAction','$hitAndRun'
                                                                    ,'$fieldType','$direction','$disabled','$editor','$id'
                                                                    ,'$script','$bgcolor','$label','$numbering','$study'
                                                                    ,'$fontSize','$fontFamily','$color','$updateTime')";
            echo "$sql ------\n";
            mysql_query($sql);
        } else
            echo "$id AND $tag AND $owner ... はすでに存在します";
    } else if (strcmp($command,"MERGE_PRICE") == 0){
        // PriceList を DB のものとマージ
        $args = decodeObject($value);
        $code = $args['code'];
        $requestCode = $args['requestCode'];
        $alias = $args['alias'];
        $name = $args['name'];
        $point = $args['point'];
        $unitName = $args['unitName'];
        $handan = $args['handan'];
        $min = $args['min'];
        $standard = $args['standard'];
        $max = $args['max'];
        $width = $args['width'];
        $effectCode = $args['effectCode'];
        $effect = $args['effect'];
        $memo = $args['memo'];
        $enforceDate = $args['enforceDate'];
        $updateTime = date("Y-m-d H:i:s",time());
        
        $sql = "SELECT * FROM `PriceList`
        WHERE `code`='$code' AND `name`='$name'";
        //echo "$sql ------\n";
        $result=mysql_query($sql);
        
        echo "<SEPARATOR>";
        if (mysql_num_rows ($result) == 0){	// 同じメニュー項目が存在しなかった
            $sql = "INSERT INTO `PriceList`
            (`code`,`requestCode`,`alias`,`name`,`point`,`unitName`
             ,`handan`,`min`,`standard`,`max`,`width`,`effectCode`
             ,`effect`,`memo`,`enforceDate`,`updateTime`) VALUES
            ('$code','$requestCode','$alias','$name','$point','$unitName'
             ,'$handan','$min','$standard','$max','$width','$effectCode'
             ,'$effect','$memo','$enforceDate','$updateTime')";
            echo "$sql ----\n";
            mysql_query($sql);
        } else
            echo "$code AND $name ... はすでに存在します";
    } else if (strcmp($command,"PUT_GROUP") == 0){
        // メニュー項目を DB のものとマージ
        $args = decodeObject($value);
        // client 側との約束ごと
        //$pageHeader = $args['pageHeader'];
        $subject = $args['subject'];
        $object = $args['object'];
        $examination = $args['examination'];
        $prescription = $args['prescription'];
        $disease = $args['disease'];
        $treatment = $args['treatment'];
        $assessment = $args['assessment'];
        $plan = $args['plan'];
        $freq = $args['freq'];
        $owner = $args['owner'];
        
        $sql = "SELECT * FROM `ProgressSection` WHERE `patientId`='GroupMenu' AND `subject`='$subject' AND `owner`='$owner'";
        echo "$sql ===\n\n";
        $result=mysql_query($sql);
        echo "<SEPARATOR>";
        if (mysql_num_rows ($result) == 0){	// 同じメニュー項目が存在しなかった
            $sql = "INSERT INTO `ProgressSection` (
            `patientId`,`pageHeader`,`subject`,`object`,`examination`
            ,`prescription`,`disease`,`treatment`,`assessment`
            ,`plan`,`freq`,`owner`
            ) VALUES (
                      'GroupMenu','$pageHeader','$subject','$object','$examination'
                      ,'$prescription','$disease','$treatment','$assessment'
                      ,'$plan','$freq','$owner')";
        } else {
            $sql = "UPDATE `ProgressSection`
            SET
            `object`='$object'
            ,`examination`='$examination'
            ,`prescription`='$prescription'
            ,`disease`='$disease'
            ,`treatment`='$treatment'
            ,`assessment`='$assessment'
            ,`plan`='$plan'
            ,`freq`='$freq'
            WHERE `patientId`='GroupMenu' AND `subject`='$subject' 
            AND `owner`='$owner'";
        }
        echo "$sql ===\n\n";
        mysql_query($sql);
    } else if (strcmp($command,"MERGE_GROUP") == 0){
        // メニュー項目を DB のものとマージ
        $args = decodeObject($value);
        // $owner は $args に含まれたものでなく "public" を使う
        $owner = $args['owner'];
        $pageHeader = $args['pageHeader'];
        $subject = $args['subject'];
        $object = $args['object'];
        $examination = $args['examination'];
        $prescription = $args['prescription'];
        $disease = $args['disease'];
        $treatment = $args['treatment'];
        $assessment = $args['assessment'];
        $plan = $args['plan'];
        $freq = $args['freq'];
        
        $sql = "SELECT * FROM `ProgressSection` WHERE `patientId`='GroupMenu' AND `subject`='$subject' AND `owner`='$owner'";
        //echo "$sql ===\n\n";
        $result=mysql_query($sql);
        echo "<SEPARATOR>";
        if (mysql_num_rows ($result) == 0){	// 同じメニュー項目が存在しなかった
            $sql = "INSERT INTO `ProgressSection` (
            `patientId`,`pageHeader`,`subject`,`object`,`examination`
            ,`prescription`,`disease`,`treatment`,`assessment`
            ,`plan`,`freq`,`owner`
            ) VALUES (
                      'GroupMenu','$pageHeader','$subject','$object','$examination'
                      ,'$prescription','$disease','$treatment','$assessment'
                      ,'$plan','$freq','$owner')";
            echo "$sql ===\n\n";
            mysql_query($sql);
        } else
            echo "$subject AND $owner ... はすでに存在します";
    } else if (strcmp($command,"REMOVE_GROUP_MENU") == 0){
        // MenuTable のデータを空にする
        $args = decodeObject($value);
        $owner = $args['owner'];
        $subject = $args['subject'];
        
        $sql = "DELETE FROM `ProgressSection` WHERE `owner`='$owner' AND `subject`='$subject' AND `patientId`='GroupMenu'";
        echo "$sql ------\n";
        $result=mysql_query($sql);
        echo "<SEPARATOR>";
    } else if (strcmp($command,"GET_LOGIN_USER") == 0){
        echo get_current_user(); // PHP の関数
    } else if (strcmp($command,"GET_USER_AGENT") == 0){
        // user_agent は以下のような型式の文字列
        // Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_1) AppleWebKit/537.1
        // (KHTML, like Gecko) Chrome/21.0.1180.82 Safari/537.1
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        echo $user_agent;
    } else if (strcmp($command,"RREMOVE_NOA") == 0){
        // NOA DB を全て削除
        $sql = "DROP DATABASE `NOA`";
        echo "$sql ===\n\n";
        mysql_query($sql);
        echo "NOA データベースを削除しました";
    } else if (strcmp($command,"PUT_GLOBAL_TO_PRICE") == 0){
        // グローバル辞書から PriceList へ同じ requestCode のレコードを書き込む
        // PriceList の requestCode をスキャン
        $sql = "SELECT * FROM `PriceList`";
        //echo "$sql ------\n";
        $result=mysql_query($sql);
        
        // PriceListGlobal に一致したものがあれば PriceList へ上書き
        echo "<SEPARATOR>";
        while ($row=mysql_fetch_array($result)){
            $requestCode = $row['requestCode'];
            if ($requestCode && (strlen($requestCode))){
                // 同じ requestCode のレコードを PriceListGlobal から取り出す
                //if (strcmp($requestCode,"620002506") != 0) continue; //##
                
                $newRec = recordOfGlobal($requestCode);
                $name = $row['name'];
                echo "=== $requestCode ( $name ) を上書き<br>";
                
                // それを PriceList の該当レコードに書き込む
                overWriteToPriceList($newRec);
            }
        }
    } else if (strcmp($command,"GET_USER_LIST") == 0){
        $sql = "SELECT * FROM `UserTable`";
        echo "$sql \n"; //##
        $array = array();
        $result=mysql_query($sql);
        if (mysql_num_rows ($result) > 0){
            while ($row=mysql_fetch_array($result)){
                $logname = $row['loginName'];
                $array[$logname] = $row['kanjiName'];
                echo $row['loginName']."\n"; //##
            }
        }
        echo "<SEPARATOR>";
        echo json_encode($array);
    } else if (strcmp($command,"ARCHIVE_TABLE_SOURCE") == 0){
        // $value を $filename で保存
        // args: $target $owner $value
        // バックアップファイルの場合は pathWith() の $filename パラメータを省略
        $args = decodeObject($value);
        $owner = $args['owner'];
        $target = $args['target'];
        $val = $args['val'];

        $file = pathWith($owner, $target);
        if (strlen($file) == 0) return; // Irregular $target
        
        echo "ARCHIVE_TABLE_SOURCE -> owner($owner) file($file) <br>";
        echo "val-> $val <br>";
        
        if (strcmp($val, "C_L_E_A_T_E__F_I_L_E") == 0){
            // 既存の $target が存在すればバックアップをとる
            //		backup($dir, "$target");
            // 既存の $target を書き込みモードで初期化する
            if (!$handle = fopen($file, 'w')) {
                echo "Cannot create file ($file)";
                return;
            } else {
                if (fwrite($handle, "") === FALSE) {
                    echo "Cannot write to file ($file)";
                    return;
                }
                fclose($handle);
                echo "created ($file) to save...\n";
            }
        } else {
            if (!$handle = fopen($file, 'a')) {
                echo "Cannot open file ($file)";
                return;
            } else {
                // オープンしたファイルに$buffを書き込む
                //echo "will save .. ($file)...\n";
                $val = decodeMenu($val);
                if (fwrite($handle, $val) === FALSE) {
                    echo "Cannot write to file ($file)";
                    return;
                }
                echo "save: $value \n";
                fclose($handle);
            }
        }
    } else if (strcmp($command,"REMOVE_BACKUP") == 0){
        $args = decodeObject($value);
        $owner = $args['owner'];
        $target = $args['target'];
        $filename = $args['filename'];
        
        $path = pathWith($owner, $target, $filename);
        if (strlen($path) == 0) return; // Irregular $target
        
        $msg = (unlink($path)) ? "を削除しました" : "$path を削除できませんでした";
        echo "$filename $msg";
    } else if (strcmp($command,"PUT_FIELD") == 0){
        $args = decodeObject($value);
        // client 側との約束ごと
        $owner = $args['owner'];
        $tag = $args['tag'];
        $buttonType = $args['buttonType'];
        $menuType = $args['menuType'];
        $menuAction = $args['menuAction'];
        $fieldType = $args['fieldType'];
        $direction = $args['direction'];
        $disabled = $args['disabled'];
        $editor = $args['editor'];
        $id= $args['id'];
        $script = $args['script'];
        $bgcolor = $args['bgcolor'];
        $label = $args['label'];
        $numbering= $args['numbering'];
        $fontSize = $args['fontSize'];
        $fontFamily = $args['fontFamily'];
        $color = $args['color'];
        $updateTime = timeStamp();
        
        $sql = "SELECT * FROM `FieldTable` WHERE `tag`='$tag' AND `id`='$id' AND `owner`='$owner'";
        echo "$sql ==========\n";
        $result=mysql_query($sql);
        
        if (mysql_num_rows ($result) > 0){
            $sql = "UPDATE `FieldTable`
            SET `buttonType`='$buttonType',`menuType`='$menuType'
            ,`menuAction`='$menuAction',`fieldType`='$fieldType'
            ,`direction`='$direction',`disabled`='$disabled'
            ,`editor`='$editor',`script`='$script',`bgcolor`='$bgcolor'
            ,`label`='$label',`numbering`='$numbering'
            ,`study`='$study',`fontSize`='$fontSize'
            ,`fontFamily`='$fontFamily',`color`='$color'
            ,`updateTime`='$updateTime'
            WHERE `tag`='$tag' AND `id`='$id' AND `owner`='$owner'";
        } else {
            $sql = "INSERT INTO `FieldTable` (
            `owner`,`tag`,`buttonType`,`menuType`,`menuAction`
            ,`fieldType`,`direction`,`disabled`,`editor`,`id`
            ,`script`,`bgcolor`,`label`,`numbering`,`study`
            ,`fontSize`,`fontFamily`,`color`,`updateTime`)
            VALUES (
                    '$owner','$tag','$buttonType','$menuType','$menuAction'
                    ,'$fieldType','$direction','$disabled','$editor','$id'
                    ,'$script','$bgcolor','$label','$numbering','$study'
                    ,'$fontSize','$fontFamily','$color','$updateTime')";
        }
        echo "$sql ==========\n";
        $result=mysql_query($sql);
        echo "<SEPARATOR>";
    } else if (strcmp($command,"REMOVE_FIELD") == 0){
        // $target $value
        $args = decodeObject($value);
        $tag = $args['tag'];
        $id = $args['id'];
        $owner = $args['owner'];
        
        $sql = "DELETE FROM `FieldTable` 
        WHERE `tag`='$tag' AND `id`='$id' AND `owner`='$owner'";
        echo "$sql ==========\n";
        $result=mysql_query($sql);
        
        if ($result)
            echo "<SEPARATOR>";
    } else if (strcmp($command,"CLEAR_TABLE") == 0){
        // MenuTable のデータを空にする
        $args = decodeObject($value);
        $owner = $args['owner'];
        $table = $args['table'];
        $patientId = $args['patientId'];
        
        if ($patientId){ // GROUP MENU の場合
            $sql = "DELETE FROM `$table` WHERE `owner`='$owner' AND `patientId`='$patientId'";
        } else if (strcmp($table, "PriceList") == 0){
            $sql = "DELETE FROM `PriceList`";
        } else {
            $sql = "DELETE FROM `$table` WHERE `owner`='$owner'";
        }
        echo "$sql ------\n";
        $result=mysql_query($sql);
        echo "<SEPARATOR>";
    } else {
        echo "*** unknown command: $command ***";
    }
    
?>