diff --git a/adm/shop_admin/configform.php b/adm/shop_admin/configform.php index 17fa35f47..b8759959a 100644 --- a/adm/shop_admin/configform.php +++ b/adm/shop_admin/configform.php @@ -74,6 +74,11 @@ if(!isset($default['de_inicis_mid'])) { ADD `de_inicis_admin_key` varchar(255) NOT NULL DEFAULT '' AFTER `de_inicis_mid` ", true); } +if(!isset($default['de_inicis_sign_key'])) { + sql_query(" ALTER TABLE `{$g5['g5_shop_default_table']}` + ADD `de_inicis_sign_key` varchar(255) NOT NULL DEFAULT '' AFTER `de_inicis_mid` ", true); +} + // 모바일 초기화면 이미지 줄 수 필드 추가 if(!isset($default['de_mobile_type1_list_row'])) { @@ -693,6 +698,13 @@ if(!isset($default['de_kakaopay_mid'])) { + + + + 계약정보 > 부가정보의 웹결제 signkey생성 조회 버튼 클릭, 팝업창에서 생성 버튼 클릭 후 해당 값을 입력합니다."); ?> + + + diff --git a/adm/shop_admin/configformupdate.php b/adm/shop_admin/configformupdate.php index 03dc56158..4836b14ef 100644 --- a/adm/shop_admin/configformupdate.php +++ b/adm/shop_admin/configformupdate.php @@ -158,6 +158,7 @@ $sql = " update {$g5['g5_shop_default_table']} de_kcp_site_key = '{$_POST['de_kcp_site_key']}', de_inicis_mid = '{$_POST['de_inicis_mid']}', de_inicis_admin_key = '{$_POST['de_inicis_admin_key']}', + de_inicis_sign_key = '{$_POST['de_inicis_sign_key']}', de_iche_use = '{$_POST['de_iche_use']}', de_sms_cont1 = '{$_POST['de_sms_cont1']}', de_sms_cont2 = '{$_POST['de_sms_cont2']}', diff --git a/shop/inicis/INIStdPayResult.php b/shop/inicis/INIStdPayResult.php new file mode 100644 index 000000000..794109c32 --- /dev/null +++ b/shop/inicis/INIStdPayResult.php @@ -0,0 +1,28 @@ +'.PHP_EOL; + +echo make_order_field($data, $exclude); + +echo ''.PHP_EOL; +?> + +
+ + 주문완료 중입니다. 잠시만 기다려 주십시오. +
+ + \ No newline at end of file diff --git a/shop/inicis/INIStdPayReturn.php b/shop/inicis/INIStdPayReturn.php new file mode 100644 index 000000000..983081041 --- /dev/null +++ b/shop/inicis/INIStdPayReturn.php @@ -0,0 +1,171 @@ +makeHash(signKey, "sha256"); // 가맹점 확인을 위한 signKey를 해시값으로 변경 (SHA-256방식 사용) + $mKey = hash("sha256", $signKey); + + //##################### + // 2.signature 생성 + //##################### + $signParam['authToken'] = $authToken; // 필수 + $signParam['timestamp'] = $timestamp; // 필수 + // signature 데이터 생성 (모듈에서 자동으로 signParam을 알파벳 순으로 정렬후 NVP 방식으로 나열해 hash) + $signature = $util->makeSignature($signParam); + + + //##################### + // 3.API 요청 전문 생성 + //##################### + $authMap['mid'] = $mid; // 필수 + $authMap['authToken'] = $authToken; // 필수 + $authMap['signature'] = $signature; // 필수 + $authMap['timestamp'] = $timestamp; // 필수 + $authMap['charset'] = $charset; // default=UTF-8 + $authMap['format'] = $format; // default=XML + //if(null != notiUrl && notiUrl.length() > 0){ + // authMap.put("notiUrl" ,notiUrl); + //} + + + try { + + $httpUtil = new HttpClient(); + + //##################### + // 4.API 통신 시작 + //##################### + + $authResultString = ""; + if ($httpUtil->processHTTP($authUrl, $authMap)) { + $authResultString = $httpUtil->body; + } else { + echo "Http Connect Error\n"; + echo $httpUtil->errormsg; + + throw new Exception("Http Connect Error"); + } + + //############################################################ + //5.API 통신결과 처리(***가맹점 개발수정***) + //############################################################ + + $resultMap = json_decode($authResultString, true); + + $tid = $resultMap['tid']; + $oid = $resultMap['MOID']; + + $sql = " select * from {$g5['g5_shop_order_data_table']} where od_id = '$oid' "; + $row = sql_fetch($sql); + + $data = unserialize(base64_decode($row['dt_data'])); + + if(isset($data['pp_id']) && $data['pp_id']) { + $order_action_url = G5_HTTPS_SHOP_URL.'/personalpayformupdate.php'; + $page_return_url = G5_SHOP_URL.'/personalpayform.php?pp_id='.$data['pp_id']; + } else { + $order_action_url = G5_HTTPS_SHOP_URL.'/orderformupdate.php'; + $page_return_url = G5_SHOP_URL.'/orderform.php'; + if($_SESSION['ss_direct']) + $page_return_url .= '?sw_direct=1'; + } + + if (strcmp('0000', $resultMap['resultCode']) == 0) { + /* * *************************************************************************** + * 여기에 가맹점 내부 DB에 결제 결과를 반영하는 관련 프로그램 코드를 구현한다. + + [중요!] 승인내용에 이상이 없음을 확인한 뒤 가맹점 DB에 해당건이 정상처리 되었음을 반영함 + 처리중 에러 발생시 망취소를 한다. + * **************************************************************************** */ + + // 결제결과 session에 저장 + set_session('resultMap', $resultMap); + + require G5_SHOP_PATH.'/inicis/INIStdPayResult.php'; + exit; + } else { + $s = '(오류코드:'.$resultMap['resultCode'].') '.$resultMap['resultMsg']; + alert($s, $page_return_url); + } + + // 수신결과를 파싱후 resultCode가 "0000"이면 승인성공 이외 실패 + // 가맹점에서 스스로 파싱후 내부 DB 처리 후 화면에 결과 표시 + // payViewType을 popup으로 해서 결제를 하셨을 경우 + // 내부처리후 스크립트를 이용해 opener의 화면 전환처리를 하세요 + //throw new Exception("강제 Exception"); + } catch (Exception $e) { + // $s = $e->getMessage() . ' (오류코드:' . $e->getCode() . ')'; + //#################################### + // 실패시 처리(***가맹점 개발수정***) + //#################################### + //---- db 저장 실패시 등 예외처리----// + $s = $e->getMessage() . ' (오류코드:' . $e->getCode() . ')'; + echo $s; + + //##################### + // 망취소 API + //##################### + + $netcancelResultString = ""; // 망취소 요청 API url(고정, 임의 세팅 금지) + if ($httpUtil->processHTTP($netCancel, $authMap)) { + $netcancelResultString = $httpUtil->body; + } else { + echo "Http Connect Error\n"; + echo $httpUtil->errormsg; + + throw new Exception("Http Connect Error"); + } + + echo "## 망취소 API 결과 ##"; + + $netcancelResultString = str_replace("<", "<", $$netcancelResultString); + $netcancelResultString = str_replace(">", ">", $$netcancelResultString); + + echo "
", $netcancelResultString . "
"; + // 취소 결과 확인 + } + } else { + + //############# + // 인증 실패시 + //############# + echo "
"; + echo "####인증실패####"; + + echo "
" . var_dump($_REQUEST) . "
"; + } +} catch (Exception $e) { + $s = $e->getMessage() . ' (오류코드:' . $e->getCode() . ')'; + echo $s; +} +?> \ No newline at end of file diff --git a/shop/inicis/close.php b/shop/inicis/close.php new file mode 100644 index 000000000..d7999a5d2 --- /dev/null +++ b/shop/inicis/close.php @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/shop/inicis/encryptdata.php b/shop/inicis/encryptdata.php deleted file mode 100644 index d46924982..000000000 --- a/shop/inicis/encryptdata.php +++ /dev/null @@ -1,65 +0,0 @@ -SetField("type", "chkfake"); // 고정 (절대 수정 불가) -$inipay->SetField("enctype","asym"); //asym:비대칭, symm:대칭(현재 asym으로 고정) -/************************************************************************************************** - * admin 은 키패스워드 변수명입니다. 수정하시면 안됩니다. 1111의 부분만 수정해서 사용하시기 바랍니다. - * 키패스워드는 상점관리자 페이지(https://iniweb.inicis.com)의 비밀번호가 아닙니다. 주의해 주시기 바랍니다. - * 키패스워드는 숫자 4자리로만 구성됩니다. 이 값은 키파일 발급시 결정됩니다. - * 키패스워드 값을 확인하시려면 상점측에 발급된 키파일 안의 readme.txt 파일을 참조해 주십시오. - **************************************************************************************************/ -$inipay->SetField("admin", $default['de_inicis_admin_key']); // 키패스워드(키발급시 생성, 상점관리자 패스워드와 상관없음) -$inipay->SetField("checkopt", "false"); //base64함:false, base64안함:true(현재 false로 고정) - -//필수항목 : mid, price, nointerest, quotabase -//추가가능 : INIregno, oid -//*주의* : 추가가능한 항목중 암호화 대상항목에 추가한 필드는 반드시 hidden 필드에선 제거하고 -// SESSION이나 DB를 이용해 다음페이지(INIsecureresult.php)로 전달/셋팅되어야 합니다. -$inipay->SetField("mid", $default['de_inicis_mid']); // 상점아이디 -$inipay->SetField("price", $price); // 가격 -$inipay->SetField("nointerest", $inipay_nointerest); // 무이자여부(no:일반, yes:무이자) -$inipay->SetField("quotabase", iconv_euckr($inipay_quotabase));//할부기간 - -/******************************** - * 4. 암호화 대상/값을 암호화함 * - ********************************/ -$inipay->startAction(); - -/********************* - * 5. 암호화 결과 * - *********************/ -if( $inipay->GetResult("ResultCode") != "00" ) -{ - die('{"error":"'.$inipay->GetResult("ResultMsg").'"}'); -} - -/********************* - * 6. 세션정보 저장 * - *********************/ -set_session('INI_MID', $default['de_inicis_mid']); //상점ID -set_session('INI_ADMIN', $default['de_inicis_admin_key']); // 키패스워드(키발급시 생성, 상점관리자 패스워드와 상관없음) -set_session('INI_PRICE', $price); //가격 -set_session('INI_RN', $inipay->GetResult("rn")); //고정 (절대 수정 불가) -set_session('INI_ENCTYPE', $inipay->GetResult("enctype")); //고정 (절대 수정 불가) - -$ini_encfield = $inipay->GetResult("encfield"); -$ini_certid = $inipay->GetResult("certid"); - -$result = array( - 'error' => '', - 'ini_encfield' => $ini_encfield, - 'ini_certid' => $ini_certid -); - -die(json_encode($result)); - -//die('{"error":"", "ini_encfield":"'.$ini_encfield.'", "ini_certid":"'.$ini_certid.'"}'); -?> \ No newline at end of file diff --git a/shop/inicis/inipay_result.php b/shop/inicis/inipay_result.php index a43f53b29..ae465b8ed 100644 --- a/shop/inicis/inipay_result.php +++ b/shop/inicis/inipay_result.php @@ -1,216 +1,39 @@ 구매자의 세션을 반드시 체크하도록하여 부정거래를 방지하여 주십시요. - * - * http://www.inicis.com - * Copyright (C) 2006 Inicis Co., Ltd. All rights reserved. - */ +$resultMap = get_session('resultMap'); - include_once(G5_SHOP_PATH.'/settle_inicis.inc.php'); - -/********************* - * 3. 지불 정보 설정 * -*********************/ -if($default['de_tax_flag_use']) { // 복합과세 사용 때 - $inipay->SetXPath("INIpay/GoodsInfo/Tax", $_POST['comm_vat_mny']); // 부가세 금액 - $inipay->SetXPath("INIpay/GoodsInfo/TaxFree", $_POST['comm_free_mny']); // 면세 금액 -} -$inipay->SetField("type", "securepay"); // 고정 (절대 수정 불가) -$inipay->SetField("pgid", "INIphp".$pgid); // 고정 (절대 수정 불가) -$inipay->SetField("subpgip", "203.238.3.10"); // 고정 (절대 수정 불가) -$inipay->SetField("admin", get_session('INI_ADMIN')); // 키패스워드(상점아이디에 따라 변경) -$inipay->SetField("uid", $uid); // INIpay User ID (절대 수정 불가) -$inipay->SetField("goodname", iconv_euckr($goodname)); // 상품명 -$inipay->SetField("currency", $currency); // 화폐단위 - -$inipay->SetField("mid", get_session('INI_MID')); // 상점아이디 -$inipay->SetField("rn", get_session('INI_RN')); // 웹페이지 위변조용 RN값 -$inipay->SetField("price", get_session('INI_PRICE')); // 가격 -$inipay->SetField("enctype", get_session('INI_ENCTYPE')); // 고정 (절대 수정 불가) - - - /*---------------------------------------------------------------------------------------- -price 등의 중요데이터는 -브라우저상의 위변조여부를 반드시 확인하셔야 합니다. - -결제 요청페이지에서 요청된 금액과 -실제 결제가 이루어질 금액을 반드시 비교하여 처리하십시오. - -설치 메뉴얼 2장의 결제 처리페이지 작성부분의 보안경고 부분을 확인하시기 바랍니다. -적용참조문서: 이니시스홈페이지->가맹점기술지원자료실->기타자료실 의 - '결제 처리 페이지 상에 결제 금액 변조 유무에 대한 체크' 문서를 참조하시기 바랍니다. -예제) -원 상품 가격 변수를 OriginalPrice 하고 원 가격 정보를 리턴하는 함수를 Return_OrgPrice()라 가정하면 -다음 같이 적용하여 원가격과 웹브라우저에서 Post되어 넘어온 가격을 비교 한다. - -$OriginalPrice = Return_OrgPrice(); -$PostPrice = $_SESSION['INI_PRICE']; -if ( $OriginalPrice != $PostPrice ) -{ - //결제 진행을 중단하고 금액 변경 가능성에 대한 메시지 출력 처리 - //처리 종료 -} - -----------------------------------------------------------------------------------------*/ -$inipay->SetField("buyername", iconv_euckr($buyername)); // 구매자 명 -$inipay->SetField("buyertel", $buyertel); // 구매자 연락처(휴대폰 번호 또는 유선전화번호) -$inipay->SetField("buyeremail", $buyeremail); // 구매자 이메일 주소 -$inipay->SetField("paymethod", $paymethod); // 지불방법 (절대 수정 불가) -$inipay->SetField("encrypted", $encrypted); // 암호문 -$inipay->SetField("sessionkey", $sessionkey); // 암호문 -$inipay->SetField("url", G5_URL); // 실제 서비스되는 상점 SITE URL로 변경할것 -$inipay->SetField("cardcode", $cardcode); // 카드코드 리턴 -$inipay->SetField("parentemail", $parentemail); // 보호자 이메일 주소(핸드폰 , 전화결제시에 14세 미만의 고객이 결제하면 부모 이메일로 결제 내용통보 의무, 다른결제 수단 사용시에 삭제 가능) - -/*-----------------------------------------------------------------* - * 수취인 정보 * * - *-----------------------------------------------------------------* - * 실물배송을 하는 상점의 경우에 사용되는 필드들이며 * - * 아래의 값들은 INIsecurepay.html 페이지에서 포스트 되도록 * - * 필드를 만들어 주도록 하십시요. * - * 컨텐츠 제공업체의 경우 삭제하셔도 무방합니다. * - *-----------------------------------------------------------------*/ -$inipay->SetField("recvname", iconv_euckr($recvname)); // 수취인 명 -$inipay->SetField("recvtel", $recvtel); // 수취인 연락처 -$inipay->SetField("recvaddr", iconv_euckr($recvaddr)); // 수취인 주소 -$inipay->SetField("recvpostnum", $recvpostnum); // 수취인 우편번호 -$inipay->SetField("recvmsg", $recvmsg); // 전달 메세지 - -$inipay->SetField("joincard", $joincard); // 제휴카드코드 -$inipay->SetField("joinexpire", $joinexpire); // 제휴카드유효기간 -$inipay->SetField("id_customer", $id_customer); //user_id - - -/**************** - * 4. 지불 요청 * - ****************/ -$inipay->startAction(); - -/**************************************************************************************************************** - * 5. 결제 결과 - * - * 1 모든 결제 수단에 공통되는 결제 결과 데이터 - * 거래번호 : $inipay->GetResult('TID') - * 결과코드 : $inipay->GetResult('ResultCode') ("00"이면 지불 성공) - * 결과내용 : $inipay->GetResult('ResultMsg') (지불결과에 대한 설명) - * 지불방법 : $inipay->GetResult('PayMethod') (매뉴얼 참조) - * 상점주문번호 : $inipay->GetResult('MOID') - * 결제완료금액 : $inipay->GetResult('TotPrice') - * - * 결제 되는 금액 =>원상품가격과 결제결과금액과 비교하여 금액이 동일하지 않다면 - * 결제 금액의 위변조가 의심됨으로 정상적인 처리가 되지않도록 처리 바랍니다. (해당 거래 취소 처리) - * - * - * 2. 신용카드,ISP,핸드폰, 전화 결제, 은행계좌이체, OK CASH BAG Point 결제 결과 데이터 - * (무통장입금 , 문화 상품권 포함) - * 이니시스 승인날짜 : $inipay->GetResult('ApplDate') (YYYYMMDD) - * 이니시스 승인시각 : $inipay->GetResult('ApplTime') (HHMMSS) - * - * 3. 신용카드 결제 결과 데이터 - * - * 신용카드 승인번호 : $inipay->GetResult('ApplNum') - * 할부기간 : $inipay->GetResult('CARD_Quota') - * 무이자할부 여부 : $inipay->GetResult('CARD_Interest') ("1"이면 무이자할부) - * 신용카드사 코드 : $inipay->GetResult('CARD_Code') (매뉴얼 참조) - * 카드발급사 코드 : $inipay->GetResult('CARD_BankCode') (매뉴얼 참조) - * 본인인증 수행여부 : $inipay->GetResult('CARD_AuthType') ("00"이면 수행) - * 각종 이벤트 적용 여부 : $inipay->GetResult('EventCode') - * - * ** 달러결제 시 통화코드와 환률 정보 ** - * 해당 통화코드 : $inipay->GetResult('OrgCurrency') - * 환율 : $inipay->GetResult('ExchangeRate') - * - * 아래는 "신용카드 및 OK CASH BAG 복합결제" 또는"신용카드 지불시에 OK CASH BAG적립"시에 추가되는 데이터 - * OK Cashbag 적립 승인번호 : $inipay->GetResult('OCB_SaveApplNum') - * OK Cashbag 사용 승인번호 : $inipay->GetResult('OCB_PayApplNum') - * OK Cashbag 승인일시 : $inipay->GetResult('OCB_ApplDate') (YYYYMMDDHHMMSS) - * OCB 카드번호 : $inipay->GetResult('OCB_Num') - * OK Cashbag 복합결재시 신용카드 지불금액 : $inipay->GetResult('CARD_ApplPrice') - * OK Cashbag 복합결재시 포인트 지불금액 : $inipay->GetResult('OCB_PayPrice') - * - * 4. 실시간 계좌이체 결제 결과 데이터 - * - * 은행코드 : $inipay->GetResult('ACCT_BankCode') - * 현금영수증 발행결과코드 : $inipay->GetResult('CSHR_ResultCode') - * 현금영수증 발행구분코드 : $inipay->GetResult('CSHR_Type') - * * - * 5. OK CASH BAG 결제수단을 이용시에만 결제 결과 데이터 - * OK Cashbag 적립 승인번호 : $inipay->GetResult('OCB_SaveApplNum') - * OK Cashbag 사용 승인번호 : $inipay->GetResult('OCB_PayApplNum') - * OK Cashbag 승인일시 : $inipay->GetResult('OCB_ApplDate') (YYYYMMDDHHMMSS) - * OCB 카드번호 : $inipay->GetResult('OCB_Num') - * - * 6. 무통장 입금 결제 결과 데이터 * - * 가상계좌 채번에 사용된 주민번호 : $inipay->GetResult('VACT_RegNum') * - * 가상계좌 번호 : $inipay->GetResult('VACT_Num') * - * 입금할 은행 코드 : $inipay->GetResult('VACT_BankCode') * - * 입금예정일 : $inipay->GetResult('VACT_Date') (YYYYMMDD) * - * 송금자 명 : $inipay->GetResult('VACT_InputName') * - * 예금주 명 : $inipay->GetResult('VACT_Name') * - * * - * 7. 핸드폰, 전화 결제 결과 데이터( "실패 내역 자세히 보기"에서 필요 , 상점에서는 필요없는 정보임) * - * 전화결제 사업자 코드 : $inipay->GetResult('HPP_GWCode') * - * * - * 8. 핸드폰 결제 결과 데이터 * - * 휴대폰 번호 : $inipay->GetResult('HPP_Num') (핸드폰 결제에 사용된 휴대폰번호) * - * * - * 9. 전화 결제 결과 데이터 * -* 전화번호 : $inipay->GetResult('ARSB_Num') (전화결제에 사용된 전화번호) * -* * -* 10. 문화 상품권 결제 결과 데이터 * -* 컬쳐 랜드 ID : $inipay->GetResult('CULT_UserID') * -* * -* 11. K-merce 상품권 결제 결과 데이터 (K-merce ID, 틴캐시 아이디 공통사용) * -* K-merce ID : $inipay->GetResult('CULT_UserID') * -* * -* 12. 모든 결제 수단에 대해 결제 실패시에만 결제 결과 데이터 * -* 에러코드 : $inipay->GetResult('ResultErrorCode') * -* * -* 13.현금영수증 발급 결과코드 (은행계좌이체시에만 리턴) * -* $inipay->GetResult('CSHR_ResultCode') * -* * -* 14.틴캐시 잔액 데이터 * -* $inipay->GetResult('TEEN_Remains') * -* 틴캐시 ID : $inipay->GetResult('CULT_UserID') * -* 15.게임문화 상품권 * -* 사용 카드 갯수 : $inipay->GetResult('GAMG_Cnt') * -* * -****************************************************************************************************************/ - -if( $inipay->GetResult("ResultCode") == "00" ) { +if( strcmp('0000', $resultMap['resultCode']) == 0 ) { //최종결제요청 결과 성공 DB처리 - $tno = $inipay->GetResult('TID'); - $amount = $inipay->GetResult('TotPrice'); - $app_time = $inipay->GetResult('ApplDate').$inipay->GetResult('ApplTime'); - $pay_method = $inipay->GetResult('PayMethod'); - $pay_type = $PAY_METHOD[$pay_method]; - $depositor = iconv_utf8($inipay->GetResult('VACT_InputName')); - $commid = ''; - $mobile_no = $inipay->GetResult('HPP_Num'); - $app_no = $inipay->GetResult('ApplNum'); - $card_name = $CARD_CODE[$inipay->GetResult('CARD_Code')]; - if ($default['de_escrow_use'] == 1) - $escw_yn = 'Y'; + $tno = $resultMap['tid']; + $amount = $resultMap['TotPrice']; + $app_time = $resultMap['applDate'].$resultMap['applTime']; + $pay_method = $resultMap['payMethod']; + $pay_type = $PAY_METHOD[$pay_method]; + $depositor = $resultMap['VACT_InputName']; + $commid = ''; + $mobile_no = $resultMap['HPP_Num']; + $app_no = $resultMap['applNum']; + $card_name = $CARD_CODE[$resultMap['CARD_Code']]; switch($pay_type) { case '계좌이체': - $bank_name = $BANK_CODE[$inipay->GetResult('ACCT_BankCode')]; + $bank_name = $BANK_CODE[$resultMap['ACCT_BankCode']]; + if ($default['de_escrow_use'] == 1) + $escw_yn = 'Y'; break; case '가상계좌': - $bankname = $BANK_CODE[$inipay->GetResult('VACT_BankCode')]; - $account = $inipay->GetResult('VACT_Num').' '.iconv_utf8($inipay->GetResult('VACT_Name')); - $app_no = $inipay->GetResult('VACT_Num'); + $bankname = $BANK_CODE[$resultMap['VACT_BankCode']]; + $account = $resultMap['VACT_Num'].' '.$resultMap['VACT_Name']; + $app_no = $resultMap['VACT_Num']; + if ($default['de_escrow_use'] == 1) + $escw_yn = 'Y'; break; default: break; } } else { - alert(iconv_utf8($inipay->GetResult("ResultMsg")).' 코드 : '.$inipay->GetResult("ResultCode")); + die($resultMap['resultMsg'].' 코드 : '.$resultMap['resultCode']); } ?> \ No newline at end of file diff --git a/shop/inicis/libs/CreateIdModule.php b/shop/inicis/libs/CreateIdModule.php new file mode 100644 index 000000000..7cedf2102 --- /dev/null +++ b/shop/inicis/libs/CreateIdModule.php @@ -0,0 +1,120 @@ +getPGID($payMetod) . $mid . $time . $this->makeRandNum(); + + + return $tid; + } + + function getPGID($payMethod) { + $pgid = ""; + + if ($payMethod == "Card") { + $pgid = "CARD"; + } elseif ($payMethod == "Account") { + $pgid = "ACCT"; + } elseif ($payMethod == "DirectBank") { + $pgid = "DBNK"; + } elseif ($payMethod == "OCBPoint") { + $pgid = "OCBP"; + } elseif ($payMethod == "VCard") { + $pgid = "ISP_"; + } elseif ($payMethod == "HPP") { + $pgid = "HPP_"; + } elseif ($payMethod == "Nemo") { + $pgid = "NEMO"; + } elseif ($payMethod == "ArsBill") { + $pgid = "ARSB"; + } elseif ($payMethod == "PhoneBill") { + $pgid = "PHNB"; + } elseif ($payMethod == "Ars1588Bill") { + $pgid = "1588"; + } elseif ($payMethod == "VBank") { + $pgid = "VBNK"; + } elseif ($payMethod == "Culture") { + $pgid = "CULT"; + } elseif ($payMethod == "CMS") { + $pgid = "CMS_"; + } elseif ($payMethod == "AUTH") { + $pgid = "AUTH"; + } elseif ($payMethod == "INIcard") { + $pgid = "INIC"; + } elseif ($payMethod == "MDX") { + $pgid = "MDX_"; + } elseif ($payMethod == "CASH") { + $pgid = "CASH"; + } elseif (strlen($payMethod) > 4) { + $pgid = strtoupper($payMethod); + $pgid = substr($pgid, 0, 4); + } else { + $pgid = trim($pgid); + } + + return $pgid; + } + + //랜덤 숫자 생성 + function makeRandNum() { + $strNum = ""; + $randNum = rand(0, 300); + + if ($randNum < 10) { + $strNum = $strNum . "00" . $randNum; + } elseif ($randNum < 100) { + $strNum = $strNum . "0" . $randNum; + } else { + $strNum = $randNum; + } + + return $strNum; + } + +} +?> + + + + + + + + + + + + + + + + + + + + diff --git a/shop/inicis/libs/HttpClient.php b/shop/inicis/libs/HttpClient.php new file mode 100644 index 000000000..d40c8e3f2 --- /dev/null +++ b/shop/inicis/libs/HttpClient.php @@ -0,0 +1,149 @@ + $value) { + $key2 = urlencode($key); + $value2 = urlencode($value); + $data .= "&$key2=$value2"; + } + + $data = substr($data, 1); // remove leading "&" + $url_data = parse_url($url); + + + if ($url_data["scheme"] == "https") { + $this->ssl = "ssl://"; + $this->port = 443; + } + + $this->host = $url_data["host"]; + /* + + if (is_null($url_data["port"])) { + $this->port = "80"; + } else { + $this->port = $url_data["port"]; + } + */ + + $this->path = $url_data["path"]; + + if (!$this->sock = @fsockopen($this->ssl . $this->host, $this->port, $errno, $errstr, CONNECT_TIMEOUT)) { + + switch ($errno) { + case -3: + $this->errormsg = 'Socket creation failed (-3)'; + case -4: + $this->errormsg = 'DNS lookup failure (-4)'; + case -5: + $this->errormsg = 'Connection refused or timed out (-5)'; + default: + $this->errormsg = 'Connection failed (' . $errno . ')'; + $this->errormsg .= ' ' . $errstr; + } + return false; + } + + $this->headers = ""; + $this->body = ""; + + /* Write */ + $request = "POST " . $this->path . " HTTP/1.0\r\n"; + $request .= "Connection: close\r\n"; + $request .= "Host: " . $this->host . "\r\n"; + $request .= "Content-type: application/x-www-form-urlencoded\r\n"; + $request .= "Content-length: " . strlen($data) . "\r\n"; + $request .= "Accept: */*\r\n"; + $request .= "\r\n"; + $request .= $data . "\r\n"; + $request .= "\r\n"; + fwrite($this->sock, $request); + + /* Read */ + stream_set_blocking($this->sock, FALSE); + $atStart = true; + $IsHeader = true; + $timeout = false; + $start_time = time(); + while (!feof($this->sock) && !$timeout) { + $line = fgets($this->sock, 4096); + $diff = time() - $start_time; + if ($diff >= READ_TIMEOUT) { + $timeout = true; + } + if ($IsHeader) { + if ($line == "") { + continue; + } + if (substr($line, 0, 2) == "\r\n") { + $IsHeader = false; + continue; + } + $this->headers .= $line; + if ($atStart) { + $atStart = false; + if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) { + $this->errormsg = "Status code line invalid: " . htmlentities($line) . $m[1] . $m[2] . $m[3]; + fclose($this->sock); + return false; + } + $http_version = $m[1]; + $this->status = $m[2]; + $status_string = $m[3]; + continue; + } + } else { + $this->body .= $line; + } + } + + + fclose($this->sock); + + if ($timeout) { + $this->errorcode = READ_TIMEOUT_ERR; + $this->errormsg = "Socket Timeout(" . $diff . "SEC)"; + return false; + } + + return true; + // return false; + } + + function getErrorCode() { + return $this->errorcode; + } + + function getErrorMsg() { + return $this->errormsg; + } + + function getBody() { + return $this->body; + } + +} + +?> diff --git a/shop/inicis/libs/INICls.php b/shop/inicis/libs/INICls.php index 088d41a57..2da4c4ae1 100644 --- a/shop/inicis/libs/INICls.php +++ b/shop/inicis/libs/INICls.php @@ -3,8 +3,8 @@ /** * Copyright (C) 2007 INICIS Inc. * - * ش ̺귯 Ǿ ȵ˴ϴ. - * Ƿ ڵ忡 å ڿ ˷帳ϴ. + * 해당 라이브러리는 절대 수정되어서는 안됩니다. + * 임의로 수정된 코드에 대한 책임은 전적으로 수정자에게 있음을 알려드립니다. * */ require_once ( "INIDFN.php" ); @@ -16,57 +16,57 @@ require_once ( "INIXml.php" ); extract($_POST); extract($_GET); switch ($paymethod) { - case(Card): // ſī + case(Card): // 신용카드 $pgid = "CARD"; break; - case(Account): // ü + case(Account): // 은행 계좌 이체 $pgid = "ACCT"; break; - case(DirectBank): // ǽð ü + case(DirectBank): // 실시간 계좌 이체 $pgid = "DBNK"; break; case(OCBPoint): // OCB $pgid = "OCBP"; break; - case(VCard): // ISP + case(VCard): // ISP 결제 $pgid = "ISP_"; break; - case(HPP): // ޴ + case(HPP): // 휴대폰 결제 $pgid = "HPP_"; break; - case(ArsBill): // 700 ȭ + case(ArsBill): // 700 전화결제 $pgid = "ARSB"; break; - case(PhoneBill): // PhoneBill (޴ ȭ) + case(PhoneBill): // PhoneBill 결제(받는 전화) $pgid = "PHNB"; break; - case(Ars1588Bill):// 1588 ȭ + case(Ars1588Bill):// 1588 전화결제 $pgid = "1588"; break; - case(VBank): // ü + case(VBank): // 가상계좌 이체 $pgid = "VBNK"; break; - case(Culture): // ȭǰ + case(Culture): // 문화상품권 결제 $pgid = "CULT"; break; - case(CMS): // CMS + case(CMS): // CMS 결제 $pgid = "CMS_"; break; - case(AUTH): // ſī ȿ ˻ + case(AUTH): // 신용카드 유효성 검사 $pgid = "AUTH"; break; - case(INIcard): // ƼӴ + case(INIcard): // 네티머니 결제 $pgid = "INIC"; break; - case(MDX): // 󵦽ī + case(MDX): // 몬덱스카드 $pgid = "MDX_"; break; - default: // Ҽ ߰Ǵ Ҽ ⺻ paymethod 4ڸ Ѿ´. + default: // 상기 지불수단 외 추가되는 지불수단의 경우 기본으로 paymethod가 4자리로 넘어온다. $pgid = $paymethod; } if ($quotainterest == "1") { - $interest = "(Һ)"; + $interest = "(무이자할부)"; } /* ----------------------------------------------------- */ @@ -188,7 +188,7 @@ class INIData { var $m_PG1IP; var $m_PG2IP; //---------------------------- - //IFD ûʵ + //IFD 요청필드 //---------------------------- var $m_sCmd; var $m_sCrypto; @@ -205,7 +205,7 @@ class INIData { var $m_sEncrypted; var $m_sSessionKey; //---------------------------- - //IFD ʵ + //IFD 응답헤더 필드 //---------------------------- var $m_FlgCrypto; var $m_FlgSign; @@ -215,7 +215,7 @@ class INIData { var $m_Xml = array(); var $m_REQUEST = array(); var $m_REQUEST2 = array(); //User Defined Entity - var $m_RESULT = array(); //Encrypted ʵ hash table + var $m_RESULT = array(); //Encrypted 필드 hash table var $m_RESULT2 = array(); //PG Added Entity function INIData($request, $request2) { @@ -238,7 +238,7 @@ class INIData { $this->m_sCmd = CMS_REQ_OPEN_SUB; $this->m_sCrypto = FLAG_CRYPTO_3DES; } - // κȯ ߰ + //가상계좌 부분환불 추가 else if (( $this->m_Type == TYPE_REPAY) || ( $this->m_Type == TYPE_VACCTREPAY)) { $this->m_sCmd = CMD_REQ_PRTC; $this->m_sCrypto = FLAG_CRYPTO_3DES; @@ -265,7 +265,7 @@ class INIData { $this->m_sCmd = CMD_REQ_DNY_CNF; $this->m_sCrypto = FLAG_CRYPTO_3DES; } - } else if ($this->m_Type == TYPE_REFUND) { //ȯ(09.08.05) + } else if ($this->m_Type == TYPE_REFUND) { //가상계좌환불(09.08.05) $this->m_sCmd = CMD_REQ_RFD; $this->m_sCrypto = FLAG_CRYPTO_3DES; } else { @@ -286,7 +286,7 @@ class INIData { function CheckField() { //--------------------------------- - // + //공통 //--------------------------------- if (trim($this->m_REQUEST["inipayhome"]) == "") { $this->m_ErrCode = NULL_DIR_ERR; @@ -309,7 +309,7 @@ class INIData { return false; } //--------------------------------- - //type + //type별로 //--------------------------------- if ($this->m_Type == TYPE_SECUREPAY) { /* @@ -378,7 +378,7 @@ class INIData { return false; } } - // κȯҵ κȯ ߰ + //가상계좌 부분환불도 부분환불 로직에 추가 else if (( $this->m_Type == TYPE_REPAY ) || ( $this->m_Type == TYPE_VACCTREPAY )) { if (trim($this->m_REQUEST["oldtid"]) == "") { $this->m_ErrCode = NULL_TID_ERR; @@ -396,21 +396,21 @@ class INIData { return false; } - // κȯ ȣ,ڵ,ָ ʼ + //가상계좌 부분환불 로직에서는 계조번호,은행코드,계좌주명이 필수 if ($this->m_Type == TYPE_VACCTREPAY) { if (trim($this->m_REQUEST["refundacctnum"]) == "") { $this->m_ErrCode = NULL_FIELD_REFUNDACCTNUM; - $this->m_ErrMsg = "ȯҰ¹ȣ"; + $this->m_ErrMsg = "환불계좌번호"; return false; } if (trim($this->m_REQUEST["refundbankcode"]) == "") { $this->m_ErrCode = NULL_FIELD_REFUNDBANKCODE; - $this->m_ErrMsg = "ȯڵ"; + $this->m_ErrMsg = "환불은행코드"; return false; } if (trim($this->m_REQUEST["refundacctname"]) == "") { $this->m_ErrCode = NULL_FIELD_REFUNDACCTNAME; - $this->m_ErrMsg = "ȯҰּ"; + $this->m_ErrMsg = "환불계좌주성명"; return false; } } @@ -433,17 +433,17 @@ class INIData { } if (trim($this->m_REQUEST["racctnum"]) == "") { $this->m_ErrCode = NULL_FIELD_REFUNDACCTNUM; - $this->m_ErrMsg = "ȯҰ¹ȣ"; + $this->m_ErrMsg = "환불계좌번호"; return false; } if (trim($this->m_REQUEST["rbankcode"]) == "") { $this->m_ErrCode = NULL_FIELD_REFUNDBANKCODE; - $this->m_ErrMsg = "ȯڵ"; + $this->m_ErrMsg = "환불은행코드"; return false; } if (trim($this->m_REQUEST["racctname"]) == "") { $this->m_ErrCode = NULL_FIELD_REFUNDACCTNAME; - $this->m_ErrMsg = "ȯҰּ"; + $this->m_ErrMsg = "환불계좌주성명"; return false; } } @@ -460,10 +460,10 @@ class INIData { list($usec, $sec) = explode(" ", microtime()); $datestr = date("YmdHis", $sec) . substr($usec, 2, 3); //YYYYMMDDHHMMSSSSS - $datestr_con = substr($datestr, 0, 14) . substr($datestr, 15, 2); //YYYYMMDDHHMMSSxSS ߰ x (milli second ù° ڸ) + $datestr_con = substr($datestr, 0, 14) . substr($datestr, 15, 2); //YYYYMMDDHHMMSSxSS 중간의 x값은 버림(milli second의 첫번째 자리수) - mt_srand(getmypid() * mt_rand(1, 999)); //mt_rand ϱ srand seed , seed key = pid * mt_rand(1,999) - //pgid + mid + 16ڸ ¥ ð + random_key 4ڸ (seed) + mt_srand(getmypid() * mt_rand(1, 999)); //mt_rand 하기전에 srand 로 seed 적용 , seed key = pid * mt_rand(1,999) + //pgid + mid + 16자리 날짜및 시간 + random_key 4자리 (seed적용) $this->m_sTID = $this->m_REQUEST["pgid"] . $this->m_REQUEST["mid"] . $datestr_con . mt_rand(1000, 9999); if (strlen($this->m_sTID) != TID_LEN) { return false; @@ -524,16 +524,16 @@ class INIData { $CD = $xml->add_node($CI, TX_PRTC_REMAINS, $this->m_REQUEST["confirm_price"]); $CD = $xml->add_node($CI, TX_PRTC_QUOTA, $this->m_REQUEST["cardquota"]); $CD = $xml->add_node($CI, TX_PRTC_INTEREST, $this->m_REQUEST["quotainterest"]); - //Iü κҽ ¹ȣ ּ 2011-10-06 + //I계좌이체 국민은행 부분취소시 계좌번호 계좌주성명을 받음 2011-10-06 $CD = $xml->add_node($CI, TX_PRTC_NOACCT, $this->m_REQUEST["no_acct"]); $CD = $xml->add_node($CI, TX_PRTC_NMACCT, $this->m_REQUEST["nm_acct"], array("urlencode" => "1")); - //, ߰ 2014-07-23 by jung.ks + //과세,비과세 추가 2014-07-23 by jung.ks //$CD = $xml->add_node($CI, TX_PRTC_TAX, $this->m_REQUEST["tax"] ); //$CD = $xml->add_node($CI, TX_PRTC_TAXFREE, $this->m_REQUEST["taxfree"] ); $this->AddUserDefinedEntity(PARTCANCELINFO, "", $xml, $CI); } - // κȯ + //가상계좌 부분환불 else if ($this->m_Type == TYPE_VACCTREPAY) { //PartCancelInfo(ROOT) $CI = $xml->add_node("", PARTCANCELINFO); @@ -682,18 +682,18 @@ class INIData { function MakeBody() { $xml = new XML(); - //ROOT(INIpay) ROOT ROOTINFO 2011-05-23 + //ROOT(INIpay) ROOT를 ROOTINFO로 수정 2011-05-23 $root = $xml->add_node("", ROOTINFO); if ($this->m_Type == TYPE_SECUREPAY || $this->m_Type == TYPE_RECEIPT) { //GoodsInfo - //ٱ ߰(2010.04.13) - //==goodscnt (ٱ ƴҰ) ⺻ 1 + //장바구니 기능 추가(2010.04.13) + //==goodscnt가 없을 경우(장바구니 기능이 아닐경우) 기본 값 1로 설정 $tGoodCnt = ($this->m_REQUEST["goodscnt"] != null && (int) $this->m_REQUEST["goodscnt"] > 0 ) ? $this->m_REQUEST["goodscnt"] : 1; $GI = $xml->add_node($root, GOODSINFO); - //ٱ ߰(2010.04.13) - //==TX_GOOSCNT $tGoodCnt Է + //장바구니 기능 추가(2010.04.13) + //==TX_GOOSCNT는 $tGoodCnt로 부터 입력 //$GP = $xml->add_node($GI, TX_GOOSCNT, "1" ); $GP = $xml->add_node($GI, TX_GOOSCNT, $tGoodCnt); $GP = $xml->add_node($GI, TX_MOID, $this->m_REQUEST["oid"], array("urlencode" => "1")); @@ -702,8 +702,8 @@ class INIData { $GP = $xml->add_node($GI, TX_TAXFREE, $this->m_REQUEST["taxfree"]); $this->AddUserDefinedEntity(GOODSINFO, "", $xml, $GI); - //ٱ ߰(2010.04.13) [START] - //==ٱ XML ߰ + //장바구니 기능 추가(2010.04.13) [START] + //==장바구니 XML 전문 추가 $iGoodCnt = 1; while ($iGoodCnt <= $tGoodCnt) { if ($this->m_REQUEST["smid_" . $iGoodCnt] != "" && strlen($this->m_REQUEST["smid_" . $iGoodCnt]) > 0) { @@ -728,7 +728,7 @@ class INIData { } $iGoodCnt++; } - //ٱ ߰(2010.04.13) [END] + //장바구니 기능 추가(2010.04.13) [END] $this->AddUserDefinedEntity(GOODSINFO, GOODS, $xml, $GS); //BuyerInfo @@ -765,7 +765,7 @@ class INIData { $CD = $xml->add_node($CI, TX_SESSIONKEY, $this->m_sSessionKey); $CD = $xml->add_node($CI, TX_ENCRYPTED, $this->m_sEncrypted); } - // κȯ߰ + //가상계좌 부분환불추가 else if (( $this->m_Type == TYPE_REPAY ) || ( $this->m_Type == TYPE_VACCTREPAY )) { //PartCancelInfo $CI = $xml->add_node($root, PARTCANCELINFO); @@ -804,8 +804,8 @@ class INIData { $CD = $xml->add_node($CI, TX_ENCRYPTED, $this->m_sEncrypted); } else if ($this->m_Type == TYPE_OPENSUB) { //GoodsInfo - //ٱ ߰(2010.04.13) - //==goodscnt (ٱ ƴҰ) ⺻ 1 + //장바구니 기능 추가(2010.04.13) + //==goodscnt가 없을 경우(장바구니 기능이 아닐경우) 기본 값 1로 설정 $tSubCnt = ($this->m_REQUEST["subcnt"] != null && (int) $this->m_REQUEST["subcnt"] > 0 ) ? $this->m_REQUEST["subcnt"] : 1; $OI = $xml->add_node($root, OPENSUBINFO); @@ -829,7 +829,7 @@ class INIData { $iSubCnt++; } - //ٱ ߰(2010.04.13) [END] + //장바구니 기능 추가(2010.04.13) [END] $this->AddUserDefinedEntity(OPENSUBINFO, "", $xml, $OI); } //ReservedInfo @@ -901,8 +901,8 @@ class INIData { $this->m_RESULT[NM_MOID] = $this->GetXMLData(MOID); //PAYMENTINFO - //ŸҼ paymethod ʾ ӽ÷ û Paymethod ü - //PG ִ PayMethod ûPaymethod ! + //기타지불수단이 paymethod를 주지 않아 임시로 요청 Paymethod로 대체 + //PG에서 주는 PayMethod와 요청Paymethod는 같다! $this->m_RESULT[NM_PAYMETHOD] = $this->m_sPayMethod; $ResultCode = $this->GetXMLData("ResultCode"); @@ -928,8 +928,8 @@ class INIData { $this->m_Xml = array_merge($this->m_Xml, $xml->xml_node); if ($this->m_Type == TYPE_SECUREPAY || $this->m_Type == TYPE_RECEIPT) { - //γ¥(ApplDate), νð(ApplTime), ιȣ(ApplNum) !!(OCB, ݿ ) - //ISP, CARD CARD assign. / ISP , CARD ˰ !!!-_- + //승인날짜(ApplDate), 승인시간(ApplTime), 승인번호(ApplNum)는 공통!!(OCB, 현금영수증 제외) + //ISP, CARD는 CARD로 assign. 고객/상점은 ISP가 뭔지, CARD가 뭔지 알게 뭐야!!!-_- if ($this->m_sPayMethod == NM_TX_CARD) { $this->m_RESULT[APPLDATE] = $this->GetXMLData(CARD_APPLDATE); $this->m_RESULT[APPLTIME] = $this->GetXMLData(CARD_APPLTIME); @@ -994,7 +994,7 @@ class INIData { $this->m_RESULT[APPLTIME] = $this->GetXMLData(GAMG_APPLTIME); $this->m_RESULT[APPLNUM] = $this->GetXMLData(GAMG_APPLNUM); $this->m_RESULT[GAMG_CNT] = $this->GetXMLData(GAMG_CNT); - //ӹȭǰ Multi + //게임문화상품권은 Multi결제 가능 MakePathGAMG($this->m_RESULT[GAMG_CNT]); for ($i = 1; $i <= $this->m_RESULT[GAMG_CNT]; $i++) { $this->m_RESULT[constant("GAMG_NUM$i")] = $this->GetXMLData(constant("GAMG_NUM$i")); @@ -1061,7 +1061,7 @@ class INIData { $this->m_PG2IP = $pg2ip; } - // Xpath Ȱ´. Ѵ ߴ!! + // Xpath로 안가져온다. 한달을 헛지랄 했다!! // added by ddaemiri, 2007.09.03 function GetXMLData($node) { $content = $this->m_Xml[$node . "[1]"]["text"]; @@ -1074,7 +1074,7 @@ class INIData { /* ----------------------------------------------------- */ /* Crypto Class */ -/* PHP4.2 & OpenSSL ʿ) */ +/* PHP4.2 & OpenSSL 필요) */ /* ----------------------------------------------------- */ class INICrypto { diff --git a/shop/inicis/libs/INIDFN.php b/shop/inicis/libs/INIDFN.php index b26026231..ca9402146 100644 --- a/shop/inicis/libs/INIDFN.php +++ b/shop/inicis/libs/INIDFN.php @@ -3,8 +3,8 @@ /** * Copyright (C) 2007 INICIS Inc. * - * ش ̺귯 Ǿ ȵ˴ϴ. - * Ƿ ڵ忡 å ڿ ˷帳ϴ. + * 해당 라이브러리는 절대 수정되어서는 안됩니다. + * 임의로 수정된 코드에 대한 책임은 전적으로 수정자에게 있음을 알려드립니다. * * @version 5.0 * @author ddaemiri @@ -15,37 +15,37 @@ * * @buildno 5001 * @date 2008.01.15 - * @note üũ ߰, DNS Lookup Timeout ߰, DNS Lookup н socket closeϴ κ ߰ + * @note 자체에스크로 추가, DNS Lookup Timeout 추가, DNS Lookup 실패시 socket close안하는 부분 추가 * @date 2008.01.16 - * @note Encrypt,Decrypt , pkcs5 padding ߰ + * @note Encrypt,Decrypt 모듈 개선, pkcs5 padding 추가 * @date 2008.01.24 * @note non block connect immediate return check code/str * @date 2008.02.11 - * @note key load read߻ fclose ߰ + * @note key load 후 read에러발생시 fclose 추가 * @date 2008.03.03 - * @note (passing by reference) + * @note 참조에 의한 전달(passing by reference) 수정 * @date 2008.03.11 - * @note ũ Cmd ߰ + * @note 에스크로 망취소 Cmd 추가 * @date 2008.03.12 - * @note IP + * @note 기존 연결된 IP로 망취소 수정 * @buildno 5002 - * @note ҽ Sign߰( ->5001 ҽ ,׷ ó ) + * @note 망취소시 Sign추가(기존에 안했음->5001은 망취소시 서버측에서 서명오류가 남,그래도 망취소처리는 됨) * @date 2008.03.12 * @buildno 5016 - * @note pg1ip, pg2ip ߰/ ŷ drpg õ + * @note pg1ip, pg2ip 추가/취소 원거래없음시 drpg로 재시도 * @date 2008.04.02 * @buildno 5017 - * @note 1)chkfake Ķ α (ߺ) - * 2)call-time pass-by-reference => pass-by-value + * @note 1)chkfake시 파라미터 로깅 삭제(중복) + * 2)call-time pass-by-reference => pass-by-value로 수정 * @date 2009.01.12 * @buildno 5019 * @note delete UIP * @date 2009.01.21 * @note add mkey/mergelog ( for Makeshop ) * @date 2009.02.24 - * @note 1)define MKEY deprecated 2009.02.19 ( Makeshop ʱ ѹ. 񽺵ǰ ִ ) - * 2)Makeshop PG Updrade γ 2009.02.19 (interface mkey ޾ óϰ ) - * 3)Makeshop PG Updrade γ 2009.02.24 (interface mergelog ޾ óϰ ) + * @note 1)define MKEY deprecated 2009.02.19 ( Makeshop 초기 한번나감. 서비스되고 있는지는 모름) + * 2)Makeshop PG Updrade용으로 새로나감 2009.02.19 (interface에서 mkey값을 받아 처리하게 변경) + * 3)Makeshop PG Updrade용으로 새로나감 2009.02.24 (interface에서 mergelog값을 받아 처리하게 변경) * @date 2009.05.07 * @note add BUILDDATE in TXVersion * @date 2009.08.05 @@ -57,12 +57,12 @@ * @date 2010.07.14 * @note add Tax, TaxFree info(TX_TAX, TX_TAXFREE) * @date 2010.09.09 - * @note ҿû PG (->IP, INILib.php) + * @note 취소요청시 PG 설정 변경(도메인->IP, INILib.php) * @note BUILDDATE update(100414 -> 100909) - * @note 2011.05.23 5030 XML ELEMENT ROOT ROOTINFO + * @note 2011.05.23 5030 XML ELEMENT 중 ROOT 를 ROOTINFO로 수정 * @buildno 5032 - * @note 2012.07.09 ŷȸ ߰ (TYPE_INQUIRY) - * @note 2012.07.09 PHP ini error display setting ߰ + * @note 2012.07.09 거래조회 추가 (TYPE_INQUIRY) + * @note 2012.07.09 PHP ini 파일 error display setting 추가 * @buildno 5036 * @note 2014.12.09 add gather parameter tid, type */ @@ -111,8 +111,8 @@ define("IMJK", "UkVHSVNUX05PX1JDNEtFWQ=="); define("IMJV", "UkVHSVNUX05PX1JDNElW"); //define for mkey -//deprecated 2009.02.19 ( Makeshop ʱ ѹ. 񽺵ǰ ִ ) -//Makeshop PG Updrade γ 2009.02.19 (interface mkey ޾ óϰ ) +//deprecated 2009.02.19 ( Makeshop 초기 한번나감. 서비스되고 있는지는 모름) +//Makeshop PG Updrade용으로 새로나감 2009.02.19 (interface에서 mkey값을 받아 처리하게 변경) //define("MKEY", 1); //non block connect immediate return check code/str define("ERRSTR_INPROGRESS", "Operation now in progress"); @@ -152,24 +152,24 @@ define("CMD_REQ_PRTC", "0620"); define("CMD_RES_PRTC", "0630"); define("CMD_REQ_ACK", "0800"); define("CMD_RES_ACK", "0810"); -//üũ +//자체에스크로 //added 2008.01.08 -define("CMD_REQ_DLV", "3020"); //۵ -define("CMD_REQ_CNF", "3030"); //Ȯ -define("CMD_REQ_DNY", "3040"); //Ű -define("CMD_REQ_DNY_CNF", "3080"); //Ȯ -define("CMD_REQ_DLV_NETC", "3520"); //۵ϸ -define("CMD_REQ_CNF_NETC", "3530"); //Ȯθ -define("CMD_REQ_DNY_NETC", "3540"); //Ű -//ȯ(09.08.05) +define("CMD_REQ_DLV", "3020"); //배송등록 +define("CMD_REQ_CNF", "3030"); //구매확인 +define("CMD_REQ_DNY", "3040"); //구매거절 +define("CMD_REQ_DNY_CNF", "3080"); //거절확인 +define("CMD_REQ_DLV_NETC", "3520"); //배송등록망상취소 +define("CMD_REQ_CNF_NETC", "3530"); //구매확인망상취소 +define("CMD_REQ_DNY_NETC", "3540"); //구매거절망상취소 +//가상계좌환불(09.08.05) define("CMD_REQ_RFD", "0421"); define("CMD_RES_RFD", "0431"); -//ŷȸ(12.04.20) +//거래조회(12.04.20) define("CMS_REQ_INQR", "0900"); define("CMS_RES_INQR", "0910"); -//(14.03.06) +//서브몰하위가맹점등록(14.03.06) define("CMS_REQ_OPEN_SUB", "1040"); define("CMS_RES_OPEN_SUB", "1041"); @@ -187,14 +187,14 @@ define("FLAG_SIGN_SHA1", "SHA1"); define("FLAG_SIGN_MD5", "MD5"); //------------------------------------------------------ -//TYPE(񽺺) +//TYPE(서비스별) //------------------------------------------------------ define("TYPE_SECUREPAY", "securepay"); define("TYPE_CANCEL", "cancel"); define("TYPE_FORMPAY", "formpay"); define("TYPE_RECEIPT", "receipt"); define("TYPE_REPAY", "repay"); -define("TYPE_ESCROW", "escrow"); //üũ! +define("TYPE_ESCROW", "escrow"); //자체에스크로! define("TYPE_CONFIRM", "confirm"); define("TYPE_OCBQUERY", "ocbquery"); define("TYPE_OCBSAVE", "ocbsave"); @@ -207,26 +207,26 @@ define("TYPE_VBANK", "VBank"); define("TYPE_REQREALBILL", "reqrealbill"); define("TYPE_FORMAUTH", "formauth"); define("TYPE_CHKFAKE", "chkfake"); -//ȯ(09.08.05) +//가상계좌환불(09.08.05) define("TYPE_REFUND", "refund"); -//ºκȯ(12.06.05) +//가상계좌부분환불(12.06.05) define("TYPE_VACCTREPAY", "vacctrepay"); -//ŷȸ(12.04.20) +//거래조회(12.04.20) define("TYPE_INQUIRY", "inquiry"); -//(14.03.06) +//서브몰하위가맹점등록(14.03.06) define("TYPE_OPENSUB", "opensub"); //------------------------------------------------------ -//EscrowType(üũ Ÿ) +//EscrowType(자체에스크로 타입) //added 2008.01.08 //------------------------------------------------------ define("TYPE_ESCROW_DLV", "dlv"); -define("TYPE_ESCROW_CNF", "confirm"); //Ȯ/(÷) -define("TYPE_ESCROW_DNY", "deny"); // ó,ǹ̾ +define("TYPE_ESCROW_CNF", "confirm"); //구매확인/거절(플러그인) +define("TYPE_ESCROW_DNY", "deny"); //위에서 처리됨,의미없음 define("TYPE_ESCROW_DNY_CNF", "dcnf"); //------------------------------------------------------ -//PayMethod(񽺺, TX) +//PayMethod(서비스별, TX) //------------------------------------------------------ define("NM_TX_ISP", "VCard"); define("NM_TX_CARD", "Card"); @@ -244,7 +244,7 @@ define("NM_TX_TEEN", "TEEN"); define("NM_TX_ESCR", "Escrow"); //------------------------------------------------------ -//PayMethod(񽺺, PG) +//PayMethod(서비스별, PG) //------------------------------------------------------ define("NM_ISP", "ISP"); define("NM_CARD", "CARD"); @@ -274,7 +274,7 @@ define("URLENCODE", "urlencode"); define("URLDECODE", "urldecode"); //------------------------------------------------------ -//û +//요청전문 //------------------------------------------------------ define("TX_GOOSCNT", "GoodsCnt"); define("TX_MOID", "MOID"); @@ -317,8 +317,8 @@ define("TX_RN", "TXRN"); //CancelInfo define("TX_CANCELTID", "CancelTID"); define("TX_CANCELMSG", "CancelMsg"); -define("TX_CANCELREASON", "CancelReason"); //2012-10-19 һڵ ߰ -//ȯ(09.08.05) +define("TX_CANCELREASON", "CancelReason"); //2012-10-19 취소사유코드 추가 +//가상계좌환불(09.08.05) define("TX_REFUNDACCTNUM", "RefundAcctNum"); define("TX_REFUNDBANKCODE", "RefundBankCode"); define("TX_REFUNDACCTNAME", "RefundAcctName"); @@ -333,15 +333,15 @@ define("TX_PRTC_TAXFREE", "TaxFree"); define("TX_PRTC_CURRENCY", "Currency"); -// Iü κҽ ¹ȣ/ּ߰ 2011-10-06 +//국민은행 I계좌이체 부분취소시 계좌번호/계좌주성명추가 2011-10-06 define("TX_PRTC_NOACCT", "PRTC_NoAcctFNBC"); define("TX_PRTC_NMACCT", "PRTC_NmAcctFNBC"); -// κȯ ߰ +//가상계좌 부분환불 관련 추가 define("TX_PRTC_REFUNDFLGREMIT", "PRTC_RefundFlgRemit"); define("TX_PRTC_REFUNDBANKCODE", "PRTC_RefundBankCode"); //CaptureInfo define("TX_CAPTURETID", "CaptureTID"); -//ݿ +//현금영수증 define("TX_CSHR_APPLPRICE", "CSHR_ApplPrice"); define("TX_CSHR_SUPPLYPRICE", "CSHR_SupplyPrice"); define("TX_CSHR_TAX", "CSHR_Tax"); @@ -357,9 +357,9 @@ define("TX_CSHR_SUBREGNUM1", "CSHR_SubRegNum1"); define("TX_CSHR_SUBMID1", "CSHR_SubMID1"); define("TX_CSHR_SUBAPPLPRICE1", "CSHR_SubApplPrice1"); define("TX_CSHR_SUBSERVICEPRICE1", "CSHR_SubServicePrice1"); -//ŷȸ(12.04.20) +//거래조회(12.04.20) define("TX_INQR_TID", "INQR_TID"); -//(14.03.06) +//서브몰하위가맹점등록(14.03.06) define("TX_OPENREG_TID", "OrgTID"); define("TX_OPENREG_MID", "MID"); define("TX_OPENREG_SUBCNT", "SubCnt"); @@ -374,7 +374,7 @@ define("TX_OPENREG_SUBPRICE", "SubPrice"); //------------------------------------------------------ // -// +//응답전문 // //------------------------------------------------------ //HEAD @@ -433,9 +433,9 @@ define("CANCELINFO", "CancelInfo"); define("PARTCANCELINFO", "PartCancelInfo"); //Capture define("CAPTUREINFO", "CaptureInfo"); -//ŷȸ(12.04.20) +//거래조회(12.04.20) define("INQUIRYINFO", "InquiryInfo"); -//(14.03.06) +//서브몰하위가맹점등록(14.03.06) define("OPENSUBINFO", "OpenSubInfo"); //Escrow //added 2008.01.09 @@ -541,7 +541,7 @@ define("TEEN_APPLNUM", "TEEN_ApplNum"); //---------------------------------- //ERROR CODE //---------------------------------- -//!!TX ߰ !!! +//!!신TX에 추가된 에러!!! define("NULL_DIR_ERR", "TX9001"); define("NULL_TYPE_ERR", "TX9002"); define("NULL_NOINTEREST_ERR", "TX9003"); @@ -551,7 +551,7 @@ define("MERCHANT_DB_ERR", "TX9006"); define("DNS_LOOKUP_TIMEOUT_ERR", "TX9007"); define("PGPUB_UPDATE_ERR", "TX9612"); -//Ϻȣȭ +//암복호화 에러 define("B64DECODE_UPDATE_ERR", "TX9101"); define("B64DECODE_FINAL_ERR", "TX9102"); define("B64DECODE_LENGTH_ERR", "TX9103"); @@ -576,7 +576,7 @@ define("SIGN_CHECK_ERR", "TX9121"); define("ENC_NULL_F_ERR", "TX9122"); define("ENC_INIT_RAND_ERR", "TX9123"); define("ENC_PUTENV_ERR", "TX9124"); -//ʵüũ +//필드체크 define("NULL_KEYPW_ERR", "TX9201"); define("NULL_MID_ERR", "TX9202"); define("NULL_PGID_ERR", "TX9203"); @@ -607,37 +607,37 @@ define("NULL_BUYERNAME_ERR", "TX9227"); define("NULL_BUYERTEL_ERR", "TX9228"); define("NULL_BUYEREMAIL_ERR", "TX9229"); define("NULL_SESSIONKEY_ERR", "TX9230"); -//pgŰ ε +//pg공개키 로드 오류 define("NULL_PGCERT_FP_ERR", "TX9231"); define("NULL_X509_ERR", "TX9232"); define("NULL_PGCERT_ERR", "TX9233"); define("RESULT_MSG_FORMAT_ERR", "TX9234"); -// ü -define("NULL_PERNO_ERR", "TX9235"); // ֹιȣ -define("NULL_OID_ERR", "TX9236"); // ֹȣ -define("NULL_VCDBANK_ERR", "TX9237"); // ڵ -define("NULL_DTINPUT_ERR", "TX9238"); // Ա -define("NULL_NMINPUT_ERR", "TX9239"); // ۱ -//ǽð -define("NULL_BILLKEY_ERR", "TX9240"); // Ű -define("NULL_CARDPASS_ERR", "TX9241"); // ī -define("NULL_BILLTYPE_ERR", "TX9242"); // Ÿ -// CMS ü -define("NULL_PRICE_ORG_ERR", "TX9250"); // CMS ѱݾ -define("NULL_CMSDAY_ERR", "TX9251"); // CMS -define("NULL_CMSDATEFROM_ERR", "TX9252"); // CMS ݽۿ -define("NULL_CMSDATETO_ERR", "TX9253"); // CMS -// κ -define("NULL_CONFIRM_PRICE_ERR", "TX9260"); // ûݾ -// ݿ -define("NULL_CR_PRICE_ERR", "TX9270"); // ݰ ݾ -define("NULL_SUP_PRICE_ERR", "TX9271"); // ް -define("NULL_TAX_ERR", "TX9272"); // ΰ -define("NULL_SRVC_PRICE_ERR", "TX9273"); // -define("NULL_REG_NUM_ERR", "TX9274"); // ֹιȣ(ڹȣ) -define("NULL_USEOPT_ERR", "TX9275"); // ݿ 뵵 +// 가상 계좌 이체 예약 +define("NULL_PERNO_ERR", "TX9235"); // 주민번호 빠짐 +define("NULL_OID_ERR", "TX9236"); // 주문번호 빠짐 +define("NULL_VCDBANK_ERR", "TX9237"); // 은행코드 빠짐 +define("NULL_DTINPUT_ERR", "TX9238"); // 입금 예정일 빠짐 +define("NULL_NMINPUT_ERR", "TX9239"); // 송금자 성명 빠짐 +//실시간 빌링 +define("NULL_BILLKEY_ERR", "TX9240"); // 빌키 빠짐 +define("NULL_CARDPASS_ERR", "TX9241"); // 카드 비번 빠짐 +define("NULL_BILLTYPE_ERR", "TX9242"); // 빌타입 누락 +// CMS 계좌이체 +define("NULL_PRICE_ORG_ERR", "TX9250"); // CMS 출금총금액 빠짐 +define("NULL_CMSDAY_ERR", "TX9251"); // CMS 출금일자 빠짐 +define("NULL_CMSDATEFROM_ERR", "TX9252"); // CMS 출금시작월 빠짐 +define("NULL_CMSDATETO_ERR", "TX9253"); // CMS 출금종료월 빠짐 +// 부분취소 +define("NULL_CONFIRM_PRICE_ERR", "TX9260"); // 재승인 요청금액 누락 에러 +// 현금영수증 발행 +define("NULL_CR_PRICE_ERR", "TX9270"); // 현금결제 금액 빠짐 +define("NULL_SUP_PRICE_ERR", "TX9271"); // 공급가액 빠짐 +define("NULL_TAX_ERR", "TX9272"); // 부가세 빠짐 +define("NULL_SRVC_PRICE_ERR", "TX9273"); // 봉사료 빠짐 +define("NULL_REG_NUM_ERR", "TX9274"); // 주민번호(사업자번호) +define("NULL_USEOPT_ERR", "TX9275"); // 현금영수증 용도 구분자 빠짐 define("PRIVKEY_FILE_OPEN_ERR", "TX9301"); define("INVALID_KEYPASS_ERR", "TX9302"); diff --git a/shop/inicis/libs/INILib.php b/shop/inicis/libs/INILib.php index e8968ad28..0db332ab6 100644 --- a/shop/inicis/libs/INILib.php +++ b/shop/inicis/libs/INILib.php @@ -1,794 +1,731 @@ UnsetField(); - } - - function UnsetField() - { - unset($this->m_REQUEST); - unset($this->m_RESULT); - } - - /*--------------------------------------------------*/ - /* */ - /* / û Set or Add */ - /* */ - /*--------------------------------------------------*/ - function SetField( $key, $val ) //Default Entity - { - $this->m_REQUEST[$key] = $val; - } - function SetXPath( $xpath, $val ) //User Defined Entity - { - $this->m_REQUEST2[$xpath] = $val; - } - - /*--------------------------------------------------*/ - /* */ - /* / fetch */ - /* */ - /*--------------------------------------------------*/ - function GetResult( $name ) //Default Entity - { - $result = $this->m_RESULT[$name]; - if( $result == "" ) - $result = $this->m_Data->GetXMLData( $name ); - if( $result == "" ) - $result = $this->m_Data->m_RESULT[$name]; - return $result; - } - - /*--------------------------------------------------*/ - /* */ - /* / ó */ - /* */ - /*--------------------------------------------------*/ - function startAction() - { - - /*--------------------------------------------------*/ - /* Overhead Operation */ - /*--------------------------------------------------*/ - $this->m_Data = new INIData( $this->m_REQUEST, $this->m_REQUEST2 ); - - /*--------------------------------------------------*/ - /* Log Start */ - /*--------------------------------------------------*/ - $this->m_Log = new INILog( $this->m_REQUEST ); - if(!$this->m_Log->StartLog()) - { - $this->MakeTXErrMsg( LOG_OPEN_ERR, "α ϴ.[".$this->m_REQUEST["inipayhome"]."]"); - return; - } - - /*--------------------------------------------------*/ - /* Logging Request Parameter */ - /*--------------------------------------------------*/ - $this->m_Log->WriteLog( DEBUG, $this->m_REQUEST ); - - /*--------------------------------------------------*/ - /* Set Type */ - /*--------------------------------------------------*/ - $this->m_type = $this->m_REQUEST["type"]; - - /*--------------------------------------------------*/ - /* Check Field */ - /*--------------------------------------------------*/ - if( !$this->m_Data->CheckField() ) - { - $err_msg = "ʼ׸(".$this->m_Data->m_ErrMsg.") Ǿϴ."; - $this->MakeTXErrMsg( $this->m_Data->m_ErrCode, $err_msg ); - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - return; - } - $this->m_Log->WriteLog( INFO, "Check Field OK" ); - - /*--------------------------------------------------*/ - // Ű. ⼭ !! - /*--------------------------------------------------*/ - if( $this->m_type == TYPE_CHKFAKE ) - { - return $this->MakeChkFake(); - } - - /*--------------------------------------------------*/ - //Generate TID - /*--------------------------------------------------*/ - if( $this->m_type == TYPE_SECUREPAY || $this->m_type == TYPE_FORMPAY || $this->m_type == TYPE_OCBSAVE || - $this->m_type == TYPE_AUTHBILL || $this->m_type == TYPE_FORMAUTH || $this->m_type == TYPE_REQREALBILL || - $this->m_type == TYPE_REPAY || $this->m_type == TYPE_VACCTREPAY || $this->m_type == TYPE_RECEIPT || $this->m_type == TYPE_AUTH - ) - { - if(!$this->m_Data->MakeTID()) - { - $err_msg = "TID ߽ϴ.::".$this->m_Data->m_sTID; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( MAKE_TID_ERR, $err_msg ); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - return; - } - $this->m_Log->WriteLog( INFO, 'Make TID OK '.$this->m_Data->m_sTID ); - } - - $this->m_Crypto = new INICrypto( $this->m_REQUEST ); - - /*--------------------------------------------------*/ - //PIŰ ε - /*--------------------------------------------------*/ - $this->m_Data->ParsePIEncrypted(); - $this->m_Log->WriteLog( INFO, "PI PUB KEY LOAD OK [".$this->m_Data->m_PIPGPubSN."]" ); - - /*--------------------------------------------------*/ - //PGŰ ε - /*--------------------------------------------------*/ - if( ($rtv = $this->m_Crypto->LoadPGPubKey( $pg_cert_SN )) != OK) - { - $err_msg = "PGŰ ε"; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - return; - } - $this->m_Data->m_TXPGPubSN = $pg_cert_SN; - $this->m_Log->WriteLog( INFO, "PG PUB KEY LOAD OK [".$this->m_Data->m_TXPGPubSN."]" ); - - /*--------------------------------------------------*/ - //Ű ε - /*--------------------------------------------------*/ - if( ($rtv = $this->m_Crypto->LoadMPrivKey()) != OK ) - { - $err_msg = "Ű ε"; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - $this->m_Crypto->FreePubKey(); - return; - } - $this->m_Log->WriteLog( INFO, "MERCHANT PRIV KEY LOAD OK" ); - - /*--------------------------------------------------*/ - // Ű ε(SN ˱!!) - /*--------------------------------------------------*/ - if( ($rtv = $this->m_Crypto->LoadMPubKey( $m_cert_SN )) != OK) - { - $err_msg = "Ű ε"; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - return; - } - $this->m_Data->m_MPubSN = $m_cert_SN; - $this->m_Log->WriteLog( INFO, "MERCHANT PUB KEY LOAD OK [".$this->m_Data->m_MPubSN."]" ); - - /*--------------------------------------------------*/ - // ȣȭ( formpay, cancel, repay, recept, inquiry, opensub) - /*--------------------------------------------------*/ - if( $this->m_type == TYPE_CANCEL || $this->m_type == TYPE_REPAY || $this->m_type == TYPE_VACCTREPAY || - $this->m_type == TYPE_FORMPAY || $this->m_type == TYPE_RECEIPT || - $this->m_type == TYPE_CAPTURE || $this->m_type == TYPE_INQUIRY || $this->m_type == TYPE_OPENSUB || - ($this->m_type == TYPE_ESCROW && $this->m_Data->m_EscrowType == TYPE_ESCROW_DLV ) || - ($this->m_type == TYPE_ESCROW && $this->m_Data->m_EscrowType == TYPE_ESCROW_DNY_CNF ) || - $this->m_type == TYPE_REFUND - ) - { - if( ($rtv = $this->m_Data->MakeEncrypt( $this->m_Crypto )) != OK ) - { - $err_msg = "ȣȭ "; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - return; - } - //$this->m_Log->WriteLog( DEBUG, "MAKE ENCRYPT OK" ); - $this->m_Log->WriteLog( DEBUG, "MAKE ENCRYPT OK[".$this->m_Data->m_EncBody."]" ); - } - - /*--------------------------------------------------*/ - //(Body) - /*--------------------------------------------------*/ - $this->m_Data->MakeBody(); - $this->m_Log->WriteLog( INFO, "MAKE BODY OK" ); - //$this->m_Log->WriteLog( INFO, "MAKE BODY OK[".$this->m_Data->m_sBody."]" ); - - /*--------------------------------------------------*/ - //(sign) - /*--------------------------------------------------*/ - if( ($rtv = $this->m_Crypto->Sign( $this->m_Data->m_sBody, $sign )) != OK ) - { - $err_msg = "ν"; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - $this->m_Crypto->FreeAllKey(); - return; - } - $this->m_Data->m_sTail = $sign; - $this->m_Log->WriteLog( INFO, "SIGN OK" ); - //$this->m_Log->WriteLog( INFO, "SIGN OK[".$sign."]" ); - - /*--------------------------------------------------*/ - //(Head) - /*--------------------------------------------------*/ - $this->m_Data->MakeHead(); - $this->m_Log->WriteLog( INFO, "MAKE HEAD OK" ); - //$this->m_Log->WriteLog( INFO, "MAKE HEAD OK[".$head."]" ); - - $this->m_Log->WriteLog( INFO, "MSG_TO_PG:[".$this->m_Data->m_sMsg."]" ); - - /*--------------------------------------------------*/ - //ϻ - /*--------------------------------------------------*/ - //DRPG , added 07.11.15 - //ҽ-PG (->IP), edited 10.09.09 - if( $this->m_type == TYPE_SECUREPAY ) - { - if( $this->m_REQUEST["pgn"] == "" ) - $host = $this->m_Data->m_PG1; - else - $host = $this->m_REQUEST["pgn"]; - } - else - { - if( $this->m_REQUEST["pgn"] == "" ) - { - if( $this->m_cancelRC == 1 ) - $host = DRPG_IP; - else - $host = PG_IP; - } - else - $host = $this->m_REQUEST["pgn"]; - } - - $this->m_Socket = new INISocket($host); - if( ($rtv = $this->m_Socket->DNSLookup()) != OK ) - { - $err_msg = "[".$host."]DNS LOOKUP (MAIN)".$this->m_Socket->getErr(); - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - if( $this->m_type == TYPE_SECUREPAY ) //PIϰ, PI ִ pg1ip! - { - $this->m_Socket->ip = $this->m_Data->m_PG1IP; - } - else - { - if( $this->m_cancelRC == 1 ) - $this->m_Socket->ip = DRPG_IP; - else - $this->m_Socket->ip = PG_IP; - } - } - $this->m_Log->WriteLog( INFO, "DNS LOOKUP OK(".$this->m_Socket->host.":".$this->m_Socket->ip.":".$this->m_Socket->port.") laptime:".$this->m_Socket->dns_laptime ); - if( ($rtv = $this->m_Socket->open()) != OK ) - { - $this->m_Socket->close(); - - //PG2 ȯ - $err_msg = "[".$host."Ͽ(MAIN)::PG2 ȯ"; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - if( $this->m_type == TYPE_SECUREPAY ) - { - $host = $this->m_Data->m_PG2; - } - else - { - $host = DRPG_HOST; - } - $this->m_Socket = new INISocket($host); - if( ($rtv = $this->m_Socket->DNSLookup()) != OK ) - { - $err_msg = "[".$host."]DNS LOOKUP (MAIN)".$this->m_Socket->getErr(); - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - if( $this->m_type == TYPE_SECUREPAY ) //PIϰ, PI ִ pg2ip! - { - $this->m_Socket->ip = $this->m_Data->m_PG2IP; - } - else - { - $this->m_Socket->ip = DRPG_IP; - } - } - $this->m_Log->WriteLog( INFO, "DNS LOOKUP OK(".$this->m_Socket->host.":".$this->m_Socket->ip.":".$this->m_Socket->port.") laptime:".$this->m_Socket->dns_laptime ); - if( ($rtv = $this->m_Socket->open()) != OK ) - { - $err_msg = "[".$host."Ͽ(MAIN)::".$this->m_Socket->getErr(); - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - $this->m_Socket->close(); - $this->m_Crypto->FreeAllKey(); - return; - } - } - $this->m_connIP = $this->m_Socket->ip; - $this->m_Log->WriteLog( INFO, "SOCKET CONNECT OK" ); - - /*--------------------------------------------------*/ - //۽ - /*--------------------------------------------------*/ - if( ($rtv = $this->m_Socket->send($this->m_Data->m_sMsg)) != OK ) - { - $err_msg = "ϼ۽ſ(MAIN)::".$this->m_Socket->getErr(); - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - $this->m_Crypto->FreeAllKey(); - $this->m_Socket->close(); - return; - } - $this->m_Log->WriteLog( INFO, "SEND OK" ); - - /*--------------------------------------------------*/ - // - /*--------------------------------------------------*/ - if( ($rtv = $this->m_Socket->recv($head, $body, $tail)) != OK ) - { - $err_msg = "ϼſ(MAIN)::".$this->m_Socket->getErr(); - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Socket->close(); - $this->NetCancel(); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - $this->m_Crypto->FreeAllKey(); - return; - } - $this->m_Log->WriteLog( INFO, "RECV OK" ); - $this->m_Log->WriteLog( INFO, "MSG_FROM_PG:[".$head.$body.$tail."]" ); - $this->m_Data->m_Body = $body; - - /*--------------------------------------------------*/ - //Ȯ - /*--------------------------------------------------*/ - if( ($rtv = $this->m_Crypto->Verify( $body, $tail )) != OK ) - { - $err_msg = "VERIFY FAIL"; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Socket->close(); - $this->NetCancel(); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - $this->m_Crypto->FreeAllKey(); - return; - } - $this->m_Log->WriteLog( INFO, "VERIFY OK" ); - - /*--------------------------------------------------*/ - //Head Ľ - /*--------------------------------------------------*/ - if( ($rtv = $this->m_Data->ParseHead( $head )) != OK ) - { - $err_msg = "(HEAD) Ľ "; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Socket->close(); - $this->NetCancel(); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - $this->m_Crypto->FreeAllKey(); - return; - } - $this->m_Log->WriteLog( INFO, "PARSE HEAD OK" ); - - /*--------------------------------------------------*/ - //Body Ľ - /*--------------------------------------------------*/ - if( ($rtv = $this->m_Data->ParseBody( $body, $encrypted, $sessionkey )) != OK ) - { - $err_msg = "(Body) Ľ "; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Socket->close(); - $this->NetCancel(); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - $this->m_Crypto->FreeAllKey(); - return; - } - $this->m_Log->WriteLog( INFO, "PARSE BODY OK" ); - - /*--------------------------------------------------*/ - //ȣȭ - /*--------------------------------------------------*/ - if( $this->m_type == TYPE_SECUREPAY || $this->m_type == TYPE_FORMPAY || $this->m_type == TYPE_OCBSAVE || - $this->m_type == TYPE_CANCEL || $this->m_type == TYPE_AUTHBILL || $this->m_type == TYPE_FORMAUTH || - $this->m_type == TYPE_REQREALBILL || $this->m_type == TYPE_REPAY || $this->m_type == TYPE_VACCTREPAY || $this->m_type == TYPE_RECEIPT || - $this->m_type == TYPE_AUTH || $this->m_type == TYPE_CAPTURE || $this->m_type == TYPE_ESCROW || - $this->m_type == TYPE_REFUND || $this->m_type == TYPE_INQUIRY || $this->m_type == TYPE_OPENSUB - ) - { - if( ($rtv = $this->m_Crypto->Decrypt( $sessionkey, $encrypted, $decrypted )) != OK ) - { - $err_msg = "ȣȭ [".$this->GetResult(NM_RESULTMSG)."]"; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Socket->close(); - $this->NetCancel(); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - $this->m_Crypto->FreeAllKey(); - return; - } - $this->m_Log->WriteLog( INFO, "DECRYPT OK" ); - $this->m_Log->WriteLog( DEBUG, "DECRYPT MSG:[".$decrypted."]" ); - - //Parse Decrypt - $this->m_Data->ParseDecrypt( $decrypted ); - $this->m_Log->WriteLog( INFO, "DECRYPT PARSE OK" ); - } - - /*--------------------------------------------------*/ - //Assign Interface Variables - /*--------------------------------------------------*/ - $this->m_RESULT = $this->m_Data->m_RESULT; - - /*--------------------------------------------------*/ - //ACK - /*--------------------------------------------------*/ - //if( $this->GetResult(NM_RESULTCODE) == "00" && - if( (strcmp($this->GetResult(NM_RESULTCODE),"00") == 0) && - ( $this->m_type == TYPE_SECUREPAY || $this->m_type == TYPE_OCBSAVE || - $this->m_type == TYPE_FORMPAY || $this->m_type == TYPE_RECEIPT - ) - ) - { - $this->m_Log->WriteLog( INFO, "WAIT ACK INVOKING" ); - if( ($rtv = $this->Ack()) != OK ) - { - //ERROR - $err_msg = "ACK "; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Socket->close(); - $this->NetCancel(); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - $this->m_Crypto->FreeAllKey(); - return; - } - $this->m_Log->WriteLog( INFO, "SUCCESS ACK INVOKING" ); - } - /*--------------------------------------------------*/ - //PG Ű ٲ Ű UPDATE - /*--------------------------------------------------*/ - $pgpubkey = $this->m_Data->GetXMLData( NM_PGPUBKEY ); - if( $pgpubkey != "" ) - { - if( ($rtv = $this->m_Crypto->UpdatePGPubKey( $pgpubkey )) != OK ) - { - $err_msg = "PGŰ Ʈ "; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->m_Data->GTHR( $rtv, $err_msg ); - } - else - $this->m_Log->WriteLog( INFO, "PGPubKey UPDATED!!" ); - } - - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - $this->m_Crypto->FreeAllKey(); - $this->m_Socket->close(); - - /*--------------------------------------------------*/ - //ҽ-ŷÿ DRPG õ - //2008.04.01 - /*--------------------------------------------------*/ - if( $this->GetResult(NM_RESULTCODE) == "01" && ($this->m_type == TYPE_CANCEL || $this->m_type == TYPE_INQUIRY) && $this->m_cancelRC == 0 ) - { - if( intval($this->GetResult(NM_ERRORCODE)) > 400000 && substr( $this->GetResult(NM_ERRORCODE), 3, 3 ) == "623" ) - { - $this->m_cancelRC = 1; - $this->startAction(); - } - } - - return; - - } // End of StartAction - - /*--------------------------------------------------*/ - /* */ - /* Ÿ */ - /* */ - /*--------------------------------------------------*/ - function MakeChkFake() - { - $this->m_Crypto = new INICrypto( $this->m_REQUEST ); - - /*--------------------------------------------------*/ - //Ű ε - /*--------------------------------------------------*/ - if( ($rtv = $this->m_Crypto->LoadMPrivKey()) != OK ) - { - $err_msg = "Ű ε"; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - $this->m_Crypto->FreePubKey(); - return; - } - $this->m_Log->WriteLog( INFO, "MERCHANT PRIV KEY LOAD OK" ); - - /*--------------------------------------------------*/ - // Ű ε(SN ˱!!) - /*--------------------------------------------------*/ - if( ($rtv = $this->m_Crypto->LoadMPubKey( $m_cert_SN )) != OK) - { - $err_msg = "Ű ε"; - $this->m_Log->WriteLog( ERROR, $err_msg ); - $this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - return; - } - $this->m_Log->WriteLog( INFO, "MERCHANT PUB KEY LOAD OK [".$this->m_Data->m_MPubSN."]" ); - - foreach ($this->m_REQUEST as $key => $val) - { - if( $key == "inipayhome" || $key == "type" || $key == "debug" || - $key == "admin" || $key == "checkopt" || $key == "enctype" ) - continue; - if( $key == "mid" ) - $temp1 .= $key."=".$val."&"; //msg - else - $temp2 .= $key."=".$val."&"; //hashmsg - } - //Make RN - $this->m_RESULT["rn"] = $this->m_Data->MakeRN(); - $temp1 .= "rn=".$this->m_RESULT["rn"]."&"; - - $checkMsg = $temp1; - $checkHashMsg = $temp2; - - $retHashStr = Base64Encode(sha1( $checkHashMsg, TRUE )); - $checkMsg .= "data=".$retHashStr; - - $HashMid = Base64Encode(sha1( $this->m_REQUEST["mid"], TRUE )); - - $this->m_Crypto->RSAMPrivEncrypt( $checkMsg, $RSATemp ); - $this->m_RESULT["encfield"] = "enc=".$RSATemp."&src=".Base64Encode($checkHashMsg); - $this->m_RESULT["certid"] = $HashMid.$m_cert_SN; - - $this->m_Log->WriteLog( INFO, "CHKFAKE KEY MAKE OK:".$this->m_RESULT["rn"] ); - - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - $this->m_Crypto->FreeAllKey(); - $this->m_RESULT[NM_RESULTCODE] = "00"; - return; - } - - /*--------------------------------------------------*/ - /* */ - /* ó Ȯ ޼ */ - /* */ - /*--------------------------------------------------*/ - function Ack() - { - //ACK Data - $this->m_Data->m_sBody = ""; - $this->m_Data->m_sTail = ""; - $this->m_Data->m_sCmd = CMD_REQ_ACK; - - //(Head) - $this->m_Data->MakeHead(); - $this->m_Log->WriteLog( DEBUG, "MAKE HEAD OK" ); - //$this->m_Log->WriteLog( DEBUG, "MSG_TO_PG:[".$this->m_Data->m_sMsg."]" ); - - //Send - if( ($rtv = $this->m_Socket->send($this->m_Data->m_sMsg)) != OK ) - { - $err_msg = "ACK ۿ"; - $this->m_Log->WriteLog( ERROR, $err_msg ); - return ACK_CHECKSUM_ERR; - } - //$this->m_Log->WriteLog( DEBUG, "SEND OK" ); - - if( ($rtv = $this->m_Socket->recv($head, $body, $tail)) != OK ) - { - $err_msg = "ACK ſ(ACK)"; - $this->m_Log->WriteLog( ERROR, $err_msg ); - return ACK_CHECKSUM_ERR; - } - //$this->m_Log->WriteLog( DEBUG, "RECV OK" ); - //$this->m_Log->WriteLog( INFO, "MSG_FROM_PG:[".$recv."]" ); - return OK; - } - - /*--------------------------------------------------*/ - /* */ - /* ޼ */ - /* */ - /*--------------------------------------------------*/ - function NetCancel() - { - $this->m_Log->WriteLog( INFO, "WAIT NETCANCEL INVOKING" ); - - if ( $this->m_type == TYPE_CANCEL || $this->m_type == TYPE_REPAY || $this->m_type == TYPE_VACCTREPAY || $this->m_type == TYPE_RECEIPT || - $this->m_type == TYPE_CONFIRM || $this->m_type == TYPE_OCBQUERY || $this->m_type == TYPE_ESCROW || - $this->m_type == TYPE_CAPTURE || $this->m_type == TYPE_AUTH || $this->m_type == TYPE_AUTHBILL || - ($this->m_type == TYPE_ESCROW && $this->m_Data->m_EscrowType == TYPE_ESCROW_DNY_CNF ) || - $this->m_type == TYPE_NETCANCEL - ) - { - $this->m_Log->WriteLog( INFO, "DON'T NEED NETCANCEL" ); - return true; - } - - //NetCancel Data - $this->m_Data->m_REQUEST["cancelmsg"] = ""; - $body = ""; - $sign = ""; - - $this->m_Data->m_Type = TYPE_CANCEL; // .Ʋ..~ - - //added escrow netcancel, 08.03.11 - if( $this->m_type == TYPE_ESCROW && $this->m_Data->m_EscrowType == TYPE_ESCROW_DLV ) - $this->m_Data->m_sCmd = CMD_REQ_DLV_NETC; - else if($this->m_type == TYPE_ESCROW && $this->m_Data->m_EscrowType == TYPE_ESCROW_CNF ) - $this->m_Data->m_sCmd = CMD_REQ_CNF_NETC; - else if($this->m_type == TYPE_ESCROW && $this->m_Data->m_EscrowType == TYPE_ESCROW_DNY ) - $this->m_Data->m_sCmd = CMD_REQ_DNY_NETC; - else - $this->m_Data->m_sCmd = CMD_REQ_NETC; - - $this->m_Data->m_sCrypto = FLAG_CRYPTO_3DES; - - //ȣȭ - if( ($rtv = $this->m_Data->MakeEncrypt( $this->m_Crypto )) != OK ) - { - $err_msg = "ȣȭ "; - $this->m_Log->WriteLog( ERROR, $err_msg ); - //$this->MakeTXErrMsg( $rtv, $err_msg ); - return; - } - $this->m_Log->WriteLog( DEBUG, "MAKE ENCRYPT OK[".$this->m_Data->m_EncBody."]" ); - - //(Body) - $this->m_Data->MakeBody(); - $this->m_Log->WriteLog( INFO, "MAKE BODY OK" ); - - //(sign) - if( ($rtv = $this->m_Crypto->Sign( $this->m_Data->m_sBody, $sign )) != OK ) - { - $err_msg = "ν"; - $this->m_Log->WriteLog( ERROR, $err_msg ); - //$this->MakeTXErrMsg( $rtv, $err_msg ); - return false; - } - $this->m_Data->m_sTail = $sign; - $this->m_Log->WriteLog( INFO, "SIGN OK" ); - - //(Head) - $this->m_Data->MakeHead(); - $this->m_Log->WriteLog( INFO, "MAKE HEAD OK" ); - - $this->m_Log->WriteLog( DEBUG, "MSG_TO_PG:[".$this->m_Data->m_sMsg."]" ); - - //ϻ - $this->m_Socket = new INISocket(""); - $this->m_Socket->ip = $this->m_connIP; // IP , 08.03.12 - if( ($rtv = $this->m_Socket->open()) != OK ) - { - $err_msg = "[".$this->m_Socket->ip."]Ͽ(NETC)::".$this->m_Socket->getErr(); - $this->m_Log->WriteLog( ERROR, $err_msg ); - //$this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Log->CloseLog( $this->GetResult(NM_RESULTMSG) ); - $this->m_Socket->close(); - $this->m_Crypto->FreeAllKey(); - return; - } - $this->m_Log->WriteLog( INFO, "SOCKET CONNECT OK::".$this->m_Socket->ip ); - - //۽ - if( ($rtv = $this->m_Socket->send($this->m_Data->m_sMsg)) != OK ) - { - $err_msg = "ϼ۽ſ(NETC)".$this->m_Socket->getErr(); - $this->m_Log->WriteLog( ERROR, $err_msg ); - //$this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Socket->close(); - return false; - } - $this->m_Log->WriteLog( INFO, "SEND OK" ); - - // - if( ($rtv = $this->m_Socket->recv($head, $body, $tail)) != OK ) - { - $err_msg = "ϼſ(NETC)"; - $this->m_Log->WriteLog( ERROR, $err_msg ); - //$this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Socket->close(); - return false; - } - $this->m_Log->WriteLog( INFO, "RECV OK" ); - $this->m_Log->WriteLog( DEBUG, "MSG_FROM_PG:[".$head.$body.$tail."]" ); - - //Ȯ - if( ($rtv = $this->m_Crypto->Verify( $body, $tail )) != OK ) - { - $err_msg = "VERIFY FAIL"; - $this->m_Log->WriteLog( ERROR, $err_msg ); - //$this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Socket->close(); - return false; - } - $this->m_Log->WriteLog( INFO, "VERIFY OK" ); - - // Ľ ʴ´!!!! - //׳ ⼭ ǰϴ.-_-;; - //Head Ľ - if( ($rtv = $this->m_Data->ParseHead( $head )) != OK ) - { - $err_msg = "(HEAD) Ľ "; - $this->m_Log->WriteLog( ERROR, $err_msg ); - //$this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Socket->close(); - return; - } - //Body Ľ - if( ($rtv = $this->m_Data->ParseBody( $body, $encrypted, $sessionkey )) != OK ) - { - $err_msg = "(Body) Ľ "; - $this->m_Log->WriteLog( ERROR, $err_msg ); - //$this->MakeTXErrMsg( $rtv, $err_msg ); - $this->m_Socket->close(); - return; - } - - //if( $this->GetResult(NM_RESULTCODE) == "00" ) - if(strcmp($this->GetResult(NM_RESULTCODE),"00") == 0) - $this->m_Log->WriteLog( INFO, "SUCCESS NETCANCEL" ); - else - $this->m_Log->WriteLog( ERROR, "ERROR NETCANCEL[".$this->GetResult(NM_RESULTMSG)."]" ); - return true; - } - - function MakeIMStr($s, $t) - { - $this->m_Crypto = new INICrypto( $this->m_REQUEST ); - if( $t == "H" ) - return $this->m_Crypto->MakeIMStr($s, base64_decode(IMHK)); - else if( $t == "J" ) - return $this->m_Crypto->MakeIMStr($s, base64_decode(IMJK)); - } - - /*--------------------------------------------------*/ - /* */ - /* ޼ Make */ - /* */ - /*--------------------------------------------------*/ - function MakeTXErrMsg($err_code, $err_msg) - { - $this->m_RESULT[NM_RESULTCODE] = "01"; - $this->m_RESULT[NM_RESULTERRORCODE] = $err_code; - $this->m_RESULT[NM_RESULTMSG] = "[".$err_code."|".$err_msg."]"; - $this->m_Data->GTHR( $err_code, $err_msg ); - return; - } +require_once('INICls.php'); +require_once('INISoc.php'); + +class INIpay50 { + + var $m_type; // 거래 유형 + var $m_resulterrcode; // 결과메세지 에러코드 + var $m_connIP; + var $m_cancelRC = 0; + var $m_Data; + var $m_Log; + var $m_Socket; + var $m_Crypto; + var $m_REQUEST = array(); + var $m_REQUEST2 = array(); + var $m_RESULT = array(); + + function INIpay() { + $this->UnsetField(); + } + + function UnsetField() { + unset($this->m_REQUEST); + unset($this->m_RESULT); + } + + /* -------------------------------------------------- */ + /* */ + /* 결제/취소 요청값 Set or Add */ + /* */ + /* -------------------------------------------------- */ + + function SetField($key, $val) { //Default Entity + $this->m_REQUEST[$key] = $val; + } + + function SetXPath($xpath, $val) { //User Defined Entity + $this->m_REQUEST2[$xpath] = $val; + } + + /* -------------------------------------------------- */ + /* */ + /* 결제/취소 결과값 fetch */ + /* */ + /* -------------------------------------------------- */ + + function GetResult($name) { //Default Entity + $result = $this->m_RESULT[$name]; + if ($result == "") + $result = $this->m_Data->GetXMLData($name); + if ($result == "") + $result = $this->m_Data->m_RESULT[$name]; + return $result; + } + + /* -------------------------------------------------- */ + /* */ + /* 결제/취소 처리 메인 */ + /* */ + /* -------------------------------------------------- */ + + function startAction() { + + /* -------------------------------------------------- */ + /* Overhead Operation */ + /* -------------------------------------------------- */ + $this->m_Data = new INIData($this->m_REQUEST, $this->m_REQUEST2); + + /* -------------------------------------------------- */ + /* Log Start */ + /* -------------------------------------------------- */ + $this->m_Log = new INILog($this->m_REQUEST); + if (!$this->m_Log->StartLog()) { + $this->MakeTXErrMsg(LOG_OPEN_ERR, "로그파일을 열수가 없습니다.[" . $this->m_REQUEST["inipayhome"] . "]"); + return; + } + + /* -------------------------------------------------- */ + /* Logging Request Parameter */ + /* -------------------------------------------------- */ + $this->m_Log->WriteLog(DEBUG, $this->m_REQUEST); + + /* -------------------------------------------------- */ + /* Set Type */ + /* -------------------------------------------------- */ + $this->m_type = $this->m_REQUEST["type"]; + + /* -------------------------------------------------- */ + /* Check Field */ + /* -------------------------------------------------- */ + if (!$this->m_Data->CheckField()) { + $err_msg = "필수항목(" . $this->m_Data->m_ErrMsg . ")이 누락되었습니다."; + $this->MakeTXErrMsg($this->m_Data->m_ErrCode, $err_msg); + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + return; + } + $this->m_Log->WriteLog(INFO, "Check Field OK"); + + /* -------------------------------------------------- */ + //웹페이지위변조용 키생성. 여기서 끝!! + /* -------------------------------------------------- */ + if ($this->m_type == TYPE_CHKFAKE) { + return $this->MakeChkFake(); + } + + /* -------------------------------------------------- */ + //Generate TID + /* -------------------------------------------------- */ + if ($this->m_type == TYPE_SECUREPAY || $this->m_type == TYPE_FORMPAY || $this->m_type == TYPE_OCBSAVE || + $this->m_type == TYPE_AUTHBILL || $this->m_type == TYPE_FORMAUTH || $this->m_type == TYPE_REQREALBILL || + $this->m_type == TYPE_REPAY || $this->m_type == TYPE_VACCTREPAY || $this->m_type == TYPE_RECEIPT || $this->m_type == TYPE_AUTH + ) { + if (!$this->m_Data->MakeTID()) { + $err_msg = "TID생성에 실패했습니다.::" . $this->m_Data->m_sTID; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg(MAKE_TID_ERR, $err_msg); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + return; + } + $this->m_Log->WriteLog(INFO, 'Make TID OK ' . $this->m_Data->m_sTID); + } + + $this->m_Crypto = new INICrypto($this->m_REQUEST); + + /* -------------------------------------------------- */ + //PI공개키 로드 + /* -------------------------------------------------- */ + $this->m_Data->ParsePIEncrypted(); + $this->m_Log->WriteLog(INFO, "PI PUB KEY LOAD OK [" . $this->m_Data->m_PIPGPubSN . "]"); + + /* -------------------------------------------------- */ + //PG공개키 로드 + /* -------------------------------------------------- */ + if (($rtv = $this->m_Crypto->LoadPGPubKey($pg_cert_SN)) != OK) { + $err_msg = "PG공개키 로드오류"; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + return; + } + $this->m_Data->m_TXPGPubSN = $pg_cert_SN; + $this->m_Log->WriteLog(INFO, "PG PUB KEY LOAD OK [" . $this->m_Data->m_TXPGPubSN . "]"); + + /* -------------------------------------------------- */ + //상점개인키 로드 + /* -------------------------------------------------- */ + if (($rtv = $this->m_Crypto->LoadMPrivKey()) != OK) { + $err_msg = "상점개인키 로드오류"; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + $this->m_Crypto->FreePubKey(); + return; + } + $this->m_Log->WriteLog(INFO, "MERCHANT PRIV KEY LOAD OK"); + + /* -------------------------------------------------- */ + //상점 공개키 로드(SN 를 알기위해!!) + /* -------------------------------------------------- */ + if (($rtv = $this->m_Crypto->LoadMPubKey($m_cert_SN)) != OK) { + $err_msg = "상점공개키 로드오류"; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + return; + } + $this->m_Data->m_MPubSN = $m_cert_SN; + $this->m_Log->WriteLog(INFO, "MERCHANT PUB KEY LOAD OK [" . $this->m_Data->m_MPubSN . "]"); + + /* -------------------------------------------------- */ + //폼페이 암호화( formpay, cancel, repay, recept, inquiry, opensub) + /* -------------------------------------------------- */ + if ($this->m_type == TYPE_CANCEL || $this->m_type == TYPE_REPAY || $this->m_type == TYPE_VACCTREPAY || + $this->m_type == TYPE_FORMPAY || $this->m_type == TYPE_RECEIPT || + $this->m_type == TYPE_CAPTURE || $this->m_type == TYPE_INQUIRY || $this->m_type == TYPE_OPENSUB || + ($this->m_type == TYPE_ESCROW && $this->m_Data->m_EscrowType == TYPE_ESCROW_DLV ) || + ($this->m_type == TYPE_ESCROW && $this->m_Data->m_EscrowType == TYPE_ESCROW_DNY_CNF ) || + $this->m_type == TYPE_REFUND + ) { + if (($rtv = $this->m_Data->MakeEncrypt($this->m_Crypto)) != OK) { + $err_msg = "암호화 오류"; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + return; + } + //$this->m_Log->WriteLog( DEBUG, "MAKE ENCRYPT OK" ); + $this->m_Log->WriteLog(DEBUG, "MAKE ENCRYPT OK[" . $this->m_Data->m_EncBody . "]"); + } + + /* -------------------------------------------------- */ + //전문생성(Body) + /* -------------------------------------------------- */ + $this->m_Data->MakeBody(); + $this->m_Log->WriteLog(INFO, "MAKE BODY OK"); + //$this->m_Log->WriteLog( INFO, "MAKE BODY OK[".$this->m_Data->m_sBody."]" ); + + /* -------------------------------------------------- */ + //서명(sign) + /* -------------------------------------------------- */ + if (($rtv = $this->m_Crypto->Sign($this->m_Data->m_sBody, $sign)) != OK) { + $err_msg = "싸인실패"; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + $this->m_Crypto->FreeAllKey(); + return; + } + $this->m_Data->m_sTail = $sign; + $this->m_Log->WriteLog(INFO, "SIGN OK"); + //$this->m_Log->WriteLog( INFO, "SIGN OK[".$sign."]" ); + + /* -------------------------------------------------- */ + //전문생성(Head) + /* -------------------------------------------------- */ + $this->m_Data->MakeHead(); + $this->m_Log->WriteLog(INFO, "MAKE HEAD OK"); + //$this->m_Log->WriteLog( INFO, "MAKE HEAD OK[".$head."]" ); + + $this->m_Log->WriteLog(INFO, "MSG_TO_PG:[" . $this->m_Data->m_sMsg . "]"); + + /* -------------------------------------------------- */ + //소켓생성 + /* -------------------------------------------------- */ + //DRPG 셋팅, added 07.11.15 + //취소시-PG설정 변경(도메인->IP), edited 10.09.09 + if ($this->m_type == TYPE_SECUREPAY) { + if ($this->m_REQUEST["pgn"] == "") + $host = $this->m_Data->m_PG1; + else + $host = $this->m_REQUEST["pgn"]; + } + else { + if ($this->m_REQUEST["pgn"] == "") { + if ($this->m_cancelRC == 1) + $host = DRPG_IP; + else + $host = PG_IP; + } else + $host = $this->m_REQUEST["pgn"]; + } + + $this->m_Socket = new INISocket($host); + if (($rtv = $this->m_Socket->DNSLookup()) != OK) { + $err_msg = "[" . $host . "]DNS LOOKUP 실패(MAIN)" . $this->m_Socket->getErr(); + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + if ($this->m_type == TYPE_SECUREPAY) { //PI일경우, PI가 내려주는 pg1ip로! + $this->m_Socket->ip = $this->m_Data->m_PG1IP; + } else { + if ($this->m_cancelRC == 1) + $this->m_Socket->ip = DRPG_IP; + else + $this->m_Socket->ip = PG_IP; + } + } + $this->m_Log->WriteLog(INFO, "DNS LOOKUP OK(" . $this->m_Socket->host . ":" . $this->m_Socket->ip . ":" . $this->m_Socket->port . ") laptime:" . $this->m_Socket->dns_laptime); + if (($rtv = $this->m_Socket->open()) != OK) { + $this->m_Socket->close(); + + //PG2로 전환 + $err_msg = "[" . $host . "소켓연결오류(MAIN)::PG2로 전환"; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + if ($this->m_type == TYPE_SECUREPAY) { + $host = $this->m_Data->m_PG2; + } else { + $host = DRPG_HOST; + } + $this->m_Socket = new INISocket($host); + if (($rtv = $this->m_Socket->DNSLookup()) != OK) { + $err_msg = "[" . $host . "]DNS LOOKUP 실패(MAIN)" . $this->m_Socket->getErr(); + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + if ($this->m_type == TYPE_SECUREPAY) { //PI일경우, PI가 내려주는 pg2ip로! + $this->m_Socket->ip = $this->m_Data->m_PG2IP; + } else { + $this->m_Socket->ip = DRPG_IP; + } + } + $this->m_Log->WriteLog(INFO, "DNS LOOKUP OK(" . $this->m_Socket->host . ":" . $this->m_Socket->ip . ":" . $this->m_Socket->port . ") laptime:" . $this->m_Socket->dns_laptime); + if (($rtv = $this->m_Socket->open()) != OK) { + $err_msg = "[" . $host . "소켓연결오류(MAIN)::" . $this->m_Socket->getErr(); + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + $this->m_Socket->close(); + $this->m_Crypto->FreeAllKey(); + return; + } + } + $this->m_connIP = $this->m_Socket->ip; + $this->m_Log->WriteLog(INFO, "SOCKET CONNECT OK"); + + /* -------------------------------------------------- */ + //전문송신 + /* -------------------------------------------------- */ + if (($rtv = $this->m_Socket->send($this->m_Data->m_sMsg)) != OK) { + $err_msg = "소켓송신오류(MAIN)::" . $this->m_Socket->getErr(); + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + $this->m_Crypto->FreeAllKey(); + $this->m_Socket->close(); + return; + } + $this->m_Log->WriteLog(INFO, "SEND OK"); + + /* -------------------------------------------------- */ + //전문수신 + /* -------------------------------------------------- */ + if (($rtv = $this->m_Socket->recv($head, $body, $tail)) != OK) { + $err_msg = "소켓수신오류(MAIN)::" . $this->m_Socket->getErr(); + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Socket->close(); + $this->NetCancel(); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + $this->m_Crypto->FreeAllKey(); + return; + } + $this->m_Log->WriteLog(INFO, "RECV OK"); + $this->m_Log->WriteLog(INFO, "MSG_FROM_PG:[" . $head . $body . $tail . "]"); + $this->m_Data->m_Body = $body; + + /* -------------------------------------------------- */ + //서명확인 + /* -------------------------------------------------- */ + if (($rtv = $this->m_Crypto->Verify($body, $tail)) != OK) { + $err_msg = "VERIFY FAIL"; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Socket->close(); + $this->NetCancel(); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + $this->m_Crypto->FreeAllKey(); + return; + } + $this->m_Log->WriteLog(INFO, "VERIFY OK"); + + /* -------------------------------------------------- */ + //Head 파싱 + /* -------------------------------------------------- */ + if (($rtv = $this->m_Data->ParseHead($head)) != OK) { + $err_msg = "수신전문(HEAD) 파싱 오류"; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Socket->close(); + $this->NetCancel(); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + $this->m_Crypto->FreeAllKey(); + return; + } + $this->m_Log->WriteLog(INFO, "PARSE HEAD OK"); + + /* -------------------------------------------------- */ + //Body 파싱 + /* -------------------------------------------------- */ + if (($rtv = $this->m_Data->ParseBody($body, $encrypted, $sessionkey)) != OK) { + $err_msg = "수신전문(Body) 파싱 오류"; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Socket->close(); + $this->NetCancel(); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + $this->m_Crypto->FreeAllKey(); + return; + } + $this->m_Log->WriteLog(INFO, "PARSE BODY OK"); + + /* -------------------------------------------------- */ + //복호화 + /* -------------------------------------------------- */ + if ($this->m_type == TYPE_SECUREPAY || $this->m_type == TYPE_FORMPAY || $this->m_type == TYPE_OCBSAVE || + $this->m_type == TYPE_CANCEL || $this->m_type == TYPE_AUTHBILL || $this->m_type == TYPE_FORMAUTH || + $this->m_type == TYPE_REQREALBILL || $this->m_type == TYPE_REPAY || $this->m_type == TYPE_VACCTREPAY || $this->m_type == TYPE_RECEIPT || + $this->m_type == TYPE_AUTH || $this->m_type == TYPE_CAPTURE || $this->m_type == TYPE_ESCROW || + $this->m_type == TYPE_REFUND || $this->m_type == TYPE_INQUIRY || $this->m_type == TYPE_OPENSUB + ) { + if (($rtv = $this->m_Crypto->Decrypt($sessionkey, $encrypted, $decrypted)) != OK) { + $err_msg = "복호화 실패[" . $this->GetResult(NM_RESULTMSG) . "]"; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Socket->close(); + $this->NetCancel(); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + $this->m_Crypto->FreeAllKey(); + return; + } + $this->m_Log->WriteLog(INFO, "DECRYPT OK"); + $this->m_Log->WriteLog(DEBUG, "DECRYPT MSG:[" . $decrypted . "]"); + + //Parse Decrypt + $this->m_Data->ParseDecrypt($decrypted); + $this->m_Log->WriteLog(INFO, "DECRYPT PARSE OK"); + } + + /* -------------------------------------------------- */ + //Assign Interface Variables + /* -------------------------------------------------- */ + $this->m_RESULT = $this->m_Data->m_RESULT; + + /* -------------------------------------------------- */ + //ACK + /* -------------------------------------------------- */ + //if( $this->GetResult(NM_RESULTCODE) == "00" && + if ((strcmp($this->GetResult(NM_RESULTCODE), "00") == 0) && + ( $this->m_type == TYPE_SECUREPAY || $this->m_type == TYPE_OCBSAVE || + $this->m_type == TYPE_FORMPAY || $this->m_type == TYPE_RECEIPT + ) + ) { + $this->m_Log->WriteLog(INFO, "WAIT ACK INVOKING"); + if (($rtv = $this->Ack()) != OK) { + //ERROR + $err_msg = "ACK 실패"; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Socket->close(); + $this->NetCancel(); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + $this->m_Crypto->FreeAllKey(); + return; + } + $this->m_Log->WriteLog(INFO, "SUCCESS ACK INVOKING"); + } + /* -------------------------------------------------- */ + //PG 공개키가 바뀌었으면 공개키 UPDATE + /* -------------------------------------------------- */ + $pgpubkey = $this->m_Data->GetXMLData(NM_PGPUBKEY); + if ($pgpubkey != "") { + if (($rtv = $this->m_Crypto->UpdatePGPubKey($pgpubkey)) != OK) { + $err_msg = "PG공개키 업데이트 실패"; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->m_Data->GTHR($rtv, $err_msg); + } else + $this->m_Log->WriteLog(INFO, "PGPubKey UPDATED!!"); + } + + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + $this->m_Crypto->FreeAllKey(); + $this->m_Socket->close(); + + /* -------------------------------------------------- */ + //취소실패-원거래없음시에 DRPG로 재시도 + //2008.04.01 + /* -------------------------------------------------- */ + if ($this->GetResult(NM_RESULTCODE) == "01" && ($this->m_type == TYPE_CANCEL || $this->m_type == TYPE_INQUIRY) && $this->m_cancelRC == 0) { + if (intval($this->GetResult(NM_ERRORCODE)) > 400000 && substr($this->GetResult(NM_ERRORCODE), 3, 3) == "623") { + $this->m_cancelRC = 1; + $this->startAction(); + } + } + + return; + } + +// End of StartAction + + /* -------------------------------------------------- */ + /* */ + /* 웹페이지 위변조 방지용 데이타 생성 */ + /* */ + /* -------------------------------------------------- */ + + function MakeChkFake() { + $this->m_Crypto = new INICrypto($this->m_REQUEST); + + /* -------------------------------------------------- */ + //상점개인키 로드 + /* -------------------------------------------------- */ + if (($rtv = $this->m_Crypto->LoadMPrivKey()) != OK) { + $err_msg = "상점개인키 로드오류"; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + $this->m_Crypto->FreePubKey(); + return; + } + $this->m_Log->WriteLog(INFO, "MERCHANT PRIV KEY LOAD OK"); + + /* -------------------------------------------------- */ + //상점 공개키 로드(SN 를 알기위해!!) + /* -------------------------------------------------- */ + if (($rtv = $this->m_Crypto->LoadMPubKey($m_cert_SN)) != OK) { + $err_msg = "상점공개키 로드오류"; + $this->m_Log->WriteLog(ERROR, $err_msg); + $this->MakeTXErrMsg($rtv, $err_msg); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + return; + } + $this->m_Log->WriteLog(INFO, "MERCHANT PUB KEY LOAD OK [" . $this->m_Data->m_MPubSN . "]"); + + foreach ($this->m_REQUEST as $key => $val) { + if ($key == "inipayhome" || $key == "type" || $key == "debug" || + $key == "admin" || $key == "checkopt" || $key == "enctype") + continue; + if ($key == "mid") + $temp1 .= $key . "=" . $val . "&"; //msg + else + $temp2 .= $key . "=" . $val . "&"; //hashmsg + } + //Make RN + $this->m_RESULT["rn"] = $this->m_Data->MakeRN(); + $temp1 .= "rn=" . $this->m_RESULT["rn"] . "&"; + + $checkMsg = $temp1; + $checkHashMsg = $temp2; + + $retHashStr = Base64Encode(sha1($checkHashMsg, TRUE)); + $checkMsg .= "data=" . $retHashStr; + + $HashMid = Base64Encode(sha1($this->m_REQUEST["mid"], TRUE)); + + $this->m_Crypto->RSAMPrivEncrypt($checkMsg, $RSATemp); + $this->m_RESULT["encfield"] = "enc=" . $RSATemp . "&src=" . Base64Encode($checkHashMsg); + $this->m_RESULT["certid"] = $HashMid . $m_cert_SN; + + $this->m_Log->WriteLog(INFO, "CHKFAKE KEY MAKE OK:" . $this->m_RESULT["rn"]); + + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + $this->m_Crypto->FreeAllKey(); + $this->m_RESULT[NM_RESULTCODE] = "00"; + return; + } + + /* -------------------------------------------------- */ + /* */ + /* 결제처리 확인 메세지 전송 */ + /* */ + /* -------------------------------------------------- */ + + function Ack() { + //ACK용 Data + $this->m_Data->m_sBody = ""; + $this->m_Data->m_sTail = ""; + $this->m_Data->m_sCmd = CMD_REQ_ACK; + + //전문생성(Head) + $this->m_Data->MakeHead(); + $this->m_Log->WriteLog(DEBUG, "MAKE HEAD OK"); + //$this->m_Log->WriteLog( DEBUG, "MSG_TO_PG:[".$this->m_Data->m_sMsg."]" ); + //Send + if (($rtv = $this->m_Socket->send($this->m_Data->m_sMsg)) != OK) { + $err_msg = "ACK 전송오류"; + $this->m_Log->WriteLog(ERROR, $err_msg); + return ACK_CHECKSUM_ERR; + } + //$this->m_Log->WriteLog( DEBUG, "SEND OK" ); + + if (($rtv = $this->m_Socket->recv($head, $body, $tail)) != OK) { + $err_msg = "ACK 수신오류(ACK)"; + $this->m_Log->WriteLog(ERROR, $err_msg); + return ACK_CHECKSUM_ERR; + } + //$this->m_Log->WriteLog( DEBUG, "RECV OK" ); + //$this->m_Log->WriteLog( INFO, "MSG_FROM_PG:[".$recv."]" ); + return OK; + } + + /* -------------------------------------------------- */ + /* */ + /* 망취소 메세지 전송 */ + /* */ + /* -------------------------------------------------- */ + + function NetCancel() { + $this->m_Log->WriteLog(INFO, "WAIT NETCANCEL INVOKING"); + + if ($this->m_type == TYPE_CANCEL || $this->m_type == TYPE_REPAY || $this->m_type == TYPE_VACCTREPAY || $this->m_type == TYPE_RECEIPT || + $this->m_type == TYPE_CONFIRM || $this->m_type == TYPE_OCBQUERY || $this->m_type == TYPE_ESCROW || + $this->m_type == TYPE_CAPTURE || $this->m_type == TYPE_AUTH || $this->m_type == TYPE_AUTHBILL || + ($this->m_type == TYPE_ESCROW && $this->m_Data->m_EscrowType == TYPE_ESCROW_DNY_CNF ) || + $this->m_type == TYPE_NETCANCEL + ) { + $this->m_Log->WriteLog(INFO, "DON'T NEED NETCANCEL"); + return true; + } + + //NetCancel용 Data + $this->m_Data->m_REQUEST["cancelmsg"] = "망취소"; + $body = ""; + $sign = ""; + + $this->m_Data->m_Type = TYPE_CANCEL; //망취소 전문은 취소전문과 같음.헤더만틀리고..쩝~ + //added escrow netcancel, 08.03.11 + if ($this->m_type == TYPE_ESCROW && $this->m_Data->m_EscrowType == TYPE_ESCROW_DLV) + $this->m_Data->m_sCmd = CMD_REQ_DLV_NETC; + else if ($this->m_type == TYPE_ESCROW && $this->m_Data->m_EscrowType == TYPE_ESCROW_CNF) + $this->m_Data->m_sCmd = CMD_REQ_CNF_NETC; + else if ($this->m_type == TYPE_ESCROW && $this->m_Data->m_EscrowType == TYPE_ESCROW_DNY) + $this->m_Data->m_sCmd = CMD_REQ_DNY_NETC; + else + $this->m_Data->m_sCmd = CMD_REQ_NETC; + + $this->m_Data->m_sCrypto = FLAG_CRYPTO_3DES; + + //암호화 + if (($rtv = $this->m_Data->MakeEncrypt($this->m_Crypto)) != OK) { + $err_msg = "암호화 오류"; + $this->m_Log->WriteLog(ERROR, $err_msg); + //$this->MakeTXErrMsg( $rtv, $err_msg ); + return; + } + $this->m_Log->WriteLog(DEBUG, "MAKE ENCRYPT OK[" . $this->m_Data->m_EncBody . "]"); + + //전문생성(Body) + $this->m_Data->MakeBody(); + $this->m_Log->WriteLog(INFO, "MAKE BODY OK"); + + //서명(sign) + if (($rtv = $this->m_Crypto->Sign($this->m_Data->m_sBody, $sign)) != OK) { + $err_msg = "싸인실패"; + $this->m_Log->WriteLog(ERROR, $err_msg); + //$this->MakeTXErrMsg( $rtv, $err_msg ); + return false; + } + $this->m_Data->m_sTail = $sign; + $this->m_Log->WriteLog(INFO, "SIGN OK"); + + //전문생성(Head) + $this->m_Data->MakeHead(); + $this->m_Log->WriteLog(INFO, "MAKE HEAD OK"); + + $this->m_Log->WriteLog(DEBUG, "MSG_TO_PG:[" . $this->m_Data->m_sMsg . "]"); + + //소켓생성 + $this->m_Socket = new INISocket(""); + $this->m_Socket->ip = $this->m_connIP; //기존연결된 IP 사용, 08.03.12 + if (($rtv = $this->m_Socket->open()) != OK) { + $err_msg = "[" . $this->m_Socket->ip . "]소켓연결오류(NETC)::" . $this->m_Socket->getErr(); + $this->m_Log->WriteLog(ERROR, $err_msg); + //$this->MakeTXErrMsg( $rtv, $err_msg ); + $this->m_Log->CloseLog($this->GetResult(NM_RESULTMSG)); + $this->m_Socket->close(); + $this->m_Crypto->FreeAllKey(); + return; + } + $this->m_Log->WriteLog(INFO, "SOCKET CONNECT OK::" . $this->m_Socket->ip); + + //전문송신 + if (($rtv = $this->m_Socket->send($this->m_Data->m_sMsg)) != OK) { + $err_msg = "소켓송신오류(NETC)" . $this->m_Socket->getErr(); + $this->m_Log->WriteLog(ERROR, $err_msg); + //$this->MakeTXErrMsg( $rtv, $err_msg ); + $this->m_Socket->close(); + return false; + } + $this->m_Log->WriteLog(INFO, "SEND OK"); + + //전문수신 + if (($rtv = $this->m_Socket->recv($head, $body, $tail)) != OK) { + $err_msg = "소켓수신오류(NETC)"; + $this->m_Log->WriteLog(ERROR, $err_msg); + //$this->MakeTXErrMsg( $rtv, $err_msg ); + $this->m_Socket->close(); + return false; + } + $this->m_Log->WriteLog(INFO, "RECV OK"); + $this->m_Log->WriteLog(DEBUG, "MSG_FROM_PG:[" . $head . $body . $tail . "]"); + + //서명확인 + if (($rtv = $this->m_Crypto->Verify($body, $tail)) != OK) { + $err_msg = "VERIFY FAIL"; + $this->m_Log->WriteLog(ERROR, $err_msg); + //$this->MakeTXErrMsg( $rtv, $err_msg ); + $this->m_Socket->close(); + return false; + } + $this->m_Log->WriteLog(INFO, "VERIFY OK"); + + //이하 헤더나 본문은 파싱하지 않는다!!!! + //그냥 여기서 끝내자 피곤하다.-_-;; + //Head 파싱 + if (($rtv = $this->m_Data->ParseHead($head)) != OK) { + $err_msg = "수신전문(HEAD) 파싱 오류"; + $this->m_Log->WriteLog(ERROR, $err_msg); + //$this->MakeTXErrMsg( $rtv, $err_msg ); + $this->m_Socket->close(); + return; + } + //Body 파싱 + if (($rtv = $this->m_Data->ParseBody($body, $encrypted, $sessionkey)) != OK) { + $err_msg = "수신전문(Body) 파싱 오류"; + $this->m_Log->WriteLog(ERROR, $err_msg); + //$this->MakeTXErrMsg( $rtv, $err_msg ); + $this->m_Socket->close(); + return; + } + + //if( $this->GetResult(NM_RESULTCODE) == "00" ) + if (strcmp($this->GetResult(NM_RESULTCODE), "00") == 0) + $this->m_Log->WriteLog(INFO, "SUCCESS NETCANCEL"); + else + $this->m_Log->WriteLog(ERROR, "ERROR NETCANCEL[" . $this->GetResult(NM_RESULTMSG) . "]"); + return true; + } + + function MakeIMStr($s, $t) { + $this->m_Crypto = new INICrypto($this->m_REQUEST); + if ($t == "H") + return $this->m_Crypto->MakeIMStr($s, base64_decode(IMHK)); + else if ($t == "J") + return $this->m_Crypto->MakeIMStr($s, base64_decode(IMJK)); + } + + /* -------------------------------------------------- */ + /* */ + /* 에러메세지 Make */ + /* */ + /* -------------------------------------------------- */ + + function MakeTXErrMsg($err_code, $err_msg) { + $this->m_RESULT[NM_RESULTCODE] = "01"; + $this->m_RESULT[NM_RESULTERRORCODE] = $err_code; + $this->m_RESULT[NM_RESULTMSG] = "[" . $err_code . "|" . $err_msg . "]"; + $this->m_Data->GTHR($err_code, $err_msg); + return; + } } diff --git a/shop/inicis/libs/INISoc.php b/shop/inicis/libs/INISoc.php index 23d607957..87fb15179 100644 --- a/shop/inicis/libs/INISoc.php +++ b/shop/inicis/libs/INISoc.php @@ -1,251 +1,222 @@ hnd); - if($errCode!=0) - { - //Connection reset by peer - if($errCode==104) - $this->bConnected = false; - $errMsg = socket_strerror($errCode); - $this->sSocErr = "(".$errCode.")(".$errMsg.")"; - socket_clear_error($this->hnd); - } - elseif (strlen($msg)) - { - $this->sSocErr = $errMsg; - } - return false; - } - - function INISocket($host) - { - $this->family = AF_INET; - $this->type = SOCK_STREAM; - $this->protocol = SOL_TCP; - $this->hnd = @socket_create($this->family,$this->type,$this->protocol); - $this->error(); - $this->sBuffer = false; - $this->ip = null; - $this->host = $host; - $this->port = PG_PORT; - } - - function DNSLookUP() - { - $starttime=GetMicroTime(); - $ip = @gethostbyname($this->host); - if($ip) - { - $this->ip = $ip; - } - else - { - $this->error("Hostname ".$this->host." could not be resolved"); - return DNS_LOOKUP_ERR; - } - - $this->dns_laptime=round(GetMicroTime()-$starttime, 3); - if( $this->dns_laptime > DNS_LOOKUP_TIMEOUT ) - return DNS_LOOKUP_TIMEOUT_ERR; - - return OK; - } - - function open() - { - //Connect timeout Trickkkkkkkkk ##2. NONBLOCKING NEED , less CPU clocking!!^^ - //modified by ddaemiri, 2007.08.30 - - socket_set_nonblock($this->hnd); - if (!@socket_connect($this->hnd, $this->ip, $this->port)) - { - $err = socket_last_error($this->hnd); - $err_str = socket_strerror($err); - if ($err == 106) //EISCONN - { - $this->bConnected = true; - socket_set_block($this->hnd); - return OK; - } - //EINPROGRESS( Linux:115, Window Socket:10035, FreeBSD4.10:36, OS üũ Ұؼ strε ˻ ) - if ($err != ERRCODE_INPROGRESS_LINUX && $err != ERRCODE_INPROGRESS_WIN && - $err != ERRCODE_INPROGRESS_FREEBSD && $err_str != ERRSTR_INPROGRESS ) - { - $this->error(); - socket_close($this->hnd); - return SOCK_CONN_ERR; - } + function error($msg = null) { + $errCode = socket_last_error($this->hnd); + if ($errCode != 0) { + //Connection reset by peer + if ($errCode == 104) + $this->bConnected = false; + $errMsg = socket_strerror($errCode); + $this->sSocErr = "(" . $errCode . ")(" . $errMsg . ")"; + socket_clear_error($this->hnd); + } + elseif (strlen($msg)) { + $this->sSocErr = $errMsg; + } + return false; } - $read = array($this->hnd); - $write = array($this->hnd); - $rtv = @socket_select($read,$write,$except=NULL,TIMEOUT_CONNECT); - if( $rtv == 0 ) //TIMEOUT - { - $this->error(); - socket_close($this->hnd); - return SOCK_TIMEO_ERR; + function INISocket($host) { + $this->family = AF_INET; + $this->type = SOCK_STREAM; + $this->protocol = SOL_TCP; + $this->hnd = @socket_create($this->family, $this->type, $this->protocol); + $this->error(); + $this->sBuffer = false; + $this->ip = null; + $this->host = $host; + $this->port = PG_PORT; } - else if ( $rtv === FALSE ) - { - $this->error(); - socket_close($this->hnd); - return SOCK_ETC1_ERR; + + function DNSLookUP() { + $starttime = GetMicroTime(); + $ip = @gethostbyname($this->host); + if ($ip) { + $this->ip = $ip; + } else { + $this->error("Hostname " . $this->host . " could not be resolved"); + return DNS_LOOKUP_ERR; + } + + $this->dns_laptime = round(GetMicroTime() - $starttime, 3); + if ($this->dns_laptime > DNS_LOOKUP_TIMEOUT) + return DNS_LOOKUP_TIMEOUT_ERR; + + return OK; } - if( in_array($this->hnd,$read) || in_array($this->hnd,$write)) - { - if(@socket_get_option($this->hnd, SOL_SOCKET, SO_ERROR) === FALSE) - { - $this->error(); - socket_close($this->hnd); - return SOCK_ETC2_ERR; - } - } - $this->bConnected = true; - socket_set_block($this->hnd); - return OK; - } - function close() - { - //if(!$this->bConnected) return; - @socket_shutdown($this->hnd,2); - @socket_close($this->hnd); - } - function send($sBuf) - { - if(!$this->bConnected) - { - $this->error("Socket error. Cannot send data on a closed socket."); - return SOCK_SEND1_ERR; - } + function open() { + //Connect timeout Trickkkkkkkkk ##2. NONBLOCKING NEED , less CPU clocking!!^^ + //modified by ddaemiri, 2007.08.30 - $vWrite = array($this->hnd); + socket_set_nonblock($this->hnd); + if (!@socket_connect($this->hnd, $this->ip, $this->port)) { + $err = socket_last_error($this->hnd); + $err_str = socket_strerror($err); + if ($err == 106) { //EISCONN + $this->bConnected = true; + socket_set_block($this->hnd); + return OK; + } + //EINPROGRESS( Linux:115, Window Socket:10035, FreeBSD4.10:36, 모든 OS 체크 불가능해서 str으로도 검색 ) + if ($err != ERRCODE_INPROGRESS_LINUX && $err != ERRCODE_INPROGRESS_WIN && + $err != ERRCODE_INPROGRESS_FREEBSD && $err_str != ERRSTR_INPROGRESS) { + $this->error(); + socket_close($this->hnd); + return SOCK_CONN_ERR; + } + } - while(($rtv = @socket_select($vRead = null,$vWrite ,$vExcept = null, TIMEOUT_WRITE)) === FALSE); + $read = array($this->hnd); + $write = array($this->hnd); + $rtv = @socket_select($read, $write, $except = NULL, TIMEOUT_CONNECT); + if ($rtv == 0) { //TIMEOUT + $this->error(); + socket_close($this->hnd); + return SOCK_TIMEO_ERR; + } else if ($rtv === FALSE) { + $this->error(); + socket_close($this->hnd); + return SOCK_ETC1_ERR; + } + if (in_array($this->hnd, $read) || in_array($this->hnd, $write)) { + if (@socket_get_option($this->hnd, SOL_SOCKET, SO_ERROR) === FALSE) { + $this->error(); + socket_close($this->hnd); + return SOCK_ETC2_ERR; + } + } + $this->bConnected = true; + socket_set_block($this->hnd); + return OK; + } - if( $rtv == 0 ) - { - $this->error(); - //return SOCK_TIMEO_ERR; - return SOCK_CONN_ERR; //modify 2008.04.01 - } - if( $rtv === FALSE ) - { - $this->error(); - return SOCK_SEND2_ERR; - } + function close() { + //if(!$this->bConnected) return; + @socket_shutdown($this->hnd, 2); + @socket_close($this->hnd); + } - $tmpBuf = strlen($sBuf) ? $sBuf : $this->sBuffer; - $iBufLen = strlen($tmpBuf); - $res = @socket_send($this->hnd,$tmpBuf,$iBufLen,0); + function send($sBuf) { + if (!$this->bConnected) { + $this->error("Socket error. Cannot send data on a closed socket."); + return SOCK_SEND1_ERR; + } - if($res === FALSE) - { - $this->error(); - return SOCK_SEND2_ERR; - } - elseif ($res < $iBufLen) - { - $tmpBuf = substr($tmpBuf,$res); - $this->send($tmpBuf); - } - return OK; - } - function WaitRecv( &$recv_buf, $nleft ) - { - $recv_buf = null; - $read = array($this->hnd); - $buf = null; - while( $nleft > 0 ) - { - $rtv = @socket_select($read,$write=NULL,$except=NULL,TIMEOUT_READ); - if( $rtv == 0 ) - { - $this->error(); - return SOCK_TIMEO_ERR; - } - else if ( $rtv === FALSE ) - { - $this->error(); - return SOCK_ETC1_ERR; - } + $vWrite = array($this->hnd); - if(!in_array($this->hnd,$read)) - { - $this->error(); - return SOCK_RECV1_ERR; - } - if($buf = @socket_read($this->hnd, $nleft)) - { - $recv_buf .= $buf; - } - else - { - $this->error(); - return SOCK_RECV1_ERR; - } - $nleft -= strlen( $buf ); - } - return OK; - } - function recv(&$head, &$body, &$tail) - { - if(!$this->bConnected) - { - $this->error("Socket error. Cannot read any data on a closed socket."); - return SOCK_RECV1_ERR; - } + while (($rtv = @socket_select($vRead = null, $vWrite, $vExcept = null, TIMEOUT_WRITE)) === FALSE); - //------------------------------------------------------ - //head - //------------------------------------------------------ - if( ($rtv = $this->WaitRecv( $head, MSGHEADER_LEN)) != OK ) return $rtv; + if ($rtv == 0) { + $this->error(); + //return SOCK_TIMEO_ERR; + return SOCK_CONN_ERR; //modify 2008.04.01 + } + if ($rtv === FALSE) { + $this->error(); + return SOCK_SEND2_ERR; + } - if( $head == "" ) return SOCK_RECV2_ERR; - $body_len = intval(substr( $head, 0, BODY_LEN )); - $tail_len = intval(substr( $head, BODY_LEN, TAIL_LEN )); - - //------------------------------------------------------ - //body - //------------------------------------------------------ - if( ($rtv = $this->WaitRecv( $body, $body_len)) != OK ) return $rtv; - - //------------------------------------------------------ - //tail - //------------------------------------------------------ - if( ($rtv = $this->WaitRecv( $tail, $tail_len)) != OK ) return $rtv; + $tmpBuf = strlen($sBuf) ? $sBuf : $this->sBuffer; + $iBufLen = strlen($tmpBuf); + $res = @socket_send($this->hnd, $tmpBuf, $iBufLen, 0); - return OK; - } - function getErr() - { - return $this->sSocErr; - } + if ($res === FALSE) { + $this->error(); + return SOCK_SEND2_ERR; + } elseif ($res < $iBufLen) { + $tmpBuf = substr($tmpBuf, $res); + $this->send($tmpBuf); + } + return OK; + } + + function WaitRecv(&$recv_buf, $nleft) { + $recv_buf = null; + $read = array($this->hnd); + $buf = null; + while ($nleft > 0) { + $rtv = @socket_select($read, $write = NULL, $except = NULL, TIMEOUT_READ); + if ($rtv == 0) { + $this->error(); + return SOCK_TIMEO_ERR; + } else if ($rtv === FALSE) { + $this->error(); + return SOCK_ETC1_ERR; + } + + if (!in_array($this->hnd, $read)) { + $this->error(); + return SOCK_RECV1_ERR; + } + if ($buf = @socket_read($this->hnd, $nleft)) { + $recv_buf .= $buf; + } else { + $this->error(); + return SOCK_RECV1_ERR; + } + $nleft -= strlen($buf); + } + return OK; + } + + function recv(&$head, &$body, &$tail) { + if (!$this->bConnected) { + $this->error("Socket error. Cannot read any data on a closed socket."); + return SOCK_RECV1_ERR; + } + + //------------------------------------------------------ + //head + //------------------------------------------------------ + if (($rtv = $this->WaitRecv($head, MSGHEADER_LEN)) != OK) + return $rtv; + + if ($head == "") + return SOCK_RECV2_ERR; + $body_len = intval(substr($head, 0, BODY_LEN)); + $tail_len = intval(substr($head, BODY_LEN, TAIL_LEN)); + + //------------------------------------------------------ + //body + //------------------------------------------------------ + if (($rtv = $this->WaitRecv($body, $body_len)) != OK) + return $rtv; + + //------------------------------------------------------ + //tail + //------------------------------------------------------ + if (($rtv = $this->WaitRecv($tail, $tail_len)) != OK) + return $rtv; + + return OK; + } + + function getErr() { + return $this->sSocErr; + } } - ?> diff --git a/shop/inicis/libs/INIStdPayUtil.php b/shop/inicis/libs/INIStdPayUtil.php new file mode 100644 index 000000000..c53a46a04 --- /dev/null +++ b/shop/inicis/libs/INIStdPayUtil.php @@ -0,0 +1,74 @@ + + + $value) { + $string .= "&$key=$value"; + } + $string = substr($string, 1); // remove leading "&" + + $sign = hash( "sha256", $string); + + return $sign; + } + + function makeHash($data, $alg) { + // $s = hash_hmac('sha256', $data, 'secret', true); + // return base64_encode($s); + + ///$ret = openssl_digest($data, $alg); + $ret = hash($alg, $data); + return $ret; + } + +} +?> \ No newline at end of file diff --git a/shop/inicis/libs/INIXml.php b/shop/inicis/libs/INIXml.php index 2a0a20614..3193ffb75 100644 --- a/shop/inicis/libs/INIXml.php +++ b/shop/inicis/libs/INIXml.php @@ -30,1523 +30,1369 @@ // /** -* Class for accessing XML data through the XPath language. -* -* This class offers methods for accessing the nodes of a XML document using -* the XPath language. You can add or remove nodes, set or modify their -* content and their attributes. No additional PHP extensions like DOM XML -* or something similar are required to use these features. -* -* @link http://www.phpxml.org/ Latest release of this class -* @link http://www.w3.org/TR/xpath W3C XPath Recommendation -* @copyright Copyright (c) 2001 Michael P. Mehl. All rights reserved. -* @author Michael P. Mehl -* @version 1.0 (2001-03-08) -* @access public -*/ + * Class for accessing XML data through the XPath language. + * + * This class offers methods for accessing the nodes of a XML document using + * the XPath language. You can add or remove nodes, set or modify their + * content and their attributes. No additional PHP extensions like DOM XML + * or something similar are required to use these features. + * + * @link http://www.phpxml.org/ Latest release of this class + * @link http://www.w3.org/TR/xpath W3C XPath Recommendation + * @copyright Copyright (c) 2001 Michael P. Mehl. All rights reserved. + * @author Michael P. Mehl + * @version 1.0 (2001-03-08) + * @access public + */ /** * - * ش ̺귯 Ǿ ȵ˴ϴ. - * Ƿ ڵ忡 å ڿ ˷帳ϴ. + * 해당 라이브러리는 절대 수정되어서는 안됩니다. + * 임의로 수정된 코드에 대한 책임은 전적으로 수정자에게 있음을 알려드립니다. * */ +class XML { -class XML -{ /** - * List of all document nodes. - * - * This array contains a list of all document nodes saved as an - * associative array. - * - * @access private - * @var array - */ + * List of all document nodes. + * + * This array contains a list of all document nodes saved as an + * associative array. + * + * @access private + * @var array + */ var $nodes = array(); - + /** - * List of document node IDs. - * - * This array contains a list of all IDs of all document nodes that - * are used for counting when adding a new node. - * - * @access private - * @var array - */ + * List of document node IDs. + * + * This array contains a list of all IDs of all document nodes that + * are used for counting when adding a new node. + * + * @access private + * @var array + */ var $ids = array(); - + /** - * Current document path. - * - * This variable saves the current path while parsing a XML file and adding - * the nodes being read from the file. - * - * @access private - * @var string - */ + * Current document path. + * + * This variable saves the current path while parsing a XML file and adding + * the nodes being read from the file. + * + * @access private + * @var string + */ var $path = ""; - + /** - * Current document position. - * - * This variable counts the current document position while parsing a XML - * file and adding the nodes being read from the file. - * - * @access private - * @var int - */ + * Current document position. + * + * This variable counts the current document position while parsing a XML + * file and adding the nodes being read from the file. + * + * @access private + * @var int + */ var $position = 0; - + /** - * Path of the document root. - * - * This string contains the full path to the node that acts as the root - * node of the whole document. - * - * @access private - * @var string - */ + * Path of the document root. + * + * This string contains the full path to the node that acts as the root + * node of the whole document. + * + * @access private + * @var string + */ var $root = ""; - + /** - * Current XPath expression. - * - * This string contains the full XPath expression being parsed currently. - * - * @access private - * @var string - */ - var $xpath = ""; - + * Current XPath expression. + * + * This string contains the full XPath expression being parsed currently. + * + * @access private + * @var string + */ + var $xpath = ""; + /** - * List of entities to be converted. - * - * This array contains a list of entities to be converted when an XPath - * expression is evaluated. - * - * @access private - * @var array - */ - var $entities = array ( "&" => "&", "<" => "<", ">" => ">", - "'" => "&apos", '"' => """ ); - + * List of entities to be converted. + * + * This array contains a list of entities to be converted when an XPath + * expression is evaluated. + * + * @access private + * @var array + */ + var $entities = array("&" => "&", "<" => "<", ">" => ">", + "'" => "&apos", '"' => """); + /** - * List of supported XPath axes. - * - * This array contains a list of all valid axes that can be evaluated in an - * XPath expression. - * - * @access private - * @var array - */ - var $axes = array ( "child", "descendant", "parent", "ancestor", + * List of supported XPath axes. + * + * This array contains a list of all valid axes that can be evaluated in an + * XPath expression. + * + * @access private + * @var array + */ + var $axes = array("child", "descendant", "parent", "ancestor", "following-sibling", "preceding-sibling", "following", "preceding", "attribute", "namespace", "self", "descendant-or-self", - "ancestor-or-self" ); - + "ancestor-or-self"); + /** - * List of supported XPath functions. - * - * This array contains a list of all valid functions that can be evaluated - * in an XPath expression. - * - * @access private - * @var array - */ - var $functions = array ( "last", "position", "count", "id", "name", + * List of supported XPath functions. + * + * This array contains a list of all valid functions that can be evaluated + * in an XPath expression. + * + * @access private + * @var array + */ + var $functions = array("last", "position", "count", "id", "name", "string", "concat", "starts-with", "contains", "substring-before", "substring-after", "substring", "string-length", "translate", "boolean", "not", "true", "false", "lang", "number", "sum", "floor", - "ceiling", "round", "text" ); - - /** - * List of supported XPath operators. - * - * This array contains a list of all valid operators that can be evaluated - * in a predicate of an XPath expression. The list is ordered by the - * precedence of the operators (lowest precedence first). - * - * @access private - * @var array - */ - var $operators = array( " or ", " and ", "=", "!=", "<=", "<", ">=", ">", - "+", "-", "*", " div ", " mod " ); - - - var $xml_node = array(); + "ceiling", "round", "text"); /** - * Constructor of the class. - * - * This constructor initializes the class and, when a filename is given, - * tries to read and parse the given file. - * - * @access public - * @author Michael P. Mehl - * @param string $file Path and name of the file to read and parsed. - * @see load_xml() - */ - //modify by ddaemiri, 2007.05.28 - //load_file -> load_xml string Է¹ . - function XML ( $file = "" ) - { + * List of supported XPath operators. + * + * This array contains a list of all valid operators that can be evaluated + * in a predicate of an XPath expression. The list is ordered by the + * precedence of the operators (lowest precedence first). + * + * @access private + * @var array + */ + var $operators = array(" or ", " and ", "=", "!=", "<=", "<", ">=", ">", + "+", "-", "*", " div ", " mod "); + var $xml_node = array(); + + /** + * Constructor of the class. + * + * This constructor initializes the class and, when a filename is given, + * tries to read and parse the given file. + * + * @access public + * @author Michael P. Mehl + * @param string $file Path and name of the file to read and parsed. + * @see load_xml() + */ + //modify by ddaemiri, 2007.05.28 + //load_file -> load_xml로 파일 및 string 으로 모두 입력받을 수 있음. + function XML($file = "") { // Check whether a file was given. - if ( !empty($file) ) - { + if (!empty($file)) { // Load the XML file. return $this->load_xml($file, ""); } } /** - * Reads a file and parses the XML data. - * - * This method reads the content of a XML file, tries to parse its - * content and upon success stores the information retrieved from - * the file into an array. - * - * @access public - * @author Michael P. Mehl - * @param string $file Path and name of the file to be read and parsed. - * @see handle_start_element(), handle_end_element(), - * handle_character_data() - */ - //modify by ddaemiri, 2007.05.28 - //load_file -> load_xml string Է¹ . - function load_xml ( $file, $str ) - { + * Reads a file and parses the XML data. + * + * This method reads the content of a XML file, tries to parse its + * content and upon success stores the information retrieved from + * the file into an array. + * + * @access public + * @author Michael P. Mehl + * @param string $file Path and name of the file to be read and parsed. + * @see handle_start_element(), handle_end_element(), + * handle_character_data() + */ + //modify by ddaemiri, 2007.05.28 + //load_file -> load_xml로 파일 및 string 으로 모두 입력받을 수 있음. + function load_xml($file, $str) { // Check whether the file exists and is readable. - if ( (file_exists($file) && is_readable($file)) || $str != "") - { + if ((file_exists($file) && is_readable($file)) || $str != "") { // Read the content of the file. - if( $str == "" ) - $content = implode("", file($file)); - else - $content = $str; + if ($str == "") + $content = implode("", file($file)); + else + $content = $str; // Check whether content has been read. - if ( !empty($content) ) - { + if (!empty($content)) { // Create an XML parser. $parser = xml_parser_create(); - + // Set the options for parsing the XML data. - xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); + xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); - + // Set the object for the parser. xml_set_object($parser, $this); - + // Set the element handlers for the parser. xml_set_element_handler($parser, "handle_start_element", "handle_end_element"); xml_set_character_data_handler($parser, "handle_character_data"); - + // Parse the XML file. - if ( !xml_parse($parser, $content, true) ) - { + if (!xml_parse($parser, $content, true)) { // Display an error message. - $this->display_error("XML error in file %s, line %d: %s", - $file, xml_get_current_line_number($parser), - xml_error_string(xml_get_error_code($parser))); + $this->display_error("XML error in file %s, line %d: %s", $file, xml_get_current_line_number($parser), xml_error_string(xml_get_error_code($parser))); } - + // Free the parser. xml_parser_free($parser); - - return OK; + + return OK; } - } - else - { + } else { // Display an error message. //$this->display_error("File %s could not be found or read.", $file); - return RESULT_MSG_FORMAT_ERR; + return RESULT_MSG_FORMAT_ERR; } } - - //modify by ddaemiri, 2007.05.28 - //charset ߰( header ) - function make_xml ( $highlight = array(), $root = "", $level = 0, $charset = "UTF-8" ) - { - // header ߰ - $header = ""."\n"; - $body = $this->get_xml( $highlight, $root, $level ); - return $header.$body; - } - + + //modify by ddaemiri, 2007.05.28 + //charset 추가( header 생성 ) + function make_xml($highlight = array(), $root = "", $level = 0, $charset = "UTF-8") { + // header 추가 + $header = "" . "\n"; + $body = $this->get_xml($highlight, $root, $level); + return $header . $body; + } + /** - * Generates a XML file with the content of the current document. - * - * This method creates a string containing the XML data being read - * and modified by this class before. This string can be used to save - * a modified document back to a file or doing other nice things with - * it. - * - * @access public - * @author Michael P. Mehl - * @param array $highlight Array containing a list of full document - * paths of nodes to be highlighted by ... tags - * in the generated XML string. - * @param string $root While doing a recursion with this method, this - * parameter is used for internal purpose. - * @param int $level While doing a recursion with this method, this - * parameter is used for internal purpose. - * @return string The returned string contains well-formed XML data - * representing the content of this document. - * @see load_xml(), evaluate(), get_content() - */ - //modify by ddaemiri, 2007.05.28 - //get_file -> get_xml Լ̸ . - function get_xml ( $highlight = array(), $root = "", $level = 0 ) - { + * Generates a XML file with the content of the current document. + * + * This method creates a string containing the XML data being read + * and modified by this class before. This string can be used to save + * a modified document back to a file or doing other nice things with + * it. + * + * @access public + * @author Michael P. Mehl + * @param array $highlight Array containing a list of full document + * paths of nodes to be highlighted by ... tags + * in the generated XML string. + * @param string $root While doing a recursion with this method, this + * parameter is used for internal purpose. + * @param int $level While doing a recursion with this method, this + * parameter is used for internal purpose. + * @return string The returned string contains well-formed XML data + * representing the content of this document. + * @see load_xml(), evaluate(), get_content() + */ + //modify by ddaemiri, 2007.05.28 + //get_file -> get_xml 로 함수이름 변경. + function get_xml($highlight = array(), $root = "", $level = 0) { // Create a string to save the generated XML data. $xml = ""; - + // Create two strings containing the tags for highlighting a node. $highlight_start = ""; - $highlight_end = ""; - + $highlight_end = ""; + // Generate a string to be displayed before the tags. $before = ""; - + // Calculate the amount of whitespaces to display. - for ( $i = 0; $i < ( $level * 2 ); $i++ ) - { + for ($i = 0; $i < ( $level * 2 ); $i++) { // Add a whitespaces to the string. $before .= " "; } - + // Check whether a root node is given. - if ( empty($root) ) - { + if (empty($root)) { // Set it to the document root. $root = $this->root; } - + // Check whether the node is selected. $selected = in_array($root, $highlight); - + // Now add the whitespaces to the XML data. $xml .= $before; - + // Check whether the node is selected. - if ( $selected ) - { + if ($selected) { // Add the highlight code to the XML data. $xml .= $highlight_start; } - + // Now open the tag. - $xml .= "<".$this->nodes[$root]["name"]; - + $xml .= "<" . $this->nodes[$root]["name"]; + // Check whether there are attributes for this node. - if ( count($this->nodes[$root]["attributes"]) > 0 ) - { + if (count($this->nodes[$root]["attributes"]) > 0) { // Run through all attributes. - foreach ( $this->nodes[$root]["attributes"] as $key => $value ) - { + foreach ($this->nodes[$root]["attributes"] as $key => $value) { // Check whether this attribute is highlighted. - if ( in_array($root."/attribute::".$key, $highlight) ) - { + if (in_array($root . "/attribute::" . $key, $highlight)) { // Add the highlight code to the XML data. $xml .= $highlight_start; } - + // Add the attribute to the XML data. - $xml .= " ".$key."=\"".trim(stripslashes($value))."\""; - + $xml .= " " . $key . "=\"" . trim(stripslashes($value)) . "\""; + // Check whether this attribute is highlighted. - if ( in_array($root."/attribute::".$key, $highlight) ) - { + if (in_array($root . "/attribute::" . $key, $highlight)) { // Add the highlight code to the XML data. $xml .= $highlight_end; } } } - + // Check whether the node contains character data or has children. - if ( $this->nodes[$root]["text"] == "" && - !isset($this->nodes[$root]["children"]) ) - { + if ($this->nodes[$root]["text"] == "" && + !isset($this->nodes[$root]["children"])) { // Add the end to the tag. $xml .= "/"; } - + // Close the tag. //$xml .= ">\n"; $xml .= ">"; - + // Check whether the node is selected. - if ( $selected ) - { + if ($selected) { // Add the highlight code to the XML data. $xml .= $highlight_end; } - + // Check whether the node contains character data. - if ( $this->nodes[$root]["text"] != "" ) - { + if ($this->nodes[$root]["text"] != "") { // Add the character data to the XML data. //$xml .= $before." ".$this->nodes[$root]["text"]."\n"; //$xml .= $before.$this->nodes[$root]["text"]; $xml .= $this->nodes[$root]["text"]; } - + // Check whether the node has children. - if ( isset($this->nodes[$root]["children"]) ) - { + if (isset($this->nodes[$root]["children"])) { // Run through all children with different names. - foreach ( $this->nodes[$root]["children"] as $child => $pos ) - { + foreach ($this->nodes[$root]["children"] as $child => $pos) { // Run through all children with the same name. - for ( $i = 1; $i <= $pos; $i++ ) - { + for ($i = 1; $i <= $pos; $i++) { // Generate the full path of the child. - $fullchild = $root."/".$child."[".$i."]"; - + $fullchild = $root . "/" . $child . "[" . $i . "]"; + // Add the child's XML data to the existing data. - $xml .= "\n\t".$this->get_xml($highlight, $fullchild, $level + 1); + $xml .= "\n\t" . $this->get_xml($highlight, $fullchild, $level + 1); } } } - + // Check whether there are attributes for this node. - if ( $this->nodes[$root]["text"] != "" || - isset($this->nodes[$root]["children"]) ) - { + if ($this->nodes[$root]["text"] != "" || + isset($this->nodes[$root]["children"])) { // Add the whitespaces to the XML data. //$xml .= $before; - // Check whether the node is selected. - if ( $selected ) - { + if ($selected) { // Add the highlight code to the XML data. $xml .= $highlight_start; } - + // Add the closing tag. - $xml .= "nodes[$root]["name"].">"; - + $xml .= "nodes[$root]["name"] . ">"; + // Check whether the node is selected. - if ( $selected ) - { + if ($selected) { // Add the highlight code to the XML data. $xml .= $highlight_end; } - + // Add a linebreak. //$xml .= "\n"; } - + // Return the XML data. return $xml; } - + /** - * Adds a new node to the XML document. - * - * This method adds a new node to the tree of nodes of the XML document - * being handled by this class. The new node is created according to the - * parameters passed to this method. - * - * @access public - * @author Michael P. Mehl - * @param string $content Full path of the parent, to which the new - * node should be added as a child. - * @param string $name Name of the new node. - * @return string The string returned by this method will contain the - * full document path of the created node. - * @see remove_node(), evaluate() - */ - function add_node ( $context, $name, $value="", $attr_arr=NULL ) - { + * Adds a new node to the XML document. + * + * This method adds a new node to the tree of nodes of the XML document + * being handled by this class. The new node is created according to the + * parameters passed to this method. + * + * @access public + * @author Michael P. Mehl + * @param string $content Full path of the parent, to which the new + * node should be added as a child. + * @param string $name Name of the new node. + * @return string The string returned by this method will contain the + * full document path of the created node. + * @see remove_node(), evaluate() + */ + function add_node($context, $name, $value = "", $attr_arr = NULL) { // Check whether a name for this element is already set. - if ( empty($this->root) ) - { + if (empty($this->root)) { // Use this tag as the root element. - $this->root = "/".$name."[1]"; + $this->root = "/" . $name . "[1]"; } - + // Calculate the full path for this element. - $path = $context."/".$name; - + $path = $context . "/" . $name; + // Set the relative context and the position. $position = ++$this->ids[$path]; - $relative = $name."[".$position."]"; - + $relative = $name . "[" . $position . "]"; + // Calculate the full path. - $fullpath = $context."/".$relative; - + $fullpath = $context . "/" . $relative; + // Calculate the context position, which is the position of this // element within elements of the same name in the parent node. $this->nodes[$fullpath]["context-position"] = $position; - + // Calculate the position for the following and preceding axis // detection. - $this->nodes[$fullpath]["document-position"] = - $this->nodes[$context]["document-position"] + 1; - + $this->nodes[$fullpath]["document-position"] = $this->nodes[$context]["document-position"] + 1; + // Save the information about the node. - $this->nodes[$fullpath]["name"] = $name; - $this->nodes[$fullpath]["text"] = ""; + $this->nodes[$fullpath]["name"] = $name; + $this->nodes[$fullpath]["text"] = ""; $this->nodes[$fullpath]["parent"] = $context; - + // Add this element to the element count array. - if ( !$this->nodes[$context]["children"][$name] ) - { + if (!$this->nodes[$context]["children"][$name]) { // Set the default name. $this->nodes[$context]["children"][$name] = 1; - } - else - { + } else { // Calculate the name. - $this->nodes[$context]["children"][$name] = - $this->nodes[$context]["children"][$name] + 1; + $this->nodes[$context]["children"][$name] = $this->nodes[$context]["children"][$name] + 1; + } + + if ($value != "" && is_array($attr_arr)) { + $this->set_attributes($fullpath, $attr_arr); + if ($attr_arr["urlencode"] == "1") + $value = urlencode($value); + } + if ($value != "") { + $this->set_content($fullpath, $value); } - - if( $value != "" && is_array($attr_arr) ) - { - $this->set_attributes($fullpath, $attr_arr); - if( $attr_arr["urlencode"] == "1" ) - $value = urlencode( $value); - } - if( $value != "" ) - { - $this->set_content($fullpath, $value); - } // Return the path of the new node. return $fullpath; } /** - * Removes a node from the XML document. - * - * This method removes a node from the tree of nodes of the XML document. - * If the node is a document node, all children of the node and its - * character data will be removed. If the node is an attribute node, - * only this attribute will be removed, the node to which the attribute - * belongs as well as its children will remain unmodified. - * - * @access public - * @author Michael P. Mehl - * @param string $node Full path of the node to be removed. - * @see add_node(), evaluate() - */ - function remove_node ( $node ) - { + * Removes a node from the XML document. + * + * This method removes a node from the tree of nodes of the XML document. + * If the node is a document node, all children of the node and its + * character data will be removed. If the node is an attribute node, + * only this attribute will be removed, the node to which the attribute + * belongs as well as its children will remain unmodified. + * + * @access public + * @author Michael P. Mehl + * @param string $node Full path of the node to be removed. + * @see add_node(), evaluate() + */ + function remove_node($node) { // Check whether the node is an attribute node. - if ( preg_match("/attribute::/", $node) ) - { + if (preg_match("/attribute::/", $node)) { // Get the path to the attribute node's parent. $parent = $this->prestr($node, "/attribute::"); - + // Get the name of the attribute. $attribute = $this->afterstr($node, "/attribute::"); - + // Check whether the attribute exists. - if ( isset($this->nodes[$parent]["attributes"][$attribute]) ) - { + if (isset($this->nodes[$parent]["attributes"][$attribute])) { // Create a new array. $new = array(); - + // Run through the existing attributes. - foreach ( $this->nodes[$parent]["attributes"] - as $key => $value ) - { + foreach ($this->nodes[$parent]["attributes"] + as $key => $value) { // Check whether it's the attribute to remove. - if ( $key != $attribute ) - { + if ($key != $attribute) { // Add it to the new array again. $new[$key] = $value; } } - + // Save the new attributes. $this->nodes[$parent]["attributes"] = $new; } - } - else - { + } else { // Create an associative array, which contains information about // all nodes that required to be renamed. $rename = array(); - + // Get the name, the parent and the siblings of current node. - $name = $this->nodes[$node]["name"]; - $parent = $this->nodes[$node]["parent"]; + $name = $this->nodes[$node]["name"]; + $parent = $this->nodes[$node]["parent"]; $siblings = $this->nodes[$parent]["children"][$name]; - + // Decrease the number of children. - $this->nodes[$parent]["children"][$name]--; - + $this->nodes[$parent]["children"][$name] --; + // Create a counter for renumbering the siblings. $counter = 1; - + // Now run through the siblings. - for ( $i = 1; $i <= $siblings; $i++ ) - { + for ($i = 1; $i <= $siblings; $i++) { // Create the name of the sibling. - $sibling = $parent."/".$name."[".$i."]"; - + $sibling = $parent . "/" . $name . "[" . $i . "]"; + // Check whether it's the name of the current node. - if ( $sibling != $node ) - { + if ($sibling != $node) { // Create the new name for the sibling. - $new = $parent."/".$name."[".$counter."]"; - + $new = $parent . "/" . $name . "[" . $counter . "]"; + // Increase the counter. $counter++; - + // Add the old and the new name to the list of nodes // to be renamed. $rename[$sibling] = $new; } } - + // Create an array for saving the new node-list. $nodes = array(); - + // Now run through through the existing nodes. - foreach ( $this->nodes as $name => $values ) - { + foreach ($this->nodes as $name => $values) { // Check the position of the path of the node to be deleted // in the path of the current node. $position = strpos($name, $node); // Check whether it's not the node to be deleted. - if ( $position === false ) - { + if ($position === false) { // Run through the array of nodes to be renamed. - foreach ( $rename as $old => $new ) - { + foreach ($rename as $old => $new) { // Check whether this node and it's parent requires to // be renamed. - $name = str_replace($old, $new, $name); - $values["parent"] = str_replace($old, $new, - $values["parent"]); + $name = str_replace($old, $new, $name); + $values["parent"] = str_replace($old, $new, $values["parent"]); } - + // Add the node to the list of nodes. $nodes[$name] = $values; } } - + // Save the new array of nodes. $this->nodes = $nodes; } } /** - * Add content to a node. - * - * This method adds content to a node. If it's an attribute node, then - * the value of the attribute will be set, otherwise the character data of - * the node will be set. The content is appended to existing content, - * so nothing will be overwritten. - * - * @access public - * @author Michael P. Mehl - * @param string $path Full document path of the node. - * @param string $value String containing the content to be added. - * @see get_content(), evaluate() - */ - function add_content ( $path, $value ) - { + * Add content to a node. + * + * This method adds content to a node. If it's an attribute node, then + * the value of the attribute will be set, otherwise the character data of + * the node will be set. The content is appended to existing content, + * so nothing will be overwritten. + * + * @access public + * @author Michael P. Mehl + * @param string $path Full document path of the node. + * @param string $value String containing the content to be added. + * @see get_content(), evaluate() + */ + function add_content($path, $value) { // Check whether it's an attribute node. - if ( preg_match("/attribute::/", $path) ) - { + if (preg_match("/attribute::/", $path)) { // Get the path to the attribute node's parent. $parent = $this->prestr($path, "/attribute::"); - + // Get the parent node. $parent = $this->nodes[$parent]; - + // Get the name of the attribute. $attribute = $this->afterstr($path, "/attribute::"); - + // Set the attribute. $parent["attributes"][$attribute] .= $value; - } - else - { + } else { // Set the character data of the node. $this->nodes[$path]["text"] .= $value; } } - + /** - * Set the content of a node. - * - * This method sets the content of a node. If it's an attribute node, then - * the value of the attribute will be set, otherwise the character data of - * the node will be set. Existing content will be overwritten. - * - * @access public - * @author Michael P. Mehl - * @param string $path Full document path of the node. - * @param string $value String containing the content to be set. - * @see get_content(), evaluate() - */ - function set_content ( $path, $value ) - { + * Set the content of a node. + * + * This method sets the content of a node. If it's an attribute node, then + * the value of the attribute will be set, otherwise the character data of + * the node will be set. Existing content will be overwritten. + * + * @access public + * @author Michael P. Mehl + * @param string $path Full document path of the node. + * @param string $value String containing the content to be set. + * @see get_content(), evaluate() + */ + function set_content($path, $value) { // Check whether it's an attribute node. - if ( preg_match("/attribute::/", $path) ) - { + if (preg_match("/attribute::/", $path)) { // Get the path to the attribute node's parent. $parent = $this->prestr($path, "/attribute::"); - + // Get the parent node. $parent = $this->nodes[$parent]; - + // Get the name of the attribute. $attribute = $this->afterstr($path, "/attribute::"); - + // Set the attribute. $parent["attributes"][$attribute] = $value; - } - else - { + } else { // Set the character data of the node. $this->nodes[$path]["text"] = strtr($value, $this->entities); } } - + /** - * Retrieves the content of a node. - * - * This method retrieves the content of a node. If it's an attribute - * node, then the value of the attribute will be retrieved, otherwise - * it'll be the character data of the node. - * - * @access public - * @author Michael P. Mehl - * @param string $path Full document path of the node, from which the - * content should be retrieved. - * @return string The returned string contains either the value or the - * character data of the node. - * @see set_content(), evaluate() - */ - function get_content ( $path ) - { + * Retrieves the content of a node. + * + * This method retrieves the content of a node. If it's an attribute + * node, then the value of the attribute will be retrieved, otherwise + * it'll be the character data of the node. + * + * @access public + * @author Michael P. Mehl + * @param string $path Full document path of the node, from which the + * content should be retrieved. + * @return string The returned string contains either the value or the + * character data of the node. + * @see set_content(), evaluate() + */ + function get_content($path) { // Check whether it's an attribute node. - if ( preg_match("/attribute::/", $path) ) - { + if (preg_match("/attribute::/", $path)) { // Get the path to the attribute node's parent. $parent = $this->prestr($path, "/attribute::"); - + // Get the parent node. $parent = $this->nodes[$parent]; - + // Get the name of the attribute. $attribute = $this->afterstr($path, "/attribute::"); - + // Get the attribute. $attribute = $parent["attributes"][$attribute]; - + // Return the value of the attribute. return $attribute; - } - else - { + } else { // Return the cdata of the node. return stripslashes($this->nodes[$path]["text"]); } } - + /** - * Add attributes to a node. - * - * This method adds attributes to a node. Existing attributes will not be - * overwritten. - * - * @access public - * @author Michael P. Mehl - * @param string $path Full document path of the node, the attributes - * should be added to. - * @param array $attributes Associative array containing the new - * attributes for the node. - * @see set_content(), get_content() - */ - function add_attributes ( $path, $attributes ) - { + * Add attributes to a node. + * + * This method adds attributes to a node. Existing attributes will not be + * overwritten. + * + * @access public + * @author Michael P. Mehl + * @param string $path Full document path of the node, the attributes + * should be added to. + * @param array $attributes Associative array containing the new + * attributes for the node. + * @see set_content(), get_content() + */ + function add_attributes($path, $attributes) { // Add the attributes to the node. - $this->nodes[$path]["attributes"] = array_merge($attributes, - $this->nodes[$path]["attributes"]); + $this->nodes[$path]["attributes"] = array_merge($attributes, $this->nodes[$path]["attributes"]); } - + /** - * Sets the attributes of a node. - * - * This method sets the attributes of a node and overwrites all existing - * attributes by doing this. - * - * @access public - * @author Michael P. Mehl - * @param string $path Full document path of the node, the attributes - * of which should be set. - * @param array $attributes Associative array containing the new - * attributes for the node. - * @see set_content(), get_content() - */ - function set_attributes ( $path, $attributes ) - { + * Sets the attributes of a node. + * + * This method sets the attributes of a node and overwrites all existing + * attributes by doing this. + * + * @access public + * @author Michael P. Mehl + * @param string $path Full document path of the node, the attributes + * of which should be set. + * @param array $attributes Associative array containing the new + * attributes for the node. + * @see set_content(), get_content() + */ + function set_attributes($path, $attributes) { // Set the attributes of the node. $this->nodes[$path]["attributes"] = $attributes; } - + /** - * Retrieves a list of all attributes of a node. - * - * This method retrieves a list of all attributes of the node specified in - * the argument. - * - * @access public - * @author Michael P. Mehl - * @param string $path Full document path of the node, from which the - * list of attributes should be retrieved. - * @return array The returned associative array contains the all - * attributes of the specified node. - * @see get_content(), $nodes, $ids - */ - function get_attributes ( $path ) - { + * Retrieves a list of all attributes of a node. + * + * This method retrieves a list of all attributes of the node specified in + * the argument. + * + * @access public + * @author Michael P. Mehl + * @param string $path Full document path of the node, from which the + * list of attributes should be retrieved. + * @return array The returned associative array contains the all + * attributes of the specified node. + * @see get_content(), $nodes, $ids + */ + function get_attributes($path) { // Return the attributes of the node. return $this->nodes[$path]["attributes"]; } - + /** - * Retrieves the name of a document node. - * - * This method retrieves the name of document node specified in the - * argument. - * - * @access public - * @author Michael P. Mehl - * @param string $path Full document path of the node, from which the - * name should be retrieved. - * @return string The returned array contains the name of the specified - * node. - * @see get_content(), $nodes, $ids - */ - function get_name ( $path ) - { + * Retrieves the name of a document node. + * + * This method retrieves the name of document node specified in the + * argument. + * + * @access public + * @author Michael P. Mehl + * @param string $path Full document path of the node, from which the + * name should be retrieved. + * @return string The returned array contains the name of the specified + * node. + * @see get_content(), $nodes, $ids + */ + function get_name($path) { // Return the name of the node. return $this->nodes[$path]["name"]; } - + /** - * Evaluates an XPath expression. - * - * This method tries to evaluate an XPath expression by parsing it. A - * XML document has to be read before this method is able to work. - * - * @access public - * @author Michael P. Mehl - * @param string $path XPath expression to be evaluated. - * @param string $context Full path of a document node, starting - * from which the XPath expression should be evaluated. - * @return array The returned array contains a list of the full - * document paths of all nodes that match the evaluated - * XPath expression. - * @see $nodes, $ids - */ - function evaluate ( $path, $context = "" ) - { + * Evaluates an XPath expression. + * + * This method tries to evaluate an XPath expression by parsing it. A + * XML document has to be read before this method is able to work. + * + * @access public + * @author Michael P. Mehl + * @param string $path XPath expression to be evaluated. + * @param string $context Full path of a document node, starting + * from which the XPath expression should be evaluated. + * @return array The returned array contains a list of the full + * document paths of all nodes that match the evaluated + * XPath expression. + * @see $nodes, $ids + */ + function evaluate($path, $context = "") { // Remove slashes and quote signs. $path = stripslashes($path); $path = str_replace("\"", "", $path); $path = str_replace("'", "", $path); - + // Split the paths into different paths. $paths = $this->split_paths($path); - + // Create an empty set to save the result. $result = array(); - + // Run through all paths. - foreach ( $paths as $path ) - { + foreach ($paths as $path) { // Trim the path. $path = trim($path); - + // Save the current path. $this->xpath = $path; - + // Convert all entities. $path = strtr($path, array_flip($this->entities)); - + // Split the path at every slash. $steps = $this->split_steps($path); - + // Check whether the first element is empty. - if ( empty($steps[0]) ) - { + if (empty($steps[0])) { // Remove the first and empty element. array_shift($steps); } - + // Start to evaluate the steps. $nodes = $this->evaluate_step($context, $steps); - + // Remove duplicated nodes. $nodes = array_unique($nodes); - + // Add the nodes to the result set. $result = array_merge($result, $nodes); } - + // Return the result. return $result; } - + /** - * Handles opening XML tags while parsing. - * - * While parsing a XML document for each opening tag this method is - * called. It'll add the tag found to the tree of document nodes. - * - * @access private - * @author Michael P. Mehl - * @param int $parser Handler for accessing the current XML parser. - * @param string $name Name of the opening tag found in the document. - * @param array $attributes Associative array containing a list of - * all attributes of the tag found in the document. - * @see handle_end_element(), handle_character_data(), $nodes, $ids - */ - function handle_start_element ( $parser, $name, $attributes ) - { + * Handles opening XML tags while parsing. + * + * While parsing a XML document for each opening tag this method is + * called. It'll add the tag found to the tree of document nodes. + * + * @access private + * @author Michael P. Mehl + * @param int $parser Handler for accessing the current XML parser. + * @param string $name Name of the opening tag found in the document. + * @param array $attributes Associative array containing a list of + * all attributes of the tag found in the document. + * @see handle_end_element(), handle_character_data(), $nodes, $ids + */ + function handle_start_element($parser, $name, $attributes) { // Add a node. $this->path = $this->add_node($this->path, $name); - - // Set the attributes. - // Xpath Ȱ´. Ѵ ߴ!! - // modifyed by ddaemiri, 2007.09.03 - // $this->set_attributes($this->path, $attributes); - // add array, added by ddaemiri, 2007.09.03 - $arr = preg_split( "/[\/]+/", $this->path, -1, PREG_SPLIT_NO_EMPTY ); - $this->xml_node[$arr[count($arr)-1]]["attr"] = $attributes; + // Set the attributes. + // Xpath로 안가져온다. 한달을 헛지랄 했다!! + // modifyed by ddaemiri, 2007.09.03 + // $this->set_attributes($this->path, $attributes); + // add array, added by ddaemiri, 2007.09.03 + $arr = preg_split("/[\/]+/", $this->path, -1, PREG_SPLIT_NO_EMPTY); + $this->xml_node[$arr[count($arr) - 1]]["attr"] = $attributes; } - + /** - * Handles closing XML tags while parsing. - * - * While parsing a XML document for each closing tag this method is - * called. - * - * @access private - * @author Michael P. Mehl - * @param int $parser Handler for accessing the current XML parser. - * @param string $name Name of the closing tag found in the document. - * @see handle_start_element(), handle_character_data(), $nodes, $ids - */ - function handle_end_element ( $parser, $name ) - { + * Handles closing XML tags while parsing. + * + * While parsing a XML document for each closing tag this method is + * called. + * + * @access private + * @author Michael P. Mehl + * @param int $parser Handler for accessing the current XML parser. + * @param string $name Name of the closing tag found in the document. + * @see handle_start_element(), handle_character_data(), $nodes, $ids + */ + function handle_end_element($parser, $name) { // Jump back to the parent element. $this->path = substr($this->path, 0, strrpos($this->path, "/")); } - + /** - * Handles character data while parsing. - * - * While parsing a XML document for each character data this method - * is called. It'll add the character data to the document tree. - * - * @access private - * @author Michael P. Mehl - * @param int $parser Handler for accessing the current XML parser. - * @param string $text Character data found in the document. - * @see handle_start_element(), handle_end_element(), $nodes, $ids - */ - function handle_character_data ( $parser, $text ) - { + * Handles character data while parsing. + * + * While parsing a XML document for each character data this method + * is called. It'll add the character data to the document tree. + * + * @access private + * @author Michael P. Mehl + * @param int $parser Handler for accessing the current XML parser. + * @param string $text Character data found in the document. + * @see handle_start_element(), handle_end_element(), $nodes, $ids + */ + function handle_character_data($parser, $text) { // Replace entities. $text = strtr($text, $this->entities); - + // Save the text. - // Xpath Ȱ´. Ѵ ߴ!! - // modifyed by ddaemiri, 2007.09.03 + // Xpath로 안가져온다. 한달을 헛지랄 했다!! + // modifyed by ddaemiri, 2007.09.03 //$this->add_content($this->path, addslashes(trim($text))); - - // add array, added by ddaemiri, 2007.09.03 - $arr = preg_split( "/[\/]+/", $this->path, -1, PREG_SPLIT_NO_EMPTY ); - //edited by ddaemiri. libexpat \n иڷ ν - //$this->xml_node[$arr[count($arr)-1]]["text"] = addslashes(trim($text)); - $this->xml_node[$arr[count($arr)-1]]["text"] = $this->xml_node[$arr[count($arr)-1]]["text"].addslashes(trim($text)); + // add array, added by ddaemiri, 2007.09.03 + $arr = preg_split("/[\/]+/", $this->path, -1, PREG_SPLIT_NO_EMPTY); + //edited by ddaemiri. libexpat은 \n을 분리자로 인식 + //$this->xml_node[$arr[count($arr)-1]]["text"] = addslashes(trim($text)); + $this->xml_node[$arr[count($arr) - 1]]["text"] = $this->xml_node[$arr[count($arr) - 1]]["text"] . addslashes(trim($text)); } - + /** - * Splits an XPath expression into its different expressions. - * - * This method splits an XPath expression. Each expression can consists of - * list of expression being separated from each other by a | character. - * - * @access private - * @author Michael P. Mehl - * @param string $expression The complete expression to be splitted - * into its different expressions. - * @return array The array returned from this method contains a list - * of all expressions found in the expression passed to this - * method as a parameter. - * @see evalute() - */ - function split_paths ( $expression ) - { + * Splits an XPath expression into its different expressions. + * + * This method splits an XPath expression. Each expression can consists of + * list of expression being separated from each other by a | character. + * + * @access private + * @author Michael P. Mehl + * @param string $expression The complete expression to be splitted + * into its different expressions. + * @return array The array returned from this method contains a list + * of all expressions found in the expression passed to this + * method as a parameter. + * @see evalute() + */ + function split_paths($expression) { // Create an empty array. $paths = array(); - + // Save the position of the slash. $position = -1; - + // Run through the expression. - do - { + do { // Search for a slash. $position = $this->search_string($expression, "|"); - + // Check whether a | was found. - if ( $position >= 0 ) - { + if ($position >= 0) { // Get the left part of the expression. - $left = substr($expression, 0, $position); + $left = substr($expression, 0, $position); $right = substr($expression, $position + 1); - + // Add the left value to the steps. $paths[] = $left; - + // Reduce the expression to the right part. $expression = $right; } - } - while ( $position > -1 ); - + } while ($position > -1); + // Add the remaing expression to the list of steps. $paths[] = $expression; - + // Return the steps. return $paths; } - + /** - * Splits an XPath expression into its different steps. - * - * This method splits an XPath expression. Each expression can consists of - * list of steps being separated from each other by a / character. - * - * @access private - * @author Michael P. Mehl - * @param string $expression The complete expression to be splitted - * into its different steps. - * @return array The array returned from this method contains a list - * of all steps found in the expression passed to this - * method as a parameter. - * @see evalute() - */ - function split_steps ( $expression ) - { + * Splits an XPath expression into its different steps. + * + * This method splits an XPath expression. Each expression can consists of + * list of steps being separated from each other by a / character. + * + * @access private + * @author Michael P. Mehl + * @param string $expression The complete expression to be splitted + * into its different steps. + * @return array The array returned from this method contains a list + * of all steps found in the expression passed to this + * method as a parameter. + * @see evalute() + */ + function split_steps($expression) { // Create an empty array. $steps = array(); - + // Replace a double slashes, because they'll cause problems otherwise. $expression = str_replace("//@", "/descendant::*/@", $expression); $expression = str_replace("//", "/descendant::", $expression); - + // Save the position of the slash. $position = -1; - + // Run through the expression. - do - { + do { // Search for a slash. $position = $this->search_string($expression, "/"); - + // Check whether a slash was found. - if ( $position >= 0 ) - { + if ($position >= 0) { // Get the left part of the expression. - $left = substr($expression, 0, $position); + $left = substr($expression, 0, $position); $right = substr($expression, $position + 1); - + // Add the left value to the steps. $steps[] = $left; - + // Reduce the expression to the right part. $expression = $right; } - } - while ( $position > -1 ); - + } while ($position > -1); + // Add the remaing expression to the list of steps. $steps[] = $expression; - + // Return the steps. return $steps; } - + /** - * Retrieves axis information from an XPath expression step. - * - * This method tries to extract the name of the axis and its node-test - * from a given step of an XPath expression at a given node. - * - * @access private - * @author Michael P. Mehl - * @param string $step String containing a step of an XPath expression. - * @param string $node Full document path of the node on which the - * step is executed. - * @return array This method returns an array containing information - * about the axis found in the step. - * @see evaluate_step() - */ - function get_axis ( $step, $node ) - { + * Retrieves axis information from an XPath expression step. + * + * This method tries to extract the name of the axis and its node-test + * from a given step of an XPath expression at a given node. + * + * @access private + * @author Michael P. Mehl + * @param string $step String containing a step of an XPath expression. + * @param string $node Full document path of the node on which the + * step is executed. + * @return array This method returns an array containing information + * about the axis found in the step. + * @see evaluate_step() + */ + function get_axis($step, $node) { // Create an array to save the axis information. $axis = array( - "axis" => "", + "axis" => "", "node-test" => "", "predicate" => array() ); - + // Check whether there are predicates. - if ( preg_match("/\[/", $step) ) - { + if (preg_match("/\[/", $step)) { // Get the predicates. $predicates = substr($step, strpos($step, "[")); - + // Reduce the step. $step = $this->prestr($step, "["); - + // Try to split the predicates. $predicates = str_replace("][", "]|[", $predicates); $predicates = explode("|", $predicates); - + // Run through all predicates. - foreach ( $predicates as $predicate ) - { + foreach ($predicates as $predicate) { // Remove the brackets. $predicate = substr($predicate, 1, strlen($predicate) - 2); - + // Add the predicate to the list of predicates. $axis["predicate"][] = $predicate; } } - + // Check whether the axis is given in plain text. - if ( $this->search_string($step, "::") > -1 ) - { + if ($this->search_string($step, "::") > -1) { // Split the step to extract axis and node-test. - $axis["axis"] = $this->prestr($step, "::"); + $axis["axis"] = $this->prestr($step, "::"); $axis["node-test"] = $this->afterstr($step, "::"); - } - else - { + } else { // Check whether the step is empty. - if ( empty($step) ) - { + if (empty($step)) { // Set it to the default value. $step = "."; } - + // Check whether is an abbreviated syntax. - if ( $step == "*" ) - { + if ($step == "*") { // Use the child axis and select all children. - $axis["axis"] = "child"; + $axis["axis"] = "child"; $axis["node-test"] = "*"; } //elseif ( ereg("\(", $step) ) //elseif ( preg_match("\(", $step) ) - elseif ( preg_match("/\(/", $step) ) - { + elseif (preg_match("/\(/", $step)) { // Check whether it's a function. - if ( $this->is_function($this->prestr($step, "(")) ) - { + if ($this->is_function($this->prestr($step, "("))) { // Get the position of the first bracket. $start = strpos($step, "("); - $end = strpos($step, ")", $start); - + $end = strpos($step, ")", $start); + // Get everything before, between and after the brackets. - $before = substr($step, 0, $start); + $before = substr($step, 0, $start); $between = substr($step, $start + 1, $end - $start - 1); - $after = substr($step, $end + 1); - + $after = substr($step, $end + 1); + // Trim each string. - $before = trim($before); + $before = trim($before); $between = trim($between); - $after = trim($after); - + $after = trim($after); + // Save the evaluated function. - $axis["axis"] = "function"; - $axis["node-test"] = $this->evaluate_function($before, - $between, $node); - } - else - { + $axis["axis"] = "function"; + $axis["node-test"] = $this->evaluate_function($before, $between, $node); + } else { // Use the child axis and a function. - $axis["axis"] = "child"; + $axis["axis"] = "child"; $axis["node-test"] = $step; } } //elseif ( eregi("^@", $step) ) //elseif ( preg_match("^@/i", $step) ) - elseif ( preg_match("/^@/i", $step) ) - { + elseif (preg_match("/^@/i", $step)) { // Use the attribute axis and select the attribute. - $axis["axis"] = "attribute"; + $axis["axis"] = "attribute"; $axis["node-test"] = substr($step, 1); } //elseif ( eregi("\]$", $step) ) //elseif ( preg_match("\]$/i", $step) ) - elseif ( preg_match("/\]$/i", $step) ) - { + elseif (preg_match("/\]$/i", $step)) { // Use the child axis and select a position. - $axis["axis"] = "child"; + $axis["axis"] = "child"; $axis["node-test"] = substr($step, strpos($step, "[")); - } - elseif ( $step == "." ) - { + } elseif ($step == ".") { // Select the self axis. - $axis["axis"] = "self"; + $axis["axis"] = "self"; $axis["node-test"] = "*"; - } - elseif ( $step == ".." ) - { + } elseif ($step == "..") { // Select the parent axis. - $axis["axis"] = "parent"; + $axis["axis"] = "parent"; $axis["node-test"] = "*"; } //elseif ( ereg("^[a-zA-Z0-9\-_]+$", $step) ) //elseif ( preg_match("^[a-zA-Z0-9\-_]+$", $step) ) - elseif ( preg_match("/^[a-zA-Z0-9\-_]+$/", $step) ) - { + elseif (preg_match("/^[a-zA-Z0-9\-_]+$/", $step)) { // Select the child axis and the child. - $axis["axis"] = "child"; + $axis["axis"] = "child"; $axis["node-test"] = $step; - } - else - { + } else { // Use the child axis and a name. - $axis["axis"] = "child"; + $axis["axis"] = "child"; $axis["node-test"] = $step; } } // Check whether it's a valid axis. - if ( !in_array($axis["axis"], array_merge($this->axes, - array("function"))) ) - { + if (!in_array($axis["axis"], array_merge($this->axes, array("function")))) { // Display an error message. - $this->display_error("While parsing an XPath expression, in ". - "the step \"%s\" the invalid axis \"%s\" was found.", - str_replace($step, "".$step."", $this->xpath),# - $axis["axis"]); + $this->display_error("While parsing an XPath expression, in " . + "the step \"%s\" the invalid axis \"%s\" was found.", str_replace($step, "" . $step . "", $this->xpath), # + $axis["axis"]); } - + // Return the axis information. return $axis; } - + /** - * Looks for a string within another string. - * - * This method looks for a string within another string. Brackets in the - * string the method is looking through will be respected, which means that - * only if the string the method is looking for is located outside of - * brackets, the search will be successful. - * - * @access private - * @author Michael P. Mehl - * @param string $term String in which the search shall take place. - * @param string $expression String that should be searched. - * @return int This method returns -1 if no string was found, otherwise - * the offset at which the string was found. - * @see evaluate_step() - */ - function search_string ( $term, $expression ) - { + * Looks for a string within another string. + * + * This method looks for a string within another string. Brackets in the + * string the method is looking through will be respected, which means that + * only if the string the method is looking for is located outside of + * brackets, the search will be successful. + * + * @access private + * @author Michael P. Mehl + * @param string $term String in which the search shall take place. + * @param string $expression String that should be searched. + * @return int This method returns -1 if no string was found, otherwise + * the offset at which the string was found. + * @see evaluate_step() + */ + function search_string($term, $expression) { // Create a new counter for the brackets. $brackets = 0; - + // Run through the string. - for ( $i = 0; $i < strlen($term); $i++ ) - { + for ($i = 0; $i < strlen($term); $i++) { // Get the character at the position of the string. $character = substr($term, $i, 1); - + // Check whether it's a breacket. - if ( ( $character == "(" ) || ( $character == "[" ) ) - { + if (( $character == "(" ) || ( $character == "[" )) { // Increase the number of brackets. $brackets++; - } - elseif ( ( $character == ")" ) || ( $character == "]" ) ) - { + } elseif (( $character == ")" ) || ( $character == "]" )) { // Decrease the number of brackets. $brackets--; - } - elseif ( $brackets == 0 ) - { + } elseif ($brackets == 0) { // Check whether we can find the expression at this index. - if ( substr($term, $i, strlen($expression)) == $expression ) - { + if (substr($term, $i, strlen($expression)) == $expression) { // Return the current index. return $i; } } } - + // Check whether we had a valid number of brackets. - if ( $brackets != 0 ) - { + if ($brackets != 0) { // Display an error message. - $this->display_error("While parsing an XPath expression, in the ". - "predicate \"%s\", there was an invalid number of brackets.", - str_replace($term, "".$term."", $this->xpath)); + $this->display_error("While parsing an XPath expression, in the " . + "predicate \"%s\", there was an invalid number of brackets.", str_replace($term, "" . $term . "", $this->xpath)); } // Nothing was found. return (-1); } - + /** - * Checks for a valid function name. - * - * This method check whether an expression contains a valid name of an - * XPath function. - * - * @access private - * @author Michael P. Mehl - * @param string $expression Name of the function to be checked. - * @return boolean This method returns true if the given name is a valid - * XPath function name, otherwise false. - * @see evaluate() - */ - function is_function ( $expression ) - { + * Checks for a valid function name. + * + * This method check whether an expression contains a valid name of an + * XPath function. + * + * @access private + * @author Michael P. Mehl + * @param string $expression Name of the function to be checked. + * @return boolean This method returns true if the given name is a valid + * XPath function name, otherwise false. + * @see evaluate() + */ + function is_function($expression) { // Check whether it's in the list of supported functions. - if ( in_array($expression, $this->functions) ) - { + if (in_array($expression, $this->functions)) { // It's a function. return true; - } - else - { + } else { // It's not a function. return false; } } - + /** - * Evaluates a step of an XPath expression. - * - * This method tries to evaluate a step from an XPath expression at a - * specific context. - * - * @access private - * @author Michael P. Mehl - * @param string $context Full document path of the context from - * which starting the step should be evaluated. - * @param array $steps Array containing the remaining steps of the - * current XPath expression. - * @return array This method returns an array containing all nodes - * that are the result of evaluating the given XPath step. - * @see evaluate() - */ - function evaluate_step ( $context, $steps ) - { + * Evaluates a step of an XPath expression. + * + * This method tries to evaluate a step from an XPath expression at a + * specific context. + * + * @access private + * @author Michael P. Mehl + * @param string $context Full document path of the context from + * which starting the step should be evaluated. + * @param array $steps Array containing the remaining steps of the + * current XPath expression. + * @return array This method returns an array containing all nodes + * that are the result of evaluating the given XPath step. + * @see evaluate() + */ + function evaluate_step($context, $steps) { // Create an empty array for saving the nodes found. $nodes = array(); // Check whether the context is an array of contexts. - if ( is_array($context) ) - { + if (is_array($context)) { // Run through the array. - foreach ( $context as $path ) - { + foreach ($context as $path) { // Call this method for this single path. - $nodes = array_merge($nodes, - $this->evaluate_step($path, $steps)); + $nodes = array_merge($nodes, $this->evaluate_step($path, $steps)); } - } - else - { + } else { // Get this step. $step = array_shift($steps); - + // Create an array to save the new contexts. $contexts = array(); - + // Get the axis of the current step. $axis = $this->get_axis($step, $context); - + // Check whether it's a function. - if ( $axis["axis"] == "function" ) - { + if ($axis["axis"] == "function") { // Check whether an array was return by the function. - if ( is_array($axis["node-test"]) ) - { + if (is_array($axis["node-test"])) { // Add the results to the list of contexts. $contexts = array_merge($contexts, $axis["node-test"]); - } - else - { + } else { // Add the result to the list of contexts. $contexts[] = $axis["node-test"]; } - } - else - { + } else { // Create the name of the method. - $method = "handle_axis_".str_replace("-", "_", $axis["axis"]); - + $method = "handle_axis_" . str_replace("-", "_", $axis["axis"]); + // Check whether the axis handler is defined. - if ( !method_exists($this, $method) ) - { + if (!method_exists($this, $method)) { // Display an error message. - $this->display_error("While parsing an XPath expression, ". - "the axis \"%s\" could not be handled, because this ". - "version does not support this axis.", $axis["axis"]); + $this->display_error("While parsing an XPath expression, " . + "the axis \"%s\" could not be handled, because this " . + "version does not support this axis.", $axis["axis"]); } - + // Perform an axis action. $contexts = call_user_method($method, $this, $axis, $context); - + // Check whether there are predicates. - if ( count($axis["predicate"]) > 0 ) - { + if (count($axis["predicate"]) > 0) { // Check whether each node fits the predicates. - $contexts = $this->check_predicates($contexts, - $axis["predicate"]); + $contexts = $this->check_predicates($contexts, $axis["predicate"]); } } - + // Check whether there are more steps left. - if ( count($steps) > 0 ) - { + if (count($steps) > 0) { // Continue the evaluation of the next steps. $nodes = $this->evaluate_step($contexts, $steps); - } - else - { + } else { // Save the found contexts. $nodes = $contexts; } } - + // Return the nodes found. return $nodes; } - + /** - * Evaluates an XPath function - * - * This method evaluates a given XPath function with its arguments on a - * specific node of the document. - * - * @access private - * @author Michael P. Mehl - * @param string $function Name of the function to be evaluated. - * @param string $arguments String containing the arguments being - * passed to the function. - * @param string $node Full path to the document node on which the - * function should be evaluated. - * @return mixed This method returns the result of the evaluation of - * the function. Depending on the function the type of the - * return value can be different. - * @see evaluate() - */ - function evaluate_function ( $function, $arguments, $node ) - { + * Evaluates an XPath function + * + * This method evaluates a given XPath function with its arguments on a + * specific node of the document. + * + * @access private + * @author Michael P. Mehl + * @param string $function Name of the function to be evaluated. + * @param string $arguments String containing the arguments being + * passed to the function. + * @param string $node Full path to the document node on which the + * function should be evaluated. + * @return mixed This method returns the result of the evaluation of + * the function. Depending on the function the type of the + * return value can be different. + * @see evaluate() + */ + function evaluate_function($function, $arguments, $node) { // Remove whitespaces. - $function = trim($function); + $function = trim($function); $arguments = trim($arguments); // Create the name of the function handling function. - $method = "handle_function_".str_replace("-", "_", $function); - + $method = "handle_function_" . str_replace("-", "_", $function); + // Check whether the function handling function is available. - if ( !method_exists($this, $method) ) - { + if (!method_exists($this, $method)) { // Display an error message. - $this->display_error("While parsing an XPath expression, ". - "the function \"%s\" could not be handled, because this ". - "version does not support this function.", $function); + $this->display_error("While parsing an XPath expression, " . + "the function \"%s\" could not be handled, because this " . + "version does not support this function.", $function); } - + // Return the result of the function. return call_user_method($method, $this, $node, $arguments); } - + /** - * Evaluates a predicate on a node. - * - * This method tries to evaluate a predicate on a given node. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the predicate - * should be evaluated. - * @param string $predicate String containing the predicate expression - * to be evaluated. - * @return mixed This method is called recursively. The first call should - * return a boolean value, whether the node matches the predicate - * or not. Any call to the method being made during the recursion - * may also return other types for further processing. - * @see evaluate() - */ - function evaluate_predicate ( $node, $predicate ) - { + * Evaluates a predicate on a node. + * + * This method tries to evaluate a predicate on a given node. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the predicate + * should be evaluated. + * @param string $predicate String containing the predicate expression + * to be evaluated. + * @return mixed This method is called recursively. The first call should + * return a boolean value, whether the node matches the predicate + * or not. Any call to the method being made during the recursion + * may also return other types for further processing. + * @see evaluate() + */ + function evaluate_predicate($node, $predicate) { // Set the default position and the type of the operator. $position = 0; $operator = ""; - + // Run through all operators and try to find them. - foreach ( $this->operators as $expression ) - { + foreach ($this->operators as $expression) { // Check whether a position was already found. - if ( $position <= 0 ) - { + if ($position <= 0) { // Try to find the operator. $position = $this->search_string($predicate, $expression); - + // Check whether a operator was found. - if ( $position > 0 ) - { + if ($position > 0) { // Save the operator. $operator = $expression; - + // Check whether it's the equal operator. - if ( $operator == "=" ) - { + if ($operator == "=") { // Also look for other operators containing the // equal sign. - if ( $this->search_string($predicate, "!=") == - ( $position - 1 ) ) - { + if ($this->search_string($predicate, "!=") == + ( $position - 1 )) { // Get the new position. $position = $this->search_string($predicate, "!="); - + // Save the new operator. $operator = "!="; } - if ( $this->search_string($predicate, "<=") == - ( $position - 1 ) ) - { + if ($this->search_string($predicate, "<=") == + ( $position - 1 )) { // Get the new position. $position = $this->search_string($predicate, "<="); - + // Save the new operator. $operator = "<="; } - if ( $this->search_string($predicate, ">=") == - ( $position - 1 ) ) - { + if ($this->search_string($predicate, ">=") == + ( $position - 1 )) { // Get the new position. $position = $this->search_string($predicate, ">="); - + // Save the new operator. $operator = ">="; } @@ -1554,557 +1400,487 @@ class XML } } } - + // Check whether the operator is a - sign. - if ( $operator == "-" ) - { + if ($operator == "-") { // Check whether it's not a function containing a - in its name. - foreach ( $this->functions as $function ) - { + foreach ($this->functions as $function) { // Check whether there's a - sign in the function name. //if ( ereg("-", $function) ) //if ( preg_match("-", $function) ) - if ( preg_match("/-/", $function) ) - { + if (preg_match("/-/", $function)) { // Get the position of the - in the function name. $sign = strpos($function, "-"); - + // Extract a substring from the predicate. - $sub = substr($predicate, $position - $sign, - strlen($function)); - + $sub = substr($predicate, $position - $sign, strlen($function)); + // Check whether it's the function. - if ( $sub == $function ) - { + if ($sub == $function) { // Don't use the operator. $operator = ""; $position = -1; } } } - } - elseif ( $operator == "*" ) - { + } elseif ($operator == "*") { // Get some substrings. $character = substr($predicate, $position - 1, 1); $attribute = substr($predicate, $position - 11, 11); - + // Check whether it's an attribute selection. - if ( ( $character == "@" ) || ( $attribute == "attribute::" ) ) - { + if (( $character == "@" ) || ( $attribute == "attribute::" )) { // Don't use the operator. $operator = ""; $position = -1; } } - + // Check whether an operator was found. - if ( $position > 0 ) - { + if ($position > 0) { // Get the left and the right part of the expression. - $left = substr($predicate, 0, $position); + $left = substr($predicate, 0, $position); $right = substr($predicate, $position + strlen($operator)); - + // Remove whitespaces. - $left = trim($left); + $left = trim($left); $right = trim($right); - + // Evaluate the left and the right part. - $left = $this->evaluate_predicate($node, $left); + $left = $this->evaluate_predicate($node, $left); $right = $this->evaluate_predicate($node, $right); - + // Check the kind of operator. - switch ( $operator ) - { + switch ($operator) { case " or ": // Return the two results connected by an "or". return ( $left or $right ); - + case " and ": // Return the two results connected by an "and". return ( $left and $right ); - + case "=": // Compare the two results. return ( $left == $right ); - + case "!=": // Check whether the two results are not equal. return ( $left != $right ); - + case "<=": // Compare the two results. return ( $left <= $right ); - + case "<": // Compare the two results. return ( $left < $right ); - + case ">=": // Compare the two results. return ( $left >= $right ); - + case ">": // Compare the two results. return ( $left > $right ); - + case "+": // Return the result by adding one result to the other. return ( $left + $right ); - + case "-": // Return the result by decrease one result by the other. return ( $left - $right ); - + case "*": // Return a multiplication of the two results. return ( $left * $right ); - + case " div ": // Return a division of the two results. - if ( $right == 0 ) - { + if ($right == 0) { // Display an error message. - $this->display_error("While parsing an XPath ". - "predicate, a error due a division by zero ". - "occured."); - } - else - { + $this->display_error("While parsing an XPath " . + "predicate, a error due a division by zero " . + "occured."); + } else { // Return the result of the division. return ( $left / $right ); } break; - + case " mod ": // Return a modulo of the two results. return ( $left % $right ); } } - + // Check whether the predicate is a function. //if ( ereg("\(", $predicate) ) //if ( preg_match("\(", $predicate) ) - if ( preg_match("/\(/", $predicate) ) - { + if (preg_match("/\(/", $predicate)) { // Get the position of the first bracket. $start = strpos($predicate, "("); - $end = strpos($predicate, ")", $start); - + $end = strpos($predicate, ")", $start); + // Get everything before, between and after the brackets. - $before = substr($predicate, 0, $start); + $before = substr($predicate, 0, $start); $between = substr($predicate, $start + 1, $end - $start - 1); - $after = substr($predicate, $end + 1); - + $after = substr($predicate, $end + 1); + // Trim each string. - $before = trim($before); + $before = trim($before); $between = trim($between); - $after = trim($after); - + $after = trim($after); + // Check whether there's something after the bracket. - if ( !empty($after) ) - { + if (!empty($after)) { // Display an error message. - $this->display_error("While parsing an XPath expression ". - "there was found an error in the predicate \"%s\", ". - "because after a closing bracket there was found ". - "something unknown.", str_replace($predicate, - "".$predicate."", $this->xpath)); + $this->display_error("While parsing an XPath expression " . + "there was found an error in the predicate \"%s\", " . + "because after a closing bracket there was found " . + "something unknown.", str_replace($predicate, "" . $predicate . "", $this->xpath)); } - + // Check whether it's a function. - if ( empty($before) && empty($after) ) - { + if (empty($before) && empty($after)) { // Evaluate the content of the brackets. return $this->evaluate_predicate($node, $between); - } - elseif ( $this->is_function($before) ) - { + } elseif ($this->is_function($before)) { // Return the evaluated function. return $this->evaluate_function($before, $between, $node); - } - else - { + } else { // Display an error message. - $this->display_error("While parsing a predicate in an XPath ". - "expression, a function \"%s\" was found, which is not ". - "yet supported by the parser.", str_replace($before, - "".$before."", $this->xpath)); + $this->display_error("While parsing a predicate in an XPath " . + "expression, a function \"%s\" was found, which is not " . + "yet supported by the parser.", str_replace($before, "" . $before . "", $this->xpath)); } } - + // Check whether the predicate is just a digit. //if ( ereg("^[0-9]+(\.[0-9]+)?$", $predicate) || ereg("^\.[0-9]+$", $predicate) ) //if ( preg_match("^[0-9]+(\.[0-9]+)?$", $predicate) || preg_match("^\.[0-9]+$", $predicate) ) - if ( preg_match("/^[0-9]+(\.[0-9]+)?$/", $predicate) || preg_match("/^\.[0-9]+$/", $predicate) ) - { + if (preg_match("/^[0-9]+(\.[0-9]+)?$/", $predicate) || preg_match("/^\.[0-9]+$/", $predicate)) { // Return the value of the digit. return doubleval($predicate); } - + // Check whether it's an XPath expression. $result = $this->evaluate($predicate, $node); - if ( count($result) > 0 ) - { + if (count($result) > 0) { // Convert the array. $result = explode("|", implode("|", $result)); - + // Get the value of the first result. $value = $this->get_content($result[0]); - + // Return the value. return $value; } - + // Return the predicate as a string. return $predicate; } - + /** - * Checks whether a node matches predicates. - * - * This method checks whether a list of nodes passed to this method match - * a given list of predicates. - * - * @access private - * @author Michael P. Mehl - * @param array $nodes Array of full paths of all nodes to be tested. - * @param array $predicates Array of predicates to use. - * @return array The array returned by this method contains a list of - * all nodes matching the given predicates. - * @see evaluate_step() - */ - function check_predicates ( $nodes, $predicates ) - { + * Checks whether a node matches predicates. + * + * This method checks whether a list of nodes passed to this method match + * a given list of predicates. + * + * @access private + * @author Michael P. Mehl + * @param array $nodes Array of full paths of all nodes to be tested. + * @param array $predicates Array of predicates to use. + * @return array The array returned by this method contains a list of + * all nodes matching the given predicates. + * @see evaluate_step() + */ + function check_predicates($nodes, $predicates) { // Create an empty set of nodes. $result = array(); - + // Run through all nodes. - foreach ( $nodes as $node ) - { + foreach ($nodes as $node) { // Create a variable whether to add this node to the node-set. $add = true; - + // Run through all predicates. - foreach ( $predicates as $predicate ) - { + foreach ($predicates as $predicate) { // Check whether the predicate is just an number. //if ( ereg("^[0-9]+$", $predicate) ) //if ( preg_match("^[0-9]+$", $predicate) ) - if ( preg_match("/^[0-9]+$/", $predicate) ) - { + if (preg_match("/^[0-9]+$/", $predicate)) { // Enhance the predicate. $predicate .= "=position()"; } - + // Do the predicate check. $check = $this->evaluate_predicate($node, $predicate); - + // Check whether it's a string. - if ( is_string($check) && ( ( $check == "" ) || - ( $check == $predicate ) ) ) - { + if (is_string($check) && ( ( $check == "" ) || + ( $check == $predicate ) )) { // Set the result to false. $check = false; } - + // Check whether it's an integer. - if ( is_int($check) ) - { + if (is_int($check)) { // Check whether it's the current position. - if ( $check == $this->handle_function_position($node, "") ) - { + if ($check == $this->handle_function_position($node, "")) { // Set it to true. $check = true; - } - else - { + } else { // Set it to false. $check = false; } } - + // Check whether the predicate is OK for this node. $add = $add && $check; } - + // Check whether to add this node to the node-set. - if ( $add ) - { + if ($add) { // Add the node to the node-set. $result[] = $node; - } + } } - + // Return the array of nodes. return $result; } - + /** - * Checks whether a node matches a node-test. - * - * This method checks whether a node in the document matches a given - * node-test. - * - * @access private - * @author Michael P. Mehl - * @param string $context Full path of the node, which should be tested - * for matching the node-test. - * @param string $node_test String containing the node-test for the - * node. - * @return boolean This method returns true if the node matches the - * node-test, otherwise false. - * @see evaluate() - */ - function check_node_test ( $context, $node_test ) - { + * Checks whether a node matches a node-test. + * + * This method checks whether a node in the document matches a given + * node-test. + * + * @access private + * @author Michael P. Mehl + * @param string $context Full path of the node, which should be tested + * for matching the node-test. + * @param string $node_test String containing the node-test for the + * node. + * @return boolean This method returns true if the node matches the + * node-test, otherwise false. + * @see evaluate() + */ + function check_node_test($context, $node_test) { // Check whether it's a function. //if ( ereg("\(", $node_test) ) - if ( preg_match("/\(/", $node_test) ) - { + if (preg_match("/\(/", $node_test)) { // Get the type of function to use. $function = $this->prestr($node_test, "("); - + // Check whether the node fits the method. - switch ( $function ) - { + switch ($function) { case "node": // Add this node to the list of nodes. return true; - + case "text": // Check whether the node has some text. - if ( !empty($this->nodes[$context]["text"]) ) - { + if (!empty($this->nodes[$context]["text"])) { // Add this node to the list of nodes. return true; } break; - + case "comment": // Check whether the node has some comment. - if ( !empty($this->nodes[$context]["comment"]) ) - { + if (!empty($this->nodes[$context]["comment"])) { // Add this node to the list of nodes. return true; } break; - + case "processing-instruction": // Get the literal argument. $literal = $this->afterstr($axis["node-test"], "("); - + // Cut the literal. $literal = substr($literal, 0, strlen($literal) - 1); - + // Check whether a literal was given. - if ( !empty($literal) ) - { + if (!empty($literal)) { // Check whether the node's processing instructions // are matching the literals given. - if ( $this->nodes[$context] - ["processing-instructions"] == $literal ) - { + if ($this->nodes[$context] + ["processing-instructions"] == $literal) { // Add this node to the node-set. return true; } - } - else - { + } else { // Check whether the node has processing // instructions. - if ( !empty($this->nodes[$context] - ["processing-instructions"]) ) - { + if (!empty($this->nodes[$context] + ["processing-instructions"])) { // Add this node to the node-set. return true; } } break; - + default: // Display an error message. - $this->display_error("While parsing an XPath ". - "expression there was found an undefined ". - "function called \"%s\".", - str_replace($function, "".$function."", - $this->xpath)); + $this->display_error("While parsing an XPath " . + "expression there was found an undefined " . + "function called \"%s\".", str_replace($function, "" . $function . "", $this->xpath)); } - } - elseif ( $node_test == "*" ) - { + } elseif ($node_test == "*") { // Add this node to the node-set. return true; } //elseif ( ereg("^[a-zA-Z0-9\-_]+", $node_test) ) //elseif ( preg_match("^[a-zA-Z0-9\-_]+", $node_test) ) - elseif ( preg_match("/^[a-zA-Z0-9\-_]+/", $node_test) ) - { + elseif (preg_match("/^[a-zA-Z0-9\-_]+/", $node_test)) { // Check whether the node-test can be fulfilled. - if ( $this->nodes[$context]["name"] == $node_test ) - { + if ($this->nodes[$context]["name"] == $node_test) { // Add this node to the node-set. return true; } - } - else - { + } else { // Display an error message. - $this->display_error("While parsing the XPath expression \"%s\" ". - "an empty and therefore invalid node-test has been found.", - $this->xpath); + $this->display_error("While parsing the XPath expression \"%s\" " . + "an empty and therefore invalid node-test has been found.", $this->xpath); } - + // Don't add this context. return false; } - + /** - * Handles the XPath child axis. - * - * This method handles the XPath child axis. - * - * @access private - * @author Michael P. Mehl - * @param array $axis Array containing information about the axis. - * @param string $context Node from which starting the axis should - * be processed. - * @return array This method returns an array containing all nodes - * that were found during the evaluation of the given axis. - * @see evaluate() - */ - function handle_axis_child ( $axis, $context ) - { + * Handles the XPath child axis. + * + * This method handles the XPath child axis. + * + * @access private + * @author Michael P. Mehl + * @param array $axis Array containing information about the axis. + * @param string $context Node from which starting the axis should + * be processed. + * @return array This method returns an array containing all nodes + * that were found during the evaluation of the given axis. + * @see evaluate() + */ + function handle_axis_child($axis, $context) { // Create an empty node-set. $nodes = array(); - + // Get a list of all children. $children = $this->nodes[$context]["children"]; - + // Check whether there are children. - if ( !empty($children) ) - { + if (!empty($children)) { // Run through all children. - foreach ( $children as $child_name => $child_position ) - { + foreach ($children as $child_name => $child_position) { // Run through all childs with this name. - for ( $i = 1; $i <= $child_position; $i++ ) - { + for ($i = 1; $i <= $child_position; $i++) { // Create the path of the child. - $child = $context."/".$child_name."[".$i."]"; - + $child = $context . "/" . $child_name . "[" . $i . "]"; + // Check whether - if ( $this->check_node_test($child, $axis["node-test"]) ) - { + if ($this->check_node_test($child, $axis["node-test"])) { // Add the child to the node-set. $nodes[] = $child; } } } } - + // Return the nodeset. return $nodes; } - + /** - * Handles the XPath parent axis. - * - * This method handles the XPath parent axis. - * - * @access private - * @author Michael P. Mehl - * @param array $axis Array containing information about the axis. - * @param string $context Node from which starting the axis should - * be processed. - * @return array This method returns an array containing all nodes - * that were found during the evaluation of the given axis. - * @see evaluate() - */ - function handle_axis_parent ( $axis, $context ) - { + * Handles the XPath parent axis. + * + * This method handles the XPath parent axis. + * + * @access private + * @author Michael P. Mehl + * @param array $axis Array containing information about the axis. + * @param string $context Node from which starting the axis should + * be processed. + * @return array This method returns an array containing all nodes + * that were found during the evaluation of the given axis. + * @see evaluate() + */ + function handle_axis_parent($axis, $context) { // Create an empty node-set. $nodes = array(); - + // Check whether the parent matches the node-test. - if ( $this->check_node_test($this->nodes[$context]["parent"], - $axis["node-test"]) ) - { + if ($this->check_node_test($this->nodes[$context]["parent"], $axis["node-test"])) { // Add this node to the list of nodes. $nodes[] = $this->nodes[$context]["parent"]; } - - // Return the nodeset. - return $nodes; - } - - /** - * Handles the XPath attribute axis. - * - * This method handles the XPath attribute axis. - * - * @access private - * @author Michael P. Mehl - * @param array $axis Array containing information about the axis. - * @param string $context Node from which starting the axis should - * be processed. - * @return array This method returns an array containing all nodes - * that were found during the evaluation of the given axis. - * @see evaluate() - */ - function handle_axis_attribute ( $axis, $context ) - { - // Create an empty node-set. - $nodes = array(); - - // Check whether all nodes should be selected. - if ( $axis["node-test"] == "*" ) - { - // Check whether there are attributes. - if ( count($this->nodes[$context]["attributes"]) > 0 ) - { - // Run through the attributes. - foreach ( $this->nodes[$context]["attributes"] as - $key => $value ) - { - // Add this node to the node-set. - $nodes[] = $context."/attribute::".$key; - } - } - } - elseif ( !empty($this->nodes[$context]["attributes"] - [$axis["node-test"]]) ) - { - // Add this node to the node-set. - $nodes[] = $context."/attribute::".$axis["node-test"]; - } - + // Return the nodeset. return $nodes; } /** - * Handles the XPath self axis. - * - * This method handles the XPath self axis. - * - * @access private - * @author Michael P. Mehl - * @param array $axis Array containing information about the axis. - * @param string $context Node from which starting the axis should - * be processed. - * @return array This method returns an array containing all nodes - * that were found during the evaluation of the given axis. - * @see evaluate() - */ - function handle_axis_self ( $axis, $context ) - { + * Handles the XPath attribute axis. + * + * This method handles the XPath attribute axis. + * + * @access private + * @author Michael P. Mehl + * @param array $axis Array containing information about the axis. + * @param string $context Node from which starting the axis should + * be processed. + * @return array This method returns an array containing all nodes + * that were found during the evaluation of the given axis. + * @see evaluate() + */ + function handle_axis_attribute($axis, $context) { // Create an empty node-set. $nodes = array(); - + + // Check whether all nodes should be selected. + if ($axis["node-test"] == "*") { + // Check whether there are attributes. + if (count($this->nodes[$context]["attributes"]) > 0) { + // Run through the attributes. + foreach ($this->nodes[$context]["attributes"] as $key => $value) { + // Add this node to the node-set. + $nodes[] = $context . "/attribute::" . $key; + } + } + } elseif (!empty($this->nodes[$context]["attributes"] + [$axis["node-test"]])) { + // Add this node to the node-set. + $nodes[] = $context . "/attribute::" . $axis["node-test"]; + } + + // Return the nodeset. + return $nodes; + } + + /** + * Handles the XPath self axis. + * + * This method handles the XPath self axis. + * + * @access private + * @author Michael P. Mehl + * @param array $axis Array containing information about the axis. + * @param string $context Node from which starting the axis should + * be processed. + * @return array This method returns an array containing all nodes + * that were found during the evaluation of the given axis. + * @see evaluate() + */ + function handle_axis_self($axis, $context) { + // Create an empty node-set. + $nodes = array(); + // Check whether the context match the node-test. - if ( $this->check_node_test($context, $axis["node-test"]) ) - { + if ($this->check_node_test($context, $axis["node-test"])) { // Add this node to the node-set. $nodes[] = $context; } @@ -2114,1381 +1890,1248 @@ class XML } /** - * Handles the XPath descendant axis. - * - * This method handles the XPath descendant axis. - * - * @access private - * @author Michael P. Mehl - * @param array $axis Array containing information about the axis. - * @param string $context Node from which starting the axis should - * be processed. - * @return array This method returns an array containing all nodes - * that were found during the evaluation of the given axis. - * @see evaluate() - */ - function handle_axis_descendant ( $axis, $context ) - { + * Handles the XPath descendant axis. + * + * This method handles the XPath descendant axis. + * + * @access private + * @author Michael P. Mehl + * @param array $axis Array containing information about the axis. + * @param string $context Node from which starting the axis should + * be processed. + * @return array This method returns an array containing all nodes + * that were found during the evaluation of the given axis. + * @see evaluate() + */ + function handle_axis_descendant($axis, $context) { // Create an empty node-set. $nodes = array(); - + // Check whether the current node has children. - if ( count($this->nodes[$context]["children"]) > 0 ) - { + if (count($this->nodes[$context]["children"]) > 0) { // Get a list of children. $children = $this->nodes[$context]["children"]; - + // Run through all children. - foreach ( $children as $child_name => $child_position ) - { + foreach ($children as $child_name => $child_position) { // Run through all children of this name. - for ( $i = 1; $i <= $child_position; $i++ ) - { + for ($i = 1; $i <= $child_position; $i++) { // Create the full path for the children. - $child = $context."/".$child_name."[".$i."]"; - + $child = $context . "/" . $child_name . "[" . $i . "]"; + // Check whether the child matches the node-test. - if ( $this->check_node_test($child, $axis["node-test"]) ) - { + if ($this->check_node_test($child, $axis["node-test"])) { // Add the child to the list of nodes. $nodes[] = $child; } - + // Recurse to the next level. - $nodes = array_merge($nodes, - $this->handle_axis_descendant($axis, $child)); + $nodes = array_merge($nodes, $this->handle_axis_descendant($axis, $child)); } } } - + // Return the nodeset. return $nodes; } /** - * Handles the XPath ancestor axis. - * - * This method handles the XPath ancestor axis. - * - * @access private - * @author Michael P. Mehl - * @param array $axis Array containing information about the axis. - * @param string $context Node from which starting the axis should - * be processed. - * @return array This method returns an array containing all nodes - * that were found during the evaluation of the given axis. - * @see evaluate() - */ - function handle_axis_ancestor ( $axis, $context ) - { + * Handles the XPath ancestor axis. + * + * This method handles the XPath ancestor axis. + * + * @access private + * @author Michael P. Mehl + * @param array $axis Array containing information about the axis. + * @param string $context Node from which starting the axis should + * be processed. + * @return array This method returns an array containing all nodes + * that were found during the evaluation of the given axis. + * @see evaluate() + */ + function handle_axis_ancestor($axis, $context) { // Create an empty node-set. $nodes = array(); - + // Get the parent of the current node. $parent = $this->nodes[$context]["parent"]; - + // Check whether the parent isn't empty. - if ( !empty($parent) ) - { + if (!empty($parent)) { // Check whether the parent matches the node-test. - if ( $this->check_node_test($parent, $axis["node-test"]) ) - { + if ($this->check_node_test($parent, $axis["node-test"])) { // Add the parent to the list of nodes. $nodes[] = $parent; } - + // Handle all other ancestors. - $nodes = array_merge($nodes, - $this->handle_axis_ancestor($axis, $parent)); + $nodes = array_merge($nodes, $this->handle_axis_ancestor($axis, $parent)); } - + // Return the nodeset. return $nodes; } /** - * Handles the XPath namespace axis. - * - * This method handles the XPath namespace axis. - * - * @access private - * @author Michael P. Mehl - * @param array $axis Array containing information about the axis. - * @param string $context Node from which starting the axis should - * be processed. - * @return array This method returns an array containing all nodes - * that were found during the evaluation of the given axis. - * @see evaluate() - */ - function handle_axis_namespace ( $axis, $context ) - { + * Handles the XPath namespace axis. + * + * This method handles the XPath namespace axis. + * + * @access private + * @author Michael P. Mehl + * @param array $axis Array containing information about the axis. + * @param string $context Node from which starting the axis should + * be processed. + * @return array This method returns an array containing all nodes + * that were found during the evaluation of the given axis. + * @see evaluate() + */ + function handle_axis_namespace($axis, $context) { // Create an empty node-set. $nodes = array(); - + // Check whether all nodes should be selected. - if ( !empty($this->nodes[$context]["namespace"]) ) - { + if (!empty($this->nodes[$context]["namespace"])) { // Add this node to the node-set. $nodes[] = $context; } - + // Return the nodeset. return $nodes; } - + /** - * Handles the XPath following axis. - * - * This method handles the XPath following axis. - * - * @access private - * @author Michael P. Mehl - * @param array $axis Array containing information about the axis. - * @param string $context Node from which starting the axis should - * be processed. - * @return array This method returns an array containing all nodes - * that were found during the evaluation of the given axis. - * @see evaluate() - */ - function handle_axis_following ( $axis, $context ) - { + * Handles the XPath following axis. + * + * This method handles the XPath following axis. + * + * @access private + * @author Michael P. Mehl + * @param array $axis Array containing information about the axis. + * @param string $context Node from which starting the axis should + * be processed. + * @return array This method returns an array containing all nodes + * that were found during the evaluation of the given axis. + * @see evaluate() + */ + function handle_axis_following($axis, $context) { // Create an empty node-set. $nodes = array(); - + // Get the current document position. $position = $this->nodes[$context]["document-position"]; - + // Create a flag, whether we already found the context node. $found = false; - + // Run through all nodes of the document. - foreach ( $this->nodes as $node => $data ) - { + foreach ($this->nodes as $node => $data) { // Check whether the context node has already been found. - if ( $found ) - { + if ($found) { // Check whether the position is correct. - if ( $this->nodes[$node]["document-position"] == $position ) - { + if ($this->nodes[$node]["document-position"] == $position) { // Check whether the node fits the node-test. - if ( $this->check_node_test($node, $axis["node-test"]) ) - { + if ($this->check_node_test($node, $axis["node-test"])) { // Add the node to the list of nodes. $nodes[] = $node; } } } - + // Check whether this is the context node. - if ( $node == $context ) - { + if ($node == $context) { // After this we'll look for more nodes. $found = true; } } - + // Return the nodeset. return $nodes; } - + /** - * Handles the XPath preceding axis. - * - * This method handles the XPath preceding axis. - * - * @access private - * @author Michael P. Mehl - * @param array $axis Array containing information about the axis. - * @param string $context Node from which starting the axis should - * be processed. - * @return array This method returns an array containing all nodes - * that were found during the evaluation of the given axis. - * @see evaluate() - */ - function handle_axis_preceding ( $axis, $context ) - { + * Handles the XPath preceding axis. + * + * This method handles the XPath preceding axis. + * + * @access private + * @author Michael P. Mehl + * @param array $axis Array containing information about the axis. + * @param string $context Node from which starting the axis should + * be processed. + * @return array This method returns an array containing all nodes + * that were found during the evaluation of the given axis. + * @see evaluate() + */ + function handle_axis_preceding($axis, $context) { // Create an empty node-set. $nodes = array(); - + // Get the current document position. $position = $this->nodes[$context]["document-position"]; - + // Create a flag, whether we already found the context node. $found = true; - + // Run through all nodes of the document. - foreach ( $this->nodes as $node => $data ) - { + foreach ($this->nodes as $node => $data) { // Check whether this is the context node. - if ( $node == $context ) - { + if ($node == $context) { // After this we won't look for more nodes. $found = false; } - + // Check whether the context node has already been found. - if ( $found ) - { + if ($found) { // Check whether the position is correct. - if ( $this->nodes[$node]["document-position"] == $position ) - { + if ($this->nodes[$node]["document-position"] == $position) { // Check whether the node fits the node-test. - if ( $this->check_node_test($node, $axis["node-test"]) ) - { + if ($this->check_node_test($node, $axis["node-test"])) { // Add the node to the list of nodes. $nodes[] = $node; } } } } - + // Return the nodeset. return $nodes; } - + /** - * Handles the XPath following-sibling axis. - * - * This method handles the XPath following-sibling axis. - * - * @access private - * @author Michael P. Mehl - * @param array $axis Array containing information about the axis. - * @param string $context Node from which starting the axis should - * be processed. - * @return array This method returns an array containing all nodes - * that were found during the evaluation of the given axis. - * @see evaluate() - */ - function handle_axis_following_sibling ( $axis, $context ) - { + * Handles the XPath following-sibling axis. + * + * This method handles the XPath following-sibling axis. + * + * @access private + * @author Michael P. Mehl + * @param array $axis Array containing information about the axis. + * @param string $context Node from which starting the axis should + * be processed. + * @return array This method returns an array containing all nodes + * that were found during the evaluation of the given axis. + * @see evaluate() + */ + function handle_axis_following_sibling($axis, $context) { // Create an empty node-set. $nodes = array(); - + // Get all children from the parent. - $siblings = $this->handle_axis_child($axis, - $this->nodes[$context]["parent"]); - + $siblings = $this->handle_axis_child($axis, $this->nodes[$context]["parent"]); + // Create a flag whether the context node was already found. $found = false; - + // Run through all siblings. - foreach ( $siblings as $sibling ) - { + foreach ($siblings as $sibling) { // Check whether the context node was already found. - if ( $found ) - { + if ($found) { // Check whether the sibling is a real sibling. - if ( $this->nodes[$sibling]["name"] == - $this->nodes[$context]["name"] ) - { + if ($this->nodes[$sibling]["name"] == + $this->nodes[$context]["name"]) { // Check whether the sibling matches the node-test. - if ( $this->check_node_test($sibling, $axis["node-test"]) ) - { + if ($this->check_node_test($sibling, $axis["node-test"])) { // Add the sibling to the list of nodes. $nodes[] = $sibling; } } } - + // Check whether this is the context node. - if ( $sibling == $context ) - { + if ($sibling == $context) { // Continue looking for other siblings. $found = true; } } - + // Return the nodeset. return $nodes; } - + /** - * Handles the XPath preceding-sibling axis. - * - * This method handles the XPath preceding-sibling axis. - * - * @access private - * @author Michael P. Mehl - * @param array $axis Array containing information about the axis. - * @param string $context Node from which starting the axis should - * be processed. - * @return array This method returns an array containing all nodes - * that were found during the evaluation of the given axis. - * @see evaluate() - */ - function handle_axis_preceding_sibling ( $axis, $context ) - { + * Handles the XPath preceding-sibling axis. + * + * This method handles the XPath preceding-sibling axis. + * + * @access private + * @author Michael P. Mehl + * @param array $axis Array containing information about the axis. + * @param string $context Node from which starting the axis should + * be processed. + * @return array This method returns an array containing all nodes + * that were found during the evaluation of the given axis. + * @see evaluate() + */ + function handle_axis_preceding_sibling($axis, $context) { // Create an empty node-set. $nodes = array(); - + // Get all children from the parent. - $siblings = $this->handle_axis_child($axis, - $this->nodes[$context]["parent"]); - + $siblings = $this->handle_axis_child($axis, $this->nodes[$context]["parent"]); + // Create a flag whether the context node was already found. $found = true; - + // Run through all siblings. - foreach ( $siblings as $sibling ) - { + foreach ($siblings as $sibling) { // Check whether this is the context node. - if ( $sibling == $context ) - { + if ($sibling == $context) { // Don't continue looking for other siblings. $found = false; } - + // Check whether the context node was already found. - if ( $found ) - { + if ($found) { // Check whether the sibling is a real sibling. - if ( $this->nodes[$sibling]["name"] == - $this->nodes[$context]["name"] ) - { + if ($this->nodes[$sibling]["name"] == + $this->nodes[$context]["name"]) { // Check whether the sibling matches the node-test. - if ( $this->check_node_test($sibling, $axis["node-test"]) ) - { + if ($this->check_node_test($sibling, $axis["node-test"])) { // Add the sibling to the list of nodes. $nodes[] = $sibling; } } } } - + // Return the nodeset. return $nodes; } - + /** - * Handles the XPath descendant-or-self axis. - * - * This method handles the XPath descendant-or-self axis. - * - * @access private - * @author Michael P. Mehl - * @param array $axis Array containing information about the axis. - * @param string $context Node from which starting the axis should - * be processed. - * @return array This method returns an array containing all nodes - * that were found during the evaluation of the given axis. - * @see evaluate() - */ - function handle_axis_descendant_or_self ( $axis, $context ) - { + * Handles the XPath descendant-or-self axis. + * + * This method handles the XPath descendant-or-self axis. + * + * @access private + * @author Michael P. Mehl + * @param array $axis Array containing information about the axis. + * @param string $context Node from which starting the axis should + * be processed. + * @return array This method returns an array containing all nodes + * that were found during the evaluation of the given axis. + * @see evaluate() + */ + function handle_axis_descendant_or_self($axis, $context) { // Create an empty node-set. $nodes = array(); - + // Read the nodes. $nodes = array_merge( - $this->handle_axis_descendant($axis, $context), - $this->handle_axis_self($axis, $context)); - + $this->handle_axis_descendant($axis, $context), $this->handle_axis_self($axis, $context)); + // Return the nodeset. return $nodes; } - + /** - * Handles the XPath ancestor-or-self axis. - * - * This method handles the XPath ancestor-or-self axis. - * - * @access private - * @author Michael P. Mehl - * @param array $axis Array containing information about the axis. - * @param string $context Node from which starting the axis should - * be processed. - * @return array This method returns an array containing all nodes - * that were found during the evaluation of the given axis. - * @see evaluate() - */ - function handle_axis_ancestor_or_self ( $axis, $context ) - { + * Handles the XPath ancestor-or-self axis. + * + * This method handles the XPath ancestor-or-self axis. + * + * @access private + * @author Michael P. Mehl + * @param array $axis Array containing information about the axis. + * @param string $context Node from which starting the axis should + * be processed. + * @return array This method returns an array containing all nodes + * that were found during the evaluation of the given axis. + * @see evaluate() + */ + function handle_axis_ancestor_or_self($axis, $context) { // Create an empty node-set. $nodes = array(); - + // Read the nodes. $nodes = array_merge( - $this->handle_axis_ancestor($axis, $context), - $this->handle_axis_self($axis, $context)); - + $this->handle_axis_ancestor($axis, $context), $this->handle_axis_self($axis, $context)); + // Return the nodeset. return $nodes; } - + /** - * Handles the XPath function last. - * - * This method handles the XPath function last. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_last ( $node, $arguments ) - { + * Handles the XPath function last. + * + * This method handles the XPath function last. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_last($node, $arguments) { // Calculate the size of the context. - $parent = $this->nodes[$node]["parent"]; + $parent = $this->nodes[$node]["parent"]; $children = $this->nodes[$parent]["children"]; - $context = $children[$this->nodes[$node]["name"]]; + $context = $children[$this->nodes[$node]["name"]]; // Return the size. return $context; } /** - * Handles the XPath function position. - * - * This method handles the XPath function position. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_position ( $node, $arguments ) - { + * Handles the XPath function position. + * + * This method handles the XPath function position. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_position($node, $arguments) { // return the context-position. return $this->nodes[$node]["context-position"]; } - + /** - * Handles the XPath function count. - * - * This method handles the XPath function count. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_count ( $node, $arguments ) - { + * Handles the XPath function count. + * + * This method handles the XPath function count. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_count($node, $arguments) { // Evaluate the argument of the method as an XPath and return // the number of results. return count($this->evaluate($arguments, $node)); } - + /** - * Handles the XPath function id. - * - * This method handles the XPath function id. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_id ( $node, $arguments ) - { + * Handles the XPath function id. + * + * This method handles the XPath function id. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_id($node, $arguments) { // Trim the arguments. $arguments = trim($arguments); - + // Now split the arguments. $arguments = explode(" ", $arguments); - + // Check whether - // Create a list of nodes. $nodes = array(); - + // Run through all document node. - foreach ( $this->nodes as $node => $position ) - { + foreach ($this->nodes as $node => $position) { // Check whether the node has the ID we're looking for. - if ( in_array($this->nodes[$node]["attributes"]["id"], - $arguments) ) - { + if (in_array($this->nodes[$node]["attributes"]["id"], $arguments)) { // Add this node to the list of nodes. $nodes[] = $node; } } - + // Return the list of nodes. return $nodes; } - + /** - * Handles the XPath function name. - * - * This method handles the XPath function name. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_name ( $node, $arguments ) - { + * Handles the XPath function name. + * + * This method handles the XPath function name. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_name($node, $arguments) { // Return the name of the node. return $this->nodes[$node]["name"]; } - + /** - * Handles the XPath function string. - * - * This method handles the XPath function string. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_string ( $node, $arguments ) - { + * Handles the XPath function string. + * + * This method handles the XPath function string. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_string($node, $arguments) { // Check what type of parameter is given //if ( ereg("^[0-9]+(\.[0-9]+)?$", $arguments) || ereg("^\.[0-9]+$", $arguments) ) //if ( preg_match("^[0-9]+(\.[0-9]+)?$", $arguments) || preg_match("^\.[0-9]+$", $arguments) ) - if ( preg_match("/^[0-9]+(\.[0-9]+)?$/", $arguments) || preg_match("/^\.[0-9]+$/", $arguments) ) - { + if (preg_match("/^[0-9]+(\.[0-9]+)?$/", $arguments) || preg_match("/^\.[0-9]+$/", $arguments)) { // Convert the digits to a number. $number = doubleval($arguments); - + // Return the number. return strval($number); - } - elseif ( is_bool($arguments) ) - { + } elseif (is_bool($arguments)) { // Check whether it's true. - if ( $arguments == true ) - { + if ($arguments == true) { // Return true as a string. return "true"; - } - else - { + } else { // Return false as a string. return "false"; } - } - elseif ( !empty($arguments) ) - { + } elseif (!empty($arguments)) { // Use the argument as an XPath. $result = $this->evaluate($arguments, $node); - + // Get the first argument. $result = explode("|", implode("|", $result)); - + // Return the first result as a string. return $result[0]; - } - elseif ( empty($arguments) ) - { + } elseif (empty($arguments)) { // Return the current node. return $node; - } - else - { + } else { // Return an empty string. return ""; } } - + /** - * Handles the XPath function concat. - * - * This method handles the XPath function concat. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_concat ( $node, $arguments ) - { + * Handles the XPath function concat. + * + * This method handles the XPath function concat. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_concat($node, $arguments) { // Split the arguments. $arguments = explode(",", $arguments); - + // Run through each argument and evaluate it. - for ( $i = 0; $i < sizeof($arguments); $i++ ) - { + for ($i = 0; $i < sizeof($arguments); $i++) { // Trim each argument. $arguments[$i] = trim($arguments[$i]); - + // Evaluate it. $arguments[$i] = $this->evaluate_predicate($node, $arguments[$i]); } - + // Put the string together. $arguments = implode("", $arguments); - + // Return the string. return $arguments; } - + /** - * Handles the XPath function starts-with. - * - * This method handles the XPath function starts-with. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_starts_with ( $node, $arguments ) - { + * Handles the XPath function starts-with. + * + * This method handles the XPath function starts-with. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_starts_with($node, $arguments) { // Get the arguments. - $first = trim($this->prestr($arguments, ",")); + $first = trim($this->prestr($arguments, ",")); $second = trim($this->afterstr($arguments, ",")); - + // Evaluate each argument. - $first = $this->evaluate_predicate($node, $first); + $first = $this->evaluate_predicate($node, $first); $second = $this->evaluate_predicate($node, $second); - + // Check whether the first string starts with the second one. //if ( ereg("^".$second, $first) ) //if ( preg_match("^".$second, $first) ) - if ( preg_match("/^".$second."/", $first) ) - { + if (preg_match("/^" . $second . "/", $first)) { // Return true. return true; - } - else - { + } else { // Return false. return false; } } - + /** - * Handles the XPath function contains. - * - * This method handles the XPath function contains. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_contains ( $node, $arguments ) - { + * Handles the XPath function contains. + * + * This method handles the XPath function contains. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_contains($node, $arguments) { // Get the arguments. - $first = trim($this->prestr($arguments, ",")); + $first = trim($this->prestr($arguments, ",")); $second = trim($this->afterstr($arguments, ",")); - + // Evaluate each argument. - $first = $this->evaluate_predicate($node, $first); + $first = $this->evaluate_predicate($node, $first); $second = $this->evaluate_predicate($node, $second); - + // Check whether the first string starts with the second one. //if ( ereg($second, $first) ) //if ( preg_match($second, $first) ) - if ( preg_match("/^".$second."/", $first) ) - { + if (preg_match("/^" . $second . "/", $first)) { // Return true. return true; - } - else - { + } else { // Return false. return false; } } - + /** - * Handles the XPath function substring-before. - * - * This method handles the XPath function substring-before. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_substring_before ( $node, $arguments ) - { + * Handles the XPath function substring-before. + * + * This method handles the XPath function substring-before. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_substring_before($node, $arguments) { // Get the arguments. - $first = trim($this->prestr($arguments, ",")); + $first = trim($this->prestr($arguments, ",")); $second = trim($this->afterstr($arguments, ",")); - + // Evaluate each argument. - $first = $this->evaluate_predicate($node, $first); + $first = $this->evaluate_predicate($node, $first); $second = $this->evaluate_predicate($node, $second); - + // Return the substring. return $this->prestr(strval($first), strval($second)); } - + /** - * Handles the XPath function substring-after. - * - * This method handles the XPath function substring-after. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_substring_after ( $node, $arguments ) - { + * Handles the XPath function substring-after. + * + * This method handles the XPath function substring-after. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_substring_after($node, $arguments) { // Get the arguments. - $first = trim($this->prestr($arguments, ",")); + $first = trim($this->prestr($arguments, ",")); $second = trim($this->afterstr($arguments, ",")); - + // Evaluate each argument. - $first = $this->evaluate_predicate($node, $first); + $first = $this->evaluate_predicate($node, $first); $second = $this->evaluate_predicate($node, $second); - + // Return the substring. return $this->afterstr(strval($first), strval($second)); } - + /** - * Handles the XPath function substring. - * - * This method handles the XPath function substring. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_substring ( $node, $arguments ) - { + * Handles the XPath function substring. + * + * This method handles the XPath function substring. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_substring($node, $arguments) { // Split the arguments. $arguments = explode(",", $arguments); - + // Run through all arguments. - for ( $i = 0; $i < sizeof($arguments); $i++ ) - { + for ($i = 0; $i < sizeof($arguments); $i++) { // Trim the string. $arguments[$i] = trim($arguments[$i]); - + // Evaluate each argument. $arguments[$i] = $this->evaluate_predicate($node, $arguments[$i]); } - + // Check whether a third argument was given. - if ( !empty($arguments[2]) ) - { + if (!empty($arguments[2])) { // Return the substring. - return substr(strval($arguments[0]), $arguments[1] - 1, - $arguments[2]); - } - else - { + return substr(strval($arguments[0]), $arguments[1] - 1, $arguments[2]); + } else { // Return the substring. return substr(strval($arguments[0]), $arguments[1] - 1); } } - + /** - * Handles the XPath function string-length. - * - * This method handles the XPath function string-length. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_string_length ( $node, $arguments ) - { + * Handles the XPath function string-length. + * + * This method handles the XPath function string-length. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_string_length($node, $arguments) { // Trim the argument. $arguments = trim($arguments); - + // Evaluate the argument. $arguments = $this->evaluate_predicate($node, $arguments); - + // Return the length of the string. return strlen(strval($arguments)); } - + /** - * Handles the XPath function translate. - * - * This method handles the XPath function translate. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_translate ( $node, $arguments ) - { + * Handles the XPath function translate. + * + * This method handles the XPath function translate. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_translate($node, $arguments) { // Split the arguments. $arguments = explode(",", $arguments); - + // Run through all arguments. - for ( $i = 0; $i < sizeof($arguments); $i++ ) - { + for ($i = 0; $i < sizeof($arguments); $i++) { // Trim the argument. $arguments[$i] = trim($arguments[$i]); - + // Evaluate the argument. $arguments[$i] = $this->evaluate_predicate($node, $arguments[$i]); } - + // Return the translated string. return strtr($arguments[0], $arguments[1], $arguments[2]); } - + /** - * Handles the XPath function boolean. - * - * This method handles the XPath function boolean. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_boolean ( $node, $arguments ) - { + * Handles the XPath function boolean. + * + * This method handles the XPath function boolean. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_boolean($node, $arguments) { // Trim the arguments. $arguments = trim($arguments); - + // Check what type of parameter is given //if ( ereg("^[0-9]+(\.[0-9]+)?$", $arguments) || ereg("^\.[0-9]+$", $arguments) ) //if ( preg_match("^[0-9]+(\.[0-9]+)?$", $arguments) || preg_match("^\.[0-9]+$", $arguments) ) - if ( preg_match("/^[0-9]+(\.[0-9]+)?$/", $arguments) || preg_match("/^\.[0-9]+$/", $arguments) ) - { + if (preg_match("/^[0-9]+(\.[0-9]+)?$/", $arguments) || preg_match("/^\.[0-9]+$/", $arguments)) { // Convert the digits to a number. $number = doubleval($arguments); - + // Check whether the number zero. - if ( $number == 0 ) - { + if ($number == 0) { // Return false. return false; - } - else - { + } else { // Return true. return true; } - } - elseif ( empty($arguments) ) - { + } elseif (empty($arguments)) { // Sorry, there were no arguments. return false; - } - else - { + } else { // Try to evaluate the argument as an XPath. $result = $this->evaluate($arguments, $node); - + // Check whether we found something. - if ( count($result) > 0 ) - { + if (count($result) > 0) { // Return true. return true; - } - else - { + } else { // Return false. return false; } } } - + /** - * Handles the XPath function not. - * - * This method handles the XPath function not. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_not ( $node, $arguments ) - { + * Handles the XPath function not. + * + * This method handles the XPath function not. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_not($node, $arguments) { // Trim the arguments. $arguments = trim($arguments); - + // Return the negative value of the content of the brackets. return !$this->evaluate_predicate($node, $arguments); } - + /** - * Handles the XPath function true. - * - * This method handles the XPath function true. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_true ( $node, $arguments ) - { + * Handles the XPath function true. + * + * This method handles the XPath function true. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_true($node, $arguments) { // Return true. return true; } - + /** - * Handles the XPath function false. - * - * This method handles the XPath function false. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_false ( $node, $arguments ) - { + * Handles the XPath function false. + * + * This method handles the XPath function false. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_false($node, $arguments) { // Return false. return false; } - + /** - * Handles the XPath function lang. - * - * This method handles the XPath function lang. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_lang ( $node, $arguments ) - { + * Handles the XPath function lang. + * + * This method handles the XPath function lang. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_lang($node, $arguments) { // Trim the arguments. $arguments = trim($arguments); - + // Check whether the node has an language attribute. - if ( empty($this->nodes[$node]["attributes"]["xml:lang"]) ) - { + if (empty($this->nodes[$node]["attributes"]["xml:lang"])) { // Run through the ancestors. - while ( !empty($node) ) - { + while (!empty($node)) { // Select the parent node. $node = $this->nodes[$node]["parent"]; - + // Check whether there's a language definition. - if ( !empty($this->nodes[$node]["attributes"]["xml:lang"]) ) - { + if (!empty($this->nodes[$node]["attributes"]["xml:lang"])) { // Check whether it's the language, the user asks for. //if ( eregi("^".$arguments, $this->nodes[$node] // ["attributes"]["xml:lang"]) ) //if ( preg_match("^/i".$arguments, $this->nodes[$node] - if ( preg_match("/^".$arguments."/i", $this->nodes[$node] - ["attributes"]["xml:lang"]) ) - { + if (preg_match("/^" . $arguments . "/i", $this->nodes[$node] + ["attributes"]["xml:lang"])) { // Return true. return true; - } - else - { + } else { // Return false. return false; } } } - + // Return false. return false; - } - else - { + } else { // Check whether it's the language, the user asks for. //if ( eregi("^".$arguments, $this->nodes[$node]["attributes"] // ["xml:lang"]) ) //if ( preg_match("^/i".$arguments, $this->nodes[$node]["attributes"] - if ( preg_match("/^".$arguments."/i", $this->nodes[$node]["attributes"] - ["xml:lang"]) ) - { + if (preg_match("/^" . $arguments . "/i", $this->nodes[$node]["attributes"] + ["xml:lang"])) { // Return true. return true; - } - else - { + } else { // Return false. return false; } } } - + /** - * Handles the XPath function number. - * - * This method handles the XPath function number. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_number ( $node, $arguments ) - { + * Handles the XPath function number. + * + * This method handles the XPath function number. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_number($node, $arguments) { // Check the type of argument. //if ( ereg("^[0-9]+(\.[0-9]+)?$", $arguments) || // ereg("^\.[0-9]+$", $arguments) ) //if ( preg_match("^[0-9]+(\.[0-9]+)?$", $arguments) || preg_match("^\.[0-9]+$", $arguments) ) - if ( preg_match("/^[0-9]+(\.[0-9]+)?$/", $arguments) || preg_match("/^\.[0-9]+$/", $arguments) ) - { + if (preg_match("/^[0-9]+(\.[0-9]+)?$/", $arguments) || preg_match("/^\.[0-9]+$/", $arguments)) { // Return the argument as a number. return doubleval($arguments); - } - elseif ( is_bool($arguments) ) - { + } elseif (is_bool($arguments)) { // Check whether it's true. - if ( $arguments == true ) - { + if ($arguments == true) { // Return 1. return 1; - } - else - { + } else { // Return 0. return 0; } } } - + /** - * Handles the XPath function sum. - * - * This method handles the XPath function sum. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_sum ( $node, $arguments ) - { + * Handles the XPath function sum. + * + * This method handles the XPath function sum. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_sum($node, $arguments) { // Trim the arguments. $arguments = trim($arguments); - + // Evaluate the arguments as an XPath expression. $results = $this->evaluate($arguments, $node); - + // Create a variable to save the sum. $sum = 0; - + // Run through all results. - foreach ( $results as $result ) - { + foreach ($results as $result) { // Get the value of the node. $result = $this->get_content($result); - + // Add it to the sum. $sum += doubleval($result); } - + // Return the sum. return $sum; } - + /** - * Handles the XPath function floor. - * - * This method handles the XPath function floor. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_floor ( $node, $arguments ) - { + * Handles the XPath function floor. + * + * This method handles the XPath function floor. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_floor($node, $arguments) { // Trim the arguments. $arguments = trim($arguments); - + // Convert the arguments to a number. $arguments = doubleval($arguments); - + // Return the result return floor($arguments); } - + /** - * Handles the XPath function ceiling. - * - * This method handles the XPath function ceiling. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_ceiling ( $node, $arguments ) - { + * Handles the XPath function ceiling. + * + * This method handles the XPath function ceiling. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_ceiling($node, $arguments) { // Trim the arguments. $arguments = trim($arguments); - + // Convert the arguments to a number. $arguments = doubleval($arguments); - + // Return the result return ceil($arguments); } - + /** - * Handles the XPath function round. - * - * This method handles the XPath function round. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_round ( $node, $arguments ) - { + * Handles the XPath function round. + * + * This method handles the XPath function round. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_round($node, $arguments) { // Trim the arguments. $arguments = trim($arguments); - + // Convert the arguments to a number. $arguments = doubleval($arguments); - + // Return the result return round($arguments); } - + /** - * Handles the XPath function text. - * - * This method handles the XPath function text. - * - * @access private - * @author Michael P. Mehl - * @param string $node Full path of the node on which the function - * should be processed. - * @param string $arguments String containing the arguments that were - * passed to the function. - * @return mixed Depending on the type of function being processed this - * method returns different types. - * @see evaluate() - */ - function handle_function_text ( $node, $arguments ) - { + * Handles the XPath function text. + * + * This method handles the XPath function text. + * + * @access private + * @author Michael P. Mehl + * @param string $node Full path of the node on which the function + * should be processed. + * @param string $arguments String containing the arguments that were + * passed to the function. + * @return mixed Depending on the type of function being processed this + * method returns different types. + * @see evaluate() + */ + function handle_function_text($node, $arguments) { // Return the character data of the node. return $this->nodes[$node]["text"]; } - + /** - * Retrieves a substring before a delimiter. - * - * This method retrieves everything from a string before a given delimiter, - * not including the delimiter. - * - * @access private - * @author Michael P. Mehl - * @param string $string String, from which the substring should be - * extracted. - * @param string $delimiter String containing the delimiter to use. - * @return string Substring from the original string before the - * delimiter. - * @see afterstr() - */ - function prestr ( $string, $delimiter ) - { + * Retrieves a substring before a delimiter. + * + * This method retrieves everything from a string before a given delimiter, + * not including the delimiter. + * + * @access private + * @author Michael P. Mehl + * @param string $string String, from which the substring should be + * extracted. + * @param string $delimiter String containing the delimiter to use. + * @return string Substring from the original string before the + * delimiter. + * @see afterstr() + */ + function prestr($string, $delimiter) { // Return the substring. - return substr($string, 0, strlen($string) - strlen(strstr($string, - "$delimiter"))); - } - - /** - * Retrieves a substring after a delimiter. - * - * This method retrieves everything from a string after a given delimiter, - * not including the delimiter. - * - * @access private - * @author Michael P. Mehl - * @param string $string String, from which the substring should be - * extracted. - * @param string $delimiter String containing the delimiter to use. - * @return string Substring from the original string after the - * delimiter. - * @see prestr() - */ - function afterstr ( $string, $delimiter ) - { - // Return the substring. - return substr($string, - strpos($string, $delimiter) + strlen($delimiter)); - } - - /** - * Displays an error message. - * - * This method displays an error messages and stops the execution of the - * script. This method is called exactly in the same way as the printf - * function. The first argument contains the message and additional - * arguments of various types may be passed to this method to be inserted - * into the message. - * - * @access private - * @author Michael P. Mehl - * @param string $message Error message to be displayed. - */ - function display_error ( $message ) - { - // Check whether more than one argument was given. - if ( func_num_args() > 1 ) - { - // Read all arguments. - $arguments = func_get_args(); - - // Create a new string for the inserting command. - $command = "\$message = sprintf(\$message, "; - - // Run through the array of arguments. - for ( $i = 1; $i < sizeof($arguments); $i++ ) - { - // Add the number of the argument to the command. - $command .= "\$arguments[".$i."], "; - } - - // Replace the last separator. - //$command = eregi_replace(", $", ");", $command); - $command = preg_replace("/, $/i", ");", $command); - - // Execute the command. - eval($command); - } - - // Display the error message. - echo "phpXML error: ".$message; - - // End the execution of this script. - exit; + return substr($string, 0, strlen($string) - strlen(strstr($string, "$delimiter"))); } - //added by ddaemiri, 2007.05.28 - //entity ϳ ִٰ !! 迭 ù° . - function get_content_fetch ( $path ) - { - $e = $this->evaluate($path); - $content = $this->get_content($e[0]); - $a = $this->get_attributes_patch( $path, "urlencode" ); - if( $a != "" ) - $content = urldecode( $content ); - return $content; - } - function get_attributes_patch ( $path, $attr ) - { - $e = $this->evaluate($path); - $a = $this->get_attributes($e[0]); - return $a[$attr]; - } + /** + * Retrieves a substring after a delimiter. + * + * This method retrieves everything from a string after a given delimiter, + * not including the delimiter. + * + * @access private + * @author Michael P. Mehl + * @param string $string String, from which the substring should be + * extracted. + * @param string $delimiter String containing the delimiter to use. + * @return string Substring from the original string after the + * delimiter. + * @see prestr() + */ + function afterstr($string, $delimiter) { + // Return the substring. + return substr($string, strpos($string, $delimiter) + strlen($delimiter)); + } + + /** + * Displays an error message. + * + * This method displays an error messages and stops the execution of the + * script. This method is called exactly in the same way as the printf + * function. The first argument contains the message and additional + * arguments of various types may be passed to this method to be inserted + * into the message. + * + * @access private + * @author Michael P. Mehl + * @param string $message Error message to be displayed. + */ + function display_error($message) { + // Check whether more than one argument was given. + if (func_num_args() > 1) { + // Read all arguments. + $arguments = func_get_args(); + + // Create a new string for the inserting command. + $command = "\$message = sprintf(\$message, "; + + // Run through the array of arguments. + for ($i = 1; $i < sizeof($arguments); $i++) { + // Add the number of the argument to the command. + $command .= "\$arguments[" . $i . "], "; + } + + // Replace the last separator. + //$command = eregi_replace(", $", ");", $command); + $command = preg_replace("/, $/i", ");", $command); + + // Execute the command. + eval($command); + } + + // Display the error message. + echo "phpXML error: " . $message; + + // End the execution of this script. + exit; + } + + //added by ddaemiri, 2007.05.28 + //entity 가 하나만 있다고 가정!! 배열의 첫번째만 가져옴. + function get_content_fetch($path) { + $e = $this->evaluate($path); + $content = $this->get_content($e[0]); + $a = $this->get_attributes_patch($path, "urlencode"); + if ($a != "") + $content = urldecode($content); + return $content; + } + + function get_attributes_patch($path, $attr) { + $e = $this->evaluate($path); + $a = $this->get_attributes($e[0]); + return $a[$attr]; + } } diff --git a/shop/inicis/libs/INIpayStdMakeSignature.php b/shop/inicis/libs/INIpayStdMakeSignature.php new file mode 100644 index 000000000..516296e34 --- /dev/null +++ b/shop/inicis/libs/INIpayStdMakeSignature.php @@ -0,0 +1,15 @@ + $SignatureUtil->makeHash($input, "sha256") + 'signature' => hash("sha256", $input) +); + +echo json_encode($output); +?> diff --git a/shop/inicis/libs/JSON.php b/shop/inicis/libs/JSON.php new file mode 100644 index 000000000..0cddbddb4 --- /dev/null +++ b/shop/inicis/libs/JSON.php @@ -0,0 +1,806 @@ + + * @author Matt Knapp + * @author Brett Stimmerman + * @copyright 2005 Michal Migurski + * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $ + * @license http://www.opensource.org/licenses/bsd-license.php + * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 + */ + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_SLICE', 1); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_STR', 2); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_ARR', 3); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_OBJ', 4); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_CMT', 5); + +/** + * Behavior switch for Services_JSON::decode() + */ +define('SERVICES_JSON_LOOSE_TYPE', 16); + +/** + * Behavior switch for Services_JSON::decode() + */ +define('SERVICES_JSON_SUPPRESS_ERRORS', 32); + +/** + * Converts to and from JSON format. + * + * Brief example of use: + * + * + * // create a new instance of Services_JSON + * $json = new Services_JSON(); + * + * // convert a complexe value to JSON notation, and send it to the browser + * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); + * $output = $json->encode($value); + * + * print($output); + * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] + * + * // accept incoming POST data, assumed to be in JSON notation + * $input = file_get_contents('php://input', 1000000); + * $value = $json->decode($input); + * + */ +class Services_JSON +{ + /** + * constructs a new JSON instance + * + * @param int $use object behavior flags; combine with boolean-OR + * + * possible values: + * - SERVICES_JSON_LOOSE_TYPE: loose typing. + * "{...}" syntax creates associative arrays + * instead of objects in decode(). + * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression. + * Values which can't be encoded (e.g. resources) + * appear as NULL instead of throwing errors. + * By default, a deeply-nested resource will + * bubble up with an error, so all return values + * from encode() should be checked with isError() + */ + function Services_JSON($use = 0) + { + $this->use = $use; + } + + /** + * convert a string from one UTF-16 char to one UTF-8 char + * + * Normally should be handled by mb_convert_encoding, but + * provides a slower PHP-only method for installations + * that lack the multibye string extension. + * + * @param string $utf16 UTF-16 character + * @return string UTF-8 character + * @access private + */ + function utf162utf8($utf16) + { + // oh please oh please oh please oh please oh please + if(function_exists('mb_convert_encoding')) { + return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); + } + + $bytes = (ord($utf16{0}) << 8) | ord($utf16{1}); + + switch(true) { + case ((0x7F & $bytes) == $bytes): + // this case should never be reached, because we are in ASCII range + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0x7F & $bytes); + + case (0x07FF & $bytes) == $bytes: + // return a 2-byte UTF-8 character + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0xC0 | (($bytes >> 6) & 0x1F)) + . chr(0x80 | ($bytes & 0x3F)); + + case (0xFFFF & $bytes) == $bytes: + // return a 3-byte UTF-8 character + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0xE0 | (($bytes >> 12) & 0x0F)) + . chr(0x80 | (($bytes >> 6) & 0x3F)) + . chr(0x80 | ($bytes & 0x3F)); + } + + // ignoring UTF-32 for now, sorry + return ''; + } + + /** + * convert a string from one UTF-8 char to one UTF-16 char + * + * Normally should be handled by mb_convert_encoding, but + * provides a slower PHP-only method for installations + * that lack the multibye string extension. + * + * @param string $utf8 UTF-8 character + * @return string UTF-16 character + * @access private + */ + function utf82utf16($utf8) + { + // oh please oh please oh please oh please oh please + if(function_exists('mb_convert_encoding')) { + return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); + } + + switch(strlen($utf8)) { + case 1: + // this case should never be reached, because we are in ASCII range + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return $utf8; + + case 2: + // return a UTF-16 character from a 2-byte UTF-8 char + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0x07 & (ord($utf8{0}) >> 2)) + . chr((0xC0 & (ord($utf8{0}) << 6)) + | (0x3F & ord($utf8{1}))); + + case 3: + // return a UTF-16 character from a 3-byte UTF-8 char + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr((0xF0 & (ord($utf8{0}) << 4)) + | (0x0F & (ord($utf8{1}) >> 2))) + . chr((0xC0 & (ord($utf8{1}) << 6)) + | (0x7F & ord($utf8{2}))); + } + + // ignoring UTF-32 for now, sorry + return ''; + } + + /** + * encodes an arbitrary variable into JSON format + * + * @param mixed $var any number, boolean, string, array, or object to be encoded. + * see argument 1 to Services_JSON() above for array-parsing behavior. + * if var is a strng, note that encode() always expects it + * to be in ASCII or UTF-8 format! + * + * @return mixed JSON string representation of input var or an error if a problem occurs + * @access public + */ + function encode($var) + { + switch (gettype($var)) { + case 'boolean': + return $var ? 'true' : 'false'; + + case 'NULL': + return 'null'; + + case 'integer': + return (int) $var; + + case 'double': + case 'float': + return (float) $var; + + case 'string': + // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT + $ascii = ''; + $strlen_var = strlen($var); + + /* + * Iterate over every character in the string, + * escaping with a slash or encoding to UTF-8 where necessary + */ + for ($c = 0; $c < $strlen_var; ++$c) { + + $ord_var_c = ord($var{$c}); + + switch (true) { + case $ord_var_c == 0x08: + $ascii .= '\b'; + break; + case $ord_var_c == 0x09: + $ascii .= '\t'; + break; + case $ord_var_c == 0x0A: + $ascii .= '\n'; + break; + case $ord_var_c == 0x0C: + $ascii .= '\f'; + break; + case $ord_var_c == 0x0D: + $ascii .= '\r'; + break; + + case $ord_var_c == 0x22: + case $ord_var_c == 0x2F: + case $ord_var_c == 0x5C: + // double quote, slash, slosh + $ascii .= '\\'.$var{$c}; + break; + + case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): + // characters U-00000000 - U-0000007F (same as ASCII) + $ascii .= $var{$c}; + break; + + case (($ord_var_c & 0xE0) == 0xC0): + // characters U-00000080 - U-000007FF, mask 110XXXXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, ord($var{$c + 1})); + $c += 1; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xF0) == 0xE0): + // characters U-00000800 - U-0000FFFF, mask 1110XXXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2})); + $c += 2; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xF8) == 0xF0): + // characters U-00010000 - U-001FFFFF, mask 11110XXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2}), + ord($var{$c + 3})); + $c += 3; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xFC) == 0xF8): + // characters U-00200000 - U-03FFFFFF, mask 111110XX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2}), + ord($var{$c + 3}), + ord($var{$c + 4})); + $c += 4; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xFE) == 0xFC): + // characters U-04000000 - U-7FFFFFFF, mask 1111110X + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2}), + ord($var{$c + 3}), + ord($var{$c + 4}), + ord($var{$c + 5})); + $c += 5; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + } + } + + return '"'.$ascii.'"'; + + case 'array': + /* + * As per JSON spec if any array key is not an integer + * we must treat the the whole array as an object. We + * also try to catch a sparsely populated associative + * array with numeric keys here because some JS engines + * will create an array with empty indexes up to + * max_index which can cause memory issues and because + * the keys, which may be relevant, will be remapped + * otherwise. + * + * As per the ECMA and JSON specification an object may + * have any string as a property. Unfortunately due to + * a hole in the ECMA specification if the key is a + * ECMA reserved word or starts with a digit the + * parameter is only accessible using ECMAScript's + * bracket notation. + */ + + // treat as a JSON object + if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { + $properties = array_map(array($this, 'name_value'), + array_keys($var), + array_values($var)); + + foreach($properties as $property) { + if(Services_JSON::isError($property)) { + return $property; + } + } + + return '{' . join(',', $properties) . '}'; + } + + // treat it like a regular array + $elements = array_map(array($this, 'encode'), $var); + + foreach($elements as $element) { + if(Services_JSON::isError($element)) { + return $element; + } + } + + return '[' . join(',', $elements) . ']'; + + case 'object': + $vars = get_object_vars($var); + + $properties = array_map(array($this, 'name_value'), + array_keys($vars), + array_values($vars)); + + foreach($properties as $property) { + if(Services_JSON::isError($property)) { + return $property; + } + } + + return '{' . join(',', $properties) . '}'; + + default: + return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS) + ? 'null' + : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string"); + } + } + + /** + * array-walking function for use in generating JSON-formatted name-value pairs + * + * @param string $name name of key to use + * @param mixed $value reference to an array element to be encoded + * + * @return string JSON-formatted name-value pair, like '"name":value' + * @access private + */ + function name_value($name, $value) + { + $encoded_value = $this->encode($value); + + if(Services_JSON::isError($encoded_value)) { + return $encoded_value; + } + + return $this->encode(strval($name)) . ':' . $encoded_value; + } + + /** + * reduce a string by removing leading and trailing comments and whitespace + * + * @param $str string string value to strip of comments and whitespace + * + * @return string string value stripped of comments and whitespace + * @access private + */ + function reduce_string($str) + { + $str = preg_replace(array( + + // eliminate single line comments in '// ...' form + '#^\s*//(.+)$#m', + + // eliminate multi-line comments in '/* ... */' form, at start of string + '#^\s*/\*(.+)\*/#Us', + + // eliminate multi-line comments in '/* ... */' form, at end of string + '#/\*(.+)\*/\s*$#Us' + + ), '', $str); + + // eliminate extraneous space + return trim($str); + } + + /** + * decodes a JSON string into appropriate variable + * + * @param string $str JSON-formatted string + * + * @return mixed number, boolean, string, array, or object + * corresponding to given JSON input string. + * See argument 1 to Services_JSON() above for object-output behavior. + * Note that decode() always returns strings + * in ASCII or UTF-8 format! + * @access public + */ + function decode($str) + { + $str = $this->reduce_string($str); + + switch (strtolower($str)) { + case 'true': + return true; + + case 'false': + return false; + + case 'null': + return null; + + default: + $m = array(); + + if (is_numeric($str)) { + // Lookie-loo, it's a number + + // This would work on its own, but I'm trying to be + // good about returning integers where appropriate: + // return (float)$str; + + // Return float or int, as appropriate + return ((float)$str == (integer)$str) + ? (integer)$str + : (float)$str; + + } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) { + // STRINGS RETURNED IN UTF-8 FORMAT + $delim = substr($str, 0, 1); + $chrs = substr($str, 1, -1); + $utf8 = ''; + $strlen_chrs = strlen($chrs); + + for ($c = 0; $c < $strlen_chrs; ++$c) { + + $substr_chrs_c_2 = substr($chrs, $c, 2); + $ord_chrs_c = ord($chrs{$c}); + + switch (true) { + case $substr_chrs_c_2 == '\b': + $utf8 .= chr(0x08); + ++$c; + break; + case $substr_chrs_c_2 == '\t': + $utf8 .= chr(0x09); + ++$c; + break; + case $substr_chrs_c_2 == '\n': + $utf8 .= chr(0x0A); + ++$c; + break; + case $substr_chrs_c_2 == '\f': + $utf8 .= chr(0x0C); + ++$c; + break; + case $substr_chrs_c_2 == '\r': + $utf8 .= chr(0x0D); + ++$c; + break; + + case $substr_chrs_c_2 == '\\"': + case $substr_chrs_c_2 == '\\\'': + case $substr_chrs_c_2 == '\\\\': + case $substr_chrs_c_2 == '\\/': + if (($delim == '"' && $substr_chrs_c_2 != '\\\'') || + ($delim == "'" && $substr_chrs_c_2 != '\\"')) { + $utf8 .= $chrs{++$c}; + } + break; + + case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)): + // single, escaped unicode character + $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2))) + . chr(hexdec(substr($chrs, ($c + 4), 2))); + $utf8 .= $this->utf162utf8($utf16); + $c += 5; + break; + + case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F): + $utf8 .= $chrs{$c}; + break; + + case ($ord_chrs_c & 0xE0) == 0xC0: + // characters U-00000080 - U-000007FF, mask 110XXXXX + //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 2); + ++$c; + break; + + case ($ord_chrs_c & 0xF0) == 0xE0: + // characters U-00000800 - U-0000FFFF, mask 1110XXXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 3); + $c += 2; + break; + + case ($ord_chrs_c & 0xF8) == 0xF0: + // characters U-00010000 - U-001FFFFF, mask 11110XXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 4); + $c += 3; + break; + + case ($ord_chrs_c & 0xFC) == 0xF8: + // characters U-00200000 - U-03FFFFFF, mask 111110XX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 5); + $c += 4; + break; + + case ($ord_chrs_c & 0xFE) == 0xFC: + // characters U-04000000 - U-7FFFFFFF, mask 1111110X + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 6); + $c += 5; + break; + + } + + } + + return $utf8; + + } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) { + // array, or object notation + + if ($str{0} == '[') { + $stk = array(SERVICES_JSON_IN_ARR); + $arr = array(); + } else { + if ($this->use & SERVICES_JSON_LOOSE_TYPE) { + $stk = array(SERVICES_JSON_IN_OBJ); + $obj = array(); + } else { + $stk = array(SERVICES_JSON_IN_OBJ); + $obj = new stdClass(); + } + } + + array_push($stk, array('what' => SERVICES_JSON_SLICE, + 'where' => 0, + 'delim' => false)); + + $chrs = substr($str, 1, -1); + $chrs = $this->reduce_string($chrs); + + if ($chrs == '') { + if (reset($stk) == SERVICES_JSON_IN_ARR) { + return $arr; + + } else { + return $obj; + + } + } + + //print("\nparsing {$chrs}\n"); + + $strlen_chrs = strlen($chrs); + + for ($c = 0; $c <= $strlen_chrs; ++$c) { + + $top = end($stk); + $substr_chrs_c_2 = substr($chrs, $c, 2); + + if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) { + // found a comma that is not inside a string, array, etc., + // OR we've reached the end of the character list + $slice = substr($chrs, $top['where'], ($c - $top['where'])); + array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false)); + //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + if (reset($stk) == SERVICES_JSON_IN_ARR) { + // we are in an array, so just push an element onto the stack + array_push($arr, $this->decode($slice)); + + } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { + // we are in an object, so figure + // out the property name and set an + // element in an associative array, + // for now + $parts = array(); + + if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { + // "name":value pair + $key = $this->decode($parts[1]); + $val = $this->decode($parts[2]); + + if ($this->use & SERVICES_JSON_LOOSE_TYPE) { + $obj[$key] = $val; + } else { + $obj->$key = $val; + } + } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { + // name:value pair, where name is unquoted + $key = $parts[1]; + $val = $this->decode($parts[2]); + + if ($this->use & SERVICES_JSON_LOOSE_TYPE) { + $obj[$key] = $val; + } else { + $obj->$key = $val; + } + } + + } + + } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) { + // found a quote, and we are not inside a string + array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c})); + //print("Found start of string at {$c}\n"); + + } elseif (($chrs{$c} == $top['delim']) && + ($top['what'] == SERVICES_JSON_IN_STR) && + ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) { + // found a quote, we're in a string, and it's not escaped + // we know that it's not escaped becase there is _not_ an + // odd number of backslashes at the end of the string so far + array_pop($stk); + //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n"); + + } elseif (($chrs{$c} == '[') && + in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { + // found a left-bracket, and we are in an array, object, or slice + array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false)); + //print("Found start of array at {$c}\n"); + + } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) { + // found a right-bracket, and we're in an array + array_pop($stk); + //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + } elseif (($chrs{$c} == '{') && + in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { + // found a left-brace, and we are in an array, object, or slice + array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false)); + //print("Found start of object at {$c}\n"); + + } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) { + // found a right-brace, and we're in an object + array_pop($stk); + //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + } elseif (($substr_chrs_c_2 == '/*') && + in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { + // found a comment start, and we are in an array, object, or slice + array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false)); + $c++; + //print("Found start of comment at {$c}\n"); + + } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) { + // found a comment end, and we're in one now + array_pop($stk); + $c++; + + for ($i = $top['where']; $i <= $c; ++$i) + $chrs = substr_replace($chrs, ' ', $i, 1); + + //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + } + + } + + if (reset($stk) == SERVICES_JSON_IN_ARR) { + return $arr; + + } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { + return $obj; + + } + + } + } + } + + /** + * @todo Ultimately, this should just call PEAR::isError() + */ + function isError($data, $code = null) + { + if (class_exists('pear')) { + return PEAR::isError($data, $code); + } elseif (is_object($data) && (get_class($data) == 'services_json_error' || + is_subclass_of($data, 'services_json_error'))) { + return true; + } + + return false; + } +} + +if (class_exists('PEAR_Error')) { + + class Services_JSON_Error extends PEAR_Error + { + function Services_JSON_Error($message = 'unknown error', $code = null, + $mode = null, $options = null, $userinfo = null) + { + parent::PEAR_Error($message, $code, $mode, $options, $userinfo); + } + } + +} else { + + /** + * @todo Ultimately, this class shall be descended from PEAR_Error + */ + class Services_JSON_Error + { + function Services_JSON_Error($message = 'unknown error', $code = null, + $mode = null, $options = null, $userinfo = null) + { + + } + } + +} + +?> diff --git a/shop/inicis/libs/json_lib.php b/shop/inicis/libs/json_lib.php new file mode 100644 index 000000000..5e34a6610 --- /dev/null +++ b/shop/inicis/libs/json_lib.php @@ -0,0 +1,30 @@ +decode($content); + } +} + +if (!function_exists('json_encode')) { + function json_encode($content) { + require_once 'JSON.php'; + $json = new Services_JSON; + return $json->encode($content); + } +} + +?> \ No newline at end of file diff --git a/shop/inicis/libs/sha256.inc.php b/shop/inicis/libs/sha256.inc.php new file mode 100644 index 000000000..3d9859208 --- /dev/null +++ b/shop/inicis/libs/sha256.inc.php @@ -0,0 +1,414 @@ +. + * + * Include: + * + * require_once("[path/]sha256.inc.php"); + * + * Usage Options: + * + * 1) $shaStr = hash('sha256', $string_to_hash); + * + * 2) $shaStr = sha256($string_to_hash[, bool ignore_php5_hash = false]); + * + * 3) $obj = new nanoSha2([bool $upper_case_output = false]); + * $shaStr = $obj->hash($string_to_hash[, bool $ignore_php5_hash = false]); + * + * Reference: http://csrc.nist.gov/groups/ST/toolkit/secure_hashing.html + * + * 2007-12-13: Cleaned up for initial public release + * 2008-05-10: Moved all helper functions into a class. API access unchanged. + * 2009-06-23: Created abstraction of hash() routine + * 2009-07-23: Added detection of 32 vs 64bit platform, and patches. + * Ability to define "_NANO_SHA2_UPPER" to yeild upper case hashes. + * 2009-08-01: Added ability to attempt to use mhash() prior to running pure + * php code. + * + * NOTE: Some sporadic versions of PHP do not handle integer overflows the + * same as the majority of builds. If you get hash results of: + * 7fffffff7fffffff7fffffff7fffffff7fffffff7fffffff7fffffff7fffffff + * + * If you do not have permissions to change PHP versions (if you did + * you'd probably upgrade to PHP 5 anyway) it is advised you install a + * module that will allow you to use their hashing routines, examples are: + * - mhash module : http://ca3.php.net/mhash + * - Suhosin : http://www.hardened-php.net/suhosin/ + * + * If you install the Suhosin module, this script will transparently + * use their routine and define the PHP routine as _nano_sha256(). + * + * If the mhash module is present, and $ignore_php5_hash = false the + * script will attempt to use the output from mhash prior to running + * the PHP code. + */ +if (!class_exists('nanoSha2')) +{ + class nanoSha2 + { + // php 4 - 5 compatable class properties + var $toUpper; + var $platform; + + // Php 4 - 6 compatable constructor + function nanoSha2($toUpper = false) { + // Determine if the caller wants upper case or not. + $this->toUpper = is_bool($toUpper) + ? $toUpper + : ((defined('_NANO_SHA2_UPPER')) ? true : false); + + // Deteremine if the system is 32 or 64 bit. + $tmpInt = (int)4294967295; + $this->platform = ($tmpInt > 0) ? 64 : 32; + } + + // Do the SHA-256 Padding routine (make input a multiple of 512 bits) + function char_pad($str) + { + $tmpStr = $str; + + $l = strlen($tmpStr)*8; // # of bits from input string + + $tmpStr .= "\x80"; // append the "1" bit followed by 7 0's + + $k = (512 - (($l + 8 + 64) % 512)) / 8; // # of 0 bytes to append + $k += 4; // PHP Strings will never exceed (2^31)-1, 1st 32bits of + // the 64-bit value representing $l can be all 0's + + for ($x = 0; $x < $k; $x++) { + $tmpStr .= "\0"; + } + + // append the 32-bits representing # of bits from input string ($l) + $tmpStr .= chr((($l>>24) & 0xFF)); + $tmpStr .= chr((($l>>16) & 0xFF)); + $tmpStr .= chr((($l>>8) & 0xFF)); + $tmpStr .= chr(($l & 0xFF)); + + return $tmpStr; + } + + // Here are the bitwise and functions as defined in FIPS180-2 Standard + function addmod2n($x, $y, $n = 4294967296) // Z = (X + Y) mod 2^32 + { + $mask = 0x80000000; + + if ($x < 0) { + $x &= 0x7FFFFFFF; + $x = (float)$x + $mask; + } + + if ($y < 0) { + $y &= 0x7FFFFFFF; + $y = (float)$y + $mask; + } + + $r = $x + $y; + + if ($r >= $n) { + while ($r >= $n) { + $r -= $n; + } + } + + return (int)$r; + } + + // Logical bitwise right shift (PHP default is arithmetic shift) + function SHR($x, $n) // x >> n + { + if ($n >= 32) { // impose some limits to keep it 32-bit + return (int)0; + } + + if ($n <= 0) { + return (int)$x; + } + + $mask = 0x40000000; + + if ($x < 0) { + $x &= 0x7FFFFFFF; + $mask = $mask >> ($n-1); + return ($x >> $n) | $mask; + } + + return (int)$x >> (int)$n; + } + + function ROTR($x, $n) { return (int)(($this->SHR($x, $n) | ($x << (32-$n)) & 0xFFFFFFFF)); } + function Ch($x, $y, $z) { return ($x & $y) ^ ((~$x) & $z); } + function Maj($x, $y, $z) { return ($x & $y) ^ ($x & $z) ^ ($y & $z); } + function Sigma0($x) { return (int) ($this->ROTR($x, 2)^$this->ROTR($x, 13)^$this->ROTR($x, 22)); } + function Sigma1($x) { return (int) ($this->ROTR($x, 6)^$this->ROTR($x, 11)^$this->ROTR($x, 25)); } + function sigma_0($x) { return (int) ($this->ROTR($x, 7)^$this->ROTR($x, 18)^$this->SHR($x, 3)); } + function sigma_1($x) { return (int) ($this->ROTR($x, 17)^$this->ROTR($x, 19)^$this->SHR($x, 10)); } + + /* + * Custom functions to provide PHP support + */ + // split a byte-string into integer array values + function int_split($input) + { + $l = strlen($input); + + if ($l <= 0) { + return (int)0; + } + + if (($l % 4) != 0) { // invalid input + return false; + } + + for ($i = 0; $i < $l; $i += 4) + { + $int_build = (ord($input[$i]) << 24); + $int_build += (ord($input[$i+1]) << 16); + $int_build += (ord($input[$i+2]) << 8); + $int_build += (ord($input[$i+3])); + + $result[] = $int_build; + } + + return $result; + } + + /** + * Process and return the hash. + * + * @param $str Input string to hash + * @param $ig_func Option param to ignore checking for php > 5.1.2 + * @return string Hexadecimal representation of the message digest + */ + function hash($str, $ig_func = false) + { + unset($binStr); // binary representation of input string + unset($hexStr); // 256-bit message digest in readable hex format + + // check for php's internal sha256 function, ignore if ig_func==true + if ($ig_func == false) { + if (version_compare(PHP_VERSION,'5.1.2','>=')) { + return hash("sha256", $str, false); + } else if (function_exists('mhash') && defined('MHASH_SHA256')) { + return base64_encode(bin2hex(mhash(MHASH_SHA256, $str))); + } + } + + /* + * SHA-256 Constants + * Sequence of sixty-four constant 32-bit words representing the + * first thirty-two bits of the fractional parts of the cube roots + * of the first sixtyfour prime numbers. + */ + $K = array((int)0x428a2f98, (int)0x71374491, (int)0xb5c0fbcf, + (int)0xe9b5dba5, (int)0x3956c25b, (int)0x59f111f1, + (int)0x923f82a4, (int)0xab1c5ed5, (int)0xd807aa98, + (int)0x12835b01, (int)0x243185be, (int)0x550c7dc3, + (int)0x72be5d74, (int)0x80deb1fe, (int)0x9bdc06a7, + (int)0xc19bf174, (int)0xe49b69c1, (int)0xefbe4786, + (int)0x0fc19dc6, (int)0x240ca1cc, (int)0x2de92c6f, + (int)0x4a7484aa, (int)0x5cb0a9dc, (int)0x76f988da, + (int)0x983e5152, (int)0xa831c66d, (int)0xb00327c8, + (int)0xbf597fc7, (int)0xc6e00bf3, (int)0xd5a79147, + (int)0x06ca6351, (int)0x14292967, (int)0x27b70a85, + (int)0x2e1b2138, (int)0x4d2c6dfc, (int)0x53380d13, + (int)0x650a7354, (int)0x766a0abb, (int)0x81c2c92e, + (int)0x92722c85, (int)0xa2bfe8a1, (int)0xa81a664b, + (int)0xc24b8b70, (int)0xc76c51a3, (int)0xd192e819, + (int)0xd6990624, (int)0xf40e3585, (int)0x106aa070, + (int)0x19a4c116, (int)0x1e376c08, (int)0x2748774c, + (int)0x34b0bcb5, (int)0x391c0cb3, (int)0x4ed8aa4a, + (int)0x5b9cca4f, (int)0x682e6ff3, (int)0x748f82ee, + (int)0x78a5636f, (int)0x84c87814, (int)0x8cc70208, + (int)0x90befffa, (int)0xa4506ceb, (int)0xbef9a3f7, + (int)0xc67178f2); + + // Pre-processing: Padding the string + $binStr = $this->char_pad($str); + + // Parsing the Padded Message (Break into N 512-bit blocks) + $M = str_split($binStr, 64); + + // Set the initial hash values + $h[0] = (int)0x6a09e667; + $h[1] = (int)0xbb67ae85; + $h[2] = (int)0x3c6ef372; + $h[3] = (int)0xa54ff53a; + $h[4] = (int)0x510e527f; + $h[5] = (int)0x9b05688c; + $h[6] = (int)0x1f83d9ab; + $h[7] = (int)0x5be0cd19; + + // loop through message blocks and compute hash. ( For i=1 to N : ) + $N = count($M); + for ($i = 0; $i < $N; $i++) + { + // Break input block into 16 32bit words (message schedule prep) + $MI = $this->int_split($M[$i]); + + // Initialize working variables + $_a = (int)$h[0]; + $_b = (int)$h[1]; + $_c = (int)$h[2]; + $_d = (int)$h[3]; + $_e = (int)$h[4]; + $_f = (int)$h[5]; + $_g = (int)$h[6]; + $_h = (int)$h[7]; + unset($_s0); + unset($_s1); + unset($_T1); + unset($_T2); + $W = array(); + + // Compute the hash and update + for ($t = 0; $t < 16; $t++) + { + // Prepare the first 16 message schedule values as we loop + $W[$t] = $MI[$t]; + + // Compute hash + $_T1 = $this->addmod2n($this->addmod2n($this->addmod2n($this->addmod2n($_h, $this->Sigma1($_e)), $this->Ch($_e, $_f, $_g)), $K[$t]), $W[$t]); + $_T2 = $this->addmod2n($this->Sigma0($_a), $this->Maj($_a, $_b, $_c)); + + // Update working variables + $_h = $_g; $_g = $_f; $_f = $_e; $_e = $this->addmod2n($_d, $_T1); + $_d = $_c; $_c = $_b; $_b = $_a; $_a = $this->addmod2n($_T1, $_T2); + } + + for (; $t < 64; $t++) + { + // Continue building the message schedule as we loop + $_s0 = $W[($t+1)&0x0F]; + $_s0 = $this->sigma_0($_s0); + $_s1 = $W[($t+14)&0x0F]; + $_s1 = $this->sigma_1($_s1); + + $W[$t&0xF] = $this->addmod2n($this->addmod2n($this->addmod2n($W[$t&0xF], $_s0), $_s1), $W[($t+9)&0x0F]); + + // Compute hash + $_T1 = $this->addmod2n($this->addmod2n($this->addmod2n($this->addmod2n($_h, $this->Sigma1($_e)), $this->Ch($_e, $_f, $_g)), $K[$t]), $W[$t&0xF]); + $_T2 = $this->addmod2n($this->Sigma0($_a), $this->Maj($_a, $_b, $_c)); + + // Update working variables + $_h = $_g; $_g = $_f; $_f = $_e; $_e = $this->addmod2n($_d, $_T1); + $_d = $_c; $_c = $_b; $_b = $_a; $_a = $this->addmod2n($_T1, $_T2); + } + + $h[0] = $this->addmod2n($h[0], $_a); + $h[1] = $this->addmod2n($h[1], $_b); + $h[2] = $this->addmod2n($h[2], $_c); + $h[3] = $this->addmod2n($h[3], $_d); + $h[4] = $this->addmod2n($h[4], $_e); + $h[5] = $this->addmod2n($h[5], $_f); + $h[6] = $this->addmod2n($h[6], $_g); + $h[7] = $this->addmod2n($h[7], $_h); + } + + // Convert the 32-bit words into human readable hexadecimal format. + $hexStr = sprintf("%08x%08x%08x%08x%08x%08x%08x%08x", $h[0], $h[1], $h[2], $h[3], $h[4], $h[5], $h[6], $h[7]); + + return ($this->toUpper) ? strtoupper($hexStr) : $hexStr; + } + + } +} + +if (!function_exists('str_split')) +{ + /** + * Splits a string into an array of strings with specified length. + * Compatability with older verions of PHP + */ + function str_split($string, $split_length = 1) + { + $sign = ($split_length < 0) ? -1 : 1; + $strlen = strlen($string); + $split_length = abs($split_length); + + if (($split_length == 0) || ($strlen == 0)) { + $result = false; + } elseif ($split_length >= $strlen) { + $result[] = $string; + } else { + $length = $split_length; + + for ($i = 0; $i < $strlen; $i++) + { + $i = (($sign < 0) ? $i + $length : $i); + $result[] = substr($string, $sign*$i, $length); + $i--; + $i = (($sign < 0) ? $i : $i + $length); + + $length = (($i + $split_length) > $strlen) + ? ($strlen - ($i + 1)) + : $split_length; + } + } + + return $result; + } +} + +/** + * Main routine called from an application using this include. + * + * General usage: + * require_once('sha256.inc.php'); + * $hashstr = sha256('abc'); + * + * Note: + * PHP Strings are limitd to (2^31)-1, so it is not worth it to + * check for input strings > 2^64 as the FIPS180-2 defines. + */ +// 2009-07-23: Added check for function as the Suhosin plugin adds this routine. +if (!function_exists('sha256')) { + function sha256($str, $ig_func = false) { + $obj = new nanoSha2((defined('_NANO_SHA2_UPPER')) ? true : false); + return $obj->hash($str, $ig_func); + } +} else { + function _nano_sha256($str, $ig_func = false) { + $obj = new nanoSha2((defined('_NANO_SHA2_UPPER')) ? true : false); + return $obj->hash($str, $ig_func); + } +} + +// support to give php4 the hash() routine which abstracts this code. +if (!function_exists('hash')) +{ + function hash($algo, $data) + { + if (empty($algo) || !is_string($algo) || !is_string($data)) { + return false; + } + + if (function_exists($algo)) { + return $algo($data); + } + } +} + +?> \ No newline at end of file diff --git a/shop/inicis/makesignature.php b/shop/inicis/makesignature.php new file mode 100644 index 000000000..90247d1ae --- /dev/null +++ b/shop/inicis/makesignature.php @@ -0,0 +1,30 @@ +'가격이 올바르지 않습니다.'))); + +// +//################################### +// 2. 가맹점 확인을 위한 signKey를 해시값으로 변경 (SHA-256방식 사용) +//################################### +$mKey = hash("sha256", $signKey); + +/* + //*** 위변조 방지체크를 signature 생성 *** + oid, price, timestamp 3개의 키와 값을 + key=value 형식으로 하여 '&'로 연결한 하여 SHA-256 Hash로 생성 된값 + ex) oid=INIpayTest_1432813606995&price=819000×tamp=2012-02-01 09:19:04.004 + * key기준 알파벳 정렬 + * timestamp는 반드시 signature생성에 사용한 timestamp 값을 timestamp input에 그대로 사용하여야함 + */ +$params = "oid=" . $orderNumber . "&price=" . $price . "×tamp=" . $timestamp; +$sign = hash("sha256", $params); + +die(json_encode(array('error'=>'', 'mKey'=>$mKey, 'timestamp'=>$timestamp, 'sign'=>$sign))); +?> \ No newline at end of file diff --git a/shop/inicis/orderform.1.php b/shop/inicis/orderform.1.php index 859b3d343..c29e8fdfd 100644 --- a/shop/inicis/orderform.1.php +++ b/shop/inicis/orderform.1.php @@ -5,20 +5,15 @@ if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가 if($default['de_iche_use'] || $default['de_vbank_use'] || $default['de_hp_use'] || $default['de_card_use'] || $default['de_easy_pay_use']) { ?> - - + - \ No newline at end of file diff --git a/shop/inicis/orderform.2.php b/shop/inicis/orderform.2.php index 81eb3b188..a41c53bc2 100644 --- a/shop/inicis/orderform.2.php +++ b/shop/inicis/orderform.2.php @@ -7,14 +7,18 @@ if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가 - - - + + + + + + + @@ -37,17 +41,7 @@ Card(0): 신용카드 지불시에 이니시스 대표 가맹점인 경우에 OCB : OK CASH BAG 가맹점으로 신용카드 결제시에 OK CASH BAG 적립을 적용하시기 원하시면 "OCB" 세팅 필요 그 외에 경우에는 삭제해야 정상적인 결제 이루어짐. no_receipt : 은행계좌이체시 현금영수증 발행여부 체크박스 비활성화 (현금영수증 발급 계약이 되어 있어야 사용가능) --> - - - - - - + - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + \ No newline at end of file diff --git a/shop/inicis/orderform.3.php b/shop/inicis/orderform.3.php index 398d4d448..e7f68b1be 100644 --- a/shop/inicis/orderform.3.php +++ b/shop/inicis/orderform.3.php @@ -1,20 +1,12 @@ - \ No newline at end of file diff --git a/shop/inicis/popup.php b/shop/inicis/popup.php new file mode 100644 index 000000000..bdef45db7 --- /dev/null +++ b/shop/inicis/popup.php @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/shop/orderform.php b/shop/orderform.php index de72fd6f2..7ba0c3d8e 100644 --- a/shop/orderform.php +++ b/shop/orderform.php @@ -29,23 +29,6 @@ $s_cart_id = $tmp_cart_id; $g5['title'] = '주문서 작성'; -// 전자결제를 사용할 때만 실행 -if(!$is_mobile_order) { - if($default['de_iche_use'] || $default['de_vbank_use'] || $default['de_hp_use'] || $default['de_card_use'] || $default['de_easy_pay_use']) { - switch($default['de_pg_service']) { - case 'lg': - $g5['body_script'] = ''; - break; - case 'inicis': - $g5['body_script'] = ' onload="javascript:enable_click()"'; - break; - default: - $g5['body_script'] = ''; - break; - } - } -} - if(G5_IS_MOBILE) include_once(G5_MSHOP_PATH.'/_head.php'); else diff --git a/shop/orderform.sub.php b/shop/orderform.sub.php index 5b5b5b5a1..d4bde5724 100644 --- a/shop/orderform.sub.php +++ b/shop/orderform.sub.php @@ -1374,20 +1374,20 @@ function forderform_check(f) switch(settle_method) { case "계좌이체": - f.gopaymethod.value = "onlydbank"; + f.gopaymethod.value = "DirectBank"; break; case "가상계좌": - f.gopaymethod.value = "onlyvbank"; + f.gopaymethod.value = "VBank"; break; case "휴대폰": - f.gopaymethod.value = "onlyhpp"; + f.gopaymethod.value = "HPP"; break; case "신용카드": - f.gopaymethod.value = "onlycard"; + f.gopaymethod.value = "Card"; f.acceptmethod.value = f.acceptmethod.value.replace(":useescrow", ""); break; case "간편결제": - f.gopaymethod.value = "onlykpay"; + f.gopaymethod.value = "Kpay"; break; default: f.gopaymethod.value = "무통장"; @@ -1439,6 +1439,11 @@ function forderform_check(f) } + f.price.value = f.good_mny.value; + + f.tax.value = f.comm_vat_mny.value; + f.taxfree.value = f.comm_free_mny.value; + f.buyername.value = f.od_name.value; f.buyeremail.value = f.od_email.value; f.buyertel.value = f.od_hp.value ? f.od_hp.value : f.od_tel.value; @@ -1448,12 +1453,31 @@ function forderform_check(f) f.recvaddr.value = f.od_b_addr1.value + " " +f.od_b_addr2.value; if(f.gopaymethod.value != "무통장") { - if(!set_encrypt_data(f)) + // 주문정보 임시저장 + var order_data = $(f).serialize(); + var save_result = ""; + $.ajax({ + type: "POST", + data: order_data, + url: g5_url+"/shop/ajax.orderdatasave.php", + cache: false, + async: false, + success: function(data) { + save_result = data; + } + }); + + if(save_result) { + alert(save_result); + return false; + } + + if(!make_signature(f)) return false; - return pay(f); + paybtn(f); } else { - return true; + f.submit(); } } diff --git a/shop/orderformupdate.php b/shop/orderformupdate.php index 93e91e847..8ef214d37 100644 --- a/shop/orderformupdate.php +++ b/shop/orderformupdate.php @@ -814,6 +814,10 @@ if($config['cf_sms_use'] && ($default['de_sms_use2'] || $default['de_sms_use3']) $uid = md5($od_id.G5_TIME_YMDHIS.$REMOTE_ADDR); set_session('ss_orderview_uid', $uid); +// 주문 정보 임시 데이터 삭제 +$sql = " delete from {$g5['g5_shop_order_data_table']} where od_id = '$od_id' and dt_pg = '$od_pg' "; +sql_query($sql); + // 주문번호제거 set_session('ss_order_id', ''); diff --git a/shop/settle_inicis.inc.php b/shop/settle_inicis.inc.php index 72fbb013d..a611f3445 100644 --- a/shop/settle_inicis.inc.php +++ b/shop/settle_inicis.inc.php @@ -1,17 +1,21 @@ SetField("inipayhome", G5_SHOP_PATH.'/inicis'); // 이니페이 홈디렉터리(상점수정 필요) -$inipay->SetField("debug", "false"); // 로그모드("true"로 설정하면 상세로그가 생성됨.) +$inipay->SetField("debug", "false"); -$inipay_nointerest = 'no'; //무이자여부(no:일반, yes:무이자) -$inipay_quotabase = '선택:일시불:2개월:3개월:4개월:5개월:6개월:7개월:8개월:9개월:10개월:11개월:12개월'; // 할부기간 +$util = new INIStdPayUtil(); + +$timestamp = $util->getTimestamp(); // util에 의해서 자동생성 + +$cardNoInterestQuota = ''; // 카드 무이자 여부 설정(가맹점에서 직접 설정) +$cardQuotaBase = '2:3:4:5:6:7:8:9:10:11:12'; // 가맹점에서 사용할 할부 개월수 설정 + +$acceptmethod = 'HPP(2):no_receipt:vbank('.date('Ymd', strtotime("+3 days", G5_SERVER_TIME)).'):below1000'.$useescrow; + +/* 기타 */ +$siteDomain = G5_SHOP_URL.'/inicis'; //가맹점 도메인 입력 +// 페이지 URL에서 고정된 부분을 적는다. +// Ex) returnURL이 http://localhost:8082/demo/INIpayStdSample/INIStdPayReturn.php 라면 +// http://localhost:8082/demo/INIpayStdSample 까지만 기입한다. + +$returnUrl = $siteDomain.'/INIStdPayReturn.php'; +$closeUrl = $siteDomain.'/close.php'; +$popupUrl = $siteDomain.'/popup.php'; $BANK_CODE = array( '03' => '기업은행', @@ -101,11 +128,4 @@ $PAY_METHOD = array( 'HPP' => '휴대폰', 'VBank' => '가상계좌' ); - -// 플러그인 호출 URL -if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on') { - $ini_js_url = 'https://plugin.inicis.com/pay61_secunissl_cross.js'; -} else { - $ini_js_url = 'http://plugin.inicis.com/pay61_secuni_cross.js'; -} ?> \ No newline at end of file