<?php
    
	function decodeSTRING($val){
		// #, &, +  < > などが URI 送信で化けるため encode して送られたものを decode
		$array = explode("%x0;", $val);
		$val = implode("#", $array);
		$array = explode("%x1;", $val);
		$val = implode("&", $array);
		$array = explode("%x2;", $val);
		$val = implode("+", $array);
		$array = explode("%x3;", $val);
		$val = implode("<", $array);
		$array = explode("%x4;", $val);
		$val = implode(">", $array);
		$array = explode("%x5;", $val);
		$val = implode(" ", $array);
		$array = explode("%x6;", $val);
		$val = implode("\n", $array);
		$array = explode("%x7;", $val);
		$val = implode("\"", $array);
		$array = explode("%x8;", $val);
		$val = implode("$", $array);
		$array = explode("%x9;", $val);
		$val = implode("\'", $array);
		return $val;
	}

    function getMBasicInfo($serverURL, $patientId){
        // 受信履歴をリクエスト: XML2 のみ対応
        $results = array();
        
        // ##### ORCA 指定 URL が変わった場合は以下も変更 #####
        $results['url'] = "$serverURL/api01rv2/patientgetv2?id=$patientId";
        
        return $results;
    }
    
    function getMedical($serverURL, $patientId, $entryDate){
        // 受信履歴をリクエスト: XML2 のみ対応
        $results = array();

        // ##### ORCA 指定 URL が変わった場合は以下も変更 #####
        $results['url'] = "$serverURL/api01rv2/medicalgetv2?class=02";
        $results['xml'] = '
        <data>
        <medicalgetreq type="record">
		<Patient_ID type="string">'.$patientId.'</Patient_ID>
		<Perform_Date type="string">'.$entryDate.'</Perform_Date>
		<Medical_Information type="record">
        <Department_Code type="string">01</Department_Code>
        <Sequential_Number type="string"></Sequential_Number>
        <Insurance_Combination_Number type="string"></Insurance_Combination_Number>
        <HealthInsurance_Information type="record">
        <InsuranceProvider_Class type="string"></InsuranceProvider_Class>
        <InsuranceProvider_WholeName type="string"></InsuranceProvider_WholeName>
        <InsuranceProvider_Number type="string"> </InsuranceProvider_Number>
        <HealthInsuredPerson_Symbol type="string"> </HealthInsuredPerson_Symbol>
        <HealthInsuredPerson_Number type="string"> </HealthInsuredPerson_Number>
        <PublicInsurance_Information type="array">
        <PublicInsurance_Information_child type="record">
        <PublicInsurance_Class type="string"></PublicInsurance_Class>
        <PublicInsurance_Name type="string"></PublicInsurance_Name>
        <PublicInsurance_Number type="string"></PublicInsurance_Number>
        <PublicInsuredPerson_Number type="string"></PublicInsuredPerson_Number>
        </PublicInsurance_Information_child>
        </PublicInsurance_Information>
        </HealthInsurance_Information>
		</Medical_Information>
        </medicalgetreq>
        </data>';

        return $results;
    }
	
    function getPatientList($serverURL, $entryDate){
        // 患者番号一覧の取得：XML2 未対応
        // $startDate 以降に登録・更新された患者情報を返却
        $results = array();
        
        // ##### ORCA 指定 URL が変わった場合は以下も変更 #####
        $results['url'] = "$serverURL/api01r/patientlst1?class=01";
        $results['xml'] = '
        <data>
        <record>
        <record name="patientlst1req">
        <string name="Base_StartDate">'.$startDate.'</string>
        <string name="Base_EndDate"></string>
        <string name="Contain_TestPatient_Flag"></string>
        </record>
        </record>
        </data>';
        
        return $results;
    }
    
    function getDiseaseInfo($serverURL, $patientId, $entryDate){
        // 病名の取得：XML2 未対応
        $results = array();
        $date = substr($entryDate, 0, 7); // "2014-01-8" を "2014-01" にする
        
        // ##### ORCA 指定 URL が変わった場合は以下も変更 #####
        $results['url'] = "$serverURL/api01r/diseaseget?class=01";
        $results['xml'] = '
        <data>
        <record>
        <record name="disease_inforeq">
        <string name="Patient_ID">'.$patientId.'</string>
        <string name="Base_Date">'.$date.'</string>
        </record>
        </record>
        </data>';

        return $results;
    }
    
    
	
	/*** Basic認証がかかったページにアクセスする方法 ***
	 http://www.phppro.jp/qa/212
	 
	 PEARのHTTP_Requestを使用するのが楽ではないでしょうか？
	 http://pear.php.net/manual/ja/package.http.http-request.basic-auth.php
	 */
    
    /*******************************
     http://pear.php.net 提供のライブラリーを使用
     HTTP/Request.php
     require_once 'PEAR.php';
     require_once 'Net/Socket.php';
     require_once 'Net/URL.php';
     *******************************/
    
    require_once 'HTTP/Request.php';
    
    $command = $_POST['command'];
    $serverURL = $_POST['uri'];
    $user = $_POST['user'];
    $pwd = $_POST['pwd'];
    $patientId = $_POST['patientId'];
    $date = $_POST['entryDate']; 
    $mode = $_POST['mode'];
    
    if (strcmp($command,"POST_ORCA") == 0){
        echo "serverURL($serverURL) \n"; //##
        echo "usr($user) \n"; //##
        echo "pwd($pwd) \n"; //##
        echo "mode($mode) \n"; //##
        echo "patientId($patientId) \n"; //##
        echo "entryDate($date) \n"; //##

        if (strcmp($mode, "BASIC_INFO") == 0){
            // 認証を処理しつつ URL の内容を表示
            $results = getMBasicInfo($serverURL, $patientId);
            $url = $results['url'];
        } else if (strcmp($mode, "PATIENT_INFO") == 0){
            $results = getMedical($serverURL, $patientId, $date);
            $url = $results['url'];
            $xml = $results['xml'];
        } else if (strcmp($mode, "PATIENT_LIST") == 0){
            $results = getPatientList($serverURL, $date);
            $url = $results['url'];
            $xml = $results['xml'];
        } else if (strcmp($mode, "DISEASE_INFO") == 0){
            $results = getDiseaseInfo($serverURL, $patientId, $date);
            $url = $results['url'];
            $xml = $results['xml'];
        }

        echo "xml($xml) \n"; //##

        // BASIC 認証を処理しつつ URL の内容を取得
		$req = & new HTTP_Request($url);
		$req->setBasicAuth($user, $pwd);

        if ($xml){
            // ORCA POST で追加すべきもの
            // PEAR manual: http://www.bnote.net/php/pear_idx.shtml
            // http://www.bnote.net/php/pear/http_req_03_post.shtml
            $req->setMethod(HTTP_REQUEST_METHOD_POST); // PEAR に指定するメソッド
            
            // POSTパラメータをセット
            $req->setBody($xml);
        }
        
		$response = $req->sendRequest();
		
		if (PEAR::isError($response)) {
            echo "ERROR === \n";
			echo $req->getMessage();
		} else {
            //echo "XML ====\n$xml";
            echo "<SEPARATOR>";
			echo $req->getResponseBody();
		}
//    } else if (strcmp($command,"ALL_INFO") == 0){
    } else if (strcmp($command,"TEST") == 0){
        $path = "resp1.xml";
        $handle = @fopen($path, "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 {
        echo "<p>( $command ) is wrong command *****</p>";
    }
    
?>