code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
<? echo phpinfo();?> | 10npsite | trunk/Index/Lib/Order/IPSCATphp/demo/11.php | PHP | asf20 | 20 |
<?php
header("Content-type:text/html; charset=utf-8");
/****************正式环境请更换以下信息***********************/
//3DES密钥
$DESkey = 'Mv9bWA2tX1m8ocCeyiSnVK2D';
//3DES向量
$DESiv = 'aExIs4TP';
//商户的md5证书
$MD5key = 'gs14FHDIwYLwbc7bV3Y8fwQabe3MnOeOP618R0JLHa8DZwDaXKxvQILK112AnR57TX65AYj5JnReNmaF02O20JXhKGg0Xi7Q5bKcPhzZBSBDRGWp0MkKccgjazKTSJ8A';
//商户的RSA公钥
$RSAkey = '<RSAKeyValue><Modulus>72e/QDvxv8DuxCA7xqapw07jl8G++2d152Db5T8Xe99WniuLAnPnY2V4GcTwRWjHqamoKh82SFgz+Y8SuQfXP+giGItOvCoR5k0JzWaeuFXVey5CbqYnVu7+2dNFTwbnWmFNo8Bqwra8Y1SbxqSA1HhQ6cem2bRWCWklJiFqp6c=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>';
/****************获取表单信息******************************/
//商户号
$pMerCode = $_POST['pMerCode'];
//商户交易订单号
$pBillNo = $_POST['pBillNo'];
//支付币种
$pCurrency = $_POST['pCurrency'];
//语种
$pLang = $_POST['pLang'];
//订单金额(保留两位小数)
$pAmount = number_format($_POST['pAmount'], 2, '.', '');
//商户录入日期
$pDate = $_POST['pDate'];
//信用卡种类
$pGateWayType = $_POST['pGateWayType'];
//商户附加信息
$pAttach = $_POST['pAttach'];
//录入返回签名方式
$pRetEncodeType = $_POST['pRetEncodeType'];
//订单有效期
$pBillEXP = $_POST['pBillEXP'];
//支付结果返回地址
$pReturnUrl = $_POST['pReturnUrl'];
//错误返回地址
$pErrorUrl = $_POST['pErrorUrl'];
//订单加密方式(pCardInfo的加密方式)
$pOrderEncodeType = $_POST['pOrderEncodeType'];
//支付结果返回方式:0 ( HTTP方式)
$pResultType = '0';
//访问者权限
$pAuthority = $_POST['pAuthority'];
//备用
$pDetails = '';
//商品信息
$pGoodsInfo = $_POST['pGoodsInfo'];
//是否直连
$pDirect = $_POST['pDirect'];
//持卡人加密信息
$pCardInfo = '';
//pDirect=1是直连方式,pDirect为空是非直连方式
if ($_POST['pDirect'] == '1')
{
$pCardInfo = $_POST['pName'] . '|' .
$_POST['pIDType'] . '|' .
$_POST['pIDNum'] . '|' .
$_POST['pTel'] . '|' .
$_POST['pCardExp'] . '|' .
$_POST['pCardType'] . '|' .
$_POST['pCardNum'] . '|' .
$_POST['pIssueBank'] . '|' .
$_POST['pIssueCountry'] . '|' .
$_POST['pCVV'];
}
else
{
$pCardInfo = $_POST['pName'] . '|' .
$_POST['pIDType'] . '|' .
$_POST['pIDNum'] . '|' .
$_POST['pTel'];
}
//RSA加密
if ($pOrderEncodeType == '1')
{
require_once('rsa.function.php');
//读取RSA公钥中的Modulus和Exponent
$xml = new DOMDocument();
$xml->loadXML($RSAkey);
$Modulus = $xml->getElementsByTagName('Modulus')->item(0)->nodeValue;
$Exponent = $xml->getElementsByTagName('Exponent')->item(0)->nodeValue;
unset($xml);
$publicKey = kimssl_pkey_get_public($Modulus, $Exponent);
openssl_public_encrypt($pCardInfo, $pCardInfo, $publicKey);
$pCardInfo = base64_encode($pCardInfo);
openssl_free_key($publicKey);
}
//3DES加密
if ($pOrderEncodeType == '2')
{
require_once('des.class.php');
//创建3DES的对象
$DES = new DES;
//3DES密钥
$DES->key = $DESkey;
//3DES向量
$DES->iv = $DESiv;
//调用3DES的加密方法
$pCardInfo = $DES->DESEncrypt($pCardInfo);
}
//md5的source
$strMd5Temp = $pBillNo . $pMerCode . $pCurrency . $pAmount . $pDate . $MD5key;
//md5的摘要
$pSignMD5 = md5($strMd5Temp);
//提交的信用卡支付网关的url地址(正式环境请更改为:https://gw5.ips.com.cn:444/B2C/AuthTrade/Pay.aspx)
$actionUrl = 'http://payat.ips.net.cn/B2C/AuthTrade/Pay.aspx';
//pDirect=1采用webservice直连方式处理
if($pDirect == '1')
{
//参数转为数组形式传递
$strxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<OrderInfo>
<pBillNo>{$pBillNo}</pBillNo>
<pMerCode>{$pMerCode}</pMerCode>
<pCurrency>{$pCurrency}</pCurrency>
<pLang>{$pLang}</pLang>
<pAmount>{$pAmount}</pAmount>
<pDate>{$pDate}</pDate>
<pGateWayType>{$pGateWayType}</pGateWayType>
<pAttach>{$pAttach}</pAttach>
<pRetEncodeType>{$pRetEncodeType}</pRetEncodeType>
<pOrderEncodeType>{$pOrderEncodeType}</pOrderEncodeType>
<pSignMD5>{$pSignMD5}</pSignMD5>
<pBillEXP>{$pBillEXP}</pBillEXP>
<pReturnUrl>{$pReturnUrl}</pReturnUrl>
<pCardInfo>{$pCardInfo}</pCardInfo>
<pResultType>{$pResultType}</pResultType>
<pAuthority>{$pAuthority}</pAuthority>
<pDetails>{$pDetails}</pDetails>
<pGoodsInfo>{$pGoodsInfo}</pGoodsInfo>
</OrderInfo>";
if(!extension_loaded('soap'))
{
echo '请安装并加载soap扩展!';
exit;
}
//调用WebService:正式环境请更改webservice地址为https://gw5.ips.com.cn:444/B2C/AuthTrade/PaymentWService.asmx?WSDL
$objSoapClient = new SoapClient('http://payAT.ips.net.cn/B2C/AuthTrade/PaymentWService.asmx?WSDL');
$aryResult = $objSoapClient->SubmitOrder($strxml);
/**************************WebService返回处理逻辑********************************
1.判断pSucc
若 pSucc 等“S”, 表示录入成功; 若等于“F”, 表示录入失败, 此时无需再进行以下步骤。
2.数据验证
可以使用IPS 提供的签名验证组件,对返回的关键信息进行验证,以确保订单信息
安全,防止黑客恶意攻击及篡改订单信息。
3.判断订单号和金额
为安全起见,商户应该将自己系统中存放的订单信息和IPS 返回的订单信息进行比对,
以保证订单数据真实可信。建议比对的项:订单编号和订单金额。
4.在成功完成以上步骤后,商户可以根据需要进行其他操作。
*******************************************************************************/
if(!extension_loaded('dom'))
{
echo '不支持DOM!';
exit;
}
$xml = new DOMDocument();
$xml->loadXML($aryResult);
//录入结果: S-录入成功 F-录入失败
$pSucc = $xml->getElementsByTagName('pSucc')->item(0)->nodeValue;
//返回信息
$pMsg = $xml->getElementsByTagName('pMsg')->item(0)->nodeValue;
if($pSucc == 'S')
{
//商户订单号
$pBillNo = $xml->getElementsByTagName('pBillNo')->item(0)->nodeValue;
//订单金额
$pAmount = $xml->getElementsByTagName('pAmount')->item(0)->nodeValue;
//订单日期
$pDate = $xml->getElementsByTagName('pDate')->item(0)->nodeValue;
//IPS订单号
$pIpsBillNo = $xml->getElementsByTagName('pIpsBillNo')->item(0)->nodeValue;
//币种
$pCurrency = $xml->getElementsByTagName('pCurrency')->item(0)->nodeValue;
//签名
$pSignature = $xml->getElementsByTagName('pSignature')->item(0)->nodeValue;
unset($xml);
//签名原文:订单编号+订单金额+订单日期+成功标志+IPS订单编号+币种
$content = $pBillNo . $pAmount . $pDate . $pSucc . $pIpsBillNo . $pCurrency;
//签名验证是否通过
$verify = false;
//md5withrsa的签名验证方式
if($pRetEncodeType == '11')
{
//创建com组件
$MD5withRSA = new COM('IpsVerify.RSAMd5');
//使用公钥文件的绝对路径
$result = $MD5withRSA->VerifyMessage("C:\\PubKey\\pub.txt", $content, $pSignature);
/*******************
返回代码定义
0 表示签名验证成功
-1 表示系统错误
-2 表示文件绑定错误
-3 表示读取公钥失败
-4 表示签名长度错
-5 表示签名验证失败
-99 表示系统锁定失败
*******************/
if($result == 0)
{
$verify = true;
}
}
//md5摘要验证方式
if($pRetEncodeType == '12')
{
//明文=订单编号+订单金额+订单日期+成功标志+IPS订单编号+币种+商户证书
$signature_local = md5($content . $MD5key);
if($pSignature == $signature_local)
{
$verify = true;
}
}
if($verify)
{
echo '录入成功!';
exit();
}
else
{
echo '签名验证失败!';
exit();
}
}
else
{
echo "录入失败:$pMsg";
exit();
}
}
else
{
//录入成功返回地址
$pAuthSuccessUrl = $_POST['pAuthSuccessUrl'];
//录入失败返回地址
$pAuthFailureUrl = $_POST['pAuthFailureUrl'];
?>
<html>
<head>
<title>跳转......</title>
<meta http-equiv="content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form name="sendOrder" id="sendOrder" method="post" action="<?php echo $actionUrl; ?>">
<input type="hidden" name="pBillNo" value="<?php echo $pBillNo; ?>" />
<input type="hidden" name="pMerCode" value="<?php echo $pMerCode; ?>" />
<input type="hidden" name="pCurrency" value="<?php echo $pCurrency; ?>" />
<input type="hidden" name="pLang" value="<?php echo $pLang; ?>" />
<input type="hidden" name="pAmount" value="<?php echo $pAmount; ?>" />
<input type="hidden" name="pDate" value="<?php echo $pDate; ?>" />
<input type="hidden" name="pAttach" value="<?php echo $pAttach; ?>" />
<input type="hidden" name="pGateWayType" value="<?php echo $pGateWayType; ?>" />
<input type="hidden" name="pRetEncodeType" value="<?php echo $pRetEncodeType; ?>" />
<input type="hidden" name="pOrderEncodeType" value="<?php echo $pOrderEncodeType; ?>" />
<input type="hidden" name="pSignMD5" value="<?php echo $pSignMD5; ?>" />
<input type="hidden" name="pAuthority" value="<?php echo $pAuthority; ?>" />
<input type="hidden" name="pBillEXP" value="<?php echo $pBillEXP; ?>" />
<input type="hidden" name="pCardInfo" value="<?php echo $pCardInfo; ?>" />
<input type="hidden" name="pResultType" value="<?php echo $pResultType; ?>" />
<input type="hidden" name="pReturnUrl" value="<?php echo $pReturnUrl; ?>" />
<input type="hidden" name="pAuthSuccessUrl" value="<?php echo $pAuthSuccessUrl; ?>" />
<input type="hidden" name="pAuthFailureUrl" value="<?php echo $pAuthFailureUrl; ?>" />
<input type="hidden" name="pGoodsInfo" value="<?php echo $pGoodsInfo; ?>" />
</form>
<script language="javascript">
document.getElementById("sendOrder").submit();
</script>
</body>
</html>
<?php
}
?> | 10npsite | trunk/Index/Lib/Order/IPSCATphp/demo/redirect.php | PHP | asf20 | 10,577 |
<?php
header("Content-type:text/html; charset=utf-8");
/*信用卡支付订单返回接收页面
*注意:由于可能多次返回支付结果,故需要商户的系统有能力处理多次返回的情况.
*/
//商户证书
$md5cert = 'gs14FHDIwYLwbc7bV3Y8fwQabe3MnOeOP618R0JLHa8DZwDaXKxvQILK112AnR57TX65AYj5JnReNmaF02O20JXhKGg0Xi7Q5bKcPhzZBSBDRGWp0MkKccgjazKTSJ8A';
//商户订单号
$pBillNo = $_GET['pBillNo'];
//商户号
$pMerCode = $_GET['pMerCode'];
//支付币种
$pCurrency = $_GET['pCurrency'];
//交易金额
$pAmount = $_GET['pAmount'];
//商户录入日期
$pDate = $_GET['pDate'];
//结果标志: Y– 成功 N – 失败 S-录入成功 F-录入失败
$pSucc = $_GET['pSucc'];
//返回的加密方式
$pRetEncodeType = $_GET['pRetEncodeType'];
//附加信息
$pAttach = $_GET['pAttach'];
//数字签名
$pSignature = $_GET['pSignature'];
//IPS处理时间
$pIpsBankTime = $_GET['pIpsBankTime'];
//IPS订单号
$pIpsBillNo = $_GET['pIpsBillNo'];
//银行返回信息
$pMsg = $_GET['pMsg'];
//验证明文
$content = $pBillNo . $pAmount . $pDate . $pSucc . $pIpsBillNo . $pCurrency;
/********************************非直连返回处理逻辑*****************************
1.数据验证
可以使用IPS 提供的签名验证组件,对返回的关键信息进行验证,以确保订单信息
安全,防止黑客恶意攻击及篡改订单信息。
2.判断 pSucc
若 pSucc 等“S”, 表示录入成功; 若等于“F”, 表示录入失败, 此时无需再进行以下步骤。
若 pSucc 等“Y”, 表示支付成功; 若等于“N”, 表示支付失败。
3.判断订单号和金额
为安全起见,商户应该将自己系统中存放的订单信息和IPS 返回的订单信息进行比对,
以保证订单数据真实可信。建议比对的项:订单编号和订单金额。
4.在成功完成以上步骤后,商户可以根据需要进行其他操作。
*******************************************************************************/
//验证结果
$verify = false;
//先验证签名,再判断交易是否成功
//MD5WithRSA验证
if ($pRetEncodeType == '11')
{
//创建com组件
$MD5withRSA = new COM('IpsVerify.RSAMd5');
//使用公钥文件的绝对路径
$result = $MD5withRSA->VerifyMessage("C:\\PubKey\\pub.txt", $content, $pSignature);
/*******************
返回代码定义
0 表示签名验证成功
-1 表示系统错误
-2 表示文件绑定错误
-3 表示读取公钥失败
-4 表示签名长度错
-5 表示签名验证失败
-99 表示系统锁定失败
*******************/
if ($result == 0)
{
$verify = true;
}
}
//md5摘要验证
if($pRetEncodeType == '12')
{
//明文=订单编号+订单金额+订单日期+成功标志+IPS订单编号+币种+商户证书
$content = $content . $md5cert;
$signature_local = MD5($content);
if ($signature_local == $pSignature)
{
$verify = true;
}
}
//签名验证结果
if($verify)
{
switch($pSucc)
{
Case "S":
//录入结果成功
echo '录入成功';
break;
Case "F":
//录入结果失败,商户可以记录失败原因或做其他操作
echo '录入失败' . $pMsg;
break;
Case "Y":
//支付结果成功,对返回的订单信息和商户数据库里的订单信息做核对--主要核对订单号,金额,日期等是否一致
echo '支付成功';
break;
Case "N":
//支付结果失败,商户可以记录失败原因或做其他操作
echo '支付失败' . $pMsg;
break;
}
}
else
{
echo '签名验证失败';
}
?>
| 10npsite | trunk/Index/Lib/Order/IPSCATphp/demo/OrderReturn.php | PHP | asf20 | 3,694 |
<?php
/**
* MARKETOOLS 跟踪API PHP Version
* ============================================================================
* 版权所有 2007-2010 海南推广易科技有限公司,并保留所有权利。
* 网站地址: http://www.marketools.cn;
* ----------------------------------------------------------------------------
* 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和
* 使用;不允许对程序代码以任何形式任何目的的再发布。
* ============================================================================
* $Author: easelify $
* $Id: track.php 2010/6/21 2011/3/30 easelify $
*/
error_reporting(E_ALL & ~E_NOTICE);
/**
* MT推广易主程序路径
*
* @since 4.0
* 末尾不要加 "/",例如:http://union.yourdomain.com
*/
define('MT_API_BASEURL', 'http://union.dreams-travel.com');
/**
* MT API安全码
*
* @since 4.0
* 请确保此值和您MT推广易程序目录 /sttings/settings.php 中定义的 API_SECURITYCODE 常量一致
*
*/
define('MT_API_SECURITYCODE', 'dec381e6c53f9tabb87eb76db3f72f69');
/* * *****************************
* 获取跟踪令牌
*
* @since 4.0
* 其他程序如ASP,JSP等,请参照此函数获取安全码
* 其中带的参数 cmd: 方法,securitycode: 预先设定好的安全验证码
* ***************************** */
function Marketools_GetTrackToken() {
return @file_get_contents(MT_API_BASEURL . '/api/getoken.php?cmd=step1&securitycode=' . MT_API_SECURITYCODE);
}
/* * *****************************
* 生成PHP跟踪请求地址的函数
*
* @since 4.0
* ***************************** */
function Marketools_GetTrackRequestAddress($params, $basicparams = array()) {
$gateway = MT_API_BASEURL . '/scripts/sale_hide.php?';
if (empty($basicparams)) {
$basicparams = array(
'lid' => '',
'trackingMethod' => 6,
'fsc' => $_COOKIE['POSTAff2Cookie'],
'fstc' => $_COOKIE['POSTAff2TimeCookie'],
'forc' => $_COOKIE['PAPR_0']
);
}
foreach ($_COOKIE as $key => $value) {
$url .= '&incookie_' . $key . '=' . $value;
}
$pms = array_merge($basicparams, $params);
foreach ($pms as $key => $value) {
$url .= '&' . $key . '=' . $value;
}
return $gateway . $url;
}
/* * *****************************
* 生成PHP跟踪请求地址基本参数
*
* @since 4.0
* ***************************** */
function Marketools_GetTrackBasicParams() {
$params = array(
'lid' => '',
'trackingMethod' => 6,
'fsc' => $_COOKIE['POSTAff2Cookie'],
'fstc' => $_COOKIE['POSTAff2TimeCookie'],
'forc' => $_COOKIE['PAPR_0']
);
foreach ($_COOKIE as $key => $value) {
$params['incookie_' . $key] = $value;
}
return serialize($params);
}
/* * ***********************************
* 销售通知API,注意键值大小写敏感
*
* @since 4.1
* ********************************** */
function Marketools_SaleNotify($params) {
$u = parse_url(MT_API_BASEURL);
$port = is_numeric($u['port']) ? $u['port'] : '80';
Marketools_SendHttpRequest($u['scheme'], $u['host'], $port, $u['path'] . '/scripts/sale_hide.php', $params);
}
/* * ***********************************
* 退款通知API,注意键值大小写敏感
*
* @since 4.1
* ********************************** */
function Marketools_RefundNotify($orderid) {
if (empty($orderid))
return false;
$token = Marketools_GetTrackToken();
$params = array(
'orderid' => $orderid,
'token' => $token
);
$u = parse_url(MT_API_BASEURL);
$port = is_numeric($u['port']) ? $u['port'] : '80';
Marketools_SendHttpRequest($u['scheme'], $u['host'], $port, $u['path'] . '/scripts/refundnotify.php', $params);
}
/* * *****************************
* 绑定客户API
*
* @since 4.0
*
* 传入参数说明
* $params = array(
* 'action'=>bind/unbind, //绑定,解绑
* 'outuserid'=>String, //外部用户ID,多个ID请用英文逗号(,)分开
* 'outusername'=>String //外部用户名
* );
*
* $type = js/socket //跟踪触发方式
* 返回信息含义
* <!-- //0 --> //未知方法
* <!-- //1 --> //绑定功能未开启
* <!-- //2 --> //参数错误
* <!-- //3 --> //推广员不存在
* <!-- //4 --> //该客户已经绑定了推广员
* <!-- //5 --> //令牌错误
* <!-- //6 --> //绑定失败
* <!-- //7 --> //绑定成功
* <!-- //8 --> //解除绑定成功
* ***************************** */
function Marketools_BindingCustomer($params, $type = 'js') {
$params['affid'] = Marketools_GetAffiliateIdFromCookie();
if (empty($params['affid']) && $params['action'] == 'bind') {
return '<!-- //2 -->';
}
$params['token'] = Marketools_GetTrackToken();
$gateway = MT_API_BASEURL . '/api/bindingclient.php?';
foreach ($params as $key => $value) {
$gateway .= $key . '=' . $value . '&';
}
if ($type == 'js') {
return '<script type="text/javascript" src="' . $gateway . '"></script>';
} elseif ($type == 'socket') {
return @file_get_contents($gateway);
}
}
/* * *****************************
* 绑定推广员API
*
* @since 4.0
*
* 传入参数说明:
* $outuserid //外部用户ID
* $type = js/socket //跟踪触发方式
* 返回 VOID
* string //推广员ID
* ***************************** */
function Marketools_BindingAffiliate($outuserid, $type) {
$type = $type == '' ? 'js' : $type;
$params['action'] = 'getaffiliate';
$params['token'] = Marketools_GetTrackToken();
$params['affid'] = Marketools_GetAffiliateIdFromCookie();
$params['outuserid'] = $outuserid;
$params['method'] = $type;
$params['cookie'] = $_COOKIE['POSTAff2Cookie'];
$gateway = MT_API_BASEURL . '/api/bindingclient.php?';
foreach ($params as $key => $value) {
$gateway .= $key . '=' . $value . '&';
}
if ($type == 'js') {
return
'<script type="text/javascript" src="' . $gateway . '"></script>' . '
<script type="text/javascript">
<!--
if(mt_aff_cover) {
var today = new Date();
var expires = new Date();
expires.setTime(today.getTime()+1000*60*60*24*365);
document.cookie = "POSTAff2Cookie="+escape(mt_aff_cover)+";expires="+expires.toGMTString();
}
-->
</script>'
;
} elseif ($type == 'socket') {
$mt_aff_cover = @file_get_contents($gateway);
if ($mt_aff_cover) {
setcookie('POSTAff2Cookie', $mt_aff_cover, 2 * time());
}
}
}
/* * *****************************
* 获取COOKIE里的推广员ID
*
* @since 4.0
* ***************************** */
function Marketools_GetAffiliateIdFromCookie() {
$r = explode('_', $_COOKIE['POSTAff2Cookie']);
return $r[0];
}
/* * *****************************
* 发送HTTP POST请求
*
* @since 4.1
* ***************************** */
function Marketools_SendHttpRequest($type, $host, $port = '80', $path = '/', $data = array(), &$response = '') {
$_err = 'lib sockets::' . __FUNCTION__ . '(): ';
switch ($type) {
case 'http': $type = '';
case 'ssl': continue;
default: die($_err . 'bad $type');
} if (!ctype_digit($port))
die($_err . 'bad port');
if (!empty($data)) {
foreach ($data as $k => $v) {
$str .= urlencode($k) . '=' . urlencode($v) . '&';
}
}
if (!empty($_COOKIE)) {
foreach ($_COOKIE as $k => $v) {
$str .= urlencode('incookie_'.$k) . '=' . urlencode($v) . '&';
}
}
$str = substr($str, 0, -1);
$fp = fsockopen($host, $port, $errno, $errstr, $timeout = 60);
if (!$fp)
die($_err . $errstr . $errno); else {
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: " . strlen($str) . "\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $str . "\r\n\r\n");
if ($response)
while (!feof($fp)) {
$response .= fgets($fp, 4096);
}
fclose($fp);
}
}
?> | 10npsite | trunk/Index/Lib/Order/track.php | PHP | asf20 | 8,539 |
<?
require "../../../global.php";
require RootDir."/inc/Function.Libary.php";
//notreflash();//防刷新
if($_REQUEST["payment_gross"]>0 and $_REQUEST["payment_status"]=="Completed" and $_REQUEST["mc_currency"]=="USD" )
{
require RootDir."/inc/Uifunction.php";
$url="/".Q."paytype_showpaysucctocustomer_orderno_".$_REQUEST["invoice"]."_moneynum_".$_REQUEST["payment_gross"]."_bizhong_USD_paytype_贝宝";
gourl($url,1);
}
else
{
echo "你的付款失败,请重新支付或联系我们,<a href='/user/".Q."tourorder_searchone'>进入订单查询</a>";
}
?> | 10npsite | trunk/Index/Lib/Order/Paypalphp/ReturnUrl.php | PHP | asf20 | 591 |
<html>
<head>
<title>PayPal WPS Toolkit PHP Samples</title>
</head>
<body alink=#0000FF vlink=#0000FF>
<center>
<font size=2 color=black face=Verdana><b>Welcome to the PayPal WPS Toolkit PHP Samples Main Page</b></font>
<br><br>
<table width=300>
<tr>
<td>
<font size=2 color=black face=Verdana>
<br><a id="STDLink" href="InputButtonParameters.php">Create an Encrypted Buy Now Button</a>
<br><a id="IPNLogLink" href="paypal-ipn.log">View IPN Logs</a>
<br><a id="CredentialsLink" href="Credentials.php">View Credentials Used to Encrypt Buy Now Buttons</a>
</font>
</td>
</tr>
</table>
</body>
</html>
| 10npsite | trunk/Index/Lib/Order/Paypalphp/index.html | HTML | asf20 | 646 |
<?php require "../../../global.php";
$h=fopen("logs_".date("Y-m-d").".txt","a+");
fwrite($h,"todo..".date("Y-m-d H:i:s")."\n ");
$rr=implode("&",$_REQUEST);
fwrite($h,"suss:arr to this:$rr ".date("Y-m-d H:i:s")."\n ");
//从PayPal 出读取POST 信息同时添加变量 "cmd
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
//建议在此将接受到的信息记录到日志文件中以确认是否收到IPN 信息
//将信息POST 回给PayPal 进行验证
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type:application/x-www-form-urlencoded\r\n";
$header .= "Content-Length:" . strlen($req) ."\r\n\r\n";
//在Sandbox 情况下,设置:
//$fp = fsockopen("www.sandbox.paypal.com‟,80,$errno,$errstr,30);
$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);
//将POST 变量记录在本地变量中
//该付款明细所有变量可参考:
//https://www.paypal.com/IntegrationCenter/ic_ipn-pdt-variable-reference.html
$item_name = $_POST['item_name']; //产品名称
$item_number = $_POST['item_number']; //数据
$payment_status = $_POST['payment_status']; //状态
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
//…
//判断回复POST 是否创建成功
if (!$fp) {
//HTTP 错误
}else {
//将回复POST 信息写入SOCKET 端口
fputs ($fp, $header .$req);
//开始接受PayPal 对回复POST 信息的认证信息
while (!feof($fp)) {
$res = fgets ($fp, 1024);
//已经通过认证
if (strcmp ($res, "VERIFIED") == 0) {
//检查付款状态
//检查txn_id 是否已经处理过
//检查receiver_email 是否是您的PayPal 账户中的EMAIL 地址
//检查付款金额和货币单位是否正确
//处理这次付款,包括写数据库
//若付款成功,写自己的数据库
preg_match("/^[a-zA-Z][0-9]+/",$_REQUEST["invoice"],$orderAr);
$invoicel=$orderAr[0];
$payflag=str_replace($invoicel,"",$_REQUEST["invoice"]);
require RootDir."/inc/dabase_mysql.php";
$mydb=new YYBDB();
$sql2="earnestmoney=".$payment_amount.",paytimeearnestmoney=".time().",paytype='paypal',earnbizhong='USD',isconfim=1";
$paytype="dj";
if($payflag!="")
{
if($payflag=="je2")
{
$sql2="balance=".$payment_amount.",paytimebalance=".time().",balancepaytye='paypal',balancebizhong='USD',balanceisconfim=1";
$paytype="je2";
}
if($payflag=="je3")
{
$sql2="je3=".$payment_amount.",je3paytime=".time().",je3paytype='paypal',je3bizhong='USD',je3isconfim=1";
$paytype="je3";
}
if($payflag=="je4")
{
$sql2="je4=".$payment_amount.",je4paytime=".time().",je4paytype='paypal',je4bizhong='USD',je4isconfim=1";
$paytype="je4";
}
}
$sql="update ".$SystemConest[7]."orderpaylist set
".$sql2."
where orderno='".$invoicel."'";
$mydb->db_query($sql);
$res=$mydb->db_query("select * from ".$SystemConest[7]."tourorder where orderno='".$invoicel."'");
$rs=$mydb->db_fetch_array($res);
/* regin 支付成功,通知联盟系统 */
require_once("../track.php");
$params = array(
"TotalCost"=>$payment_amount * 6.3,
"OrderID"=>$invoicel,
"data1"=>Marketools_GetTrackToken()
);
@Marketools_SaleNotify($params);
/* endregin 支付成功,通知联盟系统 */
//支付成功,执行发送邮件操作
echo "<iframe src='/dszSendMail_sendMailInfo_type_paysuss_orderno_".$invoicel."_paytype_paypal_djorwk_".$paytype."_email_".$rs["nuseremail"]."'
frameborder=0 scrolling=no width=1 height=1></iframe>";
?>
<script src="http://union.dreams-travel.com/api/track_js.php" type="text/javascript"></script>
<script id="pap_x2s6df8d" src="http://union.dreams-travel.com/scripts/sale.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
var TotalCost="<?php echo $payment_amount; ?>";
var OrderID="<?php echo $invoicel; ?>";
papSale();
-->
</script>
<?php
unset($rs);
fwrite($h,"updated the datebase!::$sql:".date("Y-m-d H:i:s")."\n ");
}else if (strcmp ($res, "INVALID") == 0) {
//未通过认证,有可能是编码错误或非法的POST 信息
}
}
fclose ($fp);
}
fclose($h); | 10npsite | trunk/Index/Lib/Order/Paypalphp/IPNListner.php | PHP | asf20 | 4,650 |
<?php
/**
* Copyright 2007 PayPal, Inc. All Rights Reserved.
*/
require_once "PPCrypto.php";
/**
* API for doing PayPal encryption services.
*/
class EWPServices
{
/**
* Creates a new encrypted button HTML block
*
* @param array The button parameters as key/value pairs
* @param string The file path to the EWP(merchant) certificate
* @param string The file path to the EWP(merchant) private key
* @param string The EWP(merchant) private key password
* @param string The file path to the PayPal Certificate
* @param string The URL where button will be posted
* @param string The URL of the button image
* @return array Contains a bool status, error_msg, error_no, and an encrypted string: encryptedButton if successfull
*
* @access public
* @static
*/
function encryptButton( $buttonParams_,
$ewpCertPath_,
$ewpPrivateKeyPath_,
$ewpPrivateKeyPwd_,
$paypalCertPath_,
$destinationUrl_,
$buttonImageUrl_)
{
/**
* serialize the button parameters' array to a string.
*/
$contentBytes = array();
foreach ($buttonParams_ as $name => $value) {
$contentBytes[] = "$name=$value";
}
$contentBytes = implode("\n", $contentBytes);
/**
* sign and encrypt the button parameters
*/
$encryptedDataReturn = PPCrypto::signAndEncrypt($contentBytes, $ewpCertPath_, $ewpPrivateKeyPath_, $ewpPrivateKeyPwd_, $paypalCertPath_);
if(!$encryptedDataReturn["status"]) {
return array("status" => false, "error_msg" => $encryptedDataReturn["error_msg"], "error_no" => $encryptedDataReturn["error_no"]);
}
/**
* Build and return HTML string
*/
$encryptedData = "-----BEGIN PKCS7-----".$encryptedDataReturn["encryptedData"]."-----END PKCS7-----";
$encryptedButton = <<<PPHTML
<FORM ACTION="${destinationUrl_}/cgi-bin/webscr" METHOD="post">
<INPUT TYPE="hidden" NAME="cmd" VALUE="_s-xclick">
<INPUT TYPE="hidden" NAME="encrypted" VALUE="$encryptedData">
<INPUT TYPE="image" SRC="$buttonImageUrl_" BORDER="0" NAME="submit" ALT="Make Payments with PayPal -- it's fast, free and secure!">
</FORM>
PPHTML;
return array("status" => true, "encryptedButton" => $encryptedButton);
} // encryptButton
} // EWPServices
?> | 10npsite | trunk/Index/Lib/Order/Paypalphp/EWPServices.php | PHP | asf20 | 2,299 |
<?php
/**
* Copyright 2007 PayPal, Inc. All Rights Reserved.
*/
/**
* This class provides a utility sign and encrypt function of a string using PKCS7
*/
class PPCrypto
{
/**
* Sign and Envelope the passed data string, returning a PKCS7 blob that can be posted to PayPal.
* Make sure the passed data string is seperated by UNIX linefeeds (ASCII 10, '\n').
*
* @param string The candidate for signature and encryption
* @param string The file path to the EWP(merchant) certificate
* @param string The file path to the EWP(merchant) private key
* @param string The EWP(merchant) private key password
* @param string The file path to the PayPal Certificate
* @return array Contains a bool status, error_msg, error_no, and an encrypted string: encryptedData if successfull
*
* @access public
* @static
*/
function signAndEncrypt($dataStr_, $ewpCertPath_, $ewpPrivateKeyPath_, $ewpPrivateKeyPwd_, $paypalCertPath_)
{
$dataStrFile = realpath(tempnam('/tmp', 'pp_'));
$fd = fopen($dataStrFile, 'w');
if(!$fd) {
$error = "Could not open temporary file $dataStrFile.";
return array("status" => false, "error_msg" => $error, "error_no" => 0);
}
fwrite($fd, $dataStr_);
fclose($fd);
$signedDataFile = realpath(tempnam('/tmp', 'pp_'));
if(!@openssl_pkcs7_sign( $dataStrFile,
$signedDataFile,
"file://$ewpCertPath_",
array("file://$ewpPrivateKeyPath_", $ewpPrivateKeyPwd_),
array(),
PKCS7_BINARY)) {
unlink($dataStrFile);
unlink($signedDataFile);
$error = "Could not sign data: ".openssl_error_string();
return array("status" => false, "error_msg" => $error, "error_no" => 0);
}
unlink($dataStrFile);
$signedData = file_get_contents($signedDataFile);
$signedDataArray = explode("\n\n", $signedData);
$signedData = $signedDataArray[1];
$signedData = base64_decode($signedData);
unlink($signedDataFile);
$decodedSignedDataFile = realpath(tempnam('/tmp', 'pp_'));
$fd = fopen($decodedSignedDataFile, 'w');
if(!$fd) {
$error = "Could not open temporary file $decodedSignedDataFile.";
return array("status" => false, "error_msg" => $error, "error_no" => 0);
}
fwrite($fd, $signedData);
fclose($fd);
$encryptedDataFile = realpath(tempnam('/tmp', 'pp_'));
if(!@openssl_pkcs7_encrypt( $decodedSignedDataFile,
$encryptedDataFile,
file_get_contents($paypalCertPath_),
array(),
PKCS7_BINARY)) {
unlink($decodedSignedDataFile);
unlink($encryptedDataFile);
$error = "Could not encrypt data: ".openssl_error_string();
return array("status" => false, "error_msg" => $error, "error_no" => 0);
}
unlink($decodedSignedDataFile);
$encryptedData = file_get_contents($encryptedDataFile);
if(!$encryptedData) {
$error = "Encryption and signature of data failed.";
return array("status" => false, "error_msg" => $error, "error_no" => 0);
}
unlink($encryptedDataFile);
$encryptedDataArray = explode("\n\n", $encryptedData);
$encryptedData = trim(str_replace("\n", '', $encryptedDataArray[1]));
return array("status" => true, "encryptedData" => $encryptedData);
} // signAndEncrypt
} // PPCrypto
?> | 10npsite | trunk/Index/Lib/Order/Paypalphp/PPCrypto.php | PHP | asf20 | 3,301 |
<?php
define("DEFAULT_DEV_CENTRAL", "developer");
define("DEFAULT_ENV", "sandbox");
define("DEFAULT_USER_NAME", "sdk-three_api1.sdk.com");
define("DEFAULT_PASSWORD", "QFZCWN5HZM8VBG7Q");
define("DEFAULT_SIGNATURE", "A.d9eRKfd1yVkRrtmMfCFLTqa6M9AyodL0SJkhYztxUi8W9pCXF6.4NI");
define("DEFAULT_EMAIL_ADDRESS", "sdk-seller@sdk.com");
define("DEFAULT_IDENTITY_TOKEN", "G5JgcRdmlYUwnHcYSEXI2rFuQ5yv-Ei19fMFWn30aDkZAoKt_7LTuufYXUa");
define("DEFAULT_EWP_CERT_PATH", "cert/sdk-ewp-cert.pem");
define("DEFAULT_EWP_PRIVATE_KEY_PATH", "cert/sdk-ewp-key.pem");
define("DEFAULT_EWP_PRIVATE_KEY_PWD", "password");
define("DEFAULT_CERT_ID", "KJAERUGBLVF6Y");
define("PAYPAL_CERT_PATH", "cert/sandbox-cert.pem");
define("BUTTON_IMAGE", "https://www.paypal.com/en_US/i/btn/x-click-but23.gif");
define("PAYPAL_IPN_LOG", "paypal-ipn.log");
?> | 10npsite | trunk/Index/Lib/Order/Paypalphp/constants.php | PHP | asf20 | 843 |
<?php
/**
WARNING: Do not embed plaintext credentials in your application code.
Doing so is insecure and against best practices.
Your API credentials must be handled securely. Please consider
encrypting them for use in any production environment, and ensure
that only authorized individuals may view or modify them.
*/
/**
* This class provides static utility functions that will be used by the WPS samples
*/
class Utils
{
/**
* Builds the URL for the input file using the HTTP request information
*
* @param string The name of the new file
* @return string The full URL for the input file
*
* @access public
* @static
*/
function getURL($fileContextPath_)
{
$server_protocol = htmlspecialchars($_SERVER["SERVER_PROTOCOL"]);
$server_name = htmlspecialchars($_SERVER["SERVER_NAME"]);
$server_port = htmlspecialchars($_SERVER["SERVER_PORT"]);
$url = strtolower(substr($server_protocol,0, strpos($server_protocol, '/'))); // http
$url .= "://$server_name:$server_port/$fileContextPath_";
return $url;
} // getURL
/**
* Send HTTP POST Request
*
* @param string The request URL
* @param string The POST Message fields in &name=value pair format
* @param bool determines whether to return a parsed array (true) or a raw array (false)
* @return array Contains a bool status, error_msg, error_no,
* and the HTTP Response body(parsed=httpParsedResponseAr or non-parsed=httpResponse) if successful
*
* @access public
* @static
*/
function PPHttpPost($url_, $postFields_, $parsed_)
{
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url_);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
//turning off the server and peer verification(TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
//setting the nvpreq as POST FIELD to curl
curl_setopt($ch,CURLOPT_POSTFIELDS,$postFields_);
//getting response from server
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
return array("status" => false, "error_msg" => curl_error($ch), "error_no" => curl_errno($ch));
}
if(!$parsed_) {
return array("status" => true, "httpResponse" => $httpResponse);
}
$httpResponseAr = explode("\n", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if(0 == sizeof($httpParsedResponseAr)) {
$error = "Invalid HTTP Response for POST request($postFields_) to $url_.";
return array("status" => false, "error_msg" => $error, "error_no" => 0);
}
return array("status" => true, "httpParsedResponseAr" => $httpParsedResponseAr);
} // PPHttpPost
/**
* Redirect to Error Page
*
* @param string Error message
* @param int Error number
*
* @access public
* @static
*/
function PPError($error_msg, $error_no) {
// create a new curl resource
$ch = curl_init();
// set URL and other appropriate options
$php_self = substr(htmlspecialchars($_SERVER["PHP_SELF"]), 1); // remove the leading /
$redirectURL = Utils::getURL(substr_replace($php_self, "Error.php", strrpos($php_self, '/') + 1));
curl_setopt($ch, CURLOPT_URL, $redirectURL);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// set POST fields
$postFields = "error_msg=".urlencode($error_msg)."&error_no=".urlencode($error_no);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postFields);
// grab URL, and print
curl_exec($ch);
curl_close($ch);
}
} // Utils
?> | 10npsite | trunk/Index/Lib/Order/Paypalphp/utility.php | PHP | asf20 | 3,846 |
<?php
/**
* DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
*/
require_once "utility.php";
require_once "constants.php";
if(!array_key_exists("tx", $_GET)) {
Utils::PPError("PDT received an HTTP GET request without a transaction ID.", 0);
exit;
}
$url = "https://www.".DEFAULT_ENV.".paypal.com/cgi-bin/webscr";
$postFields = "cmd=".urlencode("_notify-synch").
"&tx=".urlencode(htmlspecialchars($_GET["tx"])).
"&at=".urlencode(DEFAULT_IDENTITY_TOKEN);
$ppResponseAr = Utils::PPHttpPost($url, $postFields, true);
if(!$ppResponseAr["status"]) {
Utils::PPError($ppResponseAr["error_msg"], $ppResponseAr["error_no"]);
exit;
}
$httpParsedResponseAr = $ppResponseAr["httpParsedResponseAr"];
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PDT Response</title>
<link href="sdk.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table cellSpacing="0" cellPadding="0" width="600" align="center" border="0">
<tr>
<td>
<TABLE width="600" align="center">
<TBODY>
<TR>
<TD align="center" colSpan="2"><FONT face="Verdana" color="black" size="2"><B>Payment Success Landing Page</B>
<table cellSpacing="6" cellPadding="2" border="0">
<TBODY>
<tr>
<td align="left"><FONT face="Verdana" color="black" size="2">This page is a placeholder. Once your buyers complete a payment at PayPal, PayPal redirects
your buyers back to a URL you specify.</FONT>
</td>
</tr>
<tr>
<td align="left"><FONT face="Verdana" color="black" size="2">This URL where your buyers are sent is declared as a variable in the buy now button. PayPal includes a
subset of transaction information in the GET statement:</FONT>
</td>
</tr>
<tr>
<td align="center"><FONT face="Verdana" color="black" size="2"><b>Variables returned from HTTP GET</b></FONT></td>
</tr>
<table cellpadding="2" cellspacing="2" border="1">
<tr>
<td align="left">Transaction ID:</td>
<td align="left"><?php echo htmlspecialchars($_GET["tx"]) ?></td>
</tr>
<tr>
<td align="left">Currency Code: </td>
<td align="left"><?php echo urldecode(htmlspecialchars($_GET["cc"])) ?></td>
</tr>
<tr>
<td align="left">Status:</td>
<td align="left"><?php echo urldecode(htmlspecialchars($_GET["st"])) ?></td>
</tr>
<tr>
<td align="left">Amount: </td>
<td align="left"><?php echo urldecode(htmlspecialchars($_GET["amt"])) ?></td>
</tr>
<tr>
<td align="left">Custom Message: </td>
<td align="left"><?php echo urldecode(htmlspecialchars($_GET["cm"])) ?></td>
</tr>
<tr>
<td align="left">Signature: </td>
<td align="left"><?php echo urldecode(htmlspecialchars($_GET["sig"])) ?></td>
</tr>
</table>
<tr>
<td align="left"><FONT face="Verdana" color="black" size="2">PayPal also includes
detailed transactional information through two different methods, IPN and PDT.</FONT></td>
</tr>
</TR>
<tr>
<td align="center"><B><SPAN style="FONT-SIZE: 10pt; COLOR: black; FONT-FAMILY: Verdana">IPN</SPAN></B></td>
</tr>
</tr>
<tr>
<td align="left"><FONT face="Verdana" color="black" size="2">IPN is an asynchronous
notification method through HTTP. In this process PayPal sends a form post back
to you asynchronously showing the status of this transaction. Under most
circumstances the payment details are sent to your server within a few minutes.<BR>
</SPAN><A id=IPNLink href="paypal-ipn.log" >Click here to view
IPN logs for this transaction</A></FONT>
</td>
</tr>
</TR>
<tr>
<td align="center"><FONT face="Verdana" color="black" size="2"><b>PDT</b></FONT></td>
</tr>
<tr>
<td align="left"><FONT face="Verdana" color="black" size="2">PDT is a synchronous
method through HTTP. In this process, the GET statement from PayPal includes a
transaction token. This token can be passed back to PayPal to get further
details on the transaction. A listing of PDT variables from this transaction
are displayed below.</FONT>
</td>
</tr>
<tr>
<td align="left"><FONT face="Verdana" color="black" size="2">PayPal recommends using
IPN over using the transaction token when fulfilling orders or reconciling your
payments because PDT is triggered only when a buyer returns back to your
website. If the buyer closes his browser before returning, PDT will not
complete.</FONT></td>
</tr>
</table>
</FONT></TD></TR>
<TR>
<TD align="center"><FONT face="Verdana" color="black" size="2"><!---!--><B>Variables returned from HTTP Post </B></FONT>
</TD>
</TR>
<tr>
<CENTER>
<table cellpadding="2" cellspacing="2" border="1">
<tr>
<td align="left">SUCCESS</td>
</tr>
<tr>
<td align="left">payment_date:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["payment_date"]) ?></td>
</tr>
<tr>
<td align="left">txn_type:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["txn_type"]) ?></td>
</tr>
<tr>
<td align="left">last_name:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["last_name"]) ?></td>
</tr>
<tr>
<td align="left">residence_country:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["residence_country"]) ?></td>
</tr>
<tr>
<td align="left">item_name:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["item_name"]) ?></td>
</tr>
<tr>
<td align="left">payment_gross :</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["payment_gross"]) ?></td>
</tr>
<tr>
<td align="left">mc_currency :</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["mc_currency"]) ?></td>
</tr>
<tr>
<td align="left">business:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["business"]) ?></td>
</tr>
<tr>
<td align="left">payment_type:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["payment_type"]) ?></td>
</tr>
<tr>
<td align="left">payer_status:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["payer_status"]) ?></td>
</tr>
<tr>
<td align="left">tax:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["tax"]) ?></td>
</tr>
<tr>
<td align="left">payer_email:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["payer_email"]) ?></td>
</tr>
<tr>
<td align="left">txn_id:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["txn_id"]) ?></td>
</tr>
<tr>
<td align="left">quantity:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["quantity"]) ?></td>
</tr>
<tr>
<td align="left">receiver_email:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["receiver_email"]) ?></td>
</tr>
<tr>
<td align="left">first_name:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["first_name"]) ?></td>
</tr>
<tr>
<td align="left">payer_id:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["payer_id"]) ?></td>
</tr>
<tr>
<td align="left">receiver_id:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["receiver_id"]) ?></td>
</tr>
<tr>
<td align="left">item_number:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["item_number"]) ?></td>
</tr>
<tr>
<td align="left">payment_status:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["payment_status"]) ?></td>
</tr>
<tr>
<td align="left">shipping:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["shipping"]) ?></td>
</tr>
<tr>
<td align="left">mc_gross:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["mc_gross"]) ?></td>
</tr>
<tr>
<td align="left">custom:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["custom"]) ?></td>
</tr>
<tr>
<td align="left">charset:</td>
<td align="left"><?php echo urldecode($httpParsedResponseAr["charset"]) ?></td>
</tr>
</table>
</CENTER>
</TBODY></TABLE>
</TD></TR></TBODY></TABLE><font face="Verdana" color="black" size="2"><A href="index.html">Home</A></font>
</body>
</html> | 10npsite | trunk/Index/Lib/Order/Paypalphp/PDTResponse.php | PHP | asf20 | 8,939 |
body
{
font-size:small;
font-family:Verdana;
color:Black;
}
a
{
color:Blue;
}
#calls
{
font-family:Verdana;
width:500px;
}
#calls th
{
padding:10px;
}
table
{
font-size:x-small;
}
td.header
{
text-align:right;
font-size:x-small;
color:Black;
font-family:Verdana;
font-weight:bold;
}
#normalBold
{
color:Black;
font-family:Verdana;
font-weight:bold;
}
.smaller
{
font-size:smaller;
}
#normal
{
color:Black;
font-size:small;
font-family:Verdana;
}
#redBold
{
color:Red;
font-size:small;
font-family:Verdana;
font-weight:bold;
}
#apiheader
{
text-align:center;
font-weight:bold;
font-size:larger;
font-family:Verdana;
}
table.api
{
width:600;
}
a.home
{
font-weight:bold;
}
td.field
{
text-align:right;
}
td.header
{
text-align:center;
font-size:small;
font-family:Verdana;
font-weight:bold;
} | 10npsite | trunk/Index/Lib/Order/Paypalphp/sdk.css | CSS | asf20 | 975 |
<?php
include "ppwps_include_path.inc";
require_once "utility.php";
require_once "constants.php";
require_once "EWPServices.php";
$buttonParams = array( "cmd" => "_xclick",
"business" => DEFAULT_EMAIL_ADDRESS,
"cert_id" => DEFAULT_CERT_ID,
"charset" => "UTF-8",
"item_name" => htmlspecialchars($_POST["item_name"]),
"item_number" => htmlspecialchars($_POST["item_number"]),
"amount" => htmlspecialchars($_POST["amount"]),
"currency_code" => htmlspecialchars($_POST["currency_code"]),
"return" => htmlspecialchars($_POST["returnURL"]),
"cancel_return" => htmlspecialchars($_POST["cancelURL"]),
"notify_url" => htmlspecialchars($_POST["notifyURL"]),
"custom" => "PayPal EWP Sample");
$envURL = "https://www.".DEFAULT_ENV.".paypal.com";
$buttonReturn = EWPServices::encryptButton( $buttonParams,
realpath(DEFAULT_EWP_CERT_PATH),
realpath(DEFAULT_EWP_PRIVATE_KEY_PATH),
DEFAULT_EWP_PRIVATE_KEY_PWD,
realpath(PAYPAL_CERT_PATH),
$envURL,
BUTTON_IMAGE);
if(!$buttonReturn["status"]) {
Utils::PPError($buttonReturn["error_msg"], $buttonReturn["error_no"]);
exit;
}
$button = $buttonReturn["encryptedButton"];
?>
<html>
<head>
<title>PayPal Website Payment Standard Buy Now</title>
</head>
<body alink=#0000FF vlink=#0000FF>
<br>
<center>
<font size=2 color=black face=Verdana><b>Encrypted Website Payment (EWP) Buttons</b></font>
<br><br>
<font color=red>
<b>You must be logged into <a href="https://<?php echo DEFAULT_DEV_CENTRAL ?>.paypal.com" target="_blank">Developer Central</a></b>
</font>
<br><br>
<table cellpadding="2" cellspacing="2" border="1">
<tr><td align=left>Item Name</td><td align=left><?php echo $buttonParams["item_name"] ?></td></tr>
<tr><td align=left>Amount</td><td align=left><?php echo $buttonParams["amount"] ?></td></tr>
</table>
<br><br><?php echo $button ?>
<br>Using the credentials specified in the utility.php file, the payment details are
now encrypted. Click on the Buy Now button to complete the payment on PayPal<br><br>
<font face="Verdana" color="black" size="2">The following are the parameters being passed: </font>
<br>
<table cellpadding="2" cellspacing="2" border="1">
<tr><td align=left>cmd:</td><td align=left>_xclick</td></tr>
<tr><td align=left>business</td><td align=left><?php echo DEFAULT_EMAIL_ADDRESS ?></td></tr>
<tr><td align=left>cert_id</td><td align=left><?php echo DEFAULT_CERT_ID ?></td></tr>
<tr><td align=left>item_name</td><td align=left><?php echo $buttonParams["item_name"] ?></td></tr>
<tr><td align=left>item_number</td><td align=left><?php echo $buttonParams["item_number"] ?></td></tr>
<tr><td align=left>amount</td><td align=left><?php echo $buttonParams["amount"] ?></td></tr>
<tr><td align=left>currency_code</td><td align=left><?php echo $buttonParams["currency_code"] ?></td></tr>
<tr><td align=left>return</td><td align=left><?php echo $buttonParams["return"] ?></td></tr>
<tr><td align=left>cancel_return</td><td align=left><?php echo $buttonParams["cancel_return"] ?></td></tr>
<tr><td align=left>notify_url</td><td align=left><?php echo $buttonParams["notify_url"] ?></td></tr>
</table>
<br><br>
</center>
</body>
</html> | 10npsite | trunk/Index/Lib/Order/Paypalphp/BuyNow.php | PHP | asf20 | 3,344 |
<?
require "../../../global.php";
//header('Content-Type: text/html; charset=utf-8');
echo "正在支付跳转中,请稍候.....";
?>
<FORM name="paypalments" id="paypalments" action="https://www.paypal.com/cgi-bin/webscr/?" method=post >
<?
//此页面是jroam自行加上,用于判断定单支付列表里有没支付的记录,没有的话加上一条
$urlc="https://www.paypal.com/cgi-bin/webscr/?";
foreach($_POST as $k =>$v)
{
$urlc=$urlc."&".$k."=".$v;
echo "<input type='hidden' name='$k' value='$v' id='$k'>";
}
$urlc=str_replace("?&","?",$urlc);
require RootDir."/inc/dabase_mysql.php";
$mydb=new YYBDB();
$sql="select orderno from ".$SystemConest[7]."orderpaylist where orderno='".$_REQUEST["invoice"]."'";
$res=$mydb->db_query($sql);
if($mydb->db_num_rows($res)<1)
{
$sql="insert into ".$SystemConest[7]."orderpaylist (tourid,orderno,paytype,earnbizhong) value(".$_REQUEST['productid'].",'".$_REQUEST["invoice"]."','payal','USD')";
$mydb->db_query($sql);
}
//跳转到支付页面
//echo "<meta http-equiv=\"refresh\" content=\"0; url=".$urlc."\">";
?>
<input type="hidden" name="charset" value="utf-8">
</FORM>
<script src="/jsLibrary/jquery/jquery.js"></script>
<script language="javascript">
$(document).ready(function(){
$("#paypalments").submit();
});
</script> | 10npsite | trunk/Index/Lib/Order/Paypalphp/redirect.php | PHP | asf20 | 1,341 |
<?php
/* DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd" */
require_once "utility.php";
require_once "constants.php";
$php_self = substr(htmlspecialchars($_SERVER["PHP_SELF"]), 1); // remove the leading /
$returnURL = Utils::getURL(substr_replace($php_self, "PDTResponse.php", strrpos($php_self, '/') + 1));
$cancelURL = Utils::getURL(substr_replace($php_self, ".", strrpos($php_self, '/') + 1));
$notifyURL = Utils::getURL(substr_replace($php_self, "IPNListner.php", strrpos($php_self, '/') + 1));
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Buy Now</title>
<link href="sdk.css" rel="stylesheet" type="text/css" />
</head>
<body>
<center>
<form id= InputBuyNowParametersForm action="BuyNow.php" method="post">
<br />
<font face="Verdana" color="black" size="2"><b>Enter Parameters to Create an Encrypted Buy Now Button.
</b></font>
<br /><br />
<font face="Verdana" color="black" size="2"></font>
<table id="info" cellSpacing="3" cellPadding="2" border="0">
<tr>
<td>Enter the required parameters below to create an encrypted buy now button.
</td>
</tr>
<tr>
<td>To learn more about optional variables for buy now buttons, review the Website
Payments Standard on the <A href="https://www.paypal.com/IntegrationCenter/ic_standard_home.html#BuyNowButtons" target="_blank"
>PayPal Integration Center</A>.
</td>
</tr>
<tr>
<td>Variables that are not editable are set in the utility.php file. (view your
complete credentials for Website Payments Standard <A href="Credentials.php" target="_blank">
here</A>)<br>
</td>
</tr>
</table>
<br>
<table >
<tr>
<td align="left">cmd:</td>
<td align="left">_xclick</td>
</tr>
<tr>
<td align="left">PayPal Account:</td>
<td align="left">sdk-seller@sdk.com</td>
</tr>
<tr>
<td align="left">item_name:</td>
<td align="left"><input name="item_name" value="Widget" /></td>
</tr>
<tr>
<td align="left">item_number:</td>
<td align="left" ><input name="item_number" value="1"/></td>
</tr>
<tr>
<td align="left">amount:</td>
<td align="left" ><input name="amount" value="1"/></td>
</tr>
<tr>
<td align="left" height="7">currency_code:</td>
<td align="left">
<select name="currency_code">
<option value="USD" selected="selected">USD</option>
<option value="GBP">GBP</option>
<option value="EUR">EUR</option>
<option value="JPY">JPY</option>
<option value="CAD">CAD</option>
<option value="AUD">AUD</option>
</select>
</td>
</tr>
<tr>
<td align="left">return:</td>
<td align="left"><?php echo $returnURL ?></td>
</tr>
<tr>
<td align="left">cancel_return:</td>
<td align="left"><?php echo $cancelURL ?></td>
</tr>
<tr>
<td align="left">notify_url:</td>
<td align="left"><?php echo $notifyURL ?></td>
</tr>
<tr>
<td align="left">endpoint:</td>
<td align="left">https://www.<?php echo DEFAULT_ENV ?>.paypal.com/cgi-bin/webscr/</td>
</tr>
<tr>
<td></td>
<td>
<input type="hidden" name="returnURL" value="<?php echo $returnURL ?>">
<input type="hidden" name="notifyURL" value="<?php echo $notifyURL ?>">
<input type="hidden" name="bn" value="PP-WPS_PHP">
<input type="hidden" name="cancelURL" value="<?php echo $cancelURL ?>">
<input type="submit" value="Submit" name="SubmitButton" />
</td>
</tr>
</table>
</form>
</center>
<font size="2" color="black" face="Verdana"><a href="index.html">Home</a></font>
</body>
</html> | 10npsite | trunk/Index/Lib/Order/Paypalphp/InputButtonParameters.php | PHP | asf20 | 4,541 |
<html>
<head>
<title>PayPal SDK - PHP Exception</title>
</head>
<body alink=#0000FF vlink=#0000FF>
<center>
<br>
<font size=2 color=black face=Verdana><b>PHP Exception</b></font>
<br><br>
<b>A PHP exception has occured!</b><br><br>
<?php
if(array_key_exists("error_msg", $_POST)) {
$error_msg = htmlspecialchars($_POST["error_msg"]);
if(array_key_exists("error_no", $_POST)) {
if(0 != htmlspecialchars($_POST["error_no"])) {
$error_msg = "Error ".htmlspecialchars($_POST["error_no"]).": $error_msg";
}
}
echo "<b>$error_msg</b><br><br>";
}
?>
<b>Please check your configuration.</b>
<br><br>
</center>
<b>Help:</b>
<ul>
<li><a href='https://www.paypal.com/IntegrationCenter'>PayPal Integration Center</a><br>
<li><a href='https://www.paypal.com/IntegrationCenter/ic_button-encryption.html'>Encrypted Website Payments (EWP)</a><br>
<li>For Encrypted Website Payments (EWP) functionality of the SDK, make sure you have installed the OpenSSL Extension.
</ul>
<a href="index.html">Index</a>
</body>
</html> | 10npsite | trunk/Index/Lib/Order/Paypalphp/Error.php | PHP | asf20 | 1,053 |
<?php
/* DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd" */
require_once 'constants.php';
?>
<HTML>
<HEAD>
<title>PayPal Website Payment Standard Credentials Page</title>
<LINK href="sdk.css" type="text/css" rel="stylesheet">
</HEAD>
<body>
<center>
<form id="LoginForm" runat="server">
<p>
<font face="Verdana, Arial, Helvetica, sans-serif" color="#000000">
<br>
<b>Credentials Used To Create Encrypted Buy Now Buttons</b></font></p>
<p align="left"><font face="Verdana, Arial, Helvetica, sans-serif" color="#000000"><br>
<span style="FONT-SIZE: 10pt; FONT-FAMILY: Arial; mso-fareast-font-family: 'Arial Unicode MS'; mso-bidi-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA">
Below are the credentials used to encrypt buy now buttons. </span></font></p>
<p align="left"><font face="Verdana, Arial, Helvetica, sans-serif" color="#000000"><span style="FONT-SIZE: 10pt; FONT-FAMILY: Arial; mso-fareast-font-family: 'Arial Unicode MS'; mso-bidi-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA">PayPal
includes a default account for testing on the PayPal sandbox. You can modify
these credentials by editing the utility.jsp file</span></font></p>
<p align="left"><font face="Verdana, Arial, Helvetica, sans-serif" color="#000000"><span style="FONT-WEIGHT: bold; COLOR: red">NOTES:
</span></font></p>
<ul>
<li>
<div align="left"><font face="Verdana, Arial, Helvetica, sans-serif" color="#000000">Production
code should NEVER expose credentials in this manner. We are showing you
credentials for testing purposes only.</font></div>
<li>
<div align="left"><font face="Verdana, Arial, Helvetica, sans-serif">Sandbox
credentials are different than that of live credentials. You will need a different set
to encrypt buy now buttons on the live production system.</font></div>
<li>
<div align="left"><font face="Verdana, Arial, Helvetica, sans-serif" color="#000000">The
credentials given below are used to encrypt buy now buttons. They are not the
credentials used to make PayPal API calls.</font></div>
</li>
</ul>
<table border="1">
<tr>
<td align="left">PayPal Account:</td>
<td align="left"><?php echo DEFAULT_EMAIL_ADDRESS ?></td>
</tr>
<tr>
<td align="left">Certificate PKCS12 (.p12) format:</td>
<td align="left"><?php echo DEFAULT_EWP_CERT_PATH ?></td>
</tr>
<tr>
<td align="left">Certificate Private Key Password
<br>
(OpenSSL Export Password):</td>
<td align="left"><?php echo DEFAULT_EWP_PRIVATE_KEY_PWD ?></td>
</tr>
<tr>
<td align="left">Private Key File:</td>
<td align="left"><?php echo DEFAULT_EWP_PRIVATE_KEY_PATH ?></td>
</tr>
<tr>
<td align="left">Cert ID:</td>
<td align="left"><?php echo DEFAULT_CERT_ID ?></td>
</tr>
<tr>
<td align="left">PayPal Certificate:</td>
<td align="left"><?php echo PAYPAL_CERT_PATH ?></td>
</tr>
<tr>
<td align="left">Identity token:</td>
<td align="left"><?php echo DEFAULT_IDENTITY_TOKEN ?></td>
</tr>
<tr>
<td align="left" height="16">
Endpoint(sandbox or live):
</td>
<td align="left" height="16"><?php echo DEFAULT_ENV ?></td>
</tr>
</table>
</form>
</center>
<font size="2" color="black" face="Verdana"><a href="index.html">Home</a></font>
</body>
</HTML> | 10npsite | trunk/Index/Lib/Order/Paypalphp/Credentials.php | PHP | asf20 | 3,774 |
<?php
header("Content-type:text/html; charset=utf-8");
//商户订单号
$pBillNo = date('YmdHis') . mt_rand(100000,999999);
//商户交易日期
$pDate = date('Ymd');
//商户返回地址
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? 'https://' : 'http://';
$url .= str_ireplace('localhost', '127.0.0.1', $_SERVER['HTTP_HOST']) . $_SERVER['SCRIPT_NAME'];
$url = str_ireplace('orderpay', 'OrderReturn', $url);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-Type" content="text/html; charset=utf-8" />
<title>标准商户订单支付接口(新接口)</title>
<style type="text/css">
<!--
TD {FONT-SIZE: 9pt}
SELECT {FONT-SIZE: 9pt}
OPTION {COLOR: #5040aa; FONT-SIZE: 9pt}
INPUT {FONT-SIZE: 9pt}
-->
</style>
<script language="javascript">
function show(zhilian)
{
var obj = document.getElementById("tb1");
if(zhilian == "1")
{
for(i=14; i<20; i++)
{
obj.rows[i].style.display = "block";
}
obj.rows[20].style.display = "none";
obj.rows[21].style.display = "none";
}
else
{
for(i=14; i<20; i++)
{
obj.rows[i].style.display = "none";
}
obj.rows[20].style.display = "block";
obj.rows[21].style.display = "block";
}
}
</script>
</head>
<body>
<form id="form1" action="redirect.php" method="post" >
<table id="tb1" width="400" border="1" cellspacing="0" cellpadding="3" bordercolordark="#FFFFFF" bordercolorlight="#333333" bgcolor="#F0F0FF" align="center">
<tr bgcolor="#8070FF">
<td colspan="2" align="center">
<font color="#FFFF00"><b>商户模拟测试(模拟交易接口)</b></font>
</td>
</tr>
<tr>
<td>商户号</td>
<td>
<input type="text" name="pMerCode" size="18" value="120039" /><!--测试商户号-->
</td>
</tr>
<tr>
<td>订单号</td>
<td>
<input type="text" name="pBillNo" size="24" value="<?php echo $pBillNo; ?>" />
</td>
</tr>
<tr>
<td>支付币种</td>
<td>
<input type="text" name="pCurrency" size="16" value="RMB" />
</td>
</tr>
<tr>
<td>语言</td>
<td>
<select name="pLang" style="width:115px">
<option value="GB">GB中文</option>
<option value="EN">英语</option>
</select>
</td>
</tr>
<tr>
<td>金 额</td>
<td>
<input type="text" name="pAmount" size="16" value="0.10" />
</td>
</tr>
<tr>
<td>日 期</td>
<td>
<input type="text" name="pDate" size="16" value="<?php echo $pDate; ?>" />
</td>
</tr>
<tr>
<td>订单有效期(小时)</td>
<td>
<input type="text" name="pBillEXP" size="16" value="1" />
</td>
</tr>
<tr>
<td>访问者权限</td>
<td>
<input type="text" name="pAuthority" size="16" value="" />
</td>
</tr>
<tr>
<td>持卡人姓名</td>
<td>
<input type="text" name="pName" size="16" value="Dale" />
</td>
</tr>
<tr>
<td>持卡人证件类型</td>
<td>
<select name="pIDType">
<option value="1" selected="selected">身份证</option>
<option value="2">护照</option>
<option value="3">军官证</option>
<option value="4">回乡证</option>
<option value="5">台胞证</option>
<option value="6">港澳通行证</option>
<option value="7">国际海员证</option>
<option value="8">外国人永久居住证</option>
<option value="9">其他</option>
</select>
</td>
</tr>
<tr>
<td>持卡人证件号码</td>
<td>
<input type="text" name="pIDNum" size="24" value="123456789012345678" />
</td>
</tr>
<tr>
<td>持卡人电话</td>
<td>
<input type="text" name="pTel" size="16" value="62107829" />
</td>
</tr>
<tr>
<td>是否直连</td>
<td>
<select name="pDirect" style="width:115px" onchange="show(this.value)">
<option value="1">直连</option>
<option value="" selected="selected">非直连</option>
</select>
</td>
</tr>
<tr>
<td>网关号</td>
<td>
<input type="text" name="pCardType" size="16" value="" />
</td>
</tr>
<tr>
<td>发卡行</td>
<td>
<input type="text" name="pIssueBank" size="16" value="" />
</td>
</tr>
<tr>
<td>发卡行国家</td>
<td>
<input type="text" name="pIssueCountry" size="16" value="" />
</td>
</tr>
<tr>
<td>信用卡号</td>
<td>
<input type="text" name="pCardNum" size="20" value="" />
</td>
</tr>
<tr>
<td>信用卡有效期(MM/YY)</td>
<td>
<input type="text" name="pCardExp" size="16" value="" />
</td>
</tr>
<tr>
<td>CVV2</td>
<td>
<input type="text" name="pCVV" size="3" value="" />
</td>
</tr>
<tr>
<td>授权录入成功返回地址</td>
<td>
<input type="text" name="pAuthSuccessUrl" size="35" value="<?php echo $url; ?>" />
</td>
</tr>
<tr>
<td>授权录入失败返回地址</td>
<td>
<input type="text" name="pAuthFailureUrl" size="35" value="" />
</td>
</tr>
<tr>
<td>网关类型</td>
<td>
<select name="pGateWayType" style="width:115px">
<option value="1">国内信用卡</option>
<option value="2">国际信用卡</option>
</select>
</td>
</tr>
<tr>
<td>订单加密方式</td>
<td>
<select name="pOrderEncodeType" style="width:115px">
<option value="1" selected="selected">RSA</option>
<option value="2">3DES</option>
</select>
</td>
</tr>
<tr>
<td>商品信息(名称|摘要)</td>
<td>
<input type="text" name="pGoodsInfo" size="16" value="测试商品|测试摘要" />
</td>
</tr>
<tr>
<td>商户附加信息</td>
<td>
<input type="text" name="pAttach" size="16" value="test" />
</td>
</tr>
<tr>
<td colspan=2 align=center>
<font color=red>以下是新增的接口参数</font>
</td>
</tr>
<tr>
<td>交易返回加密方式</td>
<td>
<select name="pRetEncodeType" style="width:115px">
<option value="11">md5withRsa</option>
<option value="12" selected="selected">md5摘要</option>
</select>
</td>
</tr>
<tr>
<td>错误信息返回地址</td>
<td>
<input type="text" name="pErrorUrl" size="35" value="" />
</td>
</tr>
<tr>
<td>成功返回的商户URL</td>
<td>
<input type="text" name="pReturnUrl" size="35" value="<?php echo $url; ?>" />
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="submit" /></td>
</tr>
</table>
</form>
<script language="javascript">
show("");
</script>
</body>
</html> | 10npsite | trunk/Index/Lib/Order/CardOnlineIpsRmb/OrderPay.php | PHP | asf20 | 8,149 |
<? echo phpinfo();?> | 10npsite | trunk/Index/Lib/Order/CardOnlineIpsRmb/11.php | PHP | asf20 | 20 |
<?php
require "../../../../global.php";
/****************正式环境请更换以下信息***********************/
//3DES密钥
$DESkey = '1E5HsITy8EtdcC4LrSDKuFSc';
//3DES向量
$DESiv = '1E5HsITy';
//商户的md5证书
$MD5key = '36451620901856065970269330053246181842887948974683586506701057676567422219322046647065958403072037230625137727476541950060891824';
//商户的RSA公钥
$RSAkey = '<RSAKeyValue><Modulus>yPJGRlr88jmJtR31g4mhwDo3qonw9/mR1cWGeYY/a9bk9MyP1BjTu6QRb96Z+V033HLUngYL+pfqZN9+HPjfI5bMsFwScJ+KKDst88ZWP8bs8OWQ89RKr3Voff922rGE3wGZ4N2ycpnE2p+Z9+2wBQJ2UqVoDmj4dGVS4LnCBQ0=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>';
/****************获取表单信息******************************/
//商户号
$pMerCode = $_POST['pMerCode'];
//商户交易订单号
$pBillNo = $_POST['pBillNo'];
//构建特殊的订单形式
if(strstr($pBillNo,",")){
$pBillNo=str_replace(",", $_REQUEST["pAttachpaty"]."", $pBillNo).$_REQUEST["pAttachpaty"];
}else {
$pBillNo.=$_REQUEST["pAttachpaty"];
}
$realorderno=$pBillNo;
//商户附加信息 这里是完整的订单信息
$pAttach = $pBillNo."^".$_REQUEST["pAttach"];
//构建映射表,把真实订单号存入数据库里,再生成一个简短的订单号供支付
require RootDir."/inc/dabase_mysql.php";
$mydb=new YYBDB();
$sql="select * from ".DQ."onlingpayorder where onlingpayorder2='".$pAttach."'";
$res=$mydb->db_query($sql);
if($rs=$mydb->db_fetch_array($res)){
$newordern=$rs["onlingpayorder1"];
}
else{
//生成新的订单号用于向第三方支付
$newordern="M".date("ydmhis").rand(10, 99);
$sql="insert into ".DQ."onlingpayorder (onlingpayorder1,onlingpayorder2) value('".$newordern."','".$pAttach."')";
$mydb->db_query($sql);
}
$pBillNo=$newordern.rand(10, 99);//新生成的16位订单号和最后两位的随机数号
//支付币种
$pCurrency = $_POST['pCurrency'];
//语种
$pLang = $_POST['pLang'];
//订单金额(保留两位小数)
$pAmount = number_format($_POST['pAmount'], 2, '.', '');
//商户录入日期
$pDate = $_POST['pDate'];
//信用卡种类
$pGateWayType = $_POST['pGateWayType'];
//录入返回签名方式
$pRetEncodeType = $_POST['pRetEncodeType'];
//订单有效期
$pBillEXP = $_POST['pBillEXP'];
//支付结果返回地址
$pReturnUrl = "http://".$_SERVER['SERVER_NAME']."/Index/Lib/Order/CardOnlineIpsRmb/OrderReturn.php";
//错误返回地址
$pErrorUrl = "http://".$_SERVER['SERVER_NAME']."/Index/Lib/Order/CardOnlineIpsRmb/OrderReturn.php";
//订单加密方式(pCardInfo的加密方式)
$pOrderEncodeType = $_POST['pOrderEncodeType'];
//支付结果返回方式:0 ( HTTP方式)
$pResultType = '0';
//访问者权限
$pAuthority = $_POST['pAuthority'];
//备用
$pDetails = '';
//商品信息
$pGoodsInfo = $_POST['pGoodsInfo'];
//是否直连
$pDirect = $_POST['pDirect'];
//持卡人加密信息
$pCardInfo = '';
//pDirect=1是直连方式,pDirect为空是非直连方式
if ($_POST['pDirect'] == '1')
{
$pCardInfo = $_POST['pName'] . '|' .
$_POST['pIDType'] . '|' .
$_POST['pIDNum'] . '|' .
$_POST['pTel'] . '|' .
$_POST['pCardExp'] . '|' .
$_POST['pCardType'] . '|' .
$_POST['pCardNum'] . '|' .
$_POST['pIssueBank'] . '|' .
$_POST['pIssueCountry'] . '|' .
$_POST['pCVV'];
}
else
{
$pCardInfo = $_POST['pName'] . '|' .
$_POST['pIDType'] . '|' .
$_POST['pIDNum'] . '|' .
$_POST['pTel'];
}
//RSA加密
if ($pOrderEncodeType == '1')
{
require_once('rsa.function.php');
//读取RSA公钥中的Modulus和Exponent
$xml = new DOMDocument();
$xml->loadXML($RSAkey);
$Modulus = $xml->getElementsByTagName('Modulus')->item(0)->nodeValue;
$Exponent = $xml->getElementsByTagName('Exponent')->item(0)->nodeValue;
unset($xml);
$publicKey = kimssl_pkey_get_public($Modulus, $Exponent);
openssl_public_encrypt($pCardInfo, $pCardInfo, $publicKey);
$pCardInfo = base64_encode($pCardInfo);
openssl_free_key($publicKey);
}
//3DES加密
if ($pOrderEncodeType == '2')
{
require_once('des.class.php');
//创建3DES的对象
$DES = new DES;
//3DES密钥
$DES->key = $DESkey;
//3DES向量
$DES->iv = $DESiv;
//调用3DES的加密方法
$pCardInfo = $DES->DESEncrypt($pCardInfo);
}
//md5的source
$strMd5Temp = $pBillNo . $pMerCode . $pCurrency . $pAmount . $pDate . $MD5key;
//md5的摘要
$pSignMD5 = md5($strMd5Temp);
//提交的信用卡支付网关的url地址(正式环境请更改为:https://gw5.ips.com.cn:444/B2C/AuthTrade/Pay.aspx)
$actionUrl = 'https://gw5.ips.com.cn:444/B2C/AuthTrade/Pay.aspx';
//=======================================初始化梦之旅订单信息
$pBillNoarr=explode(",", $pAttach);
preg_match("/[t|h][\d]{7}j[\d]/", $pAttach,$pBillNoarr);
$pricelist=$_REQUEST["pAttach"];
$alimoneylistarr=explode(",", $pricelist);
$i=0;
$pBillNotemp="";
foreach ($pBillNoarr as $v){
$sql="select pay1 from ".$SystemConest[7]."pay where pay1='".$v."'";
$res=$mydb->db_query($sql);
if($mydb->db_num_rows($res)<1){
$sql="insert into ".$SystemConest[7]."pay (pay1,pay2,pay3,pay5) value('".$v."',573,".$alimoneylistarr[$i].",'环讯信用卡')";
$mydb->db_query($sql);
}
$i++;
}
//pDirect=1采用webservice直连方式处理
if($pDirect == '1')
{
//参数转为数组形式传递
$strxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<OrderInfo>
<pBillNo>{$pBillNo}</pBillNo>
<pMerCode>{$pMerCode}</pMerCode>
<pCurrency>{$pCurrency}</pCurrency>
<pLang>{$pLang}</pLang>
<pAmount>{$pAmount}</pAmount>
<pDate>{$pDate}</pDate>
<pGateWayType>{$pGateWayType}</pGateWayType>
<pAttach>{$pAttach}</pAttach>
<pRetEncodeType>{$pRetEncodeType}</pRetEncodeType>
<pOrderEncodeType>{$pOrderEncodeType}</pOrderEncodeType>
<pSignMD5>{$pSignMD5}</pSignMD5>
<pBillEXP>{$pBillEXP}</pBillEXP>
<pReturnUrl>{$pReturnUrl}</pReturnUrl>
<pCardInfo>{$pCardInfo}</pCardInfo>
<pResultType>{$pResultType}</pResultType>
<pAuthority>{$pAuthority}</pAuthority>
<pDetails>{$pDetails}</pDetails>
<pGoodsInfo>{$pGoodsInfo}</pGoodsInfo>
</OrderInfo>";
if(!extension_loaded('soap'))
{
echo '请安装并加载soap扩展!';
exit;
}
//调用WebService:正式环境请更改webservice地址为https://gw5.ips.com.cn:444/B2C/AuthTrade/PaymentWService.asmx?WSDL
$objSoapClient = new SoapClient('http://payAT.ips.com.cn/B2C/AuthTrade/PaymentWService.asmx?WSDL');
$aryResult = $objSoapClient->SubmitOrder($strxml);
/**************************WebService返回处理逻辑********************************
1.判断pSucc
若 pSucc 等“S”, 表示录入成功; 若等于“F”, 表示录入失败, 此时无需再进行以下步骤。
2.数据验证
可以使用IPS 提供的签名验证组件,对返回的关键信息进行验证,以确保订单信息
安全,防止黑客恶意攻击及篡改订单信息。
3.判断订单号和金额
为安全起见,商户应该将自己系统中存放的订单信息和IPS 返回的订单信息进行比对,
以保证订单数据真实可信。建议比对的项:订单编号和订单金额。
4.在成功完成以上步骤后,商户可以根据需要进行其他操作。
*******************************************************************************/
if(!extension_loaded('dom'))
{
echo '不支持DOM!';
exit;
}
$xml = new DOMDocument();
$xml->loadXML($aryResult);
//录入结果: S-录入成功 F-录入失败
$pSucc = $xml->getElementsByTagName('pSucc')->item(0)->nodeValue;
//返回信息
$pMsg = $xml->getElementsByTagName('pMsg')->item(0)->nodeValue;
if($pSucc == 'S')
{
//商户订单号
$pBillNo = $xml->getElementsByTagName('pBillNo')->item(0)->nodeValue;
//订单金额
$pAmount = $xml->getElementsByTagName('pAmount')->item(0)->nodeValue;
//订单日期
$pDate = $xml->getElementsByTagName('pDate')->item(0)->nodeValue;
//IPS订单号
$pIpsBillNo = $xml->getElementsByTagName('pIpsBillNo')->item(0)->nodeValue;
//币种
$pCurrency = $xml->getElementsByTagName('pCurrency')->item(0)->nodeValue;
//签名
$pSignature = $xml->getElementsByTagName('pSignature')->item(0)->nodeValue;
unset($xml);
//签名原文:订单编号+订单金额+订单日期+成功标志+IPS订单编号+币种
$content = $pBillNo . $pAmount . $pDate . $pSucc . $pIpsBillNo . $pCurrency;
//签名验证是否通过
$verify = false;
//md5withrsa的签名验证方式
if($pRetEncodeType == '11')
{
//创建com组件
$MD5withRSA = new COM('IpsVerify.RSAMd5');
//使用公钥文件的绝对路径
$result = $MD5withRSA->VerifyMessage("C:\\PubKey\\pub.txt", $content, $pSignature);
/*******************
返回代码定义
0 表示签名验证成功
-1 表示系统错误
-2 表示文件绑定错误
-3 表示读取公钥失败
-4 表示签名长度错
-5 表示签名验证失败
-99 表示系统锁定失败
*******************/
if($result == 0)
{
$verify = true;
}
}
//md5摘要验证方式
if($pRetEncodeType == '12')
{
//明文=订单编号+订单金额+订单日期+成功标志+IPS订单编号+币种+商户证书
$signature_local = md5($content . $MD5key);
if($pSignature == $signature_local)
{
$verify = true;
}
}
if($verify)
{
echo '录入成功!';
exit();
}
else
{
echo '签名验证失败!';
exit();
}
}
else
{
echo "录入失败:$pMsg";
exit();
}
}
else
{
//录入成功返回地址
$pAuthSuccessUrl = $_POST['pAuthSuccessUrl'];
//录入失败返回地址
$pAuthFailureUrl = $_POST['pAuthFailureUrl'];
?>
<html>
<head>
<title>跳转......</title>
<meta http-equiv="content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form name="sendOrder" id="sendOrder" method="post" action="<?php echo $actionUrl; ?>">
<input type="hidden" name="pBillNo" value="<?php echo $pBillNo; ?>" />
<input type="hidden" name="pMerCode" value="<?php echo $pMerCode; ?>" />
<input type="hidden" name="pCurrency" value="<?php echo $pCurrency; ?>" />
<input type="hidden" name="pLang" value="<?php echo $pLang; ?>" />
<input type="hidden" name="pAmount" value="<?php echo $pAmount; ?>" />
<input type="hidden" name="pDate" value="<?php echo $pDate; ?>" />
<input type="hidden" name="pAttach" value="<?php echo $pAttach; ?>" />
<input type="hidden" name="pGateWayType" value="<?php echo $pGateWayType; ?>" />
<input type="hidden" name="pRetEncodeType" value="<?php echo $pRetEncodeType; ?>" />
<input type="hidden" name="pOrderEncodeType" value="<?php echo $pOrderEncodeType; ?>" />
<input type="hidden" name="pSignMD5" value="<?php echo $pSignMD5; ?>" />
<input type="hidden" name="pAuthority" value="<?php echo $pAuthority; ?>" />
<input type="hidden" name="pBillEXP" value="<?php echo $pBillEXP; ?>" />
<input type="hidden" name="pCardInfo" value="<?php echo $pCardInfo; ?>" />
<input type="hidden" name="pResultType" value="<?php echo $pResultType; ?>" />
<input type="hidden" name="pReturnUrl" value="<?php echo $pReturnUrl; ?>" />
<input type="hidden" name="pAuthSuccessUrl" value="<?php echo $pAuthSuccessUrl; ?>" />
<input type="hidden" name="pAuthFailureUrl" value="<?php echo $pAuthFailureUrl; ?>" />
<input type="hidden" name="pGoodsInfo" value="<?php echo $pGoodsInfo; ?>" />
</form>
<script language="javascript">
document.getElementById("sendOrder").submit();
</script>
</body>
</html>
<?php
}
?> | 10npsite | trunk/Index/Lib/Order/CardOnlineIpsRmb/redirect.php | PHP | asf20 | 12,305 |
<?php
require "../../../global.php";
/*信用卡支付订单返回接收页面
*注意:由于可能多次返回支付结果,故需要商户的系统有能力处理多次返回的情况.
*/
//商户证书
$md5cert = '36451620901856065970269330053246181842887948974683586506701057676567422219322046647065958403072037230625137727476541950060891824';
//商户订单号
$pBillNo = $_GET['pBillNo'];//这里的订单号映射的订单号
//商户号
$pMerCode = $_GET['pMerCode'];
//支付币种
$pCurrency = $_GET['pCurrency'];
//交易金额
$pAmount = $_GET['pAmount'];
//商户录入日期
$pDate = $_GET['pDate'];
//结果标志: Y– 成功 N – 失败 S-录入成功 F-录入失败
$pSucc = $_GET['pSucc'];
//返回的加密方式
$pRetEncodeType = $_GET['pRetEncodeType'];
//附加信息
/*这里获取的是完整的订单号
* 格式如:t0000087j1t0000088j113^17228,36.8 * ^符号后面的是金额列表,多个用逗号分隔
*
*/
$pAttach = $_GET['pAttach'];
//数字签名
$pSignature = $_GET['pSignature'];
//IPS处理时间
$pIpsBankTime = $_GET['pIpsBankTime'];
//IPS订单号
$pIpsBillNo = $_GET['pIpsBillNo'];//只是前30位,不一定全,所以以$pAttach为准
//银行返回信息
$pMsg = $_GET['pMsg'];
//验证明文
$content = $pBillNo . $pAmount . $pDate . $pSucc . $pIpsBillNo . $pCurrency;
/********************************非直连返回处理逻辑*****************************
1.数据验证
可以使用IPS 提供的签名验证组件,对返回的关键信息进行验证,以确保订单信息
安全,防止黑客恶意攻击及篡改订单信息。
2.判断 pSucc
若 pSucc 等“S”, 表示录入成功; 若等于“F”, 表示录入失败, 此时无需再进行以下步骤。
若 pSucc 等“Y”, 表示支付成功; 若等于“N”, 表示支付失败。
3.判断订单号和金额
为安全起见,商户应该将自己系统中存放的订单信息和IPS 返回的订单信息进行比对,
以保证订单数据真实可信。建议比对的项:订单编号和订单金额。
4.在成功完成以上步骤后,商户可以根据需要进行其他操作。
*******************************************************************************/
//验证结果
$verify = false;
//先验证签名,再判断交易是否成功
//MD5WithRSA验证
if ($pRetEncodeType == '11')
{
//创建com组件
$MD5withRSA = new COM('IpsVerify.RSAMd5');
//使用公钥文件的绝对路径
$result = $MD5withRSA->VerifyMessage("C:\\PubKey\\pub.txt", $content, $pSignature);
/*******************
返回代码定义
0 表示签名验证成功
-1 表示系统错误
-2 表示文件绑定错误
-3 表示读取公钥失败
-4 表示签名长度错
-5 表示签名验证失败
-99 表示系统锁定失败
*******************/
if ($result == 0)
{
$verify = true;
}
}
//md5摘要验证
if($pRetEncodeType == '12')
{
//明文=订单编号+订单金额+订单日期+成功标志+IPS订单编号+币种+商户证书
$content = $content . $md5cert;
$signature_local = MD5($content);
if ($signature_local == $pSignature)
{
$verify = true;
}
}
//签名验证结果
if($verify)
{
switch($pSucc)
{
Case "S":
//录入结果成功
echo '录入成功';
break;
Case "F":
//录入结果失败,商户可以记录失败原因或做其他操作
echo '录入失败' . $pMsg;
break;
Case "Y":
//支付结果成功,对返回的订单信息和商户数据库里的订单信息做核对--主要核对订单号,金额,日期等是否一致
require RootDir."/inc/dabase_mysql.php";
$mydb=new YYBDB();
//获取各个订单号 $pBillNo为映射订单号
$pBillNo=substr($pBillNo, 0,-2);//去除最后两位随机数
$sql="select * from ".DQ."onlingpayorder where onlingpayorder1='".$pBillNo."'";
$res=$mydb->query($sql);
if($rs=$mydb->db_fetch_array($res)){
$realorder=$rs["onlingpayorder2"];
}
if($realorder=="") die("参数错误");
preg_match("/[t|h][\d]{7}j[\d]{1}/",$realorder,$orderlist);//获取订单号列表
$pAmounts=preg_replace("/^[\w]+\^/","",$realorder);
$pAmountsarr=explode(",", $pAmounts);
$i=0;
$dingdan="";
foreach ($orderlist as $order){
$orderno=preg_replace("/j[\d]$/", "", $order);
$payflag=str_replace($orderno, "", $order);
if($payflag=="j1"){
$sql2="pay3=".$pAmountsarr[$i].",pay4=".time().",pay5='环讯信用卡',pay6=1";
}
if($payflag=="j2"){
$sql2="pay7=".$pAmountsarr[$i].",pay8=".time().",pay9='环讯信用卡',pay10=1";
}
$sql="update ".$SystemConest[7]."pay set ".$sql2." where pay1='".$orderno."'";
$mydb->db_query($sql);
$i++;
$dingdanlist.=$orderno."|".$SystemConest[7]."|".$payflag.",";
}
//支付成功,执行发送邮件操作
$dingdan=substr($dingdan, 0,-1);
echo "<iframe src='/sendmail/paysuss-orderlist-".$dingdanlist."' frameborder=0 scrolling=no width=1 height=1></iframe>";
unset($rs);
$url="/pay/showpaysuss-orderlist-".$dingdanl."";
gourl($url,1);
break;
Case "N":
//支付结果失败,商户可以记录失败原因或做其他操作
echo '支付失败' . $pMsg;
break;
}
}
else
{
echo '签名验证失败';
}
?>
| 10npsite | trunk/Index/Lib/Order/CardOnlineIpsRmb/OrderReturn.php | PHP | asf20 | 5,459 |
<?php
/*
$Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $
NuSOAP - Web Services Toolkit for PHP
Copyright (c) 2002 NuSphere Corporation
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you have any questions or comments, please email:
Dietrich Ayala
dietrich@ganx4.com
http://dietrich.ganx4.com/nusoap
NuSphere Corporation
http://www.nusphere.com
*/
/* load classes
// necessary classes
require_once('class.soapclient.php');
require_once('class.soap_val.php');
require_once('class.soap_parser.php');
require_once('class.soap_fault.php');
// transport classes
require_once('class.soap_transport_http.php');
// optional add-on classes
require_once('class.xmlschema.php');
require_once('class.wsdl.php');
// server class
require_once('class.soap_server.php');*/
// class variable emulation
// cf. http://www.webkreator.com/php/techniques/php-static-class-variables.html
$GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel = 9;
/**
*
* nusoap_base
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $
* @access public
*/
class nusoap_base {
/**
* Identification for HTTP headers.
*
* @var string
* @access private
*/
var $title = 'NuSOAP';
/**
* Version for HTTP headers.
*
* @var string
* @access private
*/
var $version = '0.7.2';
/**
* CVS revision for HTTP headers.
*
* @var string
* @access private
*/
var $revision = '$Revision: 1.94 $';
/**
* Current error string (manipulated by getError/setError)
*
* @var string
* @access private
*/
var $error_str = '';
/**
* Current debug string (manipulated by debug/appendDebug/clearDebug/getDebug/getDebugAsXMLComment)
*
* @var string
* @access private
*/
var $debug_str = '';
/**
* toggles automatic encoding of special characters as entities
* (should always be true, I think)
*
* @var boolean
* @access private
*/
var $charencoding = true;
/**
* the debug level for this instance
*
* @var integer
* @access private
*/
var $debugLevel;
/**
* set schema version
*
* @var string
* @access public
*/
var $XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema';
/**
* charset encoding for outgoing messages
*
* @var string
* @access public
*/
var $soap_defencoding = 'ISO-8859-1';
//var $soap_defencoding = 'UTF-8';
/**
* namespaces in an array of prefix => uri
*
* this is "seeded" by a set of constants, but it may be altered by code
*
* @var array
* @access public
*/
var $namespaces = array(
'SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/',
'xsd' => 'http://www.w3.org/2001/XMLSchema',
'xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/'
);
/**
* namespaces used in the current context, e.g. during serialization
*
* @var array
* @access private
*/
var $usedNamespaces = array();
/**
* XML Schema types in an array of uri => (array of xml type => php type)
* is this legacy yet?
* no, this is used by the xmlschema class to verify type => namespace mappings.
* @var array
* @access public
*/
var $typemap = array(
'http://www.w3.org/2001/XMLSchema' => array(
'string'=>'string','boolean'=>'boolean','float'=>'double','double'=>'double','decimal'=>'double',
'duration'=>'','dateTime'=>'string','time'=>'string','date'=>'string','gYearMonth'=>'',
'gYear'=>'','gMonthDay'=>'','gDay'=>'','gMonth'=>'','hexBinary'=>'string','base64Binary'=>'string',
// abstract "any" types
'anyType'=>'string','anySimpleType'=>'string',
// derived datatypes
'normalizedString'=>'string','token'=>'string','language'=>'','NMTOKEN'=>'','NMTOKENS'=>'','Name'=>'','NCName'=>'','ID'=>'',
'IDREF'=>'','IDREFS'=>'','ENTITY'=>'','ENTITIES'=>'','integer'=>'integer','nonPositiveInteger'=>'integer',
'negativeInteger'=>'integer','long'=>'integer','int'=>'integer','short'=>'integer','byte'=>'integer','nonNegativeInteger'=>'integer',
'unsignedLong'=>'','unsignedInt'=>'','unsignedShort'=>'','unsignedByte'=>'','positiveInteger'=>''),
'http://www.w3.org/2000/10/XMLSchema' => array(
'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double',
'float'=>'double','dateTime'=>'string',
'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'),
'http://www.w3.org/1999/XMLSchema' => array(
'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double',
'float'=>'double','dateTime'=>'string',
'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'),
'http://soapinterop.org/xsd' => array('SOAPStruct'=>'struct'),
'http://schemas.xmlsoap.org/soap/encoding/' => array('base64'=>'string','array'=>'array','Array'=>'array'),
'http://xml.apache.org/xml-soap' => array('Map')
);
/**
* XML entities to convert
*
* @var array
* @access public
* @deprecated
* @see expandEntities
*/
var $xmlEntities = array('quot' => '"','amp' => '&',
'lt' => '<','gt' => '>','apos' => "'");
/**
* constructor
*
* @access public
*/
function nusoap_base() {
$this->debugLevel = $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel;
}
/**
* gets the global debug level, which applies to future instances
*
* @return integer Debug level 0-9, where 0 turns off
* @access public
*/
function getGlobalDebugLevel() {
return $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel;
}
/**
* sets the global debug level, which applies to future instances
*
* @param int $level Debug level 0-9, where 0 turns off
* @access public
*/
function setGlobalDebugLevel($level) {
$GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel = $level;
}
/**
* gets the debug level for this instance
*
* @return int Debug level 0-9, where 0 turns off
* @access public
*/
function getDebugLevel() {
return $this->debugLevel;
}
/**
* sets the debug level for this instance
*
* @param int $level Debug level 0-9, where 0 turns off
* @access public
*/
function setDebugLevel($level) {
$this->debugLevel = $level;
}
/**
* adds debug data to the instance debug string with formatting
*
* @param string $string debug data
* @access private
*/
function debug($string){
if ($this->debugLevel > 0) {
$this->appendDebug($this->getmicrotime().' '.get_class($this).": $string\n");
}
}
/**
* adds debug data to the instance debug string without formatting
*
* @param string $string debug data
* @access public
*/
function appendDebug($string){
if ($this->debugLevel > 0) {
// it would be nice to use a memory stream here to use
// memory more efficiently
$this->debug_str .= $string;
}
}
/**
* clears the current debug data for this instance
*
* @access public
*/
function clearDebug() {
// it would be nice to use a memory stream here to use
// memory more efficiently
$this->debug_str = '';
}
/**
* gets the current debug data for this instance
*
* @return debug data
* @access public
*/
function &getDebug() {
// it would be nice to use a memory stream here to use
// memory more efficiently
return $this->debug_str;
}
/**
* gets the current debug data for this instance as an XML comment
* this may change the contents of the debug data
*
* @return debug data as an XML comment
* @access public
*/
function &getDebugAsXMLComment() {
// it would be nice to use a memory stream here to use
// memory more efficiently
while (strpos($this->debug_str, '--')) {
$this->debug_str = str_replace('--', '- -', $this->debug_str);
}
return "<!--\n" . $this->debug_str . "\n-->";
}
/**
* expands entities, e.g. changes '<' to '<'.
*
* @param string $val The string in which to expand entities.
* @access private
*/
function expandEntities($val) {
if ($this->charencoding) {
$val = str_replace('&', '&', $val);
$val = str_replace("'", ''', $val);
$val = str_replace('"', '"', $val);
$val = str_replace('<', '<', $val);
$val = str_replace('>', '>', $val);
}
return $val;
}
/**
* returns error string if present
*
* @return mixed error string or false
* @access public
*/
function getError(){
if($this->error_str != ''){
return $this->error_str;
}
return false;
}
/**
* sets error string
*
* @return boolean $string error string
* @access private
*/
function setError($str){
$this->error_str = $str;
}
/**
* detect if array is a simple array or a struct (associative array)
*
* @param mixed $val The PHP array
* @return string (arraySimple|arrayStruct)
* @access private
*/
function isArraySimpleOrStruct($val) {
$keyList = array_keys($val);
foreach ($keyList as $keyListValue) {
if (!is_int($keyListValue)) {
return 'arrayStruct';
}
}
return 'arraySimple';
}
/**
* serializes PHP values in accordance w/ section 5. Type information is
* not serialized if $use == 'literal'.
*
* @param mixed $val The value to serialize
* @param string $name The name (local part) of the XML element
* @param string $type The XML schema type (local part) for the element
* @param string $name_ns The namespace for the name of the XML element
* @param string $type_ns The namespace for the type of the element
* @param array $attributes The attributes to serialize as name=>value pairs
* @param string $use The WSDL "use" (encoded|literal)
* @return string The serialized element, possibly with child elements
* @access public
*/
function serialize_val($val,$name=false,$type=false,$name_ns=false,$type_ns=false,$attributes=false,$use='encoded'){
$this->debug("in serialize_val: name=$name, type=$type, name_ns=$name_ns, type_ns=$type_ns, use=$use");
$this->appendDebug('value=' . $this->varDump($val));
$this->appendDebug('attributes=' . $this->varDump($attributes));
if(is_object($val) && get_class($val) == 'soapval'){
return $val->serialize($use);
}
// force valid name if necessary
if (is_numeric($name)) {
$name = '__numeric_' . $name;
} elseif (! $name) {
$name = 'noname';
}
// if name has ns, add ns prefix to name
$xmlns = '';
if($name_ns){
$prefix = 'nu'.rand(1000,9999);
$name = $prefix.':'.$name;
$xmlns .= " xmlns:$prefix=\"$name_ns\"";
}
// if type is prefixed, create type prefix
if($type_ns != '' && $type_ns == $this->namespaces['xsd']){
// need to fix this. shouldn't default to xsd if no ns specified
// w/o checking against typemap
$type_prefix = 'xsd';
} elseif($type_ns){
$type_prefix = 'ns'.rand(1000,9999);
$xmlns .= " xmlns:$type_prefix=\"$type_ns\"";
}
// serialize attributes if present
$atts = '';
if($attributes){
foreach($attributes as $k => $v){
$atts .= " $k=\"".$this->expandEntities($v).'"';
}
}
// serialize null value
if (is_null($val)) {
if ($use == 'literal') {
// TODO: depends on minOccurs
return "<$name$xmlns $atts/>";
} else {
if (isset($type) && isset($type_prefix)) {
$type_str = " xsi:type=\"$type_prefix:$type\"";
} else {
$type_str = '';
}
return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>";
}
}
// serialize if an xsd built-in primitive type
if($type != '' && isset($this->typemap[$this->XMLSchemaVersion][$type])){
if (is_bool($val)) {
if ($type == 'boolean') {
$val = $val ? 'true' : 'false';
} elseif (! $val) {
$val = 0;
}
} else if (is_string($val)) {
$val = $this->expandEntities($val);
}
if ($use == 'literal') {
return "<$name$xmlns $atts>$val</$name>";
} else {
return "<$name$xmlns $atts xsi:type=\"xsd:$type\">$val</$name>";
}
}
// detect type and serialize
$xml = '';
switch(true) {
case (is_bool($val) || $type == 'boolean'):
if ($type == 'boolean') {
$val = $val ? 'true' : 'false';
} elseif (! $val) {
$val = 0;
}
if ($use == 'literal') {
$xml .= "<$name$xmlns $atts>$val</$name>";
} else {
$xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val</$name>";
}
break;
case (is_int($val) || is_long($val) || $type == 'int'):
if ($use == 'literal') {
$xml .= "<$name$xmlns $atts>$val</$name>";
} else {
$xml .= "<$name$xmlns xsi:type=\"xsd:int\"$atts>$val</$name>";
}
break;
case (is_float($val)|| is_double($val) || $type == 'float'):
if ($use == 'literal') {
$xml .= "<$name$xmlns $atts>$val</$name>";
} else {
$xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val</$name>";
}
break;
case (is_string($val) || $type == 'string'):
$val = $this->expandEntities($val);
if ($use == 'literal') {
$xml .= "<$name$xmlns $atts>$val</$name>";
} else {
$xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val</$name>";
}
break;
case is_object($val):
if (! $name) {
$name = get_class($val);
$this->debug("In serialize_val, used class name $name as element name");
} else {
$this->debug("In serialize_val, do not override name $name for element name for class " . get_class($val));
}
foreach(get_object_vars($val) as $k => $v){
$pXml = isset($pXml) ? $pXml.$this->serialize_val($v,$k,false,false,false,false,$use) : $this->serialize_val($v,$k,false,false,false,false,$use);
}
$xml .= '<'.$name.'>'.$pXml.'</'.$name.'>';
break;
break;
case (is_array($val) || $type):
// detect if struct or array
$valueType = $this->isArraySimpleOrStruct($val);
if($valueType=='arraySimple' || ereg('^ArrayOf',$type)){
$i = 0;
if(is_array($val) && count($val)> 0){
foreach($val as $v){
if(is_object($v) && get_class($v) == 'soapval'){
$tt_ns = $v->type_ns;
$tt = $v->type;
} elseif (is_array($v)) {
$tt = $this->isArraySimpleOrStruct($v);
} else {
$tt = gettype($v);
}
$array_types[$tt] = 1;
// TODO: for literal, the name should be $name
$xml .= $this->serialize_val($v,'item',false,false,false,false,$use);
++$i;
}
if(count($array_types) > 1){
$array_typename = 'xsd:anyType';
} elseif(isset($tt) && isset($this->typemap[$this->XMLSchemaVersion][$tt])) {
if ($tt == 'integer') {
$tt = 'int';
}
$array_typename = 'xsd:'.$tt;
} elseif(isset($tt) && $tt == 'arraySimple'){
$array_typename = 'SOAP-ENC:Array';
} elseif(isset($tt) && $tt == 'arrayStruct'){
$array_typename = 'unnamed_struct_use_soapval';
} else {
// if type is prefixed, create type prefix
if ($tt_ns != '' && $tt_ns == $this->namespaces['xsd']){
$array_typename = 'xsd:' . $tt;
} elseif ($tt_ns) {
$tt_prefix = 'ns' . rand(1000, 9999);
$array_typename = "$tt_prefix:$tt";
$xmlns .= " xmlns:$tt_prefix=\"$tt_ns\"";
} else {
$array_typename = $tt;
}
}
$array_type = $i;
if ($use == 'literal') {
$type_str = '';
} else if (isset($type) && isset($type_prefix)) {
$type_str = " xsi:type=\"$type_prefix:$type\"";
} else {
$type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"".$array_typename."[$array_type]\"";
}
// empty array
} else {
if ($use == 'literal') {
$type_str = '';
} else if (isset($type) && isset($type_prefix)) {
$type_str = " xsi:type=\"$type_prefix:$type\"";
} else {
$type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"xsd:anyType[0]\"";
}
}
// TODO: for array in literal, there is no wrapper here
$xml = "<$name$xmlns$type_str$atts>".$xml."</$name>";
} else {
// got a struct
if(isset($type) && isset($type_prefix)){
$type_str = " xsi:type=\"$type_prefix:$type\"";
} else {
$type_str = '';
}
if ($use == 'literal') {
$xml .= "<$name$xmlns $atts>";
} else {
$xml .= "<$name$xmlns$type_str$atts>";
}
foreach($val as $k => $v){
// Apache Map
if ($type == 'Map' && $type_ns == 'http://xml.apache.org/xml-soap') {
$xml .= '<item>';
$xml .= $this->serialize_val($k,'key',false,false,false,false,$use);
$xml .= $this->serialize_val($v,'value',false,false,false,false,$use);
$xml .= '</item>';
} else {
$xml .= $this->serialize_val($v,$k,false,false,false,false,$use);
}
}
$xml .= "</$name>";
}
break;
default:
$xml .= 'not detected, got '.gettype($val).' for '.$val;
break;
}
return $xml;
}
/**
* serializes a message
*
* @param string $body the XML of the SOAP body
* @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers
* @param array $namespaces optional the namespaces used in generating the body and headers
* @param string $style optional (rpc|document)
* @param string $use optional (encoded|literal)
* @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
* @return string the message
* @access public
*/
function serializeEnvelope($body,$headers=false,$namespaces=array(),$style='rpc',$use='encoded',$encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'){
// TODO: add an option to automatically run utf8_encode on $body and $headers
// if $this->soap_defencoding is UTF-8. Not doing this automatically allows
// one to send arbitrary UTF-8 characters, not just characters that map to ISO-8859-1
$this->debug("In serializeEnvelope length=" . strlen($body) . " body (max 1000 characters)=" . substr($body, 0, 1000) . " style=$style use=$use encodingStyle=$encodingStyle");
$this->debug("headers:");
$this->appendDebug($this->varDump($headers));
$this->debug("namespaces:");
$this->appendDebug($this->varDump($namespaces));
// serialize namespaces
$ns_string = '';
foreach(array_merge($this->namespaces,$namespaces) as $k => $v){
$ns_string .= " xmlns:$k=\"$v\"";
}
if($encodingStyle) {
$ns_string = " SOAP-ENV:encodingStyle=\"$encodingStyle\"$ns_string";
}
// serialize headers
if($headers){
if (is_array($headers)) {
$xml = '';
foreach ($headers as $header) {
$xml .= $this->serialize_val($header, false, false, false, false, false, $use);
}
$headers = $xml;
$this->debug("In serializeEnvelope, serialzied array of headers to $headers");
}
$headers = "<SOAP-ENV:Header>".$headers."</SOAP-ENV:Header>";
}
// serialize envelope
return
'<?xml version="1.0" encoding="'.$this->soap_defencoding .'"?'.">".
'<SOAP-ENV:Envelope'.$ns_string.">".
$headers.
"<SOAP-ENV:Body>".
$body.
"</SOAP-ENV:Body>".
"</SOAP-ENV:Envelope>";
}
/**
* formats a string to be inserted into an HTML stream
*
* @param string $str The string to format
* @return string The formatted string
* @access public
* @deprecated
*/
function formatDump($str){
$str = htmlspecialchars($str);
return nl2br($str);
}
/**
* contracts (changes namespace to prefix) a qualified name
*
* @param string $qname qname
* @return string contracted qname
* @access private
*/
function contractQname($qname){
// get element namespace
//$this->xdebug("Contract $qname");
if (strrpos($qname, ':')) {
// get unqualified name
$name = substr($qname, strrpos($qname, ':') + 1);
// get ns
$ns = substr($qname, 0, strrpos($qname, ':'));
$p = $this->getPrefixFromNamespace($ns);
if ($p) {
return $p . ':' . $name;
}
return $qname;
} else {
return $qname;
}
}
/**
* expands (changes prefix to namespace) a qualified name
*
* @param string $string qname
* @return string expanded qname
* @access private
*/
function expandQname($qname){
// get element prefix
if(strpos($qname,':') && !ereg('^http://',$qname)){
// get unqualified name
$name = substr(strstr($qname,':'),1);
// get ns prefix
$prefix = substr($qname,0,strpos($qname,':'));
if(isset($this->namespaces[$prefix])){
return $this->namespaces[$prefix].':'.$name;
} else {
return $qname;
}
} else {
return $qname;
}
}
/**
* returns the local part of a prefixed string
* returns the original string, if not prefixed
*
* @param string $str The prefixed string
* @return string The local part
* @access public
*/
function getLocalPart($str){
if($sstr = strrchr($str,':')){
// get unqualified name
return substr( $sstr, 1 );
} else {
return $str;
}
}
/**
* returns the prefix part of a prefixed string
* returns false, if not prefixed
*
* @param string $str The prefixed string
* @return mixed The prefix or false if there is no prefix
* @access public
*/
function getPrefix($str){
if($pos = strrpos($str,':')){
// get prefix
return substr($str,0,$pos);
}
return false;
}
/**
* pass it a prefix, it returns a namespace
*
* @param string $prefix The prefix
* @return mixed The namespace, false if no namespace has the specified prefix
* @access public
*/
function getNamespaceFromPrefix($prefix){
if (isset($this->namespaces[$prefix])) {
return $this->namespaces[$prefix];
}
//$this->setError("No namespace registered for prefix '$prefix'");
return false;
}
/**
* returns the prefix for a given namespace (or prefix)
* or false if no prefixes registered for the given namespace
*
* @param string $ns The namespace
* @return mixed The prefix, false if the namespace has no prefixes
* @access public
*/
function getPrefixFromNamespace($ns) {
foreach ($this->namespaces as $p => $n) {
if ($ns == $n || $ns == $p) {
$this->usedNamespaces[$p] = $n;
return $p;
}
}
return false;
}
/**
* returns the time in ODBC canonical form with microseconds
*
* @return string The time in ODBC canonical form with microseconds
* @access public
*/
function getmicrotime() {
if (function_exists('gettimeofday')) {
$tod = gettimeofday();
$sec = $tod['sec'];
$usec = $tod['usec'];
} else {
$sec = time();
$usec = 0;
}
return strftime('%Y-%m-%d %H:%M:%S', $sec) . '.' . sprintf('%06d', $usec);
}
/**
* Returns a string with the output of var_dump
*
* @param mixed $data The variable to var_dump
* @return string The output of var_dump
* @access public
*/
function varDump($data) {
ob_start();
var_dump($data);
$ret_val = ob_get_contents();
ob_end_clean();
return $ret_val;
}
}
// XML Schema Datatype Helper Functions
//xsd:dateTime helpers
/**
* convert unix timestamp to ISO 8601 compliant date string
*
* @param string $timestamp Unix time stamp
* @access public
*/
function timestamp_to_iso8601($timestamp,$utc=true){
$datestr = date('Y-m-d\TH:i:sO',$timestamp);
if($utc){
$eregStr =
'([0-9]{4})-'. // centuries & years CCYY-
'([0-9]{2})-'. // months MM-
'([0-9]{2})'. // days DD
'T'. // separator T
'([0-9]{2}):'. // hours hh:
'([0-9]{2}):'. // minutes mm:
'([0-9]{2})(\.[0-9]*)?'. // seconds ss.ss...
'(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
if(ereg($eregStr,$datestr,$regs)){
return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',$regs[1],$regs[2],$regs[3],$regs[4],$regs[5],$regs[6]);
}
return false;
} else {
return $datestr;
}
}
/**
* convert ISO 8601 compliant date string to unix timestamp
*
* @param string $datestr ISO 8601 compliant date string
* @access public
*/
function iso8601_to_timestamp($datestr){
$eregStr =
'([0-9]{4})-'. // centuries & years CCYY-
'([0-9]{2})-'. // months MM-
'([0-9]{2})'. // days DD
'T'. // separator T
'([0-9]{2}):'. // hours hh:
'([0-9]{2}):'. // minutes mm:
'([0-9]{2})(\.[0-9]+)?'. // seconds ss.ss...
'(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
if(ereg($eregStr,$datestr,$regs)){
// not utc
if($regs[8] != 'Z'){
$op = substr($regs[8],0,1);
$h = substr($regs[8],1,2);
$m = substr($regs[8],strlen($regs[8])-2,2);
if($op == '-'){
$regs[4] = $regs[4] + $h;
$regs[5] = $regs[5] + $m;
} elseif($op == '+'){
$regs[4] = $regs[4] - $h;
$regs[5] = $regs[5] - $m;
}
}
return strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z");
} else {
return false;
}
}
/**
* sleeps some number of microseconds
*
* @param string $usec the number of microseconds to sleep
* @access public
* @deprecated
*/
function usleepWindows($usec)
{
$start = gettimeofday();
do
{
$stop = gettimeofday();
$timePassed = 1000000 * ($stop['sec'] - $start['sec'])
+ $stop['usec'] - $start['usec'];
}
while ($timePassed < $usec);
}
?><?php
/**
* Contains information for a SOAP fault.
* Mainly used for returning faults from deployed functions
* in a server instance.
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $
* @access public
*/
class soap_fault extends nusoap_base {
/**
* The fault code (client|server)
* @var string
* @access private
*/
var $faultcode;
/**
* The fault actor
* @var string
* @access private
*/
var $faultactor;
/**
* The fault string, a description of the fault
* @var string
* @access private
*/
var $faultstring;
/**
* The fault detail, typically a string or array of string
* @var mixed
* @access private
*/
var $faultdetail;
/**
* constructor
*
* @param string $faultcode (client | server)
* @param string $faultactor only used when msg routed between multiple actors
* @param string $faultstring human readable error message
* @param mixed $faultdetail detail, typically a string or array of string
*/
function soap_fault($faultcode,$faultactor='',$faultstring='',$faultdetail=''){
parent::nusoap_base();
$this->faultcode = $faultcode;
$this->faultactor = $faultactor;
$this->faultstring = $faultstring;
$this->faultdetail = $faultdetail;
}
/**
* serialize a fault
*
* @return string The serialization of the fault instance.
* @access public
*/
function serialize(){
$ns_string = '';
foreach($this->namespaces as $k => $v){
$ns_string .= "\n xmlns:$k=\"$v\"";
}
$return_msg =
'<?xml version="1.0" encoding="'.$this->soap_defencoding.'"?>'.
'<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"'.$ns_string.">\n".
'<SOAP-ENV:Body>'.
'<SOAP-ENV:Fault>'.
$this->serialize_val($this->faultcode, 'faultcode').
$this->serialize_val($this->faultactor, 'faultactor').
$this->serialize_val($this->faultstring, 'faultstring').
$this->serialize_val($this->faultdetail, 'detail').
'</SOAP-ENV:Fault>'.
'</SOAP-ENV:Body>'.
'</SOAP-ENV:Envelope>';
return $return_msg;
}
}
?><?php
/**
* parses an XML Schema, allows access to it's data, other utility methods
* no validation... yet.
* very experimental and limited. As is discussed on XML-DEV, I'm one of the people
* that just doesn't have time to read the spec(s) thoroughly, and just have a couple of trusty
* tutorials I refer to :)
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $
* @access public
*/
class XMLSchema extends nusoap_base {
// files
var $schema = '';
var $xml = '';
// namespaces
var $enclosingNamespaces;
// schema info
var $schemaInfo = array();
var $schemaTargetNamespace = '';
// types, elements, attributes defined by the schema
var $attributes = array();
var $complexTypes = array();
var $complexTypeStack = array();
var $currentComplexType = null;
var $elements = array();
var $elementStack = array();
var $currentElement = null;
var $simpleTypes = array();
var $simpleTypeStack = array();
var $currentSimpleType = null;
// imports
var $imports = array();
// parser vars
var $parser;
var $position = 0;
var $depth = 0;
var $depth_array = array();
var $message = array();
var $defaultNamespace = array();
/**
* constructor
*
* @param string $schema schema document URI
* @param string $xml xml document URI
* @param string $namespaces namespaces defined in enclosing XML
* @access public
*/
function XMLSchema($schema='',$xml='',$namespaces=array()){
parent::nusoap_base();
$this->debug('xmlschema class instantiated, inside constructor');
// files
$this->schema = $schema;
$this->xml = $xml;
// namespaces
$this->enclosingNamespaces = $namespaces;
$this->namespaces = array_merge($this->namespaces, $namespaces);
// parse schema file
if($schema != ''){
$this->debug('initial schema file: '.$schema);
$this->parseFile($schema, 'schema');
}
// parse xml file
if($xml != ''){
$this->debug('initial xml file: '.$xml);
$this->parseFile($xml, 'xml');
}
}
/**
* parse an XML file
*
* @param string $xml, path/URL to XML file
* @param string $type, (schema | xml)
* @return boolean
* @access public
*/
function parseFile($xml,$type){
// parse xml file
if($xml != ""){
$xmlStr = @join("",@file($xml));
if($xmlStr == ""){
$msg = 'Error reading XML from '.$xml;
$this->setError($msg);
$this->debug($msg);
return false;
} else {
$this->debug("parsing $xml");
$this->parseString($xmlStr,$type);
$this->debug("done parsing $xml");
return true;
}
}
return false;
}
/**
* parse an XML string
*
* @param string $xml path or URL
* @param string $type, (schema|xml)
* @access private
*/
function parseString($xml,$type){
// parse xml string
if($xml != ""){
// Create an XML parser.
$this->parser = xml_parser_create();
// Set the options for parsing the XML data.
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
// Set the object for the parser.
xml_set_object($this->parser, $this);
// Set the element handlers for the parser.
if($type == "schema"){
xml_set_element_handler($this->parser, 'schemaStartElement','schemaEndElement');
xml_set_character_data_handler($this->parser,'schemaCharacterData');
} elseif($type == "xml"){
xml_set_element_handler($this->parser, 'xmlStartElement','xmlEndElement');
xml_set_character_data_handler($this->parser,'xmlCharacterData');
}
// Parse the XML file.
if(!xml_parse($this->parser,$xml,true)){
// Display an error message.
$errstr = sprintf('XML error parsing XML schema on line %d: %s',
xml_get_current_line_number($this->parser),
xml_error_string(xml_get_error_code($this->parser))
);
$this->debug($errstr);
$this->debug("XML payload:\n" . $xml);
$this->setError($errstr);
}
xml_parser_free($this->parser);
} else{
$this->debug('no xml passed to parseString()!!');
$this->setError('no xml passed to parseString()!!');
}
}
/**
* start-element handler
*
* @param string $parser XML parser object
* @param string $name element name
* @param string $attrs associative array of attributes
* @access private
*/
function schemaStartElement($parser, $name, $attrs) {
// position in the total number of elements, starting from 0
$pos = $this->position++;
$depth = $this->depth++;
// set self as current value for this depth
$this->depth_array[$depth] = $pos;
$this->message[$pos] = array('cdata' => '');
if ($depth > 0) {
$this->defaultNamespace[$pos] = $this->defaultNamespace[$this->depth_array[$depth - 1]];
} else {
$this->defaultNamespace[$pos] = false;
}
// get element prefix
if($prefix = $this->getPrefix($name)){
// get unqualified name
$name = $this->getLocalPart($name);
} else {
$prefix = '';
}
// loop thru attributes, expanding, and registering namespace declarations
if(count($attrs) > 0){
foreach($attrs as $k => $v){
// if ns declarations, add to class level array of valid namespaces
if(ereg("^xmlns",$k)){
//$this->xdebug("$k: $v");
//$this->xdebug('ns_prefix: '.$this->getPrefix($k));
if($ns_prefix = substr(strrchr($k,':'),1)){
//$this->xdebug("Add namespace[$ns_prefix] = $v");
$this->namespaces[$ns_prefix] = $v;
} else {
$this->defaultNamespace[$pos] = $v;
if (! $this->getPrefixFromNamespace($v)) {
$this->namespaces['ns'.(count($this->namespaces)+1)] = $v;
}
}
if($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema'){
$this->XMLSchemaVersion = $v;
$this->namespaces['xsi'] = $v.'-instance';
}
}
}
foreach($attrs as $k => $v){
// expand each attribute
$k = strpos($k,':') ? $this->expandQname($k) : $k;
$v = strpos($v,':') ? $this->expandQname($v) : $v;
$eAttrs[$k] = $v;
}
$attrs = $eAttrs;
} else {
$attrs = array();
}
// find status, register data
switch($name){
case 'all': // (optional) compositor content for a complexType
case 'choice':
case 'group':
case 'sequence':
//$this->xdebug("compositor $name for currentComplexType: $this->currentComplexType and currentElement: $this->currentElement");
$this->complexTypes[$this->currentComplexType]['compositor'] = $name;
//if($name == 'all' || $name == 'sequence'){
// $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
//}
break;
case 'attribute': // complexType attribute
//$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']);
$this->xdebug("parsing attribute:");
$this->appendDebug($this->varDump($attrs));
if (!isset($attrs['form'])) {
$attrs['form'] = $this->schemaInfo['attributeFormDefault'];
}
if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) {
$v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
if (!strpos($v, ':')) {
// no namespace in arrayType attribute value...
if ($this->defaultNamespace[$pos]) {
// ...so use the default
$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'] = $this->defaultNamespace[$pos] . ':' . $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
}
}
}
if(isset($attrs['name'])){
$this->attributes[$attrs['name']] = $attrs;
$aname = $attrs['name'];
} elseif(isset($attrs['ref']) && $attrs['ref'] == 'http://schemas.xmlsoap.org/soap/encoding/:arrayType'){
if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) {
$aname = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
} else {
$aname = '';
}
} elseif(isset($attrs['ref'])){
$aname = $attrs['ref'];
$this->attributes[$attrs['ref']] = $attrs;
}
if($this->currentComplexType){ // This should *always* be
$this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs;
}
// arrayType attribute
if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']) || $this->getLocalPart($aname) == 'arrayType'){
$this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
$prefix = $this->getPrefix($aname);
if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])){
$v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
} else {
$v = '';
}
if(strpos($v,'[,]')){
$this->complexTypes[$this->currentComplexType]['multidimensional'] = true;
}
$v = substr($v,0,strpos($v,'[')); // clip the []
if(!strpos($v,':') && isset($this->typemap[$this->XMLSchemaVersion][$v])){
$v = $this->XMLSchemaVersion.':'.$v;
}
$this->complexTypes[$this->currentComplexType]['arrayType'] = $v;
}
break;
case 'complexContent': // (optional) content for a complexType
break;
case 'complexType':
array_push($this->complexTypeStack, $this->currentComplexType);
if(isset($attrs['name'])){
$this->xdebug('processing named complexType '.$attrs['name']);
//$this->currentElement = false;
$this->currentComplexType = $attrs['name'];
$this->complexTypes[$this->currentComplexType] = $attrs;
$this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';
// This is for constructs like
// <complexType name="ListOfString" base="soap:Array">
// <sequence>
// <element name="string" type="xsd:string"
// minOccurs="0" maxOccurs="unbounded" />
// </sequence>
// </complexType>
if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){
$this->xdebug('complexType is unusual array');
$this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
} else {
$this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
}
}else{
$this->xdebug('processing unnamed complexType for element '.$this->currentElement);
$this->currentComplexType = $this->currentElement . '_ContainedType';
//$this->currentElement = false;
$this->complexTypes[$this->currentComplexType] = $attrs;
$this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';
// This is for constructs like
// <complexType name="ListOfString" base="soap:Array">
// <sequence>
// <element name="string" type="xsd:string"
// minOccurs="0" maxOccurs="unbounded" />
// </sequence>
// </complexType>
if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){
$this->xdebug('complexType is unusual array');
$this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
} else {
$this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
}
}
break;
case 'element':
array_push($this->elementStack, $this->currentElement);
// elements defined as part of a complex type should
// not really be added to $this->elements, but for some
// reason, they are
if (!isset($attrs['form'])) {
$attrs['form'] = $this->schemaInfo['elementFormDefault'];
}
if(isset($attrs['type'])){
$this->xdebug("processing typed element ".$attrs['name']." of type ".$attrs['type']);
if (! $this->getPrefix($attrs['type'])) {
if ($this->defaultNamespace[$pos]) {
$attrs['type'] = $this->defaultNamespace[$pos] . ':' . $attrs['type'];
$this->xdebug('used default namespace to make type ' . $attrs['type']);
}
}
// This is for constructs like
// <complexType name="ListOfString" base="soap:Array">
// <sequence>
// <element name="string" type="xsd:string"
// minOccurs="0" maxOccurs="unbounded" />
// </sequence>
// </complexType>
if ($this->currentComplexType && $this->complexTypes[$this->currentComplexType]['phpType'] == 'array') {
$this->xdebug('arrayType for unusual array is ' . $attrs['type']);
$this->complexTypes[$this->currentComplexType]['arrayType'] = $attrs['type'];
}
$this->currentElement = $attrs['name'];
$this->elements[ $attrs['name'] ] = $attrs;
$this->elements[ $attrs['name'] ]['typeClass'] = 'element';
$ename = $attrs['name'];
} elseif(isset($attrs['ref'])){
$this->xdebug("processing element as ref to ".$attrs['ref']);
$this->currentElement = "ref to ".$attrs['ref'];
$ename = $this->getLocalPart($attrs['ref']);
} else {
$this->xdebug("processing untyped element ".$attrs['name']);
$this->currentElement = $attrs['name'];
$this->elements[ $attrs['name'] ] = $attrs;
$this->elements[ $attrs['name'] ]['typeClass'] = 'element';
$attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['name'] . '_ContainedType';
$this->elements[ $attrs['name'] ]['type'] = $attrs['type'];
$ename = $attrs['name'];
}
if(isset($ename) && $this->currentComplexType){
$this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs;
}
break;
case 'enumeration': // restriction value list member
$this->xdebug('enumeration ' . $attrs['value']);
if ($this->currentSimpleType) {
$this->simpleTypes[$this->currentSimpleType]['enumeration'][] = $attrs['value'];
} elseif ($this->currentComplexType) {
$this->complexTypes[$this->currentComplexType]['enumeration'][] = $attrs['value'];
}
break;
case 'extension': // simpleContent or complexContent type extension
$this->xdebug('extension ' . $attrs['base']);
if ($this->currentComplexType) {
$this->complexTypes[$this->currentComplexType]['extensionBase'] = $attrs['base'];
}
break;
case 'import':
if (isset($attrs['schemaLocation'])) {
//$this->xdebug('import namespace ' . $attrs['namespace'] . ' from ' . $attrs['schemaLocation']);
$this->imports[$attrs['namespace']][] = array('location' => $attrs['schemaLocation'], 'loaded' => false);
} else {
//$this->xdebug('import namespace ' . $attrs['namespace']);
$this->imports[$attrs['namespace']][] = array('location' => '', 'loaded' => true);
if (! $this->getPrefixFromNamespace($attrs['namespace'])) {
$this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace'];
}
}
break;
case 'list': // simpleType value list
break;
case 'restriction': // simpleType, simpleContent or complexContent value restriction
$this->xdebug('restriction ' . $attrs['base']);
if($this->currentSimpleType){
$this->simpleTypes[$this->currentSimpleType]['type'] = $attrs['base'];
} elseif($this->currentComplexType){
$this->complexTypes[$this->currentComplexType]['restrictionBase'] = $attrs['base'];
if(strstr($attrs['base'],':') == ':Array'){
$this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
}
}
break;
case 'schema':
$this->schemaInfo = $attrs;
$this->schemaInfo['schemaVersion'] = $this->getNamespaceFromPrefix($prefix);
if (isset($attrs['targetNamespace'])) {
$this->schemaTargetNamespace = $attrs['targetNamespace'];
}
if (!isset($attrs['elementFormDefault'])) {
$this->schemaInfo['elementFormDefault'] = 'unqualified';
}
if (!isset($attrs['attributeFormDefault'])) {
$this->schemaInfo['attributeFormDefault'] = 'unqualified';
}
break;
case 'simpleContent': // (optional) content for a complexType
break;
case 'simpleType':
array_push($this->simpleTypeStack, $this->currentSimpleType);
if(isset($attrs['name'])){
$this->xdebug("processing simpleType for name " . $attrs['name']);
$this->currentSimpleType = $attrs['name'];
$this->simpleTypes[ $attrs['name'] ] = $attrs;
$this->simpleTypes[ $attrs['name'] ]['typeClass'] = 'simpleType';
$this->simpleTypes[ $attrs['name'] ]['phpType'] = 'scalar';
} else {
$this->xdebug('processing unnamed simpleType for element '.$this->currentElement);
$this->currentSimpleType = $this->currentElement . '_ContainedType';
//$this->currentElement = false;
$this->simpleTypes[$this->currentSimpleType] = $attrs;
$this->simpleTypes[$this->currentSimpleType]['phpType'] = 'scalar';
}
break;
case 'union': // simpleType type list
break;
default:
//$this->xdebug("do not have anything to do for element $name");
}
}
/**
* end-element handler
*
* @param string $parser XML parser object
* @param string $name element name
* @access private
*/
function schemaEndElement($parser, $name) {
// bring depth down a notch
$this->depth--;
// position of current element is equal to the last value left in depth_array for my depth
if(isset($this->depth_array[$this->depth])){
$pos = $this->depth_array[$this->depth];
}
// get element prefix
if ($prefix = $this->getPrefix($name)){
// get unqualified name
$name = $this->getLocalPart($name);
} else {
$prefix = '';
}
// move on...
if($name == 'complexType'){
$this->xdebug('done processing complexType ' . ($this->currentComplexType ? $this->currentComplexType : '(unknown)'));
$this->currentComplexType = array_pop($this->complexTypeStack);
//$this->currentElement = false;
}
if($name == 'element'){
$this->xdebug('done processing element ' . ($this->currentElement ? $this->currentElement : '(unknown)'));
$this->currentElement = array_pop($this->elementStack);
}
if($name == 'simpleType'){
$this->xdebug('done processing simpleType ' . ($this->currentSimpleType ? $this->currentSimpleType : '(unknown)'));
$this->currentSimpleType = array_pop($this->simpleTypeStack);
}
}
/**
* element content handler
*
* @param string $parser XML parser object
* @param string $data element content
* @access private
*/
function schemaCharacterData($parser, $data){
$pos = $this->depth_array[$this->depth - 1];
$this->message[$pos]['cdata'] .= $data;
}
/**
* serialize the schema
*
* @access public
*/
function serializeSchema(){
$schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion);
$xml = '';
// imports
if (sizeof($this->imports) > 0) {
foreach($this->imports as $ns => $list) {
foreach ($list as $ii) {
if ($ii['location'] != '') {
$xml .= " <$schemaPrefix:import location=\"" . $ii['location'] . '" namespace="' . $ns . "\" />\n";
} else {
$xml .= " <$schemaPrefix:import namespace=\"" . $ns . "\" />\n";
}
}
}
}
// complex types
foreach($this->complexTypes as $typeName => $attrs){
$contentStr = '';
// serialize child elements
if(isset($attrs['elements']) && (count($attrs['elements']) > 0)){
foreach($attrs['elements'] as $element => $eParts){
if(isset($eParts['ref'])){
$contentStr .= " <$schemaPrefix:element ref=\"$element\"/>\n";
} else {
$contentStr .= " <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\"";
foreach ($eParts as $aName => $aValue) {
// handle, e.g., abstract, default, form, minOccurs, maxOccurs, nillable
if ($aName != 'name' && $aName != 'type') {
$contentStr .= " $aName=\"$aValue\"";
}
}
$contentStr .= "/>\n";
}
}
// compositor wraps elements
if (isset($attrs['compositor']) && ($attrs['compositor'] != '')) {
$contentStr = " <$schemaPrefix:$attrs[compositor]>\n".$contentStr." </$schemaPrefix:$attrs[compositor]>\n";
}
}
// attributes
if(isset($attrs['attrs']) && (count($attrs['attrs']) >= 1)){
foreach($attrs['attrs'] as $attr => $aParts){
$contentStr .= " <$schemaPrefix:attribute";
foreach ($aParts as $a => $v) {
if ($a == 'ref' || $a == 'type') {
$contentStr .= " $a=\"".$this->contractQName($v).'"';
} elseif ($a == 'http://schemas.xmlsoap.org/wsdl/:arrayType') {
$this->usedNamespaces['wsdl'] = $this->namespaces['wsdl'];
$contentStr .= ' wsdl:arrayType="'.$this->contractQName($v).'"';
} else {
$contentStr .= " $a=\"$v\"";
}
}
$contentStr .= "/>\n";
}
}
// if restriction
if (isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != ''){
$contentStr = " <$schemaPrefix:restriction base=\"".$this->contractQName($attrs['restrictionBase'])."\">\n".$contentStr." </$schemaPrefix:restriction>\n";
// complex or simple content
if ((isset($attrs['elements']) && count($attrs['elements']) > 0) || (isset($attrs['attrs']) && count($attrs['attrs']) > 0)){
$contentStr = " <$schemaPrefix:complexContent>\n".$contentStr." </$schemaPrefix:complexContent>\n";
}
}
// finalize complex type
if($contentStr != ''){
$contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." </$schemaPrefix:complexType>\n";
} else {
$contentStr = " <$schemaPrefix:complexType name=\"$typeName\"/>\n";
}
$xml .= $contentStr;
}
// simple types
if(isset($this->simpleTypes) && count($this->simpleTypes) > 0){
foreach($this->simpleTypes as $typeName => $eParts){
$xml .= " <$schemaPrefix:simpleType name=\"$typeName\">\n <$schemaPrefix:restriction base=\"".$this->contractQName($eParts['type'])."\"/>\n";
if (isset($eParts['enumeration'])) {
foreach ($eParts['enumeration'] as $e) {
$xml .= " <$schemaPrefix:enumeration value=\"$e\"/>\n";
}
}
$xml .= " </$schemaPrefix:simpleType>";
}
}
// elements
if(isset($this->elements) && count($this->elements) > 0){
foreach($this->elements as $element => $eParts){
$xml .= " <$schemaPrefix:element name=\"$element\" type=\"".$this->contractQName($eParts['type'])."\"/>\n";
}
}
// attributes
if(isset($this->attributes) && count($this->attributes) > 0){
foreach($this->attributes as $attr => $aParts){
$xml .= " <$schemaPrefix:attribute name=\"$attr\" type=\"".$this->contractQName($aParts['type'])."\"\n/>";
}
}
// finish 'er up
$el = "<$schemaPrefix:schema targetNamespace=\"$this->schemaTargetNamespace\"\n";
foreach (array_diff($this->usedNamespaces, $this->enclosingNamespaces) as $nsp => $ns) {
$el .= " xmlns:$nsp=\"$ns\"\n";
}
$xml = $el . ">\n".$xml."</$schemaPrefix:schema>\n";
return $xml;
}
/**
* adds debug data to the clas level debug string
*
* @param string $string debug data
* @access private
*/
function xdebug($string){
$this->debug('<' . $this->schemaTargetNamespace . '> '.$string);
}
/**
* get the PHP type of a user defined type in the schema
* PHP type is kind of a misnomer since it actually returns 'struct' for assoc. arrays
* returns false if no type exists, or not w/ the given namespace
* else returns a string that is either a native php type, or 'struct'
*
* @param string $type, name of defined type
* @param string $ns, namespace of type
* @return mixed
* @access public
* @deprecated
*/
function getPHPType($type,$ns){
if(isset($this->typemap[$ns][$type])){
//print "found type '$type' and ns $ns in typemap<br>";
return $this->typemap[$ns][$type];
} elseif(isset($this->complexTypes[$type])){
//print "getting type '$type' and ns $ns from complexTypes array<br>";
return $this->complexTypes[$type]['phpType'];
}
return false;
}
/**
* returns an associative array of information about a given type
* returns false if no type exists by the given name
*
* For a complexType typeDef = array(
* 'restrictionBase' => '',
* 'phpType' => '',
* 'compositor' => '(sequence|all)',
* 'elements' => array(), // refs to elements array
* 'attrs' => array() // refs to attributes array
* ... and so on (see addComplexType)
* )
*
* For simpleType or element, the array has different keys.
*
* @param string
* @return mixed
* @access public
* @see addComplexType
* @see addSimpleType
* @see addElement
*/
function getTypeDef($type){
//$this->debug("in getTypeDef for type $type");
if(isset($this->complexTypes[$type])){
$this->xdebug("in getTypeDef, found complexType $type");
return $this->complexTypes[$type];
} elseif(isset($this->simpleTypes[$type])){
$this->xdebug("in getTypeDef, found simpleType $type");
if (!isset($this->simpleTypes[$type]['phpType'])) {
// get info for type to tack onto the simple type
// TODO: can this ever really apply (i.e. what is a simpleType really?)
$uqType = substr($this->simpleTypes[$type]['type'], strrpos($this->simpleTypes[$type]['type'], ':') + 1);
$ns = substr($this->simpleTypes[$type]['type'], 0, strrpos($this->simpleTypes[$type]['type'], ':'));
$etype = $this->getTypeDef($uqType);
if ($etype) {
$this->xdebug("in getTypeDef, found type for simpleType $type:");
$this->xdebug($this->varDump($etype));
if (isset($etype['phpType'])) {
$this->simpleTypes[$type]['phpType'] = $etype['phpType'];
}
if (isset($etype['elements'])) {
$this->simpleTypes[$type]['elements'] = $etype['elements'];
}
}
}
return $this->simpleTypes[$type];
} elseif(isset($this->elements[$type])){
$this->xdebug("in getTypeDef, found element $type");
if (!isset($this->elements[$type]['phpType'])) {
// get info for type to tack onto the element
$uqType = substr($this->elements[$type]['type'], strrpos($this->elements[$type]['type'], ':') + 1);
$ns = substr($this->elements[$type]['type'], 0, strrpos($this->elements[$type]['type'], ':'));
$etype = $this->getTypeDef($uqType);
if ($etype) {
$this->xdebug("in getTypeDef, found type for element $type:");
$this->xdebug($this->varDump($etype));
if (isset($etype['phpType'])) {
$this->elements[$type]['phpType'] = $etype['phpType'];
}
if (isset($etype['elements'])) {
$this->elements[$type]['elements'] = $etype['elements'];
}
} elseif ($ns == 'http://www.w3.org/2001/XMLSchema') {
$this->xdebug("in getTypeDef, element $type is an XSD type");
$this->elements[$type]['phpType'] = 'scalar';
}
}
return $this->elements[$type];
} elseif(isset($this->attributes[$type])){
$this->xdebug("in getTypeDef, found attribute $type");
return $this->attributes[$type];
} elseif (ereg('_ContainedType$', $type)) {
$this->xdebug("in getTypeDef, have an untyped element $type");
$typeDef['typeClass'] = 'simpleType';
$typeDef['phpType'] = 'scalar';
$typeDef['type'] = 'http://www.w3.org/2001/XMLSchema:string';
return $typeDef;
}
$this->xdebug("in getTypeDef, did not find $type");
return false;
}
/**
* returns a sample serialization of a given type, or false if no type by the given name
*
* @param string $type, name of type
* @return mixed
* @access public
* @deprecated
*/
function serializeTypeDef($type){
//print "in sTD() for type $type<br>";
if($typeDef = $this->getTypeDef($type)){
$str .= '<'.$type;
if(is_array($typeDef['attrs'])){
foreach($attrs as $attName => $data){
$str .= " $attName=\"{type = ".$data['type']."}\"";
}
}
$str .= " xmlns=\"".$this->schema['targetNamespace']."\"";
if(count($typeDef['elements']) > 0){
$str .= ">";
foreach($typeDef['elements'] as $element => $eData){
$str .= $this->serializeTypeDef($element);
}
$str .= "</$type>";
} elseif($typeDef['typeClass'] == 'element') {
$str .= "></$type>";
} else {
$str .= "/>";
}
return $str;
}
return false;
}
/**
* returns HTML form elements that allow a user
* to enter values for creating an instance of the given type.
*
* @param string $name, name for type instance
* @param string $type, name of type
* @return string
* @access public
* @deprecated
*/
function typeToForm($name,$type){
// get typedef
if($typeDef = $this->getTypeDef($type)){
// if struct
if($typeDef['phpType'] == 'struct'){
$buffer .= '<table>';
foreach($typeDef['elements'] as $child => $childDef){
$buffer .= "
<tr><td align='right'>$childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):</td>
<td><input type='text' name='parameters[".$name."][$childDef[name]]'></td></tr>";
}
$buffer .= '</table>';
// if array
} elseif($typeDef['phpType'] == 'array'){
$buffer .= '<table>';
for($i=0;$i < 3; $i++){
$buffer .= "
<tr><td align='right'>array item (type: $typeDef[arrayType]):</td>
<td><input type='text' name='parameters[".$name."][]'></td></tr>";
}
$buffer .= '</table>';
// if scalar
} else {
$buffer .= "<input type='text' name='parameters[$name]'>";
}
} else {
$buffer .= "<input type='text' name='parameters[$name]'>";
}
return $buffer;
}
/**
* adds a complex type to the schema
*
* example: array
*
* addType(
* 'ArrayOfstring',
* 'complexType',
* 'array',
* '',
* 'SOAP-ENC:Array',
* array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'string[]'),
* 'xsd:string'
* );
*
* example: PHP associative array ( SOAP Struct )
*
* addType(
* 'SOAPStruct',
* 'complexType',
* 'struct',
* 'all',
* array('myVar'=> array('name'=>'myVar','type'=>'string')
* );
*
* @param name
* @param typeClass (complexType|simpleType|attribute)
* @param phpType: currently supported are array and struct (php assoc array)
* @param compositor (all|sequence|choice)
* @param restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
* @param elements = array ( name = array(name=>'',type=>'') )
* @param attrs = array(
* array(
* 'ref' => "http://schemas.xmlsoap.org/soap/encoding/:arrayType",
* "http://schemas.xmlsoap.org/wsdl/:arrayType" => "string[]"
* )
* )
* @param arrayType: namespace:name (http://www.w3.org/2001/XMLSchema:string)
* @access public
* @see getTypeDef
*/
function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType=''){
$this->complexTypes[$name] = array(
'name' => $name,
'typeClass' => $typeClass,
'phpType' => $phpType,
'compositor'=> $compositor,
'restrictionBase' => $restrictionBase,
'elements' => $elements,
'attrs' => $attrs,
'arrayType' => $arrayType
);
$this->xdebug("addComplexType $name:");
$this->appendDebug($this->varDump($this->complexTypes[$name]));
}
/**
* adds a simple type to the schema
*
* @param string $name
* @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
* @param string $typeClass (should always be simpleType)
* @param string $phpType (should always be scalar)
* @param array $enumeration array of values
* @access public
* @see xmlschema
* @see getTypeDef
*/
function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
$this->simpleTypes[$name] = array(
'name' => $name,
'typeClass' => $typeClass,
'phpType' => $phpType,
'type' => $restrictionBase,
'enumeration' => $enumeration
);
$this->xdebug("addSimpleType $name:");
$this->appendDebug($this->varDump($this->simpleTypes[$name]));
}
/**
* adds an element to the schema
*
* @param array $attrs attributes that must include name and type
* @see xmlschema
* @access public
*/
function addElement($attrs) {
if (! $this->getPrefix($attrs['type'])) {
$attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type'];
}
$this->elements[ $attrs['name'] ] = $attrs;
$this->elements[ $attrs['name'] ]['typeClass'] = 'element';
$this->xdebug("addElement " . $attrs['name']);
$this->appendDebug($this->varDump($this->elements[ $attrs['name'] ]));
}
}
?><?php
/**
* For creating serializable abstractions of native PHP types. This class
* allows element name/namespace, XSD type, and XML attributes to be
* associated with a value. This is extremely useful when WSDL is not
* used, but is also useful when WSDL is used with polymorphic types, including
* xsd:anyType and user-defined types.
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $
* @access public
*/
class soapval extends nusoap_base {
/**
* The XML element name
*
* @var string
* @access private
*/
var $name;
/**
* The XML type name (string or false)
*
* @var mixed
* @access private
*/
var $type;
/**
* The PHP value
*
* @var mixed
* @access private
*/
var $value;
/**
* The XML element namespace (string or false)
*
* @var mixed
* @access private
*/
var $element_ns;
/**
* The XML type namespace (string or false)
*
* @var mixed
* @access private
*/
var $type_ns;
/**
* The XML element attributes (array or false)
*
* @var mixed
* @access private
*/
var $attributes;
/**
* constructor
*
* @param string $name optional name
* @param mixed $type optional type name
* @param mixed $value optional value
* @param mixed $element_ns optional namespace of value
* @param mixed $type_ns optional namespace of type
* @param mixed $attributes associative array of attributes to add to element serialization
* @access public
*/
function soapval($name='soapval',$type=false,$value=-1,$element_ns=false,$type_ns=false,$attributes=false) {
parent::nusoap_base();
$this->name = $name;
$this->type = $type;
$this->value = $value;
$this->element_ns = $element_ns;
$this->type_ns = $type_ns;
$this->attributes = $attributes;
}
/**
* return serialized value
*
* @param string $use The WSDL use value (encoded|literal)
* @return string XML data
* @access public
*/
function serialize($use='encoded') {
return $this->serialize_val($this->value,$this->name,$this->type,$this->element_ns,$this->type_ns,$this->attributes,$use);
}
/**
* decodes a soapval object into a PHP native type
*
* @return mixed
* @access public
*/
function decode(){
return $this->value;
}
}
?><?php
/**
* transport class for sending/receiving data via HTTP and HTTPS
* NOTE: PHP must be compiled with the CURL extension for HTTPS support
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $
* @access public
*/
class soap_transport_http extends nusoap_base {
var $url = '';
var $uri = '';
var $digest_uri = '';
var $scheme = '';
var $host = '';
var $port = '';
var $path = '';
var $request_method = 'POST';
var $protocol_version = '1.0';
var $encoding = '';
var $outgoing_headers = array();
var $incoming_headers = array();
var $incoming_cookies = array();
var $outgoing_payload = '';
var $incoming_payload = '';
var $useSOAPAction = true;
var $persistentConnection = false;
var $ch = false; // cURL handle
var $username = '';
var $password = '';
var $authtype = '';
var $digestRequest = array();
var $certRequest = array(); // keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional)
// cainfofile: certificate authority file, e.g. '$pathToPemFiles/rootca.pem'
// sslcertfile: SSL certificate file, e.g. '$pathToPemFiles/mycert.pem'
// sslkeyfile: SSL key file, e.g. '$pathToPemFiles/mykey.pem'
// passphrase: SSL key password/passphrase
// verifypeer: default is 1
// verifyhost: default is 1
/**
* constructor
*/
function soap_transport_http($url){
parent::nusoap_base();
$this->setURL($url);
ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev);
$this->outgoing_headers['User-Agent'] = $this->title.'/'.$this->version.' ('.$rev[1].')';
$this->debug('set User-Agent: ' . $this->outgoing_headers['User-Agent']);
}
function setURL($url) {
$this->url = $url;
$u = parse_url($url);
foreach($u as $k => $v){
$this->debug("$k = $v");
$this->$k = $v;
}
// add any GET params to path
if(isset($u['query']) && $u['query'] != ''){
$this->path .= '?' . $u['query'];
}
// set default port
if(!isset($u['port'])){
if($u['scheme'] == 'https'){
$this->port = 443;
} else {
$this->port = 80;
}
}
$this->uri = $this->path;
$this->digest_uri = $this->uri;
// build headers
if (!isset($u['port'])) {
$this->outgoing_headers['Host'] = $this->host;
} else {
$this->outgoing_headers['Host'] = $this->host.':'.$this->port;
}
$this->debug('set Host: ' . $this->outgoing_headers['Host']);
if (isset($u['user']) && $u['user'] != '') {
$this->setCredentials(urldecode($u['user']), isset($u['pass']) ? urldecode($u['pass']) : '');
}
}
function connect($connection_timeout=0,$response_timeout=50){
// For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like
// "regular" socket.
// TODO: disabled for now because OpenSSL must be *compiled* in (not just
// loaded), and until PHP5 stream_get_wrappers is not available.
// if ($this->scheme == 'https') {
// if (version_compare(phpversion(), '4.3.0') >= 0) {
// if (extension_loaded('openssl')) {
// $this->scheme = 'ssl';
// $this->debug('Using SSL over OpenSSL');
// }
// }
// }
$this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port");
if ($this->scheme == 'http' || $this->scheme == 'ssl') {
// use persistent connection
if($this->persistentConnection && isset($this->fp) && is_resource($this->fp)){
if (!feof($this->fp)) {
$this->debug('Re-use persistent connection');
return true;
}
fclose($this->fp);
$this->debug('Closed persistent connection at EOF');
}
// munge host if using OpenSSL
if ($this->scheme == 'ssl') {
$host = 'ssl://' . $this->host;
} else {
$host = $this->host;
}
$this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout);
// open socket
if($connection_timeout > 0){
$this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str, $connection_timeout);
} else {
$this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str);
}
// test pointer
if(!$this->fp) {
$msg = 'Couldn\'t open socket connection to server ' . $this->url;
if ($this->errno) {
$msg .= ', Error ('.$this->errno.'): '.$this->error_str;
} else {
$msg .= ' prior to connect(). This is often a problem looking up the host name.';
}
$this->debug($msg);
$this->setError($msg);
return false;
}
// set response timeout
$this->debug('set response timeout to ' . $response_timeout);
socket_set_timeout( $this->fp, $response_timeout);
$this->debug('socket connected');
return true;
} else if ($this->scheme == 'https') {
if (!extension_loaded('curl')) {
$this->setError('CURL Extension, or OpenSSL extension w/ PHP version >= 4.3 is required for HTTPS');
return false;
}
$this->debug('connect using https');
// init CURL
$this->ch = curl_init();
// set url
$hostURL = ($this->port != '') ? "https://$this->host:$this->port" : "https://$this->host";
// add path
$hostURL .= $this->path;
curl_setopt($this->ch, CURLOPT_URL, $hostURL);
// follow location headers (re-directs)
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1);
// ask for headers in the response output
curl_setopt($this->ch, CURLOPT_HEADER, 1);
// ask for the response output as the return value
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
// encode
// We manage this ourselves through headers and encoding
// if(function_exists('gzuncompress')){
// curl_setopt($this->ch, CURLOPT_ENCODING, 'deflate');
// }
// persistent connection
if ($this->persistentConnection) {
// The way we send data, we cannot use persistent connections, since
// there will be some "junk" at the end of our request.
//curl_setopt($this->ch, CURL_HTTP_VERSION_1_1, true);
$this->persistentConnection = false;
$this->outgoing_headers['Connection'] = 'close';
$this->debug('set Connection: ' . $this->outgoing_headers['Connection']);
}
// set timeout
if ($connection_timeout != 0) {
curl_setopt($this->ch, CURLOPT_TIMEOUT, $connection_timeout);
}
// TODO: cURL has added a connection timeout separate from the response timeout
//if ($connection_timeout != 0) {
// curl_setopt($this->ch, CURLOPT_CONNECTIONTIMEOUT, $connection_timeout);
//}
//if ($response_timeout != 0) {
// curl_setopt($this->ch, CURLOPT_TIMEOUT, $response_timeout);
//}
// recent versions of cURL turn on peer/host checking by default,
// while PHP binaries are not compiled with a default location for the
// CA cert bundle, so disable peer/host checking.
//curl_setopt($this->ch, CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt');
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 0);
// support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo)
if ($this->authtype == 'certificate') {
if (isset($this->certRequest['cainfofile'])) {
curl_setopt($this->ch, CURLOPT_CAINFO, $this->certRequest['cainfofile']);
}
if (isset($this->certRequest['verifypeer'])) {
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $this->certRequest['verifypeer']);
} else {
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 1);
}
if (isset($this->certRequest['verifyhost'])) {
curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, $this->certRequest['verifyhost']);
} else {
curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 1);
}
if (isset($this->certRequest['sslcertfile'])) {
curl_setopt($this->ch, CURLOPT_SSLCERT, $this->certRequest['sslcertfile']);
}
if (isset($this->certRequest['sslkeyfile'])) {
curl_setopt($this->ch, CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']);
}
if (isset($this->certRequest['passphrase'])) {
curl_setopt($this->ch, CURLOPT_SSLKEYPASSWD , $this->certRequest['passphrase']);
}
}
$this->debug('cURL connection set up');
return true;
} else {
$this->setError('Unknown scheme ' . $this->scheme);
$this->debug('Unknown scheme ' . $this->scheme);
return false;
}
}
/**
* send the SOAP message via HTTP
*
* @param string $data message data
* @param integer $timeout set connection timeout in seconds
* @param integer $response_timeout set response timeout in seconds
* @param array $cookies cookies to send
* @return string data
* @access public
*/
function send($data, $timeout=0, $response_timeout=30, $cookies=NULL) {
$this->debug('entered send() with data of length: '.strlen($data));
$this->tryagain = true;
$tries = 0;
while ($this->tryagain) {
$this->tryagain = false;
if ($tries++ < 2) {
// make connnection
if (!$this->connect($timeout, $response_timeout)){
return false;
}
// send request
if (!$this->sendRequest($data, $cookies)){
return false;
}
// get response
$respdata = $this->getResponse();
} else {
$this->setError('Too many tries to get an OK response');
}
}
$this->debug('end of send()');
return $respdata;
}
/**
* send the SOAP message via HTTPS 1.0 using CURL
*
* @param string $msg message data
* @param integer $timeout set connection timeout in seconds
* @param integer $response_timeout set response timeout in seconds
* @param array $cookies cookies to send
* @return string data
* @access public
*/
function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) {
return $this->send($data, $timeout, $response_timeout, $cookies);
}
/**
* if authenticating, set user credentials here
*
* @param string $username
* @param string $password
* @param string $authtype (basic, digest, certificate)
* @param array $digestRequest (keys must be nonce, nc, realm, qop)
* @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
* @access public
*/
function setCredentials($username, $password, $authtype = 'basic', $digestRequest = array(), $certRequest = array()) {
$this->debug("Set credentials for authtype $authtype");
// cf. RFC 2617
if ($authtype == 'basic') {
$this->outgoing_headers['Authorization'] = 'Basic '.base64_encode(str_replace(':','',$username).':'.$password);
} elseif ($authtype == 'digest') {
if (isset($digestRequest['nonce'])) {
$digestRequest['nc'] = isset($digestRequest['nc']) ? $digestRequest['nc']++ : 1;
// calculate the Digest hashes (calculate code based on digest implementation found at: http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html)
// A1 = unq(username-value) ":" unq(realm-value) ":" passwd
$A1 = $username. ':' . (isset($digestRequest['realm']) ? $digestRequest['realm'] : '') . ':' . $password;
// H(A1) = MD5(A1)
$HA1 = md5($A1);
// A2 = Method ":" digest-uri-value
$A2 = 'POST:' . $this->digest_uri;
// H(A2)
$HA2 = md5($A2);
// KD(secret, data) = H(concat(secret, ":", data))
// if qop == auth:
// request-digest = <"> < KD ( H(A1), unq(nonce-value)
// ":" nc-value
// ":" unq(cnonce-value)
// ":" unq(qop-value)
// ":" H(A2)
// ) <">
// if qop is missing,
// request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <">
$unhashedDigest = '';
$nonce = isset($digestRequest['nonce']) ? $digestRequest['nonce'] : '';
$cnonce = $nonce;
if ($digestRequest['qop'] != '') {
$unhashedDigest = $HA1 . ':' . $nonce . ':' . sprintf("%08d", $digestRequest['nc']) . ':' . $cnonce . ':' . $digestRequest['qop'] . ':' . $HA2;
} else {
$unhashedDigest = $HA1 . ':' . $nonce . ':' . $HA2;
}
$hashedDigest = md5($unhashedDigest);
$this->outgoing_headers['Authorization'] = 'Digest username="' . $username . '", realm="' . $digestRequest['realm'] . '", nonce="' . $nonce . '", uri="' . $this->digest_uri . '", cnonce="' . $cnonce . '", nc=' . sprintf("%08x", $digestRequest['nc']) . ', qop="' . $digestRequest['qop'] . '", response="' . $hashedDigest . '"';
}
} elseif ($authtype == 'certificate') {
$this->certRequest = $certRequest;
}
$this->username = $username;
$this->password = $password;
$this->authtype = $authtype;
$this->digestRequest = $digestRequest;
if (isset($this->outgoing_headers['Authorization'])) {
$this->debug('set Authorization: ' . substr($this->outgoing_headers['Authorization'], 0, 12) . '...');
} else {
$this->debug('Authorization header not set');
}
}
/**
* set the soapaction value
*
* @param string $soapaction
* @access public
*/
function setSOAPAction($soapaction) {
$this->outgoing_headers['SOAPAction'] = '"' . $soapaction . '"';
$this->debug('set SOAPAction: ' . $this->outgoing_headers['SOAPAction']);
}
/**
* use http encoding
*
* @param string $enc encoding style. supported values: gzip, deflate, or both
* @access public
*/
function setEncoding($enc='gzip, deflate') {
if (function_exists('gzdeflate')) {
$this->protocol_version = '1.1';
$this->outgoing_headers['Accept-Encoding'] = $enc;
$this->debug('set Accept-Encoding: ' . $this->outgoing_headers['Accept-Encoding']);
if (!isset($this->outgoing_headers['Connection'])) {
$this->outgoing_headers['Connection'] = 'close';
$this->persistentConnection = false;
$this->debug('set Connection: ' . $this->outgoing_headers['Connection']);
}
set_magic_quotes_runtime(0);
// deprecated
$this->encoding = $enc;
}
}
/**
* set proxy info here
*
* @param string $proxyhost
* @param string $proxyport
* @param string $proxyusername
* @param string $proxypassword
* @access public
*/
function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') {
$this->uri = $this->url;
$this->host = $proxyhost;
$this->port = $proxyport;
if ($proxyusername != '' && $proxypassword != '') {
$this->outgoing_headers['Proxy-Authorization'] = ' Basic '.base64_encode($proxyusername.':'.$proxypassword);
$this->debug('set Proxy-Authorization: ' . $this->outgoing_headers['Proxy-Authorization']);
}
}
/**
* decode a string that is encoded w/ "chunked' transfer encoding
* as defined in RFC2068 19.4.6
*
* @param string $buffer
* @param string $lb
* @returns string
* @access public
* @deprecated
*/
function decodeChunked($buffer, $lb){
// length := 0
$length = 0;
$new = '';
// read chunk-size, chunk-extension (if any) and CRLF
// get the position of the linebreak
$chunkend = strpos($buffer, $lb);
if ($chunkend == FALSE) {
$this->debug('no linebreak found in decodeChunked');
return $new;
}
$temp = substr($buffer,0,$chunkend);
$chunk_size = hexdec( trim($temp) );
$chunkstart = $chunkend + strlen($lb);
// while (chunk-size > 0) {
while ($chunk_size > 0) {
$this->debug("chunkstart: $chunkstart chunk_size: $chunk_size");
$chunkend = strpos( $buffer, $lb, $chunkstart + $chunk_size);
// Just in case we got a broken connection
if ($chunkend == FALSE) {
$chunk = substr($buffer,$chunkstart);
// append chunk-data to entity-body
$new .= $chunk;
$length += strlen($chunk);
break;
}
// read chunk-data and CRLF
$chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart);
// append chunk-data to entity-body
$new .= $chunk;
// length := length + chunk-size
$length += strlen($chunk);
// read chunk-size and CRLF
$chunkstart = $chunkend + strlen($lb);
$chunkend = strpos($buffer, $lb, $chunkstart) + strlen($lb);
if ($chunkend == FALSE) {
break; //Just in case we got a broken connection
}
$temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);
$chunk_size = hexdec( trim($temp) );
$chunkstart = $chunkend;
}
return $new;
}
/*
* Writes payload, including HTTP headers, to $this->outgoing_payload.
*/
function buildPayload($data, $cookie_str = '') {
// add content-length header
$this->outgoing_headers['Content-Length'] = strlen($data);
$this->debug('set Content-Length: ' . $this->outgoing_headers['Content-Length']);
// start building outgoing payload:
$req = "$this->request_method $this->uri HTTP/$this->protocol_version";
$this->debug("HTTP request: $req");
$this->outgoing_payload = "$req\r\n";
// loop thru headers, serializing
foreach($this->outgoing_headers as $k => $v){
$hdr = $k.': '.$v;
$this->debug("HTTP header: $hdr");
$this->outgoing_payload .= "$hdr\r\n";
}
// add any cookies
if ($cookie_str != '') {
$hdr = 'Cookie: '.$cookie_str;
$this->debug("HTTP header: $hdr");
$this->outgoing_payload .= "$hdr\r\n";
}
// header/body separator
$this->outgoing_payload .= "\r\n";
// add data
$this->outgoing_payload .= $data;
}
function sendRequest($data, $cookies = NULL) {
// build cookie string
$cookie_str = $this->getCookiesForRequest($cookies, (($this->scheme == 'ssl') || ($this->scheme == 'https')));
// build payload
$this->buildPayload($data, $cookie_str);
if ($this->scheme == 'http' || $this->scheme == 'ssl') {
// send payload
if(!fputs($this->fp, $this->outgoing_payload, strlen($this->outgoing_payload))) {
$this->setError('couldn\'t write message data to socket');
$this->debug('couldn\'t write message data to socket');
return false;
}
$this->debug('wrote data to socket, length = ' . strlen($this->outgoing_payload));
return true;
} else if ($this->scheme == 'https') {
// set payload
// TODO: cURL does say this should only be the verb, and in fact it
// turns out that the URI and HTTP version are appended to this, which
// some servers refuse to work with
//curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $this->outgoing_payload);
foreach($this->outgoing_headers as $k => $v){
$curl_headers[] = "$k: $v";
}
if ($cookie_str != '') {
$curl_headers[] = 'Cookie: ' . $cookie_str;
}
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $curl_headers);
if ($this->request_method == "POST") {
curl_setopt($this->ch, CURLOPT_POST, 1);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data);
} else {
}
$this->debug('set cURL payload');
return true;
}
}
function getResponse(){
$this->incoming_payload = '';
if ($this->scheme == 'http' || $this->scheme == 'ssl') {
// loop until headers have been retrieved
$data = '';
while (!isset($lb)){
// We might EOF during header read.
if(feof($this->fp)) {
$this->incoming_payload = $data;
$this->debug('found no headers before EOF after length ' . strlen($data));
$this->debug("received before EOF:\n" . $data);
$this->setError('server failed to send headers');
return false;
}
$tmp = fgets($this->fp, 256);
$tmplen = strlen($tmp);
$this->debug("read line of $tmplen bytes: " . trim($tmp));
if ($tmplen == 0) {
$this->incoming_payload = $data;
$this->debug('socket read of headers timed out after length ' . strlen($data));
$this->debug("read before timeout: " . $data);
$this->setError('socket read of headers timed out');
return false;
}
$data .= $tmp;
$pos = strpos($data,"\r\n\r\n");
if($pos > 1){
$lb = "\r\n";
} else {
$pos = strpos($data,"\n\n");
if($pos > 1){
$lb = "\n";
}
}
// remove 100 header
if(isset($lb) && ereg('^HTTP/1.1 100',$data)){
unset($lb);
$data = '';
}//
}
// store header data
$this->incoming_payload .= $data;
$this->debug('found end of headers after length ' . strlen($data));
// process headers
$header_data = trim(substr($data,0,$pos));
$header_array = explode($lb,$header_data);
$this->incoming_headers = array();
$this->incoming_cookies = array();
foreach($header_array as $header_line){
$arr = explode(':',$header_line, 2);
if(count($arr) > 1){
$header_name = strtolower(trim($arr[0]));
$this->incoming_headers[$header_name] = trim($arr[1]);
if ($header_name == 'set-cookie') {
// TODO: allow multiple cookies from parseCookie
$cookie = $this->parseCookie(trim($arr[1]));
if ($cookie) {
$this->incoming_cookies[] = $cookie;
$this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']);
} else {
$this->debug('did not find cookie in ' . trim($arr[1]));
}
}
} else if (isset($header_name)) {
// append continuation line to previous header
$this->incoming_headers[$header_name] .= $lb . ' ' . $header_line;
}
}
// loop until msg has been received
if (isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked') {
$content_length = 2147483647; // ignore any content-length header
$chunked = true;
$this->debug("want to read chunked content");
} elseif (isset($this->incoming_headers['content-length'])) {
$content_length = $this->incoming_headers['content-length'];
$chunked = false;
$this->debug("want to read content of length $content_length");
} else {
$content_length = 2147483647;
$chunked = false;
$this->debug("want to read content to EOF");
}
$data = '';
do {
if ($chunked) {
$tmp = fgets($this->fp, 256);
$tmplen = strlen($tmp);
$this->debug("read chunk line of $tmplen bytes");
if ($tmplen == 0) {
$this->incoming_payload = $data;
$this->debug('socket read of chunk length timed out after length ' . strlen($data));
$this->debug("read before timeout:\n" . $data);
$this->setError('socket read of chunk length timed out');
return false;
}
$content_length = hexdec(trim($tmp));
$this->debug("chunk length $content_length");
}
$strlen = 0;
while (($strlen < $content_length) && (!feof($this->fp))) {
$readlen = min(8192, $content_length - $strlen);
$tmp = fread($this->fp, $readlen);
$tmplen = strlen($tmp);
$this->debug("read buffer of $tmplen bytes");
if (($tmplen == 0) && (!feof($this->fp))) {
$this->incoming_payload = $data;
$this->debug('socket read of body timed out after length ' . strlen($data));
$this->debug("read before timeout:\n" . $data);
$this->setError('socket read of body timed out');
return false;
}
$strlen += $tmplen;
$data .= $tmp;
}
if ($chunked && ($content_length > 0)) {
$tmp = fgets($this->fp, 256);
$tmplen = strlen($tmp);
$this->debug("read chunk terminator of $tmplen bytes");
if ($tmplen == 0) {
$this->incoming_payload = $data;
$this->debug('socket read of chunk terminator timed out after length ' . strlen($data));
$this->debug("read before timeout:\n" . $data);
$this->setError('socket read of chunk terminator timed out');
return false;
}
}
} while ($chunked && ($content_length > 0) && (!feof($this->fp)));
if (feof($this->fp)) {
$this->debug('read to EOF');
}
$this->debug('read body of length ' . strlen($data));
$this->incoming_payload .= $data;
$this->debug('received a total of '.strlen($this->incoming_payload).' bytes of data from server');
// close filepointer
if(
(isset($this->incoming_headers['connection']) && strtolower($this->incoming_headers['connection']) == 'close') ||
(! $this->persistentConnection) || feof($this->fp)){
fclose($this->fp);
$this->fp = false;
$this->debug('closed socket');
}
// connection was closed unexpectedly
if($this->incoming_payload == ''){
$this->setError('no response from server');
return false;
}
// decode transfer-encoding
// if(isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked'){
// if(!$data = $this->decodeChunked($data, $lb)){
// $this->setError('Decoding of chunked data failed');
// return false;
// }
//print "<pre>\nde-chunked:\n---------------\n$data\n\n---------------\n</pre>";
// set decoded payload
// $this->incoming_payload = $header_data.$lb.$lb.$data;
// }
} else if ($this->scheme == 'https') {
// send and receive
$this->debug('send and receive with cURL');
$this->incoming_payload = curl_exec($this->ch);
$data = $this->incoming_payload;
$cErr = curl_error($this->ch);
if ($cErr != '') {
$err = 'cURL ERROR: '.curl_errno($this->ch).': '.$cErr.'<br>';
// TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE
foreach(curl_getinfo($this->ch) as $k => $v){
$err .= "$k: $v<br>";
}
$this->debug($err);
$this->setError($err);
curl_close($this->ch);
return false;
} else {
//echo '<pre>';
//var_dump(curl_getinfo($this->ch));
//echo '</pre>';
}
// close curl
$this->debug('No cURL error, closing cURL');
curl_close($this->ch);
// remove 100 header(s)
while (ereg('^HTTP/1.1 100',$data)) {
if ($pos = strpos($data,"\r\n\r\n")) {
$data = ltrim(substr($data,$pos));
} elseif($pos = strpos($data,"\n\n") ) {
$data = ltrim(substr($data,$pos));
}
}
// separate content from HTTP headers
if ($pos = strpos($data,"\r\n\r\n")) {
$lb = "\r\n";
} elseif( $pos = strpos($data,"\n\n")) {
$lb = "\n";
} else {
$this->debug('no proper separation of headers and document');
$this->setError('no proper separation of headers and document');
return false;
}
$header_data = trim(substr($data,0,$pos));
$header_array = explode($lb,$header_data);
$data = ltrim(substr($data,$pos));
$this->debug('found proper separation of headers and document');
$this->debug('cleaned data, stringlen: '.strlen($data));
// clean headers
foreach ($header_array as $header_line) {
$arr = explode(':',$header_line,2);
if(count($arr) > 1){
$header_name = strtolower(trim($arr[0]));
$this->incoming_headers[$header_name] = trim($arr[1]);
if ($header_name == 'set-cookie') {
// TODO: allow multiple cookies from parseCookie
$cookie = $this->parseCookie(trim($arr[1]));
if ($cookie) {
$this->incoming_cookies[] = $cookie;
$this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']);
} else {
$this->debug('did not find cookie in ' . trim($arr[1]));
}
}
} else if (isset($header_name)) {
// append continuation line to previous header
$this->incoming_headers[$header_name] .= $lb . ' ' . $header_line;
}
}
}
$arr = explode(' ', $header_array[0], 3);
$http_version = $arr[0];
$http_status = intval($arr[1]);
$http_reason = count($arr) > 2 ? $arr[2] : '';
// see if we need to resend the request with http digest authentication
if (isset($this->incoming_headers['location']) && $http_status == 301) {
$this->debug("Got 301 $http_reason with Location: " . $this->incoming_headers['location']);
$this->setURL($this->incoming_headers['location']);
$this->tryagain = true;
return false;
}
// see if we need to resend the request with http digest authentication
if (isset($this->incoming_headers['www-authenticate']) && $http_status == 401) {
$this->debug("Got 401 $http_reason with WWW-Authenticate: " . $this->incoming_headers['www-authenticate']);
if (strstr($this->incoming_headers['www-authenticate'], "Digest ")) {
$this->debug('Server wants digest authentication');
// remove "Digest " from our elements
$digestString = str_replace('Digest ', '', $this->incoming_headers['www-authenticate']);
// parse elements into array
$digestElements = explode(',', $digestString);
foreach ($digestElements as $val) {
$tempElement = explode('=', trim($val), 2);
$digestRequest[$tempElement[0]] = str_replace("\"", '', $tempElement[1]);
}
// should have (at least) qop, realm, nonce
if (isset($digestRequest['nonce'])) {
$this->setCredentials($this->username, $this->password, 'digest', $digestRequest);
$this->tryagain = true;
return false;
}
}
$this->debug('HTTP authentication failed');
$this->setError('HTTP authentication failed');
return false;
}
if (
($http_status >= 300 && $http_status <= 307) ||
($http_status >= 400 && $http_status <= 417) ||
($http_status >= 501 && $http_status <= 505)
) {
$this->setError("Unsupported HTTP response status $http_status $http_reason (soapclient->response has contents of the response)");
return false;
}
// decode content-encoding
if(isset($this->incoming_headers['content-encoding']) && $this->incoming_headers['content-encoding'] != ''){
if(strtolower($this->incoming_headers['content-encoding']) == 'deflate' || strtolower($this->incoming_headers['content-encoding']) == 'gzip'){
// if decoding works, use it. else assume data wasn't gzencoded
if(function_exists('gzinflate')){
//$timer->setMarker('starting decoding of gzip/deflated content');
// IIS 5 requires gzinflate instead of gzuncompress (similar to IE 5 and gzdeflate v. gzcompress)
// this means there are no Zlib headers, although there should be
$this->debug('The gzinflate function exists');
$datalen = strlen($data);
if ($this->incoming_headers['content-encoding'] == 'deflate') {
if ($degzdata = @gzinflate($data)) {
$data = $degzdata;
$this->debug('The payload has been inflated to ' . strlen($data) . ' bytes');
if (strlen($data) < $datalen) {
// test for the case that the payload has been compressed twice
$this->debug('The inflated payload is smaller than the gzipped one; try again');
if ($degzdata = @gzinflate($data)) {
$data = $degzdata;
$this->debug('The payload has been inflated again to ' . strlen($data) . ' bytes');
}
}
} else {
$this->debug('Error using gzinflate to inflate the payload');
$this->setError('Error using gzinflate to inflate the payload');
}
} elseif ($this->incoming_headers['content-encoding'] == 'gzip') {
if ($degzdata = @gzinflate(substr($data, 10))) { // do our best
$data = $degzdata;
$this->debug('The payload has been un-gzipped to ' . strlen($data) . ' bytes');
if (strlen($data) < $datalen) {
// test for the case that the payload has been compressed twice
$this->debug('The un-gzipped payload is smaller than the gzipped one; try again');
if ($degzdata = @gzinflate(substr($data, 10))) {
$data = $degzdata;
$this->debug('The payload has been un-gzipped again to ' . strlen($data) . ' bytes');
}
}
} else {
$this->debug('Error using gzinflate to un-gzip the payload');
$this->setError('Error using gzinflate to un-gzip the payload');
}
}
//$timer->setMarker('finished decoding of gzip/deflated content');
//print "<xmp>\nde-inflated:\n---------------\n$data\n-------------\n</xmp>";
// set decoded payload
$this->incoming_payload = $header_data.$lb.$lb.$data;
} else {
$this->debug('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.');
$this->setError('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.');
}
} else {
$this->debug('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']);
$this->setError('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']);
}
} else {
$this->debug('No Content-Encoding header');
}
if(strlen($data) == 0){
$this->debug('no data after headers!');
$this->setError('no data present after HTTP headers');
return false;
}
return $data;
}
function setContentType($type, $charset = false) {
$this->outgoing_headers['Content-Type'] = $type . ($charset ? '; charset=' . $charset : '');
$this->debug('set Content-Type: ' . $this->outgoing_headers['Content-Type']);
}
function usePersistentConnection(){
if (isset($this->outgoing_headers['Accept-Encoding'])) {
return false;
}
$this->protocol_version = '1.1';
$this->persistentConnection = true;
$this->outgoing_headers['Connection'] = 'Keep-Alive';
$this->debug('set Connection: ' . $this->outgoing_headers['Connection']);
return true;
}
/**
* parse an incoming Cookie into it's parts
*
* @param string $cookie_str content of cookie
* @return array with data of that cookie
* @access private
*/
/*
* TODO: allow a Set-Cookie string to be parsed into multiple cookies
*/
function parseCookie($cookie_str) {
$cookie_str = str_replace('; ', ';', $cookie_str) . ';';
$data = split(';', $cookie_str);
$value_str = $data[0];
$cookie_param = 'domain=';
$start = strpos($cookie_str, $cookie_param);
if ($start > 0) {
$domain = substr($cookie_str, $start + strlen($cookie_param));
$domain = substr($domain, 0, strpos($domain, ';'));
} else {
$domain = '';
}
$cookie_param = 'expires=';
$start = strpos($cookie_str, $cookie_param);
if ($start > 0) {
$expires = substr($cookie_str, $start + strlen($cookie_param));
$expires = substr($expires, 0, strpos($expires, ';'));
} else {
$expires = '';
}
$cookie_param = 'path=';
$start = strpos($cookie_str, $cookie_param);
if ( $start > 0 ) {
$path = substr($cookie_str, $start + strlen($cookie_param));
$path = substr($path, 0, strpos($path, ';'));
} else {
$path = '/';
}
$cookie_param = ';secure;';
if (strpos($cookie_str, $cookie_param) !== FALSE) {
$secure = true;
} else {
$secure = false;
}
$sep_pos = strpos($value_str, '=');
if ($sep_pos) {
$name = substr($value_str, 0, $sep_pos);
$value = substr($value_str, $sep_pos + 1);
$cookie= array( 'name' => $name,
'value' => $value,
'domain' => $domain,
'path' => $path,
'expires' => $expires,
'secure' => $secure
);
return $cookie;
}
return false;
}
/**
* sort out cookies for the current request
*
* @param array $cookies array with all cookies
* @param boolean $secure is the send-content secure or not?
* @return string for Cookie-HTTP-Header
* @access private
*/
function getCookiesForRequest($cookies, $secure=false) {
$cookie_str = '';
if ((! is_null($cookies)) && (is_array($cookies))) {
foreach ($cookies as $cookie) {
if (! is_array($cookie)) {
continue;
}
$this->debug("check cookie for validity: ".$cookie['name'].'='.$cookie['value']);
if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) {
if (strtotime($cookie['expires']) <= time()) {
$this->debug('cookie has expired');
continue;
}
}
if ((isset($cookie['domain'])) && (! empty($cookie['domain']))) {
$domain = preg_quote($cookie['domain']);
if (! preg_match("'.*$domain$'i", $this->host)) {
$this->debug('cookie has different domain');
continue;
}
}
if ((isset($cookie['path'])) && (! empty($cookie['path']))) {
$path = preg_quote($cookie['path']);
if (! preg_match("'^$path.*'i", $this->path)) {
$this->debug('cookie is for a different path');
continue;
}
}
if ((! $secure) && (isset($cookie['secure'])) && ($cookie['secure'])) {
$this->debug('cookie is secure, transport is not');
continue;
}
$cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; ';
$this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']);
}
}
return $cookie_str;
}
}
?><?php
/**
*
* soap_server allows the user to create a SOAP server
* that is capable of receiving messages and returning responses
*
* NOTE: WSDL functionality is experimental
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $
* @access public
*/
class soap_server extends nusoap_base {
/**
* HTTP headers of request
* @var array
* @access private
*/
var $headers = array();
/**
* HTTP request
* @var string
* @access private
*/
var $request = '';
/**
* SOAP headers from request (incomplete namespace resolution; special characters not escaped) (text)
* @var string
* @access public
*/
var $requestHeaders = '';
/**
* SOAP body request portion (incomplete namespace resolution; special characters not escaped) (text)
* @var string
* @access public
*/
var $document = '';
/**
* SOAP payload for request (text)
* @var string
* @access public
*/
var $requestSOAP = '';
/**
* requested method namespace URI
* @var string
* @access private
*/
var $methodURI = '';
/**
* name of method requested
* @var string
* @access private
*/
var $methodname = '';
/**
* method parameters from request
* @var array
* @access private
*/
var $methodparams = array();
/**
* SOAP Action from request
* @var string
* @access private
*/
var $SOAPAction = '';
/**
* character set encoding of incoming (request) messages
* @var string
* @access public
*/
var $xml_encoding = '';
/**
* toggles whether the parser decodes element content w/ utf8_decode()
* @var boolean
* @access public
*/
var $decode_utf8 = true;
/**
* HTTP headers of response
* @var array
* @access public
*/
var $outgoing_headers = array();
/**
* HTTP response
* @var string
* @access private
*/
var $response = '';
/**
* SOAP headers for response (text)
* @var string
* @access public
*/
var $responseHeaders = '';
/**
* SOAP payload for response (text)
* @var string
* @access private
*/
var $responseSOAP = '';
/**
* method return value to place in response
* @var mixed
* @access private
*/
var $methodreturn = false;
/**
* whether $methodreturn is a string of literal XML
* @var boolean
* @access public
*/
var $methodreturnisliteralxml = false;
/**
* SOAP fault for response (or false)
* @var mixed
* @access private
*/
var $fault = false;
/**
* text indication of result (for debugging)
* @var string
* @access private
*/
var $result = 'successful';
/**
* assoc array of operations => opData; operations are added by the register()
* method or by parsing an external WSDL definition
* @var array
* @access private
*/
var $operations = array();
/**
* wsdl instance (if one)
* @var mixed
* @access private
*/
var $wsdl = false;
/**
* URL for WSDL (if one)
* @var mixed
* @access private
*/
var $externalWSDLURL = false;
/**
* whether to append debug to response as XML comment
* @var boolean
* @access public
*/
var $debug_flag = false;
/**
* constructor
* the optional parameter is a path to a WSDL file that you'd like to bind the server instance to.
*
* @param mixed $wsdl file path or URL (string), or wsdl instance (object)
* @access public
*/
function soap_server($wsdl=false){
parent::nusoap_base();
// turn on debugging?
global $debug;
global $HTTP_SERVER_VARS;
if (isset($_SERVER)) {
$this->debug("_SERVER is defined:");
$this->appendDebug($this->varDump($_SERVER));
} elseif (isset($HTTP_SERVER_VARS)) {
$this->debug("HTTP_SERVER_VARS is defined:");
$this->appendDebug($this->varDump($HTTP_SERVER_VARS));
} else {
$this->debug("Neither _SERVER nor HTTP_SERVER_VARS is defined.");
}
if (isset($debug)) {
$this->debug("In soap_server, set debug_flag=$debug based on global flag");
$this->debug_flag = $debug;
} elseif (isset($_SERVER['QUERY_STRING'])) {
$qs = explode('&', $_SERVER['QUERY_STRING']);
foreach ($qs as $v) {
if (substr($v, 0, 6) == 'debug=') {
$this->debug("In soap_server, set debug_flag=" . substr($v, 6) . " based on query string #1");
$this->debug_flag = substr($v, 6);
}
}
} elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
$qs = explode('&', $HTTP_SERVER_VARS['QUERY_STRING']);
foreach ($qs as $v) {
if (substr($v, 0, 6) == 'debug=') {
$this->debug("In soap_server, set debug_flag=" . substr($v, 6) . " based on query string #2");
$this->debug_flag = substr($v, 6);
}
}
}
// wsdl
if($wsdl){
$this->debug("In soap_server, WSDL is specified");
if (is_object($wsdl) && (get_class($wsdl) == 'wsdl')) {
$this->wsdl = $wsdl;
$this->externalWSDLURL = $this->wsdl->wsdl;
$this->debug('Use existing wsdl instance from ' . $this->externalWSDLURL);
} else {
$this->debug('Create wsdl from ' . $wsdl);
$this->wsdl = new wsdl($wsdl);
$this->externalWSDLURL = $wsdl;
}
$this->appendDebug($this->wsdl->getDebug());
$this->wsdl->clearDebug();
if($err = $this->wsdl->getError()){
die('WSDL ERROR: '.$err);
}
}
}
/**
* processes request and returns response
*
* @param string $data usually is the value of $HTTP_RAW_POST_DATA
* @access public
*/
function service($data){
global $HTTP_SERVER_VARS;
if (isset($_SERVER['QUERY_STRING'])) {
$qs = $_SERVER['QUERY_STRING'];
} elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
$qs = $HTTP_SERVER_VARS['QUERY_STRING'];
} else {
$qs = '';
}
$this->debug("In service, query string=$qs");
if (ereg('wsdl', $qs) ){
$this->debug("In service, this is a request for WSDL");
if($this->externalWSDLURL){
if (strpos($this->externalWSDLURL,"://")!==false) { // assume URL
header('Location: '.$this->externalWSDLURL);
} else { // assume file
header("Content-Type: text/xml\r\n");
$fp = fopen($this->externalWSDLURL, 'r');
fpassthru($fp);
}
} elseif ($this->wsdl) {
header("Content-Type: text/xml; charset=ISO-8859-1\r\n");
print $this->wsdl->serialize($this->debug_flag);
if ($this->debug_flag) {
$this->debug('wsdl:');
$this->appendDebug($this->varDump($this->wsdl));
print $this->getDebugAsXMLComment();
}
} else {
header("Content-Type: text/html; charset=ISO-8859-1\r\n");
print "This service does not provide WSDL";
}
} elseif ($data == '' && $this->wsdl) {
$this->debug("In service, there is no data, so return Web description");
print $this->wsdl->webDescription();
} else {
$this->debug("In service, invoke the request");
$this->parse_request($data);
if (! $this->fault) {
$this->invoke_method();
}
if (! $this->fault) {
$this->serialize_return();
}
$this->send_response();
}
}
/**
* parses HTTP request headers.
*
* The following fields are set by this function (when successful)
*
* headers
* request
* xml_encoding
* SOAPAction
*
* @access private
*/
function parse_http_headers() {
global $HTTP_SERVER_VARS;
$this->request = '';
$this->SOAPAction = '';
if(function_exists('getallheaders')){
$this->debug("In parse_http_headers, use getallheaders");
$headers = getallheaders();
foreach($headers as $k=>$v){
$k = strtolower($k);
$this->headers[$k] = $v;
$this->request .= "$k: $v\r\n";
$this->debug("$k: $v");
}
// get SOAPAction header
if(isset($this->headers['soapaction'])){
$this->SOAPAction = str_replace('"','',$this->headers['soapaction']);
}
// get the character encoding of the incoming request
if(isset($this->headers['content-type']) && strpos($this->headers['content-type'],'=')){
$enc = str_replace('"','',substr(strstr($this->headers["content-type"],'='),1));
if(eregi('^(ISO-8859-1|US-ASCII|UTF-8)$',$enc)){
$this->xml_encoding = strtoupper($enc);
} else {
$this->xml_encoding = 'US-ASCII';
}
} else {
// should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
$this->xml_encoding = 'ISO-8859-1';
}
} elseif(isset($_SERVER) && is_array($_SERVER)){
$this->debug("In parse_http_headers, use _SERVER");
foreach ($_SERVER as $k => $v) {
if (substr($k, 0, 5) == 'HTTP_') {
$k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5));
} else {
$k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k);
}
if ($k == 'soapaction') {
// get SOAPAction header
$k = 'SOAPAction';
$v = str_replace('"', '', $v);
$v = str_replace('\\', '', $v);
$this->SOAPAction = $v;
} else if ($k == 'content-type') {
// get the character encoding of the incoming request
if (strpos($v, '=')) {
$enc = substr(strstr($v, '='), 1);
$enc = str_replace('"', '', $enc);
$enc = str_replace('\\', '', $enc);
if (eregi('^(ISO-8859-1|US-ASCII|UTF-8)$', $enc)) {
$this->xml_encoding = strtoupper($enc);
} else {
$this->xml_encoding = 'US-ASCII';
}
} else {
// should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
$this->xml_encoding = 'ISO-8859-1';
}
}
$this->headers[$k] = $v;
$this->request .= "$k: $v\r\n";
$this->debug("$k: $v");
}
} elseif (is_array($HTTP_SERVER_VARS)) {
$this->debug("In parse_http_headers, use HTTP_SERVER_VARS");
foreach ($HTTP_SERVER_VARS as $k => $v) {
if (substr($k, 0, 5) == 'HTTP_') {
$k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5));
} else {
$k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k);
}
if ($k == 'soapaction') {
// get SOAPAction header
$k = 'SOAPAction';
$v = str_replace('"', '', $v);
$v = str_replace('\\', '', $v);
$this->SOAPAction = $v;
} else if ($k == 'content-type') {
// get the character encoding of the incoming request
if (strpos($v, '=')) {
$enc = substr(strstr($v, '='), 1);
$enc = str_replace('"', '', $enc);
$enc = str_replace('\\', '', $enc);
if (eregi('^(ISO-8859-1|US-ASCII|UTF-8)$', $enc)) {
$this->xml_encoding = strtoupper($enc);
} else {
$this->xml_encoding = 'US-ASCII';
}
} else {
// should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
$this->xml_encoding = 'ISO-8859-1';
}
}
$this->headers[$k] = $v;
$this->request .= "$k: $v\r\n";
$this->debug("$k: $v");
}
} else {
$this->debug("In parse_http_headers, HTTP headers not accessible");
$this->setError("HTTP headers not accessible");
}
}
/**
* parses a request
*
* The following fields are set by this function (when successful)
*
* headers
* request
* xml_encoding
* SOAPAction
* request
* requestSOAP
* methodURI
* methodname
* methodparams
* requestHeaders
* document
*
* This sets the fault field on error
*
* @param string $data XML string
* @access private
*/
function parse_request($data='') {
$this->debug('entering parse_request()');
$this->parse_http_headers();
$this->debug('got character encoding: '.$this->xml_encoding);
// uncompress if necessary
if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] != '') {
$this->debug('got content encoding: ' . $this->headers['content-encoding']);
if ($this->headers['content-encoding'] == 'deflate' || $this->headers['content-encoding'] == 'gzip') {
// if decoding works, use it. else assume data wasn't gzencoded
if (function_exists('gzuncompress')) {
if ($this->headers['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
$data = $degzdata;
} elseif ($this->headers['content-encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))) {
$data = $degzdata;
} else {
$this->fault('Client', 'Errors occurred when trying to decode the data');
return;
}
} else {
$this->fault('Client', 'This Server does not support compressed data');
return;
}
}
}
$this->request .= "\r\n".$data;
$data = $this->parseRequest($this->headers, $data);
$this->requestSOAP = $data;
$this->debug('leaving parse_request');
}
/**
* invokes a PHP function for the requested SOAP method
*
* The following fields are set by this function (when successful)
*
* methodreturn
*
* Note that the PHP function that is called may also set the following
* fields to affect the response sent to the client
*
* responseHeaders
* outgoing_headers
*
* This sets the fault field on error
*
* @access private
*/
function invoke_method() {
$this->debug('in invoke_method, methodname=' . $this->methodname . ' methodURI=' . $this->methodURI . ' SOAPAction=' . $this->SOAPAction);
if ($this->wsdl) {
if ($this->opData = $this->wsdl->getOperationData($this->methodname)) {
$this->debug('in invoke_method, found WSDL operation=' . $this->methodname);
$this->appendDebug('opData=' . $this->varDump($this->opData));
} elseif ($this->opData = $this->wsdl->getOperationDataForSoapAction($this->SOAPAction)) {
// Note: hopefully this case will only be used for doc/lit, since rpc services should have wrapper element
$this->debug('in invoke_method, found WSDL soapAction=' . $this->SOAPAction . ' for operation=' . $this->opData['name']);
$this->appendDebug('opData=' . $this->varDump($this->opData));
$this->methodname = $this->opData['name'];
} else {
$this->debug('in invoke_method, no WSDL for operation=' . $this->methodname);
$this->fault('Client', "Operation '" . $this->methodname . "' is not defined in the WSDL for this service");
return;
}
} else {
$this->debug('in invoke_method, no WSDL to validate method');
}
// if a . is present in $this->methodname, we see if there is a class in scope,
// which could be referred to. We will also distinguish between two deliminators,
// to allow methods to be called a the class or an instance
$class = '';
$method = '';
if (strpos($this->methodname, '..') > 0) {
$delim = '..';
} else if (strpos($this->methodname, '.') > 0) {
$delim = '.';
} else {
$delim = '';
}
if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1 &&
class_exists(substr($this->methodname, 0, strpos($this->methodname, $delim)))) {
// get the class and method name
$class = substr($this->methodname, 0, strpos($this->methodname, $delim));
$method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim));
$this->debug("in invoke_method, class=$class method=$method delim=$delim");
}
// does method exist?
if ($class == '') {
if (!function_exists($this->methodname)) {
$this->debug("in invoke_method, function '$this->methodname' not found!");
$this->result = 'fault: method not found';
$this->fault('Client',"method '$this->methodname' not defined in service");
return;
}
} else {
$method_to_compare = (substr(phpversion(), 0, 2) == '4.') ? strtolower($method) : $method;
if (!in_array($method_to_compare, get_class_methods($class))) {
$this->debug("in invoke_method, method '$this->methodname' not found in class '$class'!");
$this->result = 'fault: method not found';
$this->fault('Client',"method '$this->methodname' not defined in service");
return;
}
}
// evaluate message, getting back parameters
// verify that request parameters match the method's signature
if(! $this->verify_method($this->methodname,$this->methodparams)){
// debug
$this->debug('ERROR: request not verified against method signature');
$this->result = 'fault: request failed validation against method signature';
// return fault
$this->fault('Client',"Operation '$this->methodname' not defined in service.");
return;
}
// if there are parameters to pass
$this->debug('in invoke_method, params:');
$this->appendDebug($this->varDump($this->methodparams));
$this->debug("in invoke_method, calling '$this->methodname'");
if (!function_exists('call_user_func_array')) {
if ($class == '') {
$this->debug('in invoke_method, calling function using eval()');
$funcCall = "\$this->methodreturn = $this->methodname(";
} else {
if ($delim == '..') {
$this->debug('in invoke_method, calling class method using eval()');
$funcCall = "\$this->methodreturn = ".$class."::".$method."(";
} else {
$this->debug('in invoke_method, calling instance method using eval()');
// generate unique instance name
$instname = "\$inst_".time();
$funcCall = $instname." = new ".$class."(); ";
$funcCall .= "\$this->methodreturn = ".$instname."->".$method."(";
}
}
if ($this->methodparams) {
foreach ($this->methodparams as $param) {
if (is_array($param)) {
$this->fault('Client', 'NuSOAP does not handle complexType parameters correctly when using eval; call_user_func_array must be available');
return;
}
$funcCall .= "\"$param\",";
}
$funcCall = substr($funcCall, 0, -1);
}
$funcCall .= ');';
$this->debug('in invoke_method, function call: '.$funcCall);
@eval($funcCall);
} else {
if ($class == '') {
$this->debug('in invoke_method, calling function using call_user_func_array()');
$call_arg = "$this->methodname"; // straight assignment changes $this->methodname to lower case after call_user_func_array()
} elseif ($delim == '..') {
$this->debug('in invoke_method, calling class method using call_user_func_array()');
$call_arg = array ($class, $method);
} else {
$this->debug('in invoke_method, calling instance method using call_user_func_array()');
$instance = new $class ();
$call_arg = array(&$instance, $method);
}
$this->methodreturn = call_user_func_array($call_arg, $this->methodparams);
}
$this->debug('in invoke_method, methodreturn:');
$this->appendDebug($this->varDump($this->methodreturn));
$this->debug("in invoke_method, called method $this->methodname, received $this->methodreturn of type ".gettype($this->methodreturn));
}
/**
* serializes the return value from a PHP function into a full SOAP Envelope
*
* The following fields are set by this function (when successful)
*
* responseSOAP
*
* This sets the fault field on error
*
* @access private
*/
function serialize_return() {
$this->debug('Entering serialize_return methodname: ' . $this->methodname . ' methodURI: ' . $this->methodURI);
// if fault
if (isset($this->methodreturn) && (get_class($this->methodreturn) == 'soap_fault')) {
$this->debug('got a fault object from method');
$this->fault = $this->methodreturn;
return;
} elseif ($this->methodreturnisliteralxml) {
$return_val = $this->methodreturn;
// returned value(s)
} else {
$this->debug('got a(n) '.gettype($this->methodreturn).' from method');
$this->debug('serializing return value');
if($this->wsdl){
// weak attempt at supporting multiple output params
if(sizeof($this->opData['output']['parts']) > 1){
$opParams = $this->methodreturn;
} else {
// TODO: is this really necessary?
$opParams = array($this->methodreturn);
}
$return_val = $this->wsdl->serializeRPCParameters($this->methodname,'output',$opParams);
$this->appendDebug($this->wsdl->getDebug());
$this->wsdl->clearDebug();
if($errstr = $this->wsdl->getError()){
$this->debug('got wsdl error: '.$errstr);
$this->fault('Server', 'unable to serialize result');
return;
}
} else {
if (isset($this->methodreturn)) {
$return_val = $this->serialize_val($this->methodreturn, 'return');
} else {
$return_val = '';
$this->debug('in absence of WSDL, assume void return for backward compatibility');
}
}
}
$this->debug('return value:');
$this->appendDebug($this->varDump($return_val));
$this->debug('serializing response');
if ($this->wsdl) {
$this->debug('have WSDL for serialization: style is ' . $this->opData['style']);
if ($this->opData['style'] == 'rpc') {
$this->debug('style is rpc for serialization: use is ' . $this->opData['output']['use']);
if ($this->opData['output']['use'] == 'literal') {
$payload = '<'.$this->methodname.'Response xmlns="'.$this->methodURI.'">'.$return_val.'</'.$this->methodname."Response>";
} else {
$payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
}
} else {
$this->debug('style is not rpc for serialization: assume document');
$payload = $return_val;
}
} else {
$this->debug('do not have WSDL for serialization: assume rpc/encoded');
$payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
}
$this->result = 'successful';
if($this->wsdl){
//if($this->debug_flag){
$this->appendDebug($this->wsdl->getDebug());
// }
if (isset($opData['output']['encodingStyle'])) {
$encodingStyle = $opData['output']['encodingStyle'];
} else {
$encodingStyle = '';
}
// Added: In case we use a WSDL, return a serialized env. WITH the usedNamespaces.
$this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders,$this->wsdl->usedNamespaces,$this->opData['style'],$encodingStyle);
} else {
$this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders);
}
$this->debug("Leaving serialize_return");
}
/**
* sends an HTTP response
*
* The following fields are set by this function (when successful)
*
* outgoing_headers
* response
*
* @access private
*/
function send_response() {
$this->debug('Enter send_response');
if ($this->fault) {
$payload = $this->fault->serialize();
$this->outgoing_headers[] = "HTTP/1.0 500 Internal Server Error";
$this->outgoing_headers[] = "Status: 500 Internal Server Error";
} else {
$payload = $this->responseSOAP;
// Some combinations of PHP+Web server allow the Status
// to come through as a header. Since OK is the default
// just do nothing.
// $this->outgoing_headers[] = "HTTP/1.0 200 OK";
// $this->outgoing_headers[] = "Status: 200 OK";
}
// add debug data if in debug mode
if(isset($this->debug_flag) && $this->debug_flag){
$payload .= $this->getDebugAsXMLComment();
}
$this->outgoing_headers[] = "Server: $this->title Server v$this->version";
ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev);
$this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".$rev[1].")";
// Let the Web server decide about this
//$this->outgoing_headers[] = "Connection: Close\r\n";
$payload = $this->getHTTPBody($payload);
$type = $this->getHTTPContentType();
$charset = $this->getHTTPContentTypeCharset();
$this->outgoing_headers[] = "Content-Type: $type" . ($charset ? '; charset=' . $charset : '');
//begin code to compress payload - by John
// NOTE: there is no way to know whether the Web server will also compress
// this data.
if (strlen($payload) > 1024 && isset($this->headers) && isset($this->headers['accept-encoding'])) {
if (strstr($this->headers['accept-encoding'], 'gzip')) {
if (function_exists('gzencode')) {
if (isset($this->debug_flag) && $this->debug_flag) {
$payload .= "<!-- Content being gzipped -->";
}
$this->outgoing_headers[] = "Content-Encoding: gzip";
$payload = gzencode($payload);
} else {
if (isset($this->debug_flag) && $this->debug_flag) {
$payload .= "<!-- Content will not be gzipped: no gzencode -->";
}
}
} elseif (strstr($this->headers['accept-encoding'], 'deflate')) {
// Note: MSIE requires gzdeflate output (no Zlib header and checksum),
// instead of gzcompress output,
// which conflicts with HTTP 1.1 spec (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5)
if (function_exists('gzdeflate')) {
if (isset($this->debug_flag) && $this->debug_flag) {
$payload .= "<!-- Content being deflated -->";
}
$this->outgoing_headers[] = "Content-Encoding: deflate";
$payload = gzdeflate($payload);
} else {
if (isset($this->debug_flag) && $this->debug_flag) {
$payload .= "<!-- Content will not be deflated: no gzcompress -->";
}
}
}
}
//end code
$this->outgoing_headers[] = "Content-Length: ".strlen($payload);
reset($this->outgoing_headers);
foreach($this->outgoing_headers as $hdr){
header($hdr, false);
}
print $payload;
$this->response = join("\r\n",$this->outgoing_headers)."\r\n\r\n".$payload;
}
/**
* takes the value that was created by parsing the request
* and compares to the method's signature, if available.
*
* @param string $operation The operation to be invoked
* @param array $request The array of parameter values
* @return boolean Whether the operation was found
* @access private
*/
function verify_method($operation,$request){
if(isset($this->wsdl) && is_object($this->wsdl)){
if($this->wsdl->getOperationData($operation)){
return true;
}
} elseif(isset($this->operations[$operation])){
return true;
}
return false;
}
/**
* processes SOAP message received from client
*
* @param array $headers The HTTP headers
* @param string $data unprocessed request data from client
* @return mixed value of the message, decoded into a PHP type
* @access private
*/
function parseRequest($headers, $data) {
$this->debug('Entering parseRequest() for data of length ' . strlen($data) . ' and type ' . $headers['content-type']);
if (!strstr($headers['content-type'], 'text/xml')) {
$this->setError('Request not of type text/xml');
return false;
}
if (strpos($headers['content-type'], '=')) {
$enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1));
$this->debug('Got response encoding: ' . $enc);
if(eregi('^(ISO-8859-1|US-ASCII|UTF-8)$',$enc)){
$this->xml_encoding = strtoupper($enc);
} else {
$this->xml_encoding = 'US-ASCII';
}
} else {
// should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
$this->xml_encoding = 'ISO-8859-1';
}
$this->debug('Use encoding: ' . $this->xml_encoding . ' when creating soap_parser');
// parse response, get soap parser obj
$parser = new soap_parser($data,$this->xml_encoding,'',$this->decode_utf8);
// parser debug
$this->debug("parser debug: \n".$parser->getDebug());
// if fault occurred during message parsing
if($err = $parser->getError()){
$this->result = 'fault: error in msg parsing: '.$err;
$this->fault('Client',"error in msg parsing:\n".$err);
// else successfully parsed request into soapval object
} else {
// get/set methodname
$this->methodURI = $parser->root_struct_namespace;
$this->methodname = $parser->root_struct_name;
$this->debug('methodname: '.$this->methodname.' methodURI: '.$this->methodURI);
$this->debug('calling parser->get_response()');
$this->methodparams = $parser->get_response();
// get SOAP headers
$this->requestHeaders = $parser->getHeaders();
// add document for doclit support
$this->document = $parser->document;
}
}
/**
* gets the HTTP body for the current response.
*
* @param string $soapmsg The SOAP payload
* @return string The HTTP body, which includes the SOAP payload
* @access private
*/
function getHTTPBody($soapmsg) {
return $soapmsg;
}
/**
* gets the HTTP content type for the current response.
*
* Note: getHTTPBody must be called before this.
*
* @return string the HTTP content type for the current response.
* @access private
*/
function getHTTPContentType() {
return 'text/xml';
}
/**
* gets the HTTP content type charset for the current response.
* returns false for non-text content types.
*
* Note: getHTTPBody must be called before this.
*
* @return string the HTTP content type charset for the current response.
* @access private
*/
function getHTTPContentTypeCharset() {
return $this->soap_defencoding;
}
/**
* add a method to the dispatch map (this has been replaced by the register method)
*
* @param string $methodname
* @param string $in array of input values
* @param string $out array of output values
* @access public
* @deprecated
*/
function add_to_map($methodname,$in,$out){
$this->operations[$methodname] = array('name' => $methodname,'in' => $in,'out' => $out);
}
/**
* register a service function with the server
*
* @param string $name the name of the PHP function, class.method or class..method
* @param array $in assoc array of input values: key = param name, value = param type
* @param array $out assoc array of output values: key = param name, value = param type
* @param mixed $namespace the element namespace for the method or false
* @param mixed $soapaction the soapaction for the method or false
* @param mixed $style optional (rpc|document) or false Note: when 'document' is specified, parameter and return wrappers are created for you automatically
* @param mixed $use optional (encoded|literal) or false
* @param string $documentation optional Description to include in WSDL
* @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
* @access public
*/
function register($name,$in=array(),$out=array(),$namespace=false,$soapaction=false,$style=false,$use=false,$documentation='',$encodingStyle=''){
global $HTTP_SERVER_VARS;
if($this->externalWSDLURL){
die('You cannot bind to an external WSDL file, and register methods outside of it! Please choose either WSDL or no WSDL.');
}
if (! $name) {
die('You must specify a name when you register an operation');
}
if (!is_array($in)) {
die('You must provide an array for operation inputs');
}
if (!is_array($out)) {
die('You must provide an array for operation outputs');
}
if(false == $namespace) {
}
if(false == $soapaction) {
if (isset($_SERVER)) {
$SERVER_NAME = $_SERVER['SERVER_NAME'];
$SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
} elseif (isset($HTTP_SERVER_VARS)) {
$SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME'];
$SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME'];
} else {
$this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
}
$soapaction = "http://$SERVER_NAME$SCRIPT_NAME/$name";
}
if(false == $style) {
$style = "rpc";
}
if(false == $use) {
$use = "encoded";
}
if ($use == 'encoded' && $encodingStyle = '') {
$encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
}
$this->operations[$name] = array(
'name' => $name,
'in' => $in,
'out' => $out,
'namespace' => $namespace,
'soapaction' => $soapaction,
'style' => $style);
if($this->wsdl){
$this->wsdl->addOperation($name,$in,$out,$namespace,$soapaction,$style,$use,$documentation,$encodingStyle);
}
return true;
}
/**
* Specify a fault to be returned to the client.
* This also acts as a flag to the server that a fault has occured.
*
* @param string $faultcode
* @param string $faultstring
* @param string $faultactor
* @param string $faultdetail
* @access public
*/
function fault($faultcode,$faultstring,$faultactor='',$faultdetail=''){
if ($faultdetail == '' && $this->debug_flag) {
$faultdetail = $this->getDebug();
}
$this->fault = new soap_fault($faultcode,$faultactor,$faultstring,$faultdetail);
$this->fault->soap_defencoding = $this->soap_defencoding;
}
/**
* Sets up wsdl object.
* Acts as a flag to enable internal WSDL generation
*
* @param string $serviceName, name of the service
* @param mixed $namespace optional 'tns' service namespace or false
* @param mixed $endpoint optional URL of service endpoint or false
* @param string $style optional (rpc|document) WSDL style (also specified by operation)
* @param string $transport optional SOAP transport
* @param mixed $schemaTargetNamespace optional 'types' targetNamespace for service schema or false
*/
function configureWSDL($serviceName,$namespace = false,$endpoint = false,$style='rpc', $transport = 'http://schemas.xmlsoap.org/soap/http', $schemaTargetNamespace = false)
{
global $HTTP_SERVER_VARS;
if (isset($_SERVER)) {
$SERVER_NAME = $_SERVER['SERVER_NAME'];
$SERVER_PORT = $_SERVER['SERVER_PORT'];
$SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
$HTTPS = $_SERVER['HTTPS'];
} elseif (isset($HTTP_SERVER_VARS)) {
$SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME'];
$SERVER_PORT = $HTTP_SERVER_VARS['SERVER_PORT'];
$SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME'];
$HTTPS = $HTTP_SERVER_VARS['HTTPS'];
} else {
$this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
}
if ($SERVER_PORT == 80) {
$SERVER_PORT = '';
} else {
$SERVER_PORT = ':' . $SERVER_PORT;
}
if(false == $namespace) {
$namespace = "http://$SERVER_NAME/soap/$serviceName";
}
if(false == $endpoint) {
if ($HTTPS == '1' || $HTTPS == 'on') {
$SCHEME = 'https';
} else {
$SCHEME = 'http';
}
$endpoint = "$SCHEME://$SERVER_NAME$SERVER_PORT$SCRIPT_NAME";
}
if(false == $schemaTargetNamespace) {
$schemaTargetNamespace = $namespace;
}
$this->wsdl = new wsdl;
$this->wsdl->serviceName = $serviceName;
$this->wsdl->endpoint = $endpoint;
$this->wsdl->namespaces['tns'] = $namespace;
$this->wsdl->namespaces['soap'] = 'http://schemas.xmlsoap.org/wsdl/soap/';
$this->wsdl->namespaces['wsdl'] = 'http://schemas.xmlsoap.org/wsdl/';
if ($schemaTargetNamespace != $namespace) {
$this->wsdl->namespaces['types'] = $schemaTargetNamespace;
}
$this->wsdl->schemas[$schemaTargetNamespace][0] = new xmlschema('', '', $this->wsdl->namespaces);
$this->wsdl->schemas[$schemaTargetNamespace][0]->schemaTargetNamespace = $schemaTargetNamespace;
$this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/soap/encoding/'][0] = array('location' => '', 'loaded' => true);
$this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/wsdl/'][0] = array('location' => '', 'loaded' => true);
$this->wsdl->bindings[$serviceName.'Binding'] = array(
'name'=>$serviceName.'Binding',
'style'=>$style,
'transport'=>$transport,
'portType'=>$serviceName.'PortType');
$this->wsdl->ports[$serviceName.'Port'] = array(
'binding'=>$serviceName.'Binding',
'location'=>$endpoint,
'bindingType'=>'http://schemas.xmlsoap.org/wsdl/soap/');
}
}
?><?php
/**
* parses a WSDL file, allows access to it's data, other utility methods
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $
* @access public
*/
class wsdl extends nusoap_base {
// URL or filename of the root of this WSDL
var $wsdl;
// define internal arrays of bindings, ports, operations, messages, etc.
var $schemas = array();
var $currentSchema;
var $message = array();
var $complexTypes = array();
var $messages = array();
var $currentMessage;
var $currentOperation;
var $portTypes = array();
var $currentPortType;
var $bindings = array();
var $currentBinding;
var $ports = array();
var $currentPort;
var $opData = array();
var $status = '';
var $documentation = false;
var $endpoint = '';
// array of wsdl docs to import
var $import = array();
// parser vars
var $parser;
var $position = 0;
var $depth = 0;
var $depth_array = array();
// for getting wsdl
var $proxyhost = '';
var $proxyport = '';
var $proxyusername = '';
var $proxypassword = '';
var $timeout = 0;
var $response_timeout = 30;
/**
* constructor
*
* @param string $wsdl WSDL document URL
* @param string $proxyhost
* @param string $proxyport
* @param string $proxyusername
* @param string $proxypassword
* @param integer $timeout set the connection timeout
* @param integer $response_timeout set the response timeout
* @access public
*/
function wsdl($wsdl = '',$proxyhost=false,$proxyport=false,$proxyusername=false,$proxypassword=false,$timeout=0,$response_timeout=30){
parent::nusoap_base();
$this->wsdl = $wsdl;
$this->proxyhost = $proxyhost;
$this->proxyport = $proxyport;
$this->proxyusername = $proxyusername;
$this->proxypassword = $proxypassword;
$this->timeout = $timeout;
$this->response_timeout = $response_timeout;
// parse wsdl file
if ($wsdl != "") {
$this->debug('initial wsdl URL: ' . $wsdl);
$this->parseWSDL($wsdl);
}
// imports
// TODO: handle imports more properly, grabbing them in-line and nesting them
$imported_urls = array();
$imported = 1;
while ($imported > 0) {
$imported = 0;
// Schema imports
foreach ($this->schemas as $ns => $list) {
foreach ($list as $xs) {
$wsdlparts = parse_url($this->wsdl); // this is bogusly simple!
foreach ($xs->imports as $ns2 => $list2) {
for ($ii = 0; $ii < count($list2); $ii++) {
if (! $list2[$ii]['loaded']) {
$this->schemas[$ns]->imports[$ns2][$ii]['loaded'] = true;
$url = $list2[$ii]['location'];
if ($url != '') {
$urlparts = parse_url($url);
if (!isset($urlparts['host'])) {
$url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' .$wsdlparts['port'] : '') .
substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
}
if (! in_array($url, $imported_urls)) {
$this->parseWSDL($url);
$imported++;
$imported_urls[] = $url;
}
} else {
$this->debug("Unexpected scenario: empty URL for unloaded import");
}
}
}
}
}
}
// WSDL imports
$wsdlparts = parse_url($this->wsdl); // this is bogusly simple!
foreach ($this->import as $ns => $list) {
for ($ii = 0; $ii < count($list); $ii++) {
if (! $list[$ii]['loaded']) {
$this->import[$ns][$ii]['loaded'] = true;
$url = $list[$ii]['location'];
if ($url != '') {
$urlparts = parse_url($url);
if (!isset($urlparts['host'])) {
$url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') .
substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
}
if (! in_array($url, $imported_urls)) {
$this->parseWSDL($url);
$imported++;
$imported_urls[] = $url;
}
} else {
$this->debug("Unexpected scenario: empty URL for unloaded import");
}
}
}
}
}
// add new data to operation data
foreach($this->bindings as $binding => $bindingData) {
if (isset($bindingData['operations']) && is_array($bindingData['operations'])) {
foreach($bindingData['operations'] as $operation => $data) {
$this->debug('post-parse data gathering for ' . $operation);
$this->bindings[$binding]['operations'][$operation]['input'] =
isset($this->bindings[$binding]['operations'][$operation]['input']) ?
array_merge($this->bindings[$binding]['operations'][$operation]['input'], $this->portTypes[ $bindingData['portType'] ][$operation]['input']) :
$this->portTypes[ $bindingData['portType'] ][$operation]['input'];
$this->bindings[$binding]['operations'][$operation]['output'] =
isset($this->bindings[$binding]['operations'][$operation]['output']) ?
array_merge($this->bindings[$binding]['operations'][$operation]['output'], $this->portTypes[ $bindingData['portType'] ][$operation]['output']) :
$this->portTypes[ $bindingData['portType'] ][$operation]['output'];
if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ])){
$this->bindings[$binding]['operations'][$operation]['input']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ];
}
if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ])){
$this->bindings[$binding]['operations'][$operation]['output']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ];
}
if (isset($bindingData['style'])) {
$this->bindings[$binding]['operations'][$operation]['style'] = $bindingData['style'];
}
$this->bindings[$binding]['operations'][$operation]['transport'] = isset($bindingData['transport']) ? $bindingData['transport'] : '';
$this->bindings[$binding]['operations'][$operation]['documentation'] = isset($this->portTypes[ $bindingData['portType'] ][$operation]['documentation']) ? $this->portTypes[ $bindingData['portType'] ][$operation]['documentation'] : '';
$this->bindings[$binding]['operations'][$operation]['endpoint'] = isset($bindingData['endpoint']) ? $bindingData['endpoint'] : '';
}
}
}
}
/**
* parses the wsdl document
*
* @param string $wsdl path or URL
* @access private
*/
function parseWSDL($wsdl = '')
{
if ($wsdl == '') {
$this->debug('no wsdl passed to parseWSDL()!!');
$this->setError('no wsdl passed to parseWSDL()!!');
return false;
}
// parse $wsdl for url format
$wsdl_props = parse_url($wsdl);
if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'http' || $wsdl_props['scheme'] == 'https')) {
$this->debug('getting WSDL http(s) URL ' . $wsdl);
// get wsdl
$tr = new soap_transport_http($wsdl);
$tr->request_method = 'GET';
$tr->useSOAPAction = false;
if($this->proxyhost && $this->proxyport){
$tr->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword);
}
$tr->setEncoding('gzip, deflate');
$wsdl_string = $tr->send('', $this->timeout, $this->response_timeout);
//$this->debug("WSDL request\n" . $tr->outgoing_payload);
//$this->debug("WSDL response\n" . $tr->incoming_payload);
$this->appendDebug($tr->getDebug());
// catch errors
if($err = $tr->getError() ){
$errstr = 'HTTP ERROR: '.$err;
$this->debug($errstr);
$this->setError($errstr);
unset($tr);
return false;
}
unset($tr);
$this->debug("got WSDL URL");
} else {
// $wsdl is not http(s), so treat it as a file URL or plain file path
if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'file') && isset($wsdl_props['path'])) {
$path = isset($wsdl_props['host']) ? ($wsdl_props['host'] . ':' . $wsdl_props['path']) : $wsdl_props['path'];
} else {
$path = $wsdl;
}
$this->debug('getting WSDL file ' . $path);
if ($fp = @fopen($path, 'r')) {
$wsdl_string = '';
while ($data = fread($fp, 32768)) {
$wsdl_string .= $data;
}
fclose($fp);
} else {
$errstr = "Bad path to WSDL file $path";
$this->debug($errstr);
$this->setError($errstr);
return false;
}
}
$this->debug('Parse WSDL');
// end new code added
// Create an XML parser.
$this->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($this->parser, XML_OPTION_CASE_FOLDING, 0);
// Set the object for the parser.
xml_set_object($this->parser, $this);
// Set the element handlers for the parser.
xml_set_element_handler($this->parser, 'start_element', 'end_element');
xml_set_character_data_handler($this->parser, 'character_data');
// Parse the XML file.
if (!xml_parse($this->parser, $wsdl_string, true)) {
// Display an error message.
$errstr = sprintf(
'XML error parsing WSDL from %s on line %d: %s',
$wsdl,
xml_get_current_line_number($this->parser),
xml_error_string(xml_get_error_code($this->parser))
);
$this->debug($errstr);
$this->debug("XML payload:\n" . $wsdl_string);
$this->setError($errstr);
return false;
}
// free the parser
xml_parser_free($this->parser);
$this->debug('Parsing WSDL done');
// catch wsdl parse errors
if($this->getError()){
return false;
}
return true;
}
/**
* start-element handler
*
* @param string $parser XML parser object
* @param string $name element name
* @param string $attrs associative array of attributes
* @access private
*/
function start_element($parser, $name, $attrs)
{
if ($this->status == 'schema') {
$this->currentSchema->schemaStartElement($parser, $name, $attrs);
$this->appendDebug($this->currentSchema->getDebug());
$this->currentSchema->clearDebug();
} elseif (ereg('schema$', $name)) {
$this->debug('Parsing WSDL schema');
// $this->debug("startElement for $name ($attrs[name]). status = $this->status (".$this->getLocalPart($name).")");
$this->status = 'schema';
$this->currentSchema = new xmlschema('', '', $this->namespaces);
$this->currentSchema->schemaStartElement($parser, $name, $attrs);
$this->appendDebug($this->currentSchema->getDebug());
$this->currentSchema->clearDebug();
} else {
// position in the total number of elements, starting from 0
$pos = $this->position++;
$depth = $this->depth++;
// set self as current value for this depth
$this->depth_array[$depth] = $pos;
$this->message[$pos] = array('cdata' => '');
// process attributes
if (count($attrs) > 0) {
// register namespace declarations
foreach($attrs as $k => $v) {
if (ereg("^xmlns", $k)) {
if ($ns_prefix = substr(strrchr($k, ':'), 1)) {
$this->namespaces[$ns_prefix] = $v;
} else {
$this->namespaces['ns' . (count($this->namespaces) + 1)] = $v;
}
if ($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema') {
$this->XMLSchemaVersion = $v;
$this->namespaces['xsi'] = $v . '-instance';
}
}
}
// expand each attribute prefix to its namespace
foreach($attrs as $k => $v) {
$k = strpos($k, ':') ? $this->expandQname($k) : $k;
if ($k != 'location' && $k != 'soapAction' && $k != 'namespace') {
$v = strpos($v, ':') ? $this->expandQname($v) : $v;
}
$eAttrs[$k] = $v;
}
$attrs = $eAttrs;
} else {
$attrs = array();
}
// get element prefix, namespace and name
if (ereg(':', $name)) {
// get ns prefix
$prefix = substr($name, 0, strpos($name, ':'));
// get ns
$namespace = isset($this->namespaces[$prefix]) ? $this->namespaces[$prefix] : '';
// get unqualified name
$name = substr(strstr($name, ':'), 1);
}
// process attributes, expanding any prefixes to namespaces
// find status, register data
switch ($this->status) {
case 'message':
if ($name == 'part') {
if (isset($attrs['type'])) {
$this->debug("msg " . $this->currentMessage . ": found part $attrs[name]: " . implode(',', $attrs));
$this->messages[$this->currentMessage][$attrs['name']] = $attrs['type'];
}
if (isset($attrs['element'])) {
$this->debug("msg " . $this->currentMessage . ": found part $attrs[name]: " . implode(',', $attrs));
$this->messages[$this->currentMessage][$attrs['name']] = $attrs['element'];
}
}
break;
case 'portType':
switch ($name) {
case 'operation':
$this->currentPortOperation = $attrs['name'];
$this->debug("portType $this->currentPortType operation: $this->currentPortOperation");
if (isset($attrs['parameterOrder'])) {
$this->portTypes[$this->currentPortType][$attrs['name']]['parameterOrder'] = $attrs['parameterOrder'];
}
break;
case 'documentation':
$this->documentation = true;
break;
// merge input/output data
default:
$m = isset($attrs['message']) ? $this->getLocalPart($attrs['message']) : '';
$this->portTypes[$this->currentPortType][$this->currentPortOperation][$name]['message'] = $m;
break;
}
break;
case 'binding':
switch ($name) {
case 'binding':
// get ns prefix
if (isset($attrs['style'])) {
$this->bindings[$this->currentBinding]['prefix'] = $prefix;
}
$this->bindings[$this->currentBinding] = array_merge($this->bindings[$this->currentBinding], $attrs);
break;
case 'header':
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs;
break;
case 'operation':
if (isset($attrs['soapAction'])) {
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['soapAction'] = $attrs['soapAction'];
}
if (isset($attrs['style'])) {
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['style'] = $attrs['style'];
}
if (isset($attrs['name'])) {
$this->currentOperation = $attrs['name'];
$this->debug("current binding operation: $this->currentOperation");
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['name'] = $attrs['name'];
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['binding'] = $this->currentBinding;
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['endpoint'] = isset($this->bindings[$this->currentBinding]['endpoint']) ? $this->bindings[$this->currentBinding]['endpoint'] : '';
}
break;
case 'input':
$this->opStatus = 'input';
break;
case 'output':
$this->opStatus = 'output';
break;
case 'body':
if (isset($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus])) {
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = array_merge($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus], $attrs);
} else {
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = $attrs;
}
break;
}
break;
case 'service':
switch ($name) {
case 'port':
$this->currentPort = $attrs['name'];
$this->debug('current port: ' . $this->currentPort);
$this->ports[$this->currentPort]['binding'] = $this->getLocalPart($attrs['binding']);
break;
case 'address':
$this->ports[$this->currentPort]['location'] = $attrs['location'];
$this->ports[$this->currentPort]['bindingType'] = $namespace;
$this->bindings[ $this->ports[$this->currentPort]['binding'] ]['bindingType'] = $namespace;
$this->bindings[ $this->ports[$this->currentPort]['binding'] ]['endpoint'] = $attrs['location'];
break;
}
break;
}
// set status
switch ($name) {
case 'import':
if (isset($attrs['location'])) {
$this->import[$attrs['namespace']][] = array('location' => $attrs['location'], 'loaded' => false);
$this->debug('parsing import ' . $attrs['namespace']. ' - ' . $attrs['location'] . ' (' . count($this->import[$attrs['namespace']]).')');
} else {
$this->import[$attrs['namespace']][] = array('location' => '', 'loaded' => true);
if (! $this->getPrefixFromNamespace($attrs['namespace'])) {
$this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace'];
}
$this->debug('parsing import ' . $attrs['namespace']. ' - [no location] (' . count($this->import[$attrs['namespace']]).')');
}
break;
//wait for schema
//case 'types':
// $this->status = 'schema';
// break;
case 'message':
$this->status = 'message';
$this->messages[$attrs['name']] = array();
$this->currentMessage = $attrs['name'];
break;
case 'portType':
$this->status = 'portType';
$this->portTypes[$attrs['name']] = array();
$this->currentPortType = $attrs['name'];
break;
case "binding":
if (isset($attrs['name'])) {
// get binding name
if (strpos($attrs['name'], ':')) {
$this->currentBinding = $this->getLocalPart($attrs['name']);
} else {
$this->currentBinding = $attrs['name'];
}
$this->status = 'binding';
$this->bindings[$this->currentBinding]['portType'] = $this->getLocalPart($attrs['type']);
$this->debug("current binding: $this->currentBinding of portType: " . $attrs['type']);
}
break;
case 'service':
$this->serviceName = $attrs['name'];
$this->status = 'service';
$this->debug('current service: ' . $this->serviceName);
break;
case 'definitions':
foreach ($attrs as $name => $value) {
$this->wsdl_info[$name] = $value;
}
break;
}
}
}
/**
* end-element handler
*
* @param string $parser XML parser object
* @param string $name element name
* @access private
*/
function end_element($parser, $name){
// unset schema status
if (/*ereg('types$', $name) ||*/ ereg('schema$', $name)) {
$this->status = "";
$this->appendDebug($this->currentSchema->getDebug());
$this->currentSchema->clearDebug();
$this->schemas[$this->currentSchema->schemaTargetNamespace][] = $this->currentSchema;
$this->debug('Parsing WSDL schema done');
}
if ($this->status == 'schema') {
$this->currentSchema->schemaEndElement($parser, $name);
} else {
// bring depth down a notch
$this->depth--;
}
// end documentation
if ($this->documentation) {
//TODO: track the node to which documentation should be assigned; it can be a part, message, etc.
//$this->portTypes[$this->currentPortType][$this->currentPortOperation]['documentation'] = $this->documentation;
$this->documentation = false;
}
}
/**
* element content handler
*
* @param string $parser XML parser object
* @param string $data element content
* @access private
*/
function character_data($parser, $data)
{
$pos = isset($this->depth_array[$this->depth]) ? $this->depth_array[$this->depth] : 0;
if (isset($this->message[$pos]['cdata'])) {
$this->message[$pos]['cdata'] .= $data;
}
if ($this->documentation) {
$this->documentation .= $data;
}
}
function getBindingData($binding)
{
if (is_array($this->bindings[$binding])) {
return $this->bindings[$binding];
}
}
/**
* returns an assoc array of operation names => operation data
*
* @param string $bindingType eg: soap, smtp, dime (only soap is currently supported)
* @return array
* @access public
*/
function getOperations($bindingType = 'soap')
{
$ops = array();
if ($bindingType == 'soap') {
$bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
}
// loop thru ports
foreach($this->ports as $port => $portData) {
// binding type of port matches parameter
if ($portData['bindingType'] == $bindingType) {
//$this->debug("getOperations for port $port");
//$this->debug("port data: " . $this->varDump($portData));
//$this->debug("bindings: " . $this->varDump($this->bindings[ $portData['binding'] ]));
// merge bindings
if (isset($this->bindings[ $portData['binding'] ]['operations'])) {
$ops = array_merge ($ops, $this->bindings[ $portData['binding'] ]['operations']);
}
}
}
return $ops;
}
/**
* returns an associative array of data necessary for calling an operation
*
* @param string $operation , name of operation
* @param string $bindingType , type of binding eg: soap
* @return array
* @access public
*/
function getOperationData($operation, $bindingType = 'soap')
{
if ($bindingType == 'soap') {
$bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
}
// loop thru ports
foreach($this->ports as $port => $portData) {
// binding type of port matches parameter
if ($portData['bindingType'] == $bindingType) {
// get binding
//foreach($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
foreach(array_keys($this->bindings[ $portData['binding'] ]['operations']) as $bOperation) {
// note that we could/should also check the namespace here
if ($operation == $bOperation) {
$opData = $this->bindings[ $portData['binding'] ]['operations'][$operation];
return $opData;
}
}
}
}
}
/**
* returns an associative array of data necessary for calling an operation
*
* @param string $soapAction soapAction for operation
* @param string $bindingType type of binding eg: soap
* @return array
* @access public
*/
function getOperationDataForSoapAction($soapAction, $bindingType = 'soap') {
if ($bindingType == 'soap') {
$bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
}
// loop thru ports
foreach($this->ports as $port => $portData) {
// binding type of port matches parameter
if ($portData['bindingType'] == $bindingType) {
// loop through operations for the binding
foreach ($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
if ($opData['soapAction'] == $soapAction) {
return $opData;
}
}
}
}
}
/**
* returns an array of information about a given type
* returns false if no type exists by the given name
*
* typeDef = array(
* 'elements' => array(), // refs to elements array
* 'restrictionBase' => '',
* 'phpType' => '',
* 'order' => '(sequence|all)',
* 'attrs' => array() // refs to attributes array
* )
*
* @param $type string the type
* @param $ns string namespace (not prefix) of the type
* @return mixed
* @access public
* @see xmlschema
*/
function getTypeDef($type, $ns) {
$this->debug("in getTypeDef: type=$type, ns=$ns");
if ((! $ns) && isset($this->namespaces['tns'])) {
$ns = $this->namespaces['tns'];
$this->debug("in getTypeDef: type namespace forced to $ns");
}
if (isset($this->schemas[$ns])) {
$this->debug("in getTypeDef: have schema for namespace $ns");
for ($i = 0; $i < count($this->schemas[$ns]); $i++) {
$xs = &$this->schemas[$ns][$i];
$t = $xs->getTypeDef($type);
$this->appendDebug($xs->getDebug());
$xs->clearDebug();
if ($t) {
if (!isset($t['phpType'])) {
// get info for type to tack onto the element
$uqType = substr($t['type'], strrpos($t['type'], ':') + 1);
$ns = substr($t['type'], 0, strrpos($t['type'], ':'));
$etype = $this->getTypeDef($uqType, $ns);
if ($etype) {
$this->debug("found type for [element] $type:");
$this->debug($this->varDump($etype));
if (isset($etype['phpType'])) {
$t['phpType'] = $etype['phpType'];
}
if (isset($etype['elements'])) {
$t['elements'] = $etype['elements'];
}
if (isset($etype['attrs'])) {
$t['attrs'] = $etype['attrs'];
}
}
}
return $t;
}
}
} else {
$this->debug("in getTypeDef: do not have schema for namespace $ns");
}
return false;
}
/**
* prints html description of services
*
* @access private
*/
function webDescription(){
global $HTTP_SERVER_VARS;
if (isset($_SERVER)) {
$PHP_SELF = $_SERVER['PHP_SELF'];
} elseif (isset($HTTP_SERVER_VARS)) {
$PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
} else {
$this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
}
$b = '
<html><head><title>NuSOAP: '.$this->serviceName.'</title>
<style type="text/css">
body { font-family: arial; color: #000000; background-color: #ffffff; margin: 0px 0px 0px 0px; }
p { font-family: arial; color: #000000; margin-top: 0px; margin-bottom: 12px; }
pre { background-color: silver; padding: 5px; font-family: Courier New; font-size: x-small; color: #000000;}
ul { margin-top: 10px; margin-left: 20px; }
li { list-style-type: none; margin-top: 10px; color: #000000; }
.content{
margin-left: 0px; padding-bottom: 2em; }
.nav {
padding-top: 10px; padding-bottom: 10px; padding-left: 15px; font-size: .70em;
margin-top: 10px; margin-left: 0px; color: #000000;
background-color: #ccccff; width: 20%; margin-left: 20px; margin-top: 20px; }
.title {
font-family: arial; font-size: 26px; color: #ffffff;
background-color: #999999; width: 105%; margin-left: 0px;
padding-top: 10px; padding-bottom: 10px; padding-left: 15px;}
.hidden {
position: absolute; visibility: hidden; z-index: 200; left: 250px; top: 100px;
font-family: arial; overflow: hidden; width: 600;
padding: 20px; font-size: 10px; background-color: #999999;
layer-background-color:#FFFFFF; }
a,a:active { color: charcoal; font-weight: bold; }
a:visited { color: #666666; font-weight: bold; }
a:hover { color: cc3300; font-weight: bold; }
</style>
<script language="JavaScript" type="text/javascript">
<!--
// POP-UP CAPTIONS...
function lib_bwcheck(){ //Browsercheck (needed)
this.ver=navigator.appVersion
this.agent=navigator.userAgent
this.dom=document.getElementById?1:0
this.opera5=this.agent.indexOf("Opera 5")>-1
this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0;
this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
this.ie=this.ie4||this.ie5||this.ie6
this.mac=this.agent.indexOf("Mac")>-1
this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0;
this.ns4=(document.layers && !this.dom)?1:0;
this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5)
return this
}
var bw = new lib_bwcheck()
//Makes crossbrowser object.
function makeObj(obj){
this.evnt=bw.dom? document.getElementById(obj):bw.ie4?document.all[obj]:bw.ns4?document.layers[obj]:0;
if(!this.evnt) return false
this.css=bw.dom||bw.ie4?this.evnt.style:bw.ns4?this.evnt:0;
this.wref=bw.dom||bw.ie4?this.evnt:bw.ns4?this.css.document:0;
this.writeIt=b_writeIt;
return this
}
// A unit of measure that will be added when setting the position of a layer.
//var px = bw.ns4||window.opera?"":"px";
function b_writeIt(text){
if (bw.ns4){this.wref.write(text);this.wref.close()}
else this.wref.innerHTML = text
}
//Shows the messages
var oDesc;
function popup(divid){
if(oDesc = new makeObj(divid)){
oDesc.css.visibility = "visible"
}
}
function popout(){ // Hides message
if(oDesc) oDesc.css.visibility = "hidden"
}
//-->
</script>
</head>
<body>
<div class=content>
<br><br>
<div class=title>'.$this->serviceName.'</div>
<div class=nav>
<p>View the <a href="'.$PHP_SELF.'?wsdl">WSDL</a> for the service.
Click on an operation name to view it's details.</p>
<ul>';
foreach($this->getOperations() as $op => $data){
$b .= "<li><a href='#' onclick=\"popout();popup('$op')\">$op</a></li>";
// create hidden div
$b .= "<div id='$op' class='hidden'>
<a href='#' onclick='popout()'><font color='#ffffff'>Close</font></a><br><br>";
foreach($data as $donnie => $marie){ // loop through opdata
if($donnie == 'input' || $donnie == 'output'){ // show input/output data
$b .= "<font color='white'>".ucfirst($donnie).':</font><br>';
foreach($marie as $captain => $tenille){ // loop through data
if($captain == 'parts'){ // loop thru parts
$b .= " $captain:<br>";
//if(is_array($tenille)){
foreach($tenille as $joanie => $chachi){
$b .= " $joanie: $chachi<br>";
}
//}
} else {
$b .= " $captain: $tenille<br>";
}
}
} else {
$b .= "<font color='white'>".ucfirst($donnie).":</font> $marie<br>";
}
}
$b .= '</div>';
}
$b .= '
<ul>
</div>
</div></body></html>';
return $b;
}
/**
* serialize the parsed wsdl
*
* @param mixed $debug whether to put debug=1 in endpoint URL
* @return string serialization of WSDL
* @access public
*/
function serialize($debug = 0)
{
$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$xml .= "\n<definitions";
foreach($this->namespaces as $k => $v) {
$xml .= " xmlns:$k=\"$v\"";
}
// 10.9.02 - add poulter fix for wsdl and tns declarations
if (isset($this->namespaces['wsdl'])) {
$xml .= " xmlns=\"" . $this->namespaces['wsdl'] . "\"";
}
if (isset($this->namespaces['tns'])) {
$xml .= " targetNamespace=\"" . $this->namespaces['tns'] . "\"";
}
$xml .= '>';
// imports
if (sizeof($this->import) > 0) {
foreach($this->import as $ns => $list) {
foreach ($list as $ii) {
if ($ii['location'] != '') {
$xml .= '<import location="' . $ii['location'] . '" namespace="' . $ns . '" />';
} else {
$xml .= '<import namespace="' . $ns . '" />';
}
}
}
}
// types
if (count($this->schemas)>=1) {
$xml .= "\n<types>";
foreach ($this->schemas as $ns => $list) {
foreach ($list as $xs) {
$xml .= $xs->serializeSchema();
}
}
$xml .= '</types>';
}
// messages
if (count($this->messages) >= 1) {
foreach($this->messages as $msgName => $msgParts) {
$xml .= "\n<message name=\"" . $msgName . '">';
if(is_array($msgParts)){
foreach($msgParts as $partName => $partType) {
// print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'<br>';
if (strpos($partType, ':')) {
$typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType));
} elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) {
// print 'checking typemap: '.$this->XMLSchemaVersion.'<br>';
$typePrefix = 'xsd';
} else {
foreach($this->typemap as $ns => $types) {
if (isset($types[$partType])) {
$typePrefix = $this->getPrefixFromNamespace($ns);
}
}
if (!isset($typePrefix)) {
die("$partType has no namespace!");
}
}
$ns = $this->getNamespaceFromPrefix($typePrefix);
$typeDef = $this->getTypeDef($this->getLocalPart($partType), $ns);
if ($typeDef['typeClass'] == 'element') {
$elementortype = 'element';
} else {
$elementortype = 'type';
}
$xml .= '<part name="' . $partName . '" ' . $elementortype . '="' . $typePrefix . ':' . $this->getLocalPart($partType) . '" />';
}
}
$xml .= '</message>';
}
}
// bindings & porttypes
if (count($this->bindings) >= 1) {
$binding_xml = '';
$portType_xml = '';
foreach($this->bindings as $bindingName => $attrs) {
$binding_xml .= "\n<binding name=\"" . $bindingName . '" type="tns:' . $attrs['portType'] . '">';
$binding_xml .= '<soap:binding style="' . $attrs['style'] . '" transport="' . $attrs['transport'] . '"/>';
$portType_xml .= "\n<portType name=\"" . $attrs['portType'] . '">';
foreach($attrs['operations'] as $opName => $opParts) {
$binding_xml .= '<operation name="' . $opName . '">';
$binding_xml .= '<soap:operation soapAction="' . $opParts['soapAction'] . '" style="'. $opParts['style'] . '"/>';
if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') {
$enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"';
} else {
$enc_style = '';
}
$binding_xml .= '<input><soap:body use="' . $opParts['input']['use'] . '" namespace="' . $opParts['input']['namespace'] . '"' . $enc_style . '/></input>';
if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') {
$enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"';
} else {
$enc_style = '';
}
$binding_xml .= '<output><soap:body use="' . $opParts['output']['use'] . '" namespace="' . $opParts['output']['namespace'] . '"' . $enc_style . '/></output>';
$binding_xml .= '</operation>';
$portType_xml .= '<operation name="' . $opParts['name'] . '"';
if (isset($opParts['parameterOrder'])) {
$portType_xml .= ' parameterOrder="' . $opParts['parameterOrder'] . '"';
}
$portType_xml .= '>';
if(isset($opParts['documentation']) && $opParts['documentation'] != '') {
$portType_xml .= '<documentation>' . htmlspecialchars($opParts['documentation']) . '</documentation>';
}
$portType_xml .= '<input message="tns:' . $opParts['input']['message'] . '"/>';
$portType_xml .= '<output message="tns:' . $opParts['output']['message'] . '"/>';
$portType_xml .= '</operation>';
}
$portType_xml .= '</portType>';
$binding_xml .= '</binding>';
}
$xml .= $portType_xml . $binding_xml;
}
// services
$xml .= "\n<service name=\"" . $this->serviceName . '">';
if (count($this->ports) >= 1) {
foreach($this->ports as $pName => $attrs) {
$xml .= '<port name="' . $pName . '" binding="tns:' . $attrs['binding'] . '">';
$xml .= '<soap:address location="' . $attrs['location'] . ($debug ? '?debug=1' : '') . '"/>';
$xml .= '</port>';
}
}
$xml .= '</service>';
return $xml . "\n</definitions>";
}
/**
* serialize PHP values according to a WSDL message definition
*
* TODO
* - multi-ref serialization
* - validate PHP values against type definitions, return errors if invalid
*
* @param string $operation operation name
* @param string $direction (input|output)
* @param mixed $parameters parameter value(s)
* @return mixed parameters serialized as XML or false on error (e.g. operation not found)
* @access public
*/
function serializeRPCParameters($operation, $direction, $parameters)
{
$this->debug("in serializeRPCParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion");
$this->appendDebug('parameters=' . $this->varDump($parameters));
if ($direction != 'input' && $direction != 'output') {
$this->debug('The value of the \$direction argument needs to be either "input" or "output"');
$this->setError('The value of the \$direction argument needs to be either "input" or "output"');
return false;
}
if (!$opData = $this->getOperationData($operation)) {
$this->debug('Unable to retrieve WSDL data for operation: ' . $operation);
$this->setError('Unable to retrieve WSDL data for operation: ' . $operation);
return false;
}
$this->debug('opData:');
$this->appendDebug($this->varDump($opData));
// Get encoding style for output and set to current
$encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
$encodingStyle = $opData['output']['encodingStyle'];
$enc_style = $encodingStyle;
}
// set input params
$xml = '';
if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
$use = $opData[$direction]['use'];
$this->debug('have ' . count($opData[$direction]['parts']) . ' part(s) to serialize');
if (is_array($parameters)) {
$parametersArrayType = $this->isArraySimpleOrStruct($parameters);
$this->debug('have ' . count($parameters) . ' parameter(s) provided as ' . $parametersArrayType . ' to serialize');
foreach($opData[$direction]['parts'] as $name => $type) {
$this->debug('serializing part "'.$name.'" of type "'.$type.'"');
// Track encoding style
if (isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
$encodingStyle = $opData[$direction]['encodingStyle'];
$enc_style = $encodingStyle;
} else {
$enc_style = false;
}
// NOTE: add error handling here
// if serializeType returns false, then catch global error and fault
if ($parametersArrayType == 'arraySimple') {
$p = array_shift($parameters);
$this->debug('calling serializeType w/indexed param');
$xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
} elseif (isset($parameters[$name])) {
$this->debug('calling serializeType w/named param');
$xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
} else {
// TODO: only send nillable
$this->debug('calling serializeType w/null param');
$xml .= $this->serializeType($name, $type, null, $use, $enc_style);
}
}
} else {
$this->debug('no parameters passed.');
}
}
$this->debug("serializeRPCParameters returning: $xml");
return $xml;
}
/**
* serialize a PHP value according to a WSDL message definition
*
* TODO
* - multi-ref serialization
* - validate PHP values against type definitions, return errors if invalid
*
* @param string $ type name
* @param mixed $ param value
* @return mixed new param or false if initial value didn't validate
* @access public
* @deprecated
*/
function serializeParameters($operation, $direction, $parameters)
{
$this->debug("in serializeParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion");
$this->appendDebug('parameters=' . $this->varDump($parameters));
if ($direction != 'input' && $direction != 'output') {
$this->debug('The value of the \$direction argument needs to be either "input" or "output"');
$this->setError('The value of the \$direction argument needs to be either "input" or "output"');
return false;
}
if (!$opData = $this->getOperationData($operation)) {
$this->debug('Unable to retrieve WSDL data for operation: ' . $operation);
$this->setError('Unable to retrieve WSDL data for operation: ' . $operation);
return false;
}
$this->debug('opData:');
$this->appendDebug($this->varDump($opData));
// Get encoding style for output and set to current
$encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
$encodingStyle = $opData['output']['encodingStyle'];
$enc_style = $encodingStyle;
}
// set input params
$xml = '';
if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
$use = $opData[$direction]['use'];
$this->debug("use=$use");
$this->debug('got ' . count($opData[$direction]['parts']) . ' part(s)');
if (is_array($parameters)) {
$parametersArrayType = $this->isArraySimpleOrStruct($parameters);
$this->debug('have ' . $parametersArrayType . ' parameters');
foreach($opData[$direction]['parts'] as $name => $type) {
$this->debug('serializing part "'.$name.'" of type "'.$type.'"');
// Track encoding style
if(isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
$encodingStyle = $opData[$direction]['encodingStyle'];
$enc_style = $encodingStyle;
} else {
$enc_style = false;
}
// NOTE: add error handling here
// if serializeType returns false, then catch global error and fault
if ($parametersArrayType == 'arraySimple') {
$p = array_shift($parameters);
$this->debug('calling serializeType w/indexed param');
$xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
} elseif (isset($parameters[$name])) {
$this->debug('calling serializeType w/named param');
$xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
} else {
// TODO: only send nillable
$this->debug('calling serializeType w/null param');
$xml .= $this->serializeType($name, $type, null, $use, $enc_style);
}
}
} else {
$this->debug('no parameters passed.');
}
}
$this->debug("serializeParameters returning: $xml");
return $xml;
}
/**
* serializes a PHP value according a given type definition
*
* @param string $name name of value (part or element)
* @param string $type XML schema type of value (type or element)
* @param mixed $value a native PHP value (parameter value)
* @param string $use use for part (encoded|literal)
* @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
* @param boolean $unqualified a kludge for what should be XML namespace form handling
* @return string value serialized as an XML string
* @access private
*/
function serializeType($name, $type, $value, $use='encoded', $encodingStyle=false, $unqualified=false)
{
$this->debug("in serializeType: name=$name, type=$type, use=$use, encodingStyle=$encodingStyle, unqualified=" . ($unqualified ? "unqualified" : "qualified"));
$this->appendDebug("value=" . $this->varDump($value));
if($use == 'encoded' && $encodingStyle) {
$encodingStyle = ' SOAP-ENV:encodingStyle="' . $encodingStyle . '"';
}
// if a soapval has been supplied, let its type override the WSDL
if (is_object($value) && get_class($value) == 'soapval') {
if ($value->type_ns) {
$type = $value->type_ns . ':' . $value->type;
$forceType = true;
$this->debug("in serializeType: soapval overrides type to $type");
} elseif ($value->type) {
$type = $value->type;
$forceType = true;
$this->debug("in serializeType: soapval overrides type to $type");
} else {
$forceType = false;
$this->debug("in serializeType: soapval does not override type");
}
$attrs = $value->attributes;
$value = $value->value;
$this->debug("in serializeType: soapval overrides value to $value");
if ($attrs) {
if (!is_array($value)) {
$value['!'] = $value;
}
foreach ($attrs as $n => $v) {
$value['!' . $n] = $v;
}
$this->debug("in serializeType: soapval provides attributes");
}
} else {
$forceType = false;
}
$xml = '';
if (strpos($type, ':')) {
$uqType = substr($type, strrpos($type, ':') + 1);
$ns = substr($type, 0, strrpos($type, ':'));
$this->debug("in serializeType: got a prefixed type: $uqType, $ns");
if ($this->getNamespaceFromPrefix($ns)) {
$ns = $this->getNamespaceFromPrefix($ns);
$this->debug("in serializeType: expanded prefixed type: $uqType, $ns");
}
if($ns == $this->XMLSchemaVersion || $ns == 'http://schemas.xmlsoap.org/soap/encoding/'){
$this->debug('in serializeType: type namespace indicates XML Schema or SOAP Encoding type');
if ($unqualified && $use == 'literal') {
$elementNS = " xmlns=\"\"";
} else {
$elementNS = '';
}
if (is_null($value)) {
if ($use == 'literal') {
// TODO: depends on minOccurs
$xml = "<$name$elementNS/>";
} else {
// TODO: depends on nillable, which should be checked before calling this method
$xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>";
}
$this->debug("in serializeType: returning: $xml");
return $xml;
}
if ($uqType == 'boolean') {
if ((is_string($value) && $value == 'false') || (! $value)) {
$value = 'false';
} else {
$value = 'true';
}
}
if ($uqType == 'string' && gettype($value) == 'string') {
$value = $this->expandEntities($value);
}
if (($uqType == 'long' || $uqType == 'unsignedLong') && gettype($value) == 'double') {
$value = sprintf("%.0lf", $value);
}
// it's a scalar
// TODO: what about null/nil values?
// check type isn't a custom type extending xmlschema namespace
if (!$this->getTypeDef($uqType, $ns)) {
if ($use == 'literal') {
if ($forceType) {
$xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value</$name>";
} else {
$xml = "<$name$elementNS>$value</$name>";
}
} else {
$xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value</$name>";
}
$this->debug("in serializeType: returning: $xml");
return $xml;
}
$this->debug('custom type extends XML Schema or SOAP Encoding namespace (yuck)');
} else if ($ns == 'http://xml.apache.org/xml-soap') {
$this->debug('in serializeType: appears to be Apache SOAP type');
if ($uqType == 'Map') {
$tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap');
if (! $tt_prefix) {
$this->debug('in serializeType: Add namespace for Apache SOAP type');
$tt_prefix = 'ns' . rand(1000, 9999);
$this->namespaces[$tt_prefix] = 'http://xml.apache.org/xml-soap';
// force this to be added to usedNamespaces
$tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap');
}
$contents = '';
foreach($value as $k => $v) {
$this->debug("serializing map element: key $k, value $v");
$contents .= '<item>';
$contents .= $this->serialize_val($k,'key',false,false,false,false,$use);
$contents .= $this->serialize_val($v,'value',false,false,false,false,$use);
$contents .= '</item>';
}
if ($use == 'literal') {
if ($forceType) {
$xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\">$contents</$name>";
} else {
$xml = "<$name>$contents</$name>";
}
} else {
$xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\"$encodingStyle>$contents</$name>";
}
$this->debug("in serializeType: returning: $xml");
return $xml;
}
$this->debug('in serializeType: Apache SOAP type, but only support Map');
}
} else {
// TODO: should the type be compared to types in XSD, and the namespace
// set to XSD if the type matches?
$this->debug("in serializeType: No namespace for type $type");
$ns = '';
$uqType = $type;
}
if(!$typeDef = $this->getTypeDef($uqType, $ns)){
$this->setError("$type ($uqType) is not a supported type.");
$this->debug("in serializeType: $type ($uqType) is not a supported type.");
return false;
} else {
$this->debug("in serializeType: found typeDef");
$this->appendDebug('typeDef=' . $this->varDump($typeDef));
}
$phpType = $typeDef['phpType'];
$this->debug("in serializeType: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: " . (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '') );
// if php type == struct, map value to the <all> element names
if ($phpType == 'struct') {
if (isset($typeDef['typeClass']) && $typeDef['typeClass'] == 'element') {
$elementName = $uqType;
if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
$elementNS = " xmlns=\"$ns\"";
} else {
$elementNS = " xmlns=\"\"";
}
} else {
$elementName = $name;
if ($unqualified) {
$elementNS = " xmlns=\"\"";
} else {
$elementNS = '';
}
}
if (is_null($value)) {
if ($use == 'literal') {
// TODO: depends on minOccurs
$xml = "<$elementName$elementNS/>";
} else {
$xml = "<$elementName$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>";
}
$this->debug("in serializeType: returning: $xml");
return $xml;
}
if (is_object($value)) {
$value = get_object_vars($value);
}
if (is_array($value)) {
$elementAttrs = $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType);
if ($use == 'literal') {
if ($forceType) {
$xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">";
} else {
$xml = "<$elementName$elementNS$elementAttrs>";
}
} else {
$xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>";
}
$xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle);
$xml .= "</$elementName>";
} else {
$this->debug("in serializeType: phpType is struct, but value is not an array");
$this->setError("phpType is struct, but value is not an array: see debug output for details");
$xml = '';
}
} elseif ($phpType == 'array') {
if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
$elementNS = " xmlns=\"$ns\"";
} else {
if ($unqualified) {
$elementNS = " xmlns=\"\"";
} else {
$elementNS = '';
}
}
if (is_null($value)) {
if ($use == 'literal') {
// TODO: depends on minOccurs
$xml = "<$name$elementNS/>";
} else {
$xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" .
$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .
":Array\" " .
$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .
':arrayType="' .
$this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) .
':' .
$this->getLocalPart($typeDef['arrayType'])."[0]\"/>";
}
$this->debug("in serializeType: returning: $xml");
return $xml;
}
if (isset($typeDef['multidimensional'])) {
$nv = array();
foreach($value as $v) {
$cols = ',' . sizeof($v);
$nv = array_merge($nv, $v);
}
$value = $nv;
} else {
$cols = '';
}
if (is_array($value) && sizeof($value) >= 1) {
$rows = sizeof($value);
$contents = '';
foreach($value as $k => $v) {
$this->debug("serializing array element: $k, $v of type: $typeDef[arrayType]");
//if (strpos($typeDef['arrayType'], ':') ) {
if (!in_array($typeDef['arrayType'],$this->typemap['http://www.w3.org/2001/XMLSchema'])) {
$contents .= $this->serializeType('item', $typeDef['arrayType'], $v, $use);
} else {
$contents .= $this->serialize_val($v, 'item', $typeDef['arrayType'], null, $this->XMLSchemaVersion, false, $use);
}
}
} else {
$rows = 0;
$contents = null;
}
// TODO: for now, an empty value will be serialized as a zero element
// array. Revisit this when coding the handling of null/nil values.
if ($use == 'literal') {
$xml = "<$name$elementNS>"
.$contents
."</$name>";
} else {
$xml = "<$name$elementNS xsi:type=\"".$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/').':Array" '.
$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/')
.':arrayType="'
.$this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType']))
.":".$this->getLocalPart($typeDef['arrayType'])."[$rows$cols]\">"
.$contents
."</$name>";
}
} elseif ($phpType == 'scalar') {
if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
$elementNS = " xmlns=\"$ns\"";
} else {
if ($unqualified) {
$elementNS = " xmlns=\"\"";
} else {
$elementNS = '';
}
}
if ($use == 'literal') {
if ($forceType) {
$xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value</$name>";
} else {
$xml = "<$name$elementNS>$value</$name>";
}
} else {
$xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value</$name>";
}
}
$this->debug("in serializeType: returning: $xml");
return $xml;
}
/**
* serializes the attributes for a complexType
*
* @param array $typeDef our internal representation of an XML schema type (or element)
* @param mixed $value a native PHP value (parameter value)
* @param string $ns the namespace of the type
* @param string $uqType the local part of the type
* @return string value serialized as an XML string
* @access private
*/
function serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType) {
$xml = '';
if (isset($typeDef['attrs']) && is_array($typeDef['attrs'])) {
$this->debug("serialize attributes for XML Schema type $ns:$uqType");
if (is_array($value)) {
$xvalue = $value;
} elseif (is_object($value)) {
$xvalue = get_object_vars($value);
} else {
$this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
$xvalue = array();
}
foreach ($typeDef['attrs'] as $aName => $attrs) {
if (isset($xvalue['!' . $aName])) {
$xname = '!' . $aName;
$this->debug("value provided for attribute $aName with key $xname");
} elseif (isset($xvalue[$aName])) {
$xname = $aName;
$this->debug("value provided for attribute $aName with key $xname");
} elseif (isset($attrs['default'])) {
$xname = '!' . $aName;
$xvalue[$xname] = $attrs['default'];
$this->debug('use default value of ' . $xvalue[$aName] . ' for attribute ' . $aName);
} else {
$xname = '';
$this->debug("no value provided for attribute $aName");
}
if ($xname) {
$xml .= " $aName=\"" . $this->expandEntities($xvalue[$xname]) . "\"";
}
}
} else {
$this->debug("no attributes to serialize for XML Schema type $ns:$uqType");
}
if (isset($typeDef['extensionBase'])) {
$ns = $this->getPrefix($typeDef['extensionBase']);
$uqType = $this->getLocalPart($typeDef['extensionBase']);
if ($this->getNamespaceFromPrefix($ns)) {
$ns = $this->getNamespaceFromPrefix($ns);
}
if ($typeDef = $this->getTypeDef($uqType, $ns)) {
$this->debug("serialize attributes for extension base $ns:$uqType");
$xml .= $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType);
} else {
$this->debug("extension base $ns:$uqType is not a supported type");
}
}
return $xml;
}
/**
* serializes the elements for a complexType
*
* @param array $typeDef our internal representation of an XML schema type (or element)
* @param mixed $value a native PHP value (parameter value)
* @param string $ns the namespace of the type
* @param string $uqType the local part of the type
* @param string $use use for part (encoded|literal)
* @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
* @return string value serialized as an XML string
* @access private
*/
function serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use='encoded', $encodingStyle=false) {
$xml = '';
if (isset($typeDef['elements']) && is_array($typeDef['elements'])) {
$this->debug("in serializeComplexTypeElements, serialize elements for XML Schema type $ns:$uqType");
if (is_array($value)) {
$xvalue = $value;
} elseif (is_object($value)) {
$xvalue = get_object_vars($value);
} else {
$this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
$xvalue = array();
}
// toggle whether all elements are present - ideally should validate against schema
if (count($typeDef['elements']) != count($xvalue)){
$optionals = true;
}
foreach ($typeDef['elements'] as $eName => $attrs) {
if (!isset($xvalue[$eName])) {
if (isset($attrs['default'])) {
$xvalue[$eName] = $attrs['default'];
$this->debug('use default value of ' . $xvalue[$eName] . ' for element ' . $eName);
}
}
// if user took advantage of a minOccurs=0, then only serialize named parameters
if (isset($optionals)
&& (!isset($xvalue[$eName]))
&& ( (!isset($attrs['nillable'])) || $attrs['nillable'] != 'true')
){
if (isset($attrs['minOccurs']) && $attrs['minOccurs'] <> '0') {
$this->debug("apparent error: no value provided for element $eName with minOccurs=" . $attrs['minOccurs']);
}
// do nothing
$this->debug("no value provided for complexType element $eName and element is not nillable, so serialize nothing");
} else {
// get value
if (isset($xvalue[$eName])) {
$v = $xvalue[$eName];
} else {
$v = null;
}
if (isset($attrs['form'])) {
$unqualified = ($attrs['form'] == 'unqualified');
} else {
$unqualified = false;
}
if (isset($attrs['maxOccurs']) && ($attrs['maxOccurs'] == 'unbounded' || $attrs['maxOccurs'] > 1) && isset($v) && is_array($v) && $this->isArraySimpleOrStruct($v) == 'arraySimple') {
$vv = $v;
foreach ($vv as $k => $v) {
if (isset($attrs['type']) || isset($attrs['ref'])) {
// serialize schema-defined type
$xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
} else {
// serialize generic type (can this ever really happen?)
$this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
$xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
}
}
} else {
if (isset($attrs['type']) || isset($attrs['ref'])) {
// serialize schema-defined type
$xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
} else {
// serialize generic type (can this ever really happen?)
$this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
$xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
}
}
}
}
} else {
$this->debug("no elements to serialize for XML Schema type $ns:$uqType");
}
if (isset($typeDef['extensionBase'])) {
$ns = $this->getPrefix($typeDef['extensionBase']);
$uqType = $this->getLocalPart($typeDef['extensionBase']);
if ($this->getNamespaceFromPrefix($ns)) {
$ns = $this->getNamespaceFromPrefix($ns);
}
if ($typeDef = $this->getTypeDef($uqType, $ns)) {
$this->debug("serialize elements for extension base $ns:$uqType");
$xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle);
} else {
$this->debug("extension base $ns:$uqType is not a supported type");
}
}
return $xml;
}
/**
* adds an XML Schema complex type to the WSDL types
*
* @param string name
* @param string typeClass (complexType|simpleType|attribute)
* @param string phpType: currently supported are array and struct (php assoc array)
* @param string compositor (all|sequence|choice)
* @param string restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
* @param array elements = array ( name => array(name=>'',type=>'') )
* @param array attrs = array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'xsd:string[]'))
* @param string arrayType: namespace:name (xsd:string)
* @see xmlschema
* @access public
*/
function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType='') {
if (count($elements) > 0) {
foreach($elements as $n => $e){
// expand each element
foreach ($e as $k => $v) {
$k = strpos($k,':') ? $this->expandQname($k) : $k;
$v = strpos($v,':') ? $this->expandQname($v) : $v;
$ee[$k] = $v;
}
$eElements[$n] = $ee;
}
$elements = $eElements;
}
if (count($attrs) > 0) {
foreach($attrs as $n => $a){
// expand each attribute
foreach ($a as $k => $v) {
$k = strpos($k,':') ? $this->expandQname($k) : $k;
$v = strpos($v,':') ? $this->expandQname($v) : $v;
$aa[$k] = $v;
}
$eAttrs[$n] = $aa;
}
$attrs = $eAttrs;
}
$restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
$arrayType = strpos($arrayType,':') ? $this->expandQname($arrayType) : $arrayType;
$typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
$this->schemas[$typens][0]->addComplexType($name,$typeClass,$phpType,$compositor,$restrictionBase,$elements,$attrs,$arrayType);
}
/**
* adds an XML Schema simple type to the WSDL types
*
* @param string $name
* @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
* @param string $typeClass (should always be simpleType)
* @param string $phpType (should always be scalar)
* @param array $enumeration array of values
* @see xmlschema
* @access public
*/
function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
$restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
$typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
$this->schemas[$typens][0]->addSimpleType($name, $restrictionBase, $typeClass, $phpType, $enumeration);
}
/**
* adds an element to the WSDL types
*
* @param array $attrs attributes that must include name and type
* @see xmlschema
* @access public
*/
function addElement($attrs) {
$typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
$this->schemas[$typens][0]->addElement($attrs);
}
/**
* register an operation with the server
*
* @param string $name operation (method) name
* @param array $in assoc array of input values: key = param name, value = param type
* @param array $out assoc array of output values: key = param name, value = param type
* @param string $namespace optional The namespace for the operation
* @param string $soapaction optional The soapaction for the operation
* @param string $style (rpc|document) optional The style for the operation Note: when 'document' is specified, parameter and return wrappers are created for you automatically
* @param string $use (encoded|literal) optional The use for the parameters (cannot mix right now)
* @param string $documentation optional The description to include in the WSDL
* @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
* @access public
*/
function addOperation($name, $in = false, $out = false, $namespace = false, $soapaction = false, $style = 'rpc', $use = 'encoded', $documentation = '', $encodingStyle = ''){
if ($use == 'encoded' && $encodingStyle == '') {
$encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
}
if ($style == 'document') {
$elements = array();
foreach ($in as $n => $t) {
$elements[$n] = array('name' => $n, 'type' => $t);
}
$this->addComplexType($name . 'RequestType', 'complexType', 'struct', 'all', '', $elements);
$this->addElement(array('name' => $name, 'type' => $name . 'RequestType'));
$in = array('parameters' => 'tns:' . $name);
$elements = array();
foreach ($out as $n => $t) {
$elements[$n] = array('name' => $n, 'type' => $t);
}
$this->addComplexType($name . 'ResponseType', 'complexType', 'struct', 'all', '', $elements);
$this->addElement(array('name' => $name . 'Response', 'type' => $name . 'ResponseType'));
$out = array('parameters' => 'tns:' . $name . 'Response');
}
// get binding
$this->bindings[ $this->serviceName . 'Binding' ]['operations'][$name] =
array(
'name' => $name,
'binding' => $this->serviceName . 'Binding',
'endpoint' => $this->endpoint,
'soapAction' => $soapaction,
'style' => $style,
'input' => array(
'use' => $use,
'namespace' => $namespace,
'encodingStyle' => $encodingStyle,
'message' => $name . 'Request',
'parts' => $in),
'output' => array(
'use' => $use,
'namespace' => $namespace,
'encodingStyle' => $encodingStyle,
'message' => $name . 'Response',
'parts' => $out),
'namespace' => $namespace,
'transport' => 'http://schemas.xmlsoap.org/soap/http',
'documentation' => $documentation);
// add portTypes
// add messages
if($in)
{
foreach($in as $pName => $pType)
{
if(strpos($pType,':')) {
$pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
}
$this->messages[$name.'Request'][$pName] = $pType;
}
} else {
$this->messages[$name.'Request']= '0';
}
if($out)
{
foreach($out as $pName => $pType)
{
if(strpos($pType,':')) {
$pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
}
$this->messages[$name.'Response'][$pName] = $pType;
}
} else {
$this->messages[$name.'Response']= '0';
}
return true;
}
}
?><?php
/**
*
* soap_parser class parses SOAP XML messages into native PHP values
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $
* @access public
*/
class soap_parser extends nusoap_base {
var $xml = '';
var $xml_encoding = '';
var $method = '';
var $root_struct = '';
var $root_struct_name = '';
var $root_struct_namespace = '';
var $root_header = '';
var $document = ''; // incoming SOAP body (text)
// determines where in the message we are (envelope,header,body,method)
var $status = '';
var $position = 0;
var $depth = 0;
var $default_namespace = '';
var $namespaces = array();
var $message = array();
var $parent = '';
var $fault = false;
var $fault_code = '';
var $fault_str = '';
var $fault_detail = '';
var $depth_array = array();
var $debug_flag = true;
var $soapresponse = NULL;
var $responseHeaders = ''; // incoming SOAP headers (text)
var $body_position = 0;
// for multiref parsing:
// array of id => pos
var $ids = array();
// array of id => hrefs => pos
var $multirefs = array();
// toggle for auto-decoding element content
var $decode_utf8 = true;
/**
* constructor that actually does the parsing
*
* @param string $xml SOAP message
* @param string $encoding character encoding scheme of message
* @param string $method method for which XML is parsed (unused?)
* @param string $decode_utf8 whether to decode UTF-8 to ISO-8859-1
* @access public
*/
function soap_parser($xml,$encoding='UTF-8',$method='',$decode_utf8=true){
parent::nusoap_base();
$this->xml = $xml;
$this->xml_encoding = $encoding;
$this->method = $method;
$this->decode_utf8 = $decode_utf8;
// Check whether content has been read.
if(!empty($xml)){
// Check XML encoding
$pos_xml = strpos($xml, '<?xml');
if ($pos_xml !== FALSE) {
$xml_decl = substr($xml, $pos_xml, strpos($xml, '?>', $pos_xml + 2) - $pos_xml + 1);
if (preg_match("/encoding=[\"']([^\"']*)[\"']/", $xml_decl, $res)) {
$xml_encoding = $res[1];
if (strtoupper($xml_encoding) != $encoding) {
$err = "Charset from HTTP Content-Type '" . $encoding . "' does not match encoding from XML declaration '" . $xml_encoding . "'";
$this->debug($err);
if ($encoding != 'ISO-8859-1' || strtoupper($xml_encoding) != 'UTF-8') {
$this->setError($err);
return;
}
// when HTTP says ISO-8859-1 (the default) and XML says UTF-8 (the typical), assume the other endpoint is just sloppy and proceed
} else {
$this->debug('Charset from HTTP Content-Type matches encoding from XML declaration');
}
} else {
$this->debug('No encoding specified in XML declaration');
}
} else {
$this->debug('No XML declaration');
}
$this->debug('Entering soap_parser(), length='.strlen($xml).', encoding='.$encoding);
// Create an XML parser - why not xml_parser_create_ns?
$this->parser = xml_parser_create($this->xml_encoding);
// Set the options for parsing the XML data.
//xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->xml_encoding);
// Set the object for the parser.
xml_set_object($this->parser, $this);
// Set the element handlers for the parser.
xml_set_element_handler($this->parser, 'start_element','end_element');
xml_set_character_data_handler($this->parser,'character_data');
// Parse the XML file.
if(!xml_parse($this->parser,$xml,true)){
// Display an error message.
$err = sprintf('XML error parsing SOAP payload on line %d: %s',
xml_get_current_line_number($this->parser),
xml_error_string(xml_get_error_code($this->parser)));
$this->debug($err);
$this->debug("XML payload:\n" . $xml);
$this->setError($err);
} else {
$this->debug('parsed successfully, found root struct: '.$this->root_struct.' of name '.$this->root_struct_name);
// get final value
$this->soapresponse = $this->message[$this->root_struct]['result'];
// get header value: no, because this is documented as XML string
// if($this->root_header != '' && isset($this->message[$this->root_header]['result'])){
// $this->responseHeaders = $this->message[$this->root_header]['result'];
// }
// resolve hrefs/ids
if(sizeof($this->multirefs) > 0){
foreach($this->multirefs as $id => $hrefs){
$this->debug('resolving multirefs for id: '.$id);
$idVal = $this->buildVal($this->ids[$id]);
if (is_array($idVal) && isset($idVal['!id'])) {
unset($idVal['!id']);
}
foreach($hrefs as $refPos => $ref){
$this->debug('resolving href at pos '.$refPos);
$this->multirefs[$id][$refPos] = $idVal;
}
}
}
}
xml_parser_free($this->parser);
} else {
$this->debug('xml was empty, didn\'t parse!');
$this->setError('xml was empty, didn\'t parse!');
}
}
/**
* start-element handler
*
* @param resource $parser XML parser object
* @param string $name element name
* @param array $attrs associative array of attributes
* @access private
*/
function start_element($parser, $name, $attrs) {
// position in a total number of elements, starting from 0
// update class level pos
$pos = $this->position++;
// and set mine
$this->message[$pos] = array('pos' => $pos,'children'=>'','cdata'=>'');
// depth = how many levels removed from root?
// set mine as current global depth and increment global depth value
$this->message[$pos]['depth'] = $this->depth++;
// else add self as child to whoever the current parent is
if($pos != 0){
$this->message[$this->parent]['children'] .= '|'.$pos;
}
// set my parent
$this->message[$pos]['parent'] = $this->parent;
// set self as current parent
$this->parent = $pos;
// set self as current value for this depth
$this->depth_array[$this->depth] = $pos;
// get element prefix
if(strpos($name,':')){
// get ns prefix
$prefix = substr($name,0,strpos($name,':'));
// get unqualified name
$name = substr(strstr($name,':'),1);
}
// set status
if($name == 'Envelope'){
$this->status = 'envelope';
} elseif($name == 'Header'){
$this->root_header = $pos;
$this->status = 'header';
} elseif($name == 'Body'){
$this->status = 'body';
$this->body_position = $pos;
// set method
} elseif($this->status == 'body' && $pos == ($this->body_position+1)){
$this->status = 'method';
$this->root_struct_name = $name;
$this->root_struct = $pos;
$this->message[$pos]['type'] = 'struct';
$this->debug("found root struct $this->root_struct_name, pos $this->root_struct");
}
// set my status
$this->message[$pos]['status'] = $this->status;
// set name
$this->message[$pos]['name'] = htmlspecialchars($name);
// set attrs
$this->message[$pos]['attrs'] = $attrs;
// loop through atts, logging ns and type declarations
$attstr = '';
foreach($attrs as $key => $value){
$key_prefix = $this->getPrefix($key);
$key_localpart = $this->getLocalPart($key);
// if ns declarations, add to class level array of valid namespaces
if($key_prefix == 'xmlns'){
if(ereg('^http://www.w3.org/[0-9]{4}/XMLSchema$',$value)){
$this->XMLSchemaVersion = $value;
$this->namespaces['xsd'] = $this->XMLSchemaVersion;
$this->namespaces['xsi'] = $this->XMLSchemaVersion.'-instance';
}
$this->namespaces[$key_localpart] = $value;
// set method namespace
if($name == $this->root_struct_name){
$this->methodNamespace = $value;
}
// if it's a type declaration, set type
} elseif($key_localpart == 'type'){
$value_prefix = $this->getPrefix($value);
$value_localpart = $this->getLocalPart($value);
$this->message[$pos]['type'] = $value_localpart;
$this->message[$pos]['typePrefix'] = $value_prefix;
if(isset($this->namespaces[$value_prefix])){
$this->message[$pos]['type_namespace'] = $this->namespaces[$value_prefix];
} else if(isset($attrs['xmlns:'.$value_prefix])) {
$this->message[$pos]['type_namespace'] = $attrs['xmlns:'.$value_prefix];
}
// should do something here with the namespace of specified type?
} elseif($key_localpart == 'arrayType'){
$this->message[$pos]['type'] = 'array';
/* do arrayType ereg here
[1] arrayTypeValue ::= atype asize
[2] atype ::= QName rank*
[3] rank ::= '[' (',')* ']'
[4] asize ::= '[' length~ ']'
[5] length ::= nextDimension* Digit+
[6] nextDimension ::= Digit+ ','
*/
$expr = '([A-Za-z0-9_]+):([A-Za-z]+[A-Za-z0-9_]+)\[([0-9]+),?([0-9]*)\]';
if(ereg($expr,$value,$regs)){
$this->message[$pos]['typePrefix'] = $regs[1];
$this->message[$pos]['arrayTypePrefix'] = $regs[1];
if (isset($this->namespaces[$regs[1]])) {
$this->message[$pos]['arrayTypeNamespace'] = $this->namespaces[$regs[1]];
} else if (isset($attrs['xmlns:'.$regs[1]])) {
$this->message[$pos]['arrayTypeNamespace'] = $attrs['xmlns:'.$regs[1]];
}
$this->message[$pos]['arrayType'] = $regs[2];
$this->message[$pos]['arraySize'] = $regs[3];
$this->message[$pos]['arrayCols'] = $regs[4];
}
// specifies nil value (or not)
} elseif ($key_localpart == 'nil'){
$this->message[$pos]['nil'] = ($value == 'true' || $value == '1');
// some other attribute
} elseif ($key != 'href' && $key != 'xmlns' && $key_localpart != 'encodingStyle' && $key_localpart != 'root') {
$this->message[$pos]['xattrs']['!' . $key] = $value;
}
if ($key == 'xmlns') {
$this->default_namespace = $value;
}
// log id
if($key == 'id'){
$this->ids[$value] = $pos;
}
// root
if($key_localpart == 'root' && $value == 1){
$this->status = 'method';
$this->root_struct_name = $name;
$this->root_struct = $pos;
$this->debug("found root struct $this->root_struct_name, pos $pos");
}
// for doclit
$attstr .= " $key=\"$value\"";
}
// get namespace - must be done after namespace atts are processed
if(isset($prefix)){
$this->message[$pos]['namespace'] = $this->namespaces[$prefix];
$this->default_namespace = $this->namespaces[$prefix];
} else {
$this->message[$pos]['namespace'] = $this->default_namespace;
}
if($this->status == 'header'){
if ($this->root_header != $pos) {
$this->responseHeaders .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>";
}
} elseif($this->root_struct_name != ''){
$this->document .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>";
}
}
/**
* end-element handler
*
* @param resource $parser XML parser object
* @param string $name element name
* @access private
*/
function end_element($parser, $name) {
// position of current element is equal to the last value left in depth_array for my depth
$pos = $this->depth_array[$this->depth--];
// get element prefix
if(strpos($name,':')){
// get ns prefix
$prefix = substr($name,0,strpos($name,':'));
// get unqualified name
$name = substr(strstr($name,':'),1);
}
// build to native type
if(isset($this->body_position) && $pos > $this->body_position){
// deal w/ multirefs
if(isset($this->message[$pos]['attrs']['href'])){
// get id
$id = substr($this->message[$pos]['attrs']['href'],1);
// add placeholder to href array
$this->multirefs[$id][$pos] = 'placeholder';
// add set a reference to it as the result value
$this->message[$pos]['result'] =& $this->multirefs[$id][$pos];
// build complexType values
} elseif($this->message[$pos]['children'] != ''){
// if result has already been generated (struct/array)
if(!isset($this->message[$pos]['result'])){
$this->message[$pos]['result'] = $this->buildVal($pos);
}
// build complexType values of attributes and possibly simpleContent
} elseif (isset($this->message[$pos]['xattrs'])) {
if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) {
$this->message[$pos]['xattrs']['!'] = null;
} elseif (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') {
if (isset($this->message[$pos]['type'])) {
$this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
} else {
$parent = $this->message[$pos]['parent'];
if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
$this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
} else {
$this->message[$pos]['xattrs']['!'] = $this->message[$pos]['cdata'];
}
}
}
$this->message[$pos]['result'] = $this->message[$pos]['xattrs'];
// set value of simpleType (or nil complexType)
} else {
//$this->debug('adding data for scalar value '.$this->message[$pos]['name'].' of value '.$this->message[$pos]['cdata']);
if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) {
$this->message[$pos]['xattrs']['!'] = null;
} elseif (isset($this->message[$pos]['type'])) {
$this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
} else {
$parent = $this->message[$pos]['parent'];
if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
$this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
} else {
$this->message[$pos]['result'] = $this->message[$pos]['cdata'];
}
}
/* add value to parent's result, if parent is struct/array
$parent = $this->message[$pos]['parent'];
if($this->message[$parent]['type'] != 'map'){
if(strtolower($this->message[$parent]['type']) == 'array'){
$this->message[$parent]['result'][] = $this->message[$pos]['result'];
} else {
$this->message[$parent]['result'][$this->message[$pos]['name']] = $this->message[$pos]['result'];
}
}
*/
}
}
// for doclit
if($this->status == 'header'){
if ($this->root_header != $pos) {
$this->responseHeaders .= "</" . (isset($prefix) ? $prefix . ':' : '') . "$name>";
}
} elseif($pos >= $this->root_struct){
$this->document .= "</" . (isset($prefix) ? $prefix . ':' : '') . "$name>";
}
// switch status
if($pos == $this->root_struct){
$this->status = 'body';
$this->root_struct_namespace = $this->message[$pos]['namespace'];
} elseif($name == 'Body'){
$this->status = 'envelope';
} elseif($name == 'Header'){
$this->status = 'envelope';
} elseif($name == 'Envelope'){
//
}
// set parent back to my parent
$this->parent = $this->message[$pos]['parent'];
}
/**
* element content handler
*
* @param resource $parser XML parser object
* @param string $data element content
* @access private
*/
function character_data($parser, $data){
$pos = $this->depth_array[$this->depth];
if ($this->xml_encoding=='UTF-8'){
// TODO: add an option to disable this for folks who want
// raw UTF-8 that, e.g., might not map to iso-8859-1
// TODO: this can also be handled with xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "ISO-8859-1");
if($this->decode_utf8){
$data = utf8_decode($data);
}
}
$this->message[$pos]['cdata'] .= $data;
// for doclit
if($this->status == 'header'){
$this->responseHeaders .= $data;
} else {
$this->document .= $data;
}
}
/**
* get the parsed message
*
* @return mixed
* @access public
*/
function get_response(){
return $this->soapresponse;
}
/**
* get the parsed headers
*
* @return string XML or empty if no headers
* @access public
*/
function getHeaders(){
return $this->responseHeaders;
}
/**
* decodes simple types into PHP variables
*
* @param string $value value to decode
* @param string $type XML type to decode
* @param string $typens XML type namespace to decode
* @return mixed PHP value
* @access private
*/
function decodeSimple($value, $type, $typens) {
// TODO: use the namespace!
if ((!isset($type)) || $type == 'string' || $type == 'long' || $type == 'unsignedLong') {
return (string) $value;
}
if ($type == 'int' || $type == 'integer' || $type == 'short' || $type == 'byte') {
return (int) $value;
}
if ($type == 'float' || $type == 'double' || $type == 'decimal') {
return (double) $value;
}
if ($type == 'boolean') {
if (strtolower($value) == 'false' || strtolower($value) == 'f') {
return false;
}
return (boolean) $value;
}
if ($type == 'base64' || $type == 'base64Binary') {
$this->debug('Decode base64 value');
return base64_decode($value);
}
// obscure numeric types
if ($type == 'nonPositiveInteger' || $type == 'negativeInteger'
|| $type == 'nonNegativeInteger' || $type == 'positiveInteger'
|| $type == 'unsignedInt'
|| $type == 'unsignedShort' || $type == 'unsignedByte') {
return (int) $value;
}
// bogus: parser treats array with no elements as a simple type
if ($type == 'array') {
return array();
}
// everything else
return (string) $value;
}
/**
* builds response structures for compound values (arrays/structs)
* and scalars
*
* @param integer $pos position in node tree
* @return mixed PHP value
* @access private
*/
function buildVal($pos){
if(!isset($this->message[$pos]['type'])){
$this->message[$pos]['type'] = '';
}
$this->debug('in buildVal() for '.$this->message[$pos]['name']."(pos $pos) of type ".$this->message[$pos]['type']);
// if there are children...
if($this->message[$pos]['children'] != ''){
$this->debug('in buildVal, there are children');
$children = explode('|',$this->message[$pos]['children']);
array_shift($children); // knock off empty
// md array
if(isset($this->message[$pos]['arrayCols']) && $this->message[$pos]['arrayCols'] != ''){
$r=0; // rowcount
$c=0; // colcount
foreach($children as $child_pos){
$this->debug("in buildVal, got an MD array element: $r, $c");
$params[$r][] = $this->message[$child_pos]['result'];
$c++;
if($c == $this->message[$pos]['arrayCols']){
$c = 0;
$r++;
}
}
// array
} elseif($this->message[$pos]['type'] == 'array' || $this->message[$pos]['type'] == 'Array'){
$this->debug('in buildVal, adding array '.$this->message[$pos]['name']);
foreach($children as $child_pos){
$params[] = &$this->message[$child_pos]['result'];
}
// apache Map type: java hashtable
} elseif($this->message[$pos]['type'] == 'Map' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap'){
$this->debug('in buildVal, Java Map '.$this->message[$pos]['name']);
foreach($children as $child_pos){
$kv = explode("|",$this->message[$child_pos]['children']);
$params[$this->message[$kv[1]]['result']] = &$this->message[$kv[2]]['result'];
}
// generic compound type
//} elseif($this->message[$pos]['type'] == 'SOAPStruct' || $this->message[$pos]['type'] == 'struct') {
} else {
// Apache Vector type: treat as an array
$this->debug('in buildVal, adding Java Vector '.$this->message[$pos]['name']);
if ($this->message[$pos]['type'] == 'Vector' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap') {
$notstruct = 1;
} else {
$notstruct = 0;
}
//
foreach($children as $child_pos){
if($notstruct){
$params[] = &$this->message[$child_pos]['result'];
} else {
if (isset($params[$this->message[$child_pos]['name']])) {
// de-serialize repeated element name into an array
if ((!is_array($params[$this->message[$child_pos]['name']])) || (!isset($params[$this->message[$child_pos]['name']][0]))) {
$params[$this->message[$child_pos]['name']] = array($params[$this->message[$child_pos]['name']]);
}
$params[$this->message[$child_pos]['name']][] = &$this->message[$child_pos]['result'];
} else {
$params[$this->message[$child_pos]['name']] = &$this->message[$child_pos]['result'];
}
}
}
}
if (isset($this->message[$pos]['xattrs'])) {
$this->debug('in buildVal, handling attributes');
foreach ($this->message[$pos]['xattrs'] as $n => $v) {
$params[$n] = $v;
}
}
// handle simpleContent
if (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') {
$this->debug('in buildVal, handling simpleContent');
if (isset($this->message[$pos]['type'])) {
$params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
} else {
$parent = $this->message[$pos]['parent'];
if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
$params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
} else {
$params['!'] = $this->message[$pos]['cdata'];
}
}
}
return is_array($params) ? $params : array();
} else {
$this->debug('in buildVal, no children, building scalar');
$cdata = isset($this->message[$pos]['cdata']) ? $this->message[$pos]['cdata'] : '';
if (isset($this->message[$pos]['type'])) {
return $this->decodeSimple($cdata, $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
}
$parent = $this->message[$pos]['parent'];
if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
return $this->decodeSimple($cdata, $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
}
return $this->message[$pos]['cdata'];
}
}
}
?><?php
/**
*
* soapclient higher level class for easy usage.
*
* usage:
*
* // instantiate client with server info
* $soapclient = new soapclient( string path [ ,boolean wsdl] );
*
* // call method, get results
* echo $soapclient->call( string methodname [ ,array parameters] );
*
* // bye bye client
* unset($soapclient);
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $
* @access public
*/
class soapclientw extends nusoap_base {
var $username = '';
var $password = '';
var $authtype = '';
var $certRequest = array();
var $requestHeaders = false; // SOAP headers in request (text)
var $responseHeaders = ''; // SOAP headers from response (incomplete namespace resolution) (text)
var $document = ''; // SOAP body response portion (incomplete namespace resolution) (text)
var $endpoint;
var $forceEndpoint = ''; // overrides WSDL endpoint
var $proxyhost = '';
var $proxyport = '';
var $proxyusername = '';
var $proxypassword = '';
var $xml_encoding = ''; // character set encoding of incoming (response) messages
var $http_encoding = false;
var $timeout = 0; // HTTP connection timeout
var $response_timeout = 30; // HTTP response timeout
var $endpointType = ''; // soap|wsdl, empty for WSDL initialization error
var $persistentConnection = false;
var $defaultRpcParams = false; // This is no longer used
var $request = ''; // HTTP request
var $response = ''; // HTTP response
var $responseData = ''; // SOAP payload of response
var $cookies = array(); // Cookies from response or for request
var $decode_utf8 = true; // toggles whether the parser decodes element content w/ utf8_decode()
var $operations = array(); // WSDL operations, empty for WSDL initialization error
/*
* fault related variables
*/
/**
* @var fault
* @access public
*/
var $fault;
/**
* @var faultcode
* @access public
*/
var $faultcode;
/**
* @var faultstring
* @access public
*/
var $faultstring;
/**
* @var faultdetail
* @access public
*/
var $faultdetail;
/**
* constructor
*
* @param mixed $endpoint SOAP server or WSDL URL (string), or wsdl instance (object)
* @param bool $wsdl optional, set to true if using WSDL
* @param int $portName optional portName in WSDL document
* @param string $proxyhost
* @param string $proxyport
* @param string $proxyusername
* @param string $proxypassword
* @param integer $timeout set the connection timeout
* @param integer $response_timeout set the response timeout
* @access public
*/
function soapclientw($endpoint,$wsdl = false,$proxyhost = false,$proxyport = false,$proxyusername = false, $proxypassword = false, $timeout = 0, $response_timeout = 30){
parent::nusoap_base();
$this->endpoint = $endpoint;
$this->proxyhost = $proxyhost;
$this->proxyport = $proxyport;
$this->proxyusername = $proxyusername;
$this->proxypassword = $proxypassword;
$this->timeout = $timeout;
$this->response_timeout = $response_timeout;
// make values
if($wsdl){
if (is_object($endpoint) && (get_class($endpoint) == 'wsdl')) {
$this->wsdl = $endpoint;
$this->endpoint = $this->wsdl->wsdl;
$this->wsdlFile = $this->endpoint;
$this->debug('existing wsdl instance created from ' . $this->endpoint);
} else {
$this->wsdlFile = $this->endpoint;
// instantiate wsdl object and parse wsdl file
$this->debug('instantiating wsdl class with doc: '.$endpoint);
$this->wsdl =& new wsdl($this->wsdlFile,$this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword,$this->timeout,$this->response_timeout);
}
$this->appendDebug($this->wsdl->getDebug());
$this->wsdl->clearDebug();
// catch errors
if($errstr = $this->wsdl->getError()){
$this->debug('got wsdl error: '.$errstr);
$this->setError('wsdl error: '.$errstr);
} elseif($this->operations = $this->wsdl->getOperations()){
$this->debug( 'got '.count($this->operations).' operations from wsdl '.$this->wsdlFile);
$this->endpointType = 'wsdl';
} else {
$this->debug( 'getOperations returned false');
$this->setError('no operations defined in the WSDL document!');
}
} else {
$this->debug("instantiate SOAP with endpoint at $endpoint");
$this->endpointType = 'soap';
}
}
/**
* calls method, returns PHP native type
*
* @param string $method SOAP server URL or path
* @param mixed $params An array, associative or simple, of the parameters
* for the method call, or a string that is the XML
* for the call. For rpc style, this call will
* wrap the XML in a tag named after the method, as
* well as the SOAP Envelope and Body. For document
* style, this will only wrap with the Envelope and Body.
* IMPORTANT: when using an array with document style,
* in which case there
* is really one parameter, the root of the fragment
* used in the call, which encloses what programmers
* normally think of parameters. A parameter array
* *must* include the wrapper.
* @param string $namespace optional method namespace (WSDL can override)
* @param string $soapAction optional SOAPAction value (WSDL can override)
* @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers
* @param boolean $rpcParams optional (no longer used)
* @param string $style optional (rpc|document) the style to use when serializing parameters (WSDL can override)
* @param string $use optional (encoded|literal) the use when serializing parameters (WSDL can override)
* @return mixed response from SOAP call
* @access public
*/
function call($operation,$params=array(),$namespace='http://tempuri.org',$soapAction='',$headers=false,$rpcParams=null,$style='rpc',$use='encoded'){
$this->operation = $operation;
$this->fault = false;
$this->setError('');
$this->request = '';
$this->response = '';
$this->responseData = '';
$this->faultstring = '';
$this->faultcode = '';
$this->opData = array();
$this->debug("call: operation=$operation, namespace=$namespace, soapAction=$soapAction, rpcParams=$rpcParams, style=$style, use=$use, endpointType=$this->endpointType");
$this->appendDebug('params=' . $this->varDump($params));
$this->appendDebug('headers=' . $this->varDump($headers));
if ($headers) {
$this->requestHeaders = $headers;
}
// serialize parameters
if($this->endpointType == 'wsdl' && $opData = $this->getOperationData($operation)){
// use WSDL for operation
$this->opData = $opData;
$this->debug("found operation");
$this->appendDebug('opData=' . $this->varDump($opData));
if (isset($opData['soapAction'])) {
$soapAction = $opData['soapAction'];
}
if (! $this->forceEndpoint) {
$this->endpoint = $opData['endpoint'];
} else {
$this->endpoint = $this->forceEndpoint;
}
$namespace = isset($opData['input']['namespace']) ? $opData['input']['namespace'] : $namespace;
$style = $opData['style'];
$use = $opData['input']['use'];
// add ns to ns array
if($namespace != '' && !isset($this->wsdl->namespaces[$namespace])){
$nsPrefix = 'ns' . rand(1000, 9999);
$this->wsdl->namespaces[$nsPrefix] = $namespace;
}
$nsPrefix = $this->wsdl->getPrefixFromNamespace($namespace);
// serialize payload
if (is_string($params)) {
$this->debug("serializing param string for WSDL operation $operation");
$payload = $params;
} elseif (is_array($params)) {
$this->debug("serializing param array for WSDL operation $operation");
$payload = $this->wsdl->serializeRPCParameters($operation,'input',$params);
} else {
$this->debug('params must be array or string');
$this->setError('params must be array or string');
return false;
}
$usedNamespaces = $this->wsdl->usedNamespaces;
if (isset($opData['input']['encodingStyle'])) {
$encodingStyle = $opData['input']['encodingStyle'];
} else {
$encodingStyle = '';
}
$this->appendDebug($this->wsdl->getDebug());
$this->wsdl->clearDebug();
if ($errstr = $this->wsdl->getError()) {
$this->debug('got wsdl error: '.$errstr);
$this->setError('wsdl error: '.$errstr);
return false;
}
} elseif($this->endpointType == 'wsdl') {
// operation not in WSDL
$this->appendDebug($this->wsdl->getDebug());
$this->wsdl->clearDebug();
$this->setError( 'operation '.$operation.' not present.');
$this->debug("operation '$operation' not present.");
return false;
} else {
// no WSDL
//$this->namespaces['ns1'] = $namespace;
$nsPrefix = 'ns' . rand(1000, 9999);
// serialize
$payload = '';
if (is_string($params)) {
$this->debug("serializing param string for operation $operation");
$payload = $params;
} elseif (is_array($params)) {
$this->debug("serializing param array for operation $operation");
foreach($params as $k => $v){
$payload .= $this->serialize_val($v,$k,false,false,false,false,$use);
}
} else {
$this->debug('params must be array or string');
$this->setError('params must be array or string');
return false;
}
$usedNamespaces = array();
if ($use == 'encoded') {
$encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
} else {
$encodingStyle = '';
}
}
// wrap RPC calls with method element
if ($style == 'rpc') {
if ($use == 'literal') {
$this->debug("wrapping RPC request with literal method element");
if ($namespace) {
$payload = "<$operation xmlns=\"$namespace\">" . $payload . "</$operation>";
} else {
$payload = "<$operation>" . $payload . "</$operation>";
}
} else {
$this->debug("wrapping RPC request with encoded method element");
if ($namespace) {
$payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" .
$payload .
"</$nsPrefix:$operation>";
} else {
$payload = "<$operation>" .
$payload .
"</$operation>";
}
}
}
// serialize envelope
$soapmsg = $this->serializeEnvelope($payload,$this->requestHeaders,$usedNamespaces,$style,$use,$encodingStyle);
$this->debug("endpoint=$this->endpoint, soapAction=$soapAction, namespace=$namespace, style=$style, use=$use, encodingStyle=$encodingStyle");
$this->debug('SOAP message length=' . strlen($soapmsg) . ' contents (max 1000 bytes)=' . substr($soapmsg, 0, 1000));
// send
$return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout);
if($errstr = $this->getError()){
$this->debug('Error: '.$errstr);
return false;
} else {
$this->return = $return;
$this->debug('sent message successfully and got a(n) '.gettype($return));
$this->appendDebug('return=' . $this->varDump($return));
// fault?
if(is_array($return) && isset($return['faultcode'])){
$this->debug('got fault');
$this->setError($return['faultcode'].': '.$return['faultstring']);
$this->fault = true;
foreach($return as $k => $v){
$this->$k = $v;
$this->debug("$k = $v<br>");
}
return $return;
} elseif ($style == 'document') {
// NOTE: if the response is defined to have multiple parts (i.e. unwrapped),
// we are only going to return the first part here...sorry about that
return $return;
} else {
// array of return values
if(is_array($return)){
// multiple 'out' parameters, which we return wrapped up
// in the array
if(sizeof($return) > 1){
return $return;
}
// single 'out' parameter (normally the return value)
$return = array_shift($return);
$this->debug('return shifted value: ');
$this->appendDebug($this->varDump($return));
return $return;
// nothing returned (ie, echoVoid)
} else {
return "";
}
}
}
}
/**
* get available data pertaining to an operation
*
* @param string $operation operation name
* @return array array of data pertaining to the operation
* @access public
*/
function getOperationData($operation){
if(isset($this->operations[$operation])){
return $this->operations[$operation];
}
$this->debug("No data for operation: $operation");
}
/**
* send the SOAP message
*
* Note: if the operation has multiple return values
* the return value of this method will be an array
* of those values.
*
* @param string $msg a SOAPx4 soapmsg object
* @param string $soapaction SOAPAction value
* @param integer $timeout set connection timeout in seconds
* @param integer $response_timeout set response timeout in seconds
* @return mixed native PHP types.
* @access private
*/
function send($msg, $soapaction = '', $timeout=0, $response_timeout=30) {
$this->checkCookies();
// detect transport
switch(true){
// http(s)
case ereg('^http',$this->endpoint):
$this->debug('transporting via HTTP');
if($this->persistentConnection == true && is_object($this->persistentConnection)){
$http =& $this->persistentConnection;
} else {
$http = new soap_transport_http($this->endpoint);
if ($this->persistentConnection) {
$http->usePersistentConnection();
}
}
$http->setContentType($this->getHTTPContentType(), $this->getHTTPContentTypeCharset());
$http->setSOAPAction($soapaction);
if($this->proxyhost && $this->proxyport){
$http->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword);
}
if($this->authtype != '') {
$http->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest);
}
if($this->http_encoding != ''){
$http->setEncoding($this->http_encoding);
}
$this->debug('sending message, length='.strlen($msg));
if(ereg('^http:',$this->endpoint)){
//if(strpos($this->endpoint,'http:')){
$this->responseData = $http->send($msg,$timeout,$response_timeout,$this->cookies);
} elseif(ereg('^https',$this->endpoint)){
//} elseif(strpos($this->endpoint,'https:')){
//if(phpversion() == '4.3.0-dev'){
//$response = $http->send($msg,$timeout,$response_timeout);
//$this->request = $http->outgoing_payload;
//$this->response = $http->incoming_payload;
//} else
$this->responseData = $http->sendHTTPS($msg,$timeout,$response_timeout,$this->cookies);
} else {
$this->setError('no http/s in endpoint url');
}
$this->request = $http->outgoing_payload;
$this->response = $http->incoming_payload;
$this->appendDebug($http->getDebug());
$this->UpdateCookies($http->incoming_cookies);
// save transport object if using persistent connections
if ($this->persistentConnection) {
$http->clearDebug();
if (!is_object($this->persistentConnection)) {
$this->persistentConnection = $http;
}
}
if($err = $http->getError()){
$this->setError('HTTP Error: '.$err);
return false;
} elseif($this->getError()){
return false;
} else {
$this->debug('got response, length='. strlen($this->responseData).' type='.$http->incoming_headers['content-type']);
return $this->parseResponse($http->incoming_headers, $this->responseData);
}
break;
default:
$this->setError('no transport found, or selected transport is not yet supported!');
return false;
break;
}
}
/**
* processes SOAP message returned from server
*
* @param array $headers The HTTP headers
* @param string $data unprocessed response data from server
* @return mixed value of the message, decoded into a PHP type
* @access private
*/
function parseResponse($headers, $data) {
$this->debug('Entering parseResponse() for data of length ' . strlen($data) . ' and type ' . $headers['content-type']);
if (!strstr($headers['content-type'], 'text/xml')) {
$this->setError('Response not of type text/xml');
return false;
}
if (strpos($headers['content-type'], '=')) {
$enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1));
$this->debug('Got response encoding: ' . $enc);
if(eregi('^(ISO-8859-1|US-ASCII|UTF-8)$',$enc)){
$this->xml_encoding = strtoupper($enc);
} else {
$this->xml_encoding = 'US-ASCII';
}
} else {
// should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
$this->xml_encoding = 'ISO-8859-1';
}
$this->debug('Use encoding: ' . $this->xml_encoding . ' when creating soap_parser');
$parser = new soap_parser($data,$this->xml_encoding,$this->operation,$this->decode_utf8);
// add parser debug data to our debug
$this->appendDebug($parser->getDebug());
// if parse errors
if($errstr = $parser->getError()){
$this->setError( $errstr);
// destroy the parser object
unset($parser);
return false;
} else {
// get SOAP headers
$this->responseHeaders = $parser->getHeaders();
// get decoded message
$return = $parser->get_response();
// add document for doclit support
$this->document = $parser->document;
// destroy the parser object
unset($parser);
// return decode message
return $return;
}
}
/**
* sets the SOAP endpoint, which can override WSDL
*
* @param $endpoint string The endpoint URL to use, or empty string or false to prevent override
* @access public
*/
function setEndpoint($endpoint) {
$this->forceEndpoint = $endpoint;
}
/**
* set the SOAP headers
*
* @param $headers mixed String of XML with SOAP header content, or array of soapval objects for SOAP headers
* @access public
*/
function setHeaders($headers){
$this->requestHeaders = $headers;
}
/**
* get the SOAP response headers (namespace resolution incomplete)
*
* @return string
* @access public
*/
function getHeaders(){
return $this->responseHeaders;
}
/**
* set proxy info here
*
* @param string $proxyhost
* @param string $proxyport
* @param string $proxyusername
* @param string $proxypassword
* @access public
*/
function setHTTPProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') {
$this->proxyhost = $proxyhost;
$this->proxyport = $proxyport;
$this->proxyusername = $proxyusername;
$this->proxypassword = $proxypassword;
}
/**
* if authenticating, set user credentials here
*
* @param string $username
* @param string $password
* @param string $authtype (basic|digest|certificate)
* @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
* @access public
*/
function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) {
$this->username = $username;
$this->password = $password;
$this->authtype = $authtype;
$this->certRequest = $certRequest;
}
/**
* use HTTP encoding
*
* @param string $enc
* @access public
*/
function setHTTPEncoding($enc='gzip, deflate'){
$this->http_encoding = $enc;
}
/**
* use HTTP persistent connections if possible
*
* @access public
*/
function useHTTPPersistentConnection(){
$this->persistentConnection = true;
}
/**
* gets the default RPC parameter setting.
* If true, default is that call params are like RPC even for document style.
* Each call() can override this value.
*
* This is no longer used.
*
* @return boolean
* @access public
* @deprecated
*/
function getDefaultRpcParams() {
return $this->defaultRpcParams;
}
/**
* sets the default RPC parameter setting.
* If true, default is that call params are like RPC even for document style
* Each call() can override this value.
*
* This is no longer used.
*
* @param boolean $rpcParams
* @access public
* @deprecated
*/
function setDefaultRpcParams($rpcParams) {
$this->defaultRpcParams = $rpcParams;
}
/**
* dynamically creates an instance of a proxy class,
* allowing user to directly call methods from wsdl
*
* @return object soap_proxy object
* @access public
*/
function getProxy(){
$r = rand();
$evalStr = $this->_getProxyClassCode($r);
//$this->debug("proxy class: $evalStr";
// eval the class
eval($evalStr);
// instantiate proxy object
eval("\$proxy = new soap_proxy_$r('');");
// transfer current wsdl data to the proxy thereby avoiding parsing the wsdl twice
$proxy->endpointType = 'wsdl';
$proxy->wsdlFile = $this->wsdlFile;
$proxy->wsdl = $this->wsdl;
$proxy->operations = $this->operations;
$proxy->defaultRpcParams = $this->defaultRpcParams;
// transfer other state
$proxy->username = $this->username;
$proxy->password = $this->password;
$proxy->authtype = $this->authtype;
$proxy->proxyhost = $this->proxyhost;
$proxy->proxyport = $this->proxyport;
$proxy->proxyusername = $this->proxyusername;
$proxy->proxypassword = $this->proxypassword;
$proxy->timeout = $this->timeout;
$proxy->response_timeout = $this->response_timeout;
$proxy->http_encoding = $this->http_encoding;
$proxy->persistentConnection = $this->persistentConnection;
$proxy->requestHeaders = $this->requestHeaders;
$proxy->soap_defencoding = $this->soap_defencoding;
$proxy->endpoint = $this->endpoint;
$proxy->forceEndpoint = $this->forceEndpoint;
return $proxy;
}
/**
* dynamically creates proxy class code
*
* @return string PHP/NuSOAP code for the proxy class
* @access private
*/
function _getProxyClassCode($r) {
if ($this->endpointType != 'wsdl') {
$evalStr = 'A proxy can only be created for a WSDL client';
$this->setError($evalStr);
return $evalStr;
}
$evalStr = '';
foreach ($this->operations as $operation => $opData) {
if ($operation != '') {
// create param string and param comment string
if (sizeof($opData['input']['parts']) > 0) {
$paramStr = '';
$paramArrayStr = '';
$paramCommentStr = '';
foreach ($opData['input']['parts'] as $name => $type) {
$paramStr .= "\$$name, ";
$paramArrayStr .= "'$name' => \$$name, ";
$paramCommentStr .= "$type \$$name, ";
}
$paramStr = substr($paramStr, 0, strlen($paramStr)-2);
$paramArrayStr = substr($paramArrayStr, 0, strlen($paramArrayStr)-2);
$paramCommentStr = substr($paramCommentStr, 0, strlen($paramCommentStr)-2);
} else {
$paramStr = '';
$paramCommentStr = 'void';
}
$opData['namespace'] = !isset($opData['namespace']) ? 'http://testuri.com' : $opData['namespace'];
$evalStr .= "// $paramCommentStr
function " . str_replace('.', '__', $operation) . "($paramStr) {
\$params = array($paramArrayStr);
return \$this->call('$operation', \$params, '".$opData['namespace']."', '".(isset($opData['soapAction']) ? $opData['soapAction'] : '')."');
}
";
unset($paramStr);
unset($paramCommentStr);
}
}
$evalStr = 'class soap_proxy_'.$r.' extends soapclientw {
'.$evalStr.'
}';
return $evalStr;
}
/**
* dynamically creates proxy class code
*
* @return string PHP/NuSOAP code for the proxy class
* @access public
*/
function getProxyClassCode() {
$r = rand();
return $this->_getProxyClassCode($r);
}
/**
* gets the HTTP body for the current request.
*
* @param string $soapmsg The SOAP payload
* @return string The HTTP body, which includes the SOAP payload
* @access private
*/
function getHTTPBody($soapmsg) {
return $soapmsg;
}
/**
* gets the HTTP content type for the current request.
*
* Note: getHTTPBody must be called before this.
*
* @return string the HTTP content type for the current request.
* @access private
*/
function getHTTPContentType() {
return 'text/xml';
}
/**
* gets the HTTP content type charset for the current request.
* returns false for non-text content types.
*
* Note: getHTTPBody must be called before this.
*
* @return string the HTTP content type charset for the current request.
* @access private
*/
function getHTTPContentTypeCharset() {
return $this->soap_defencoding;
}
/*
* whether or not parser should decode utf8 element content
*
* @return always returns true
* @access public
*/
function decodeUTF8($bool){
$this->decode_utf8 = $bool;
return true;
}
/**
* adds a new Cookie into $this->cookies array
*
* @param string $name Cookie Name
* @param string $value Cookie Value
* @return if cookie-set was successful returns true, else false
* @access public
*/
function setCookie($name, $value) {
if (strlen($name) == 0) {
return false;
}
$this->cookies[] = array('name' => $name, 'value' => $value);
return true;
}
/**
* gets all Cookies
*
* @return array with all internal cookies
* @access public
*/
function getCookies() {
return $this->cookies;
}
/**
* checks all Cookies and delete those which are expired
*
* @return always return true
* @access private
*/
function checkCookies() {
if (sizeof($this->cookies) == 0) {
return true;
}
$this->debug('checkCookie: check ' . sizeof($this->cookies) . ' cookies');
$curr_cookies = $this->cookies;
$this->cookies = array();
foreach ($curr_cookies as $cookie) {
if (! is_array($cookie)) {
$this->debug('Remove cookie that is not an array');
continue;
}
if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) {
if (strtotime($cookie['expires']) > time()) {
$this->cookies[] = $cookie;
} else {
$this->debug('Remove expired cookie ' . $cookie['name']);
}
} else {
$this->cookies[] = $cookie;
}
}
$this->debug('checkCookie: '.sizeof($this->cookies).' cookies left in array');
return true;
}
/**
* updates the current cookies with a new set
*
* @param array $cookies new cookies with which to update current ones
* @return always return true
* @access private
*/
function UpdateCookies($cookies) {
if (sizeof($this->cookies) == 0) {
// no existing cookies: take whatever is new
if (sizeof($cookies) > 0) {
$this->debug('Setting new cookie(s)');
$this->cookies = $cookies;
}
return true;
}
if (sizeof($cookies) == 0) {
// no new cookies: keep what we've got
return true;
}
// merge
foreach ($cookies as $newCookie) {
if (!is_array($newCookie)) {
continue;
}
if ((!isset($newCookie['name'])) || (!isset($newCookie['value']))) {
continue;
}
$newName = $newCookie['name'];
$found = false;
for ($i = 0; $i < count($this->cookies); $i++) {
$cookie = $this->cookies[$i];
if (!is_array($cookie)) {
continue;
}
if (!isset($cookie['name'])) {
continue;
}
if ($newName != $cookie['name']) {
continue;
}
$newDomain = isset($newCookie['domain']) ? $newCookie['domain'] : 'NODOMAIN';
$domain = isset($cookie['domain']) ? $cookie['domain'] : 'NODOMAIN';
if ($newDomain != $domain) {
continue;
}
$newPath = isset($newCookie['path']) ? $newCookie['path'] : 'NOPATH';
$path = isset($cookie['path']) ? $cookie['path'] : 'NOPATH';
if ($newPath != $path) {
continue;
}
$this->cookies[$i] = $newCookie;
$found = true;
$this->debug('Update cookie ' . $newName . '=' . $newCookie['value']);
break;
}
if (! $found) {
$this->debug('Add cookie ' . $newName . '=' . $newCookie['value']);
$this->cookies[] = $newCookie;
}
}
return true;
}
}
?>
| 10npsite | trunk/Index/Lib/Order/chinabank/lib/nusoap.php | PHP | asf20 | 261,504 |
<?php
/**
*
* soap_parser class parses SOAP XML messages into native PHP values
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: class.soap_parser.php,v 1.36 2005/08/04 01:27:42 snichol Exp $
* @access public
*/
class soap_parser extends nusoap_base {
var $xml = '';
var $xml_encoding = '';
var $method = '';
var $root_struct = '';
var $root_struct_name = '';
var $root_struct_namespace = '';
var $root_header = '';
var $document = ''; // incoming SOAP body (text)
// determines where in the message we are (envelope,header,body,method)
var $status = '';
var $position = 0;
var $depth = 0;
var $default_namespace = '';
var $namespaces = array();
var $message = array();
var $parent = '';
var $fault = false;
var $fault_code = '';
var $fault_str = '';
var $fault_detail = '';
var $depth_array = array();
var $debug_flag = true;
var $soapresponse = NULL;
var $responseHeaders = ''; // incoming SOAP headers (text)
var $body_position = 0;
// for multiref parsing:
// array of id => pos
var $ids = array();
// array of id => hrefs => pos
var $multirefs = array();
// toggle for auto-decoding element content
var $decode_utf8 = true;
/**
* constructor that actually does the parsing
*
* @param string $xml SOAP message
* @param string $encoding character encoding scheme of message
* @param string $method method for which XML is parsed (unused?)
* @param string $decode_utf8 whether to decode UTF-8 to ISO-8859-1
* @access public
*/
function soap_parser($xml,$encoding='UTF-8',$method='',$decode_utf8=true){
parent::nusoap_base();
$this->xml = $xml;
$this->xml_encoding = $encoding;
$this->method = $method;
$this->decode_utf8 = $decode_utf8;
// Check whether content has been read.
if(!empty($xml)){
// Check XML encoding
$pos_xml = strpos($xml, '<?xml');
if ($pos_xml !== FALSE) {
$xml_decl = substr($xml, $pos_xml, strpos($xml, '?>', $pos_xml + 2) - $pos_xml + 1);
if (preg_match("/encoding=[\"']([^\"']*)[\"']/", $xml_decl, $res)) {
$xml_encoding = $res[1];
if (strtoupper($xml_encoding) != $encoding) {
$err = "Charset from HTTP Content-Type '" . $encoding . "' does not match encoding from XML declaration '" . $xml_encoding . "'";
$this->debug($err);
if ($encoding != 'ISO-8859-1' || strtoupper($xml_encoding) != 'UTF-8') {
$this->setError($err);
return;
}
// when HTTP says ISO-8859-1 (the default) and XML says UTF-8 (the typical), assume the other endpoint is just sloppy and proceed
} else {
$this->debug('Charset from HTTP Content-Type matches encoding from XML declaration');
}
} else {
$this->debug('No encoding specified in XML declaration');
}
} else {
$this->debug('No XML declaration');
}
$this->debug('Entering soap_parser(), length='.strlen($xml).', encoding='.$encoding);
// Create an XML parser - why not xml_parser_create_ns?
$this->parser = xml_parser_create($this->xml_encoding);
// Set the options for parsing the XML data.
//xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->xml_encoding);
// Set the object for the parser.
xml_set_object($this->parser, $this);
// Set the element handlers for the parser.
xml_set_element_handler($this->parser, 'start_element','end_element');
xml_set_character_data_handler($this->parser,'character_data');
// Parse the XML file.
if(!xml_parse($this->parser,$xml,true)){
// Display an error message.
$err = sprintf('XML error parsing SOAP payload on line %d: %s',
xml_get_current_line_number($this->parser),
xml_error_string(xml_get_error_code($this->parser)));
$this->debug($err);
$this->debug("XML payload:\n" . $xml);
$this->setError($err);
} else {
$this->debug('parsed successfully, found root struct: '.$this->root_struct.' of name '.$this->root_struct_name);
// get final value
$this->soapresponse = $this->message[$this->root_struct]['result'];
// get header value: no, because this is documented as XML string
// if($this->root_header != '' && isset($this->message[$this->root_header]['result'])){
// $this->responseHeaders = $this->message[$this->root_header]['result'];
// }
// resolve hrefs/ids
if(sizeof($this->multirefs) > 0){
foreach($this->multirefs as $id => $hrefs){
$this->debug('resolving multirefs for id: '.$id);
$idVal = $this->buildVal($this->ids[$id]);
if (is_array($idVal) && isset($idVal['!id'])) {
unset($idVal['!id']);
}
foreach($hrefs as $refPos => $ref){
$this->debug('resolving href at pos '.$refPos);
$this->multirefs[$id][$refPos] = $idVal;
}
}
}
}
xml_parser_free($this->parser);
} else {
$this->debug('xml was empty, didn\'t parse!');
$this->setError('xml was empty, didn\'t parse!');
}
}
/**
* start-element handler
*
* @param resource $parser XML parser object
* @param string $name element name
* @param array $attrs associative array of attributes
* @access private
*/
function start_element($parser, $name, $attrs) {
// position in a total number of elements, starting from 0
// update class level pos
$pos = $this->position++;
// and set mine
$this->message[$pos] = array('pos' => $pos,'children'=>'','cdata'=>'');
// depth = how many levels removed from root?
// set mine as current global depth and increment global depth value
$this->message[$pos]['depth'] = $this->depth++;
// else add self as child to whoever the current parent is
if($pos != 0){
$this->message[$this->parent]['children'] .= '|'.$pos;
}
// set my parent
$this->message[$pos]['parent'] = $this->parent;
// set self as current parent
$this->parent = $pos;
// set self as current value for this depth
$this->depth_array[$this->depth] = $pos;
// get element prefix
if(strpos($name,':')){
// get ns prefix
$prefix = substr($name,0,strpos($name,':'));
// get unqualified name
$name = substr(strstr($name,':'),1);
}
// set status
if($name == 'Envelope'){
$this->status = 'envelope';
} elseif($name == 'Header'){
$this->root_header = $pos;
$this->status = 'header';
} elseif($name == 'Body'){
$this->status = 'body';
$this->body_position = $pos;
// set method
} elseif($this->status == 'body' && $pos == ($this->body_position+1)){
$this->status = 'method';
$this->root_struct_name = $name;
$this->root_struct = $pos;
$this->message[$pos]['type'] = 'struct';
$this->debug("found root struct $this->root_struct_name, pos $this->root_struct");
}
// set my status
$this->message[$pos]['status'] = $this->status;
// set name
$this->message[$pos]['name'] = htmlspecialchars($name);
// set attrs
$this->message[$pos]['attrs'] = $attrs;
// loop through atts, logging ns and type declarations
$attstr = '';
foreach($attrs as $key => $value){
$key_prefix = $this->getPrefix($key);
$key_localpart = $this->getLocalPart($key);
// if ns declarations, add to class level array of valid namespaces
if($key_prefix == 'xmlns'){
if(ereg('^http://www.w3.org/[0-9]{4}/XMLSchema$',$value)){
$this->XMLSchemaVersion = $value;
$this->namespaces['xsd'] = $this->XMLSchemaVersion;
$this->namespaces['xsi'] = $this->XMLSchemaVersion.'-instance';
}
$this->namespaces[$key_localpart] = $value;
// set method namespace
if($name == $this->root_struct_name){
$this->methodNamespace = $value;
}
// if it's a type declaration, set type
} elseif($key_localpart == 'type'){
$value_prefix = $this->getPrefix($value);
$value_localpart = $this->getLocalPart($value);
$this->message[$pos]['type'] = $value_localpart;
$this->message[$pos]['typePrefix'] = $value_prefix;
if(isset($this->namespaces[$value_prefix])){
$this->message[$pos]['type_namespace'] = $this->namespaces[$value_prefix];
} else if(isset($attrs['xmlns:'.$value_prefix])) {
$this->message[$pos]['type_namespace'] = $attrs['xmlns:'.$value_prefix];
}
// should do something here with the namespace of specified type?
} elseif($key_localpart == 'arrayType'){
$this->message[$pos]['type'] = 'array';
/* do arrayType ereg here
[1] arrayTypeValue ::= atype asize
[2] atype ::= QName rank*
[3] rank ::= '[' (',')* ']'
[4] asize ::= '[' length~ ']'
[5] length ::= nextDimension* Digit+
[6] nextDimension ::= Digit+ ','
*/
$expr = '([A-Za-z0-9_]+):([A-Za-z]+[A-Za-z0-9_]+)\[([0-9]+),?([0-9]*)\]';
if(ereg($expr,$value,$regs)){
$this->message[$pos]['typePrefix'] = $regs[1];
$this->message[$pos]['arrayTypePrefix'] = $regs[1];
if (isset($this->namespaces[$regs[1]])) {
$this->message[$pos]['arrayTypeNamespace'] = $this->namespaces[$regs[1]];
} else if (isset($attrs['xmlns:'.$regs[1]])) {
$this->message[$pos]['arrayTypeNamespace'] = $attrs['xmlns:'.$regs[1]];
}
$this->message[$pos]['arrayType'] = $regs[2];
$this->message[$pos]['arraySize'] = $regs[3];
$this->message[$pos]['arrayCols'] = $regs[4];
}
// specifies nil value (or not)
} elseif ($key_localpart == 'nil'){
$this->message[$pos]['nil'] = ($value == 'true' || $value == '1');
// some other attribute
} elseif ($key != 'href' && $key != 'xmlns' && $key_localpart != 'encodingStyle' && $key_localpart != 'root') {
$this->message[$pos]['xattrs']['!' . $key] = $value;
}
if ($key == 'xmlns') {
$this->default_namespace = $value;
}
// log id
if($key == 'id'){
$this->ids[$value] = $pos;
}
// root
if($key_localpart == 'root' && $value == 1){
$this->status = 'method';
$this->root_struct_name = $name;
$this->root_struct = $pos;
$this->debug("found root struct $this->root_struct_name, pos $pos");
}
// for doclit
$attstr .= " $key=\"$value\"";
}
// get namespace - must be done after namespace atts are processed
if(isset($prefix)){
$this->message[$pos]['namespace'] = $this->namespaces[$prefix];
$this->default_namespace = $this->namespaces[$prefix];
} else {
$this->message[$pos]['namespace'] = $this->default_namespace;
}
if($this->status == 'header'){
if ($this->root_header != $pos) {
$this->responseHeaders .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>";
}
} elseif($this->root_struct_name != ''){
$this->document .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>";
}
}
/**
* end-element handler
*
* @param resource $parser XML parser object
* @param string $name element name
* @access private
*/
function end_element($parser, $name) {
// position of current element is equal to the last value left in depth_array for my depth
$pos = $this->depth_array[$this->depth--];
// get element prefix
if(strpos($name,':')){
// get ns prefix
$prefix = substr($name,0,strpos($name,':'));
// get unqualified name
$name = substr(strstr($name,':'),1);
}
// build to native type
if(isset($this->body_position) && $pos > $this->body_position){
// deal w/ multirefs
if(isset($this->message[$pos]['attrs']['href'])){
// get id
$id = substr($this->message[$pos]['attrs']['href'],1);
// add placeholder to href array
$this->multirefs[$id][$pos] = 'placeholder';
// add set a reference to it as the result value
$this->message[$pos]['result'] =& $this->multirefs[$id][$pos];
// build complexType values
} elseif($this->message[$pos]['children'] != ''){
// if result has already been generated (struct/array)
if(!isset($this->message[$pos]['result'])){
$this->message[$pos]['result'] = $this->buildVal($pos);
}
// build complexType values of attributes and possibly simpleContent
} elseif (isset($this->message[$pos]['xattrs'])) {
if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) {
$this->message[$pos]['xattrs']['!'] = null;
} elseif (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') {
if (isset($this->message[$pos]['type'])) {
$this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
} else {
$parent = $this->message[$pos]['parent'];
if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
$this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
} else {
$this->message[$pos]['xattrs']['!'] = $this->message[$pos]['cdata'];
}
}
}
$this->message[$pos]['result'] = $this->message[$pos]['xattrs'];
// set value of simpleType (or nil complexType)
} else {
//$this->debug('adding data for scalar value '.$this->message[$pos]['name'].' of value '.$this->message[$pos]['cdata']);
if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) {
$this->message[$pos]['xattrs']['!'] = null;
} elseif (isset($this->message[$pos]['type'])) {
$this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
} else {
$parent = $this->message[$pos]['parent'];
if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
$this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
} else {
$this->message[$pos]['result'] = $this->message[$pos]['cdata'];
}
}
/* add value to parent's result, if parent is struct/array
$parent = $this->message[$pos]['parent'];
if($this->message[$parent]['type'] != 'map'){
if(strtolower($this->message[$parent]['type']) == 'array'){
$this->message[$parent]['result'][] = $this->message[$pos]['result'];
} else {
$this->message[$parent]['result'][$this->message[$pos]['name']] = $this->message[$pos]['result'];
}
}
*/
}
}
// for doclit
if($this->status == 'header'){
if ($this->root_header != $pos) {
$this->responseHeaders .= "</" . (isset($prefix) ? $prefix . ':' : '') . "$name>";
}
} elseif($pos >= $this->root_struct){
$this->document .= "</" . (isset($prefix) ? $prefix . ':' : '') . "$name>";
}
// switch status
if($pos == $this->root_struct){
$this->status = 'body';
$this->root_struct_namespace = $this->message[$pos]['namespace'];
} elseif($name == 'Body'){
$this->status = 'envelope';
} elseif($name == 'Header'){
$this->status = 'envelope';
} elseif($name == 'Envelope'){
//
}
// set parent back to my parent
$this->parent = $this->message[$pos]['parent'];
}
/**
* element content handler
*
* @param resource $parser XML parser object
* @param string $data element content
* @access private
*/
function character_data($parser, $data){
$pos = $this->depth_array[$this->depth];
if ($this->xml_encoding=='UTF-8'){
// TODO: add an option to disable this for folks who want
// raw UTF-8 that, e.g., might not map to iso-8859-1
// TODO: this can also be handled with xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "ISO-8859-1");
if($this->decode_utf8){
$data = utf8_decode($data);
}
}
$this->message[$pos]['cdata'] .= $data;
// for doclit
if($this->status == 'header'){
$this->responseHeaders .= $data;
} else {
$this->document .= $data;
}
}
/**
* get the parsed message
*
* @return mixed
* @access public
*/
function get_response(){
return $this->soapresponse;
}
/**
* get the parsed headers
*
* @return string XML or empty if no headers
* @access public
*/
function getHeaders(){
return $this->responseHeaders;
}
/**
* decodes simple types into PHP variables
*
* @param string $value value to decode
* @param string $type XML type to decode
* @param string $typens XML type namespace to decode
* @return mixed PHP value
* @access private
*/
function decodeSimple($value, $type, $typens) {
// TODO: use the namespace!
if ((!isset($type)) || $type == 'string' || $type == 'long' || $type == 'unsignedLong') {
return (string) $value;
}
if ($type == 'int' || $type == 'integer' || $type == 'short' || $type == 'byte') {
return (int) $value;
}
if ($type == 'float' || $type == 'double' || $type == 'decimal') {
return (double) $value;
}
if ($type == 'boolean') {
if (strtolower($value) == 'false' || strtolower($value) == 'f') {
return false;
}
return (boolean) $value;
}
if ($type == 'base64' || $type == 'base64Binary') {
$this->debug('Decode base64 value');
return base64_decode($value);
}
// obscure numeric types
if ($type == 'nonPositiveInteger' || $type == 'negativeInteger'
|| $type == 'nonNegativeInteger' || $type == 'positiveInteger'
|| $type == 'unsignedInt'
|| $type == 'unsignedShort' || $type == 'unsignedByte') {
return (int) $value;
}
// bogus: parser treats array with no elements as a simple type
if ($type == 'array') {
return array();
}
// everything else
return (string) $value;
}
/**
* builds response structures for compound values (arrays/structs)
* and scalars
*
* @param integer $pos position in node tree
* @return mixed PHP value
* @access private
*/
function buildVal($pos){
if(!isset($this->message[$pos]['type'])){
$this->message[$pos]['type'] = '';
}
$this->debug('in buildVal() for '.$this->message[$pos]['name']."(pos $pos) of type ".$this->message[$pos]['type']);
// if there are children...
if($this->message[$pos]['children'] != ''){
$this->debug('in buildVal, there are children');
$children = explode('|',$this->message[$pos]['children']);
array_shift($children); // knock off empty
// md array
if(isset($this->message[$pos]['arrayCols']) && $this->message[$pos]['arrayCols'] != ''){
$r=0; // rowcount
$c=0; // colcount
foreach($children as $child_pos){
$this->debug("in buildVal, got an MD array element: $r, $c");
$params[$r][] = $this->message[$child_pos]['result'];
$c++;
if($c == $this->message[$pos]['arrayCols']){
$c = 0;
$r++;
}
}
// array
} elseif($this->message[$pos]['type'] == 'array' || $this->message[$pos]['type'] == 'Array'){
$this->debug('in buildVal, adding array '.$this->message[$pos]['name']);
foreach($children as $child_pos){
$params[] = &$this->message[$child_pos]['result'];
}
// apache Map type: java hashtable
} elseif($this->message[$pos]['type'] == 'Map' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap'){
$this->debug('in buildVal, Java Map '.$this->message[$pos]['name']);
foreach($children as $child_pos){
$kv = explode("|",$this->message[$child_pos]['children']);
$params[$this->message[$kv[1]]['result']] = &$this->message[$kv[2]]['result'];
}
// generic compound type
//} elseif($this->message[$pos]['type'] == 'SOAPStruct' || $this->message[$pos]['type'] == 'struct') {
} else {
// Apache Vector type: treat as an array
$this->debug('in buildVal, adding Java Vector '.$this->message[$pos]['name']);
if ($this->message[$pos]['type'] == 'Vector' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap') {
$notstruct = 1;
} else {
$notstruct = 0;
}
//
foreach($children as $child_pos){
if($notstruct){
$params[] = &$this->message[$child_pos]['result'];
} else {
if (isset($params[$this->message[$child_pos]['name']])) {
// de-serialize repeated element name into an array
if ((!is_array($params[$this->message[$child_pos]['name']])) || (!isset($params[$this->message[$child_pos]['name']][0]))) {
$params[$this->message[$child_pos]['name']] = array($params[$this->message[$child_pos]['name']]);
}
$params[$this->message[$child_pos]['name']][] = &$this->message[$child_pos]['result'];
} else {
$params[$this->message[$child_pos]['name']] = &$this->message[$child_pos]['result'];
}
}
}
}
if (isset($this->message[$pos]['xattrs'])) {
$this->debug('in buildVal, handling attributes');
foreach ($this->message[$pos]['xattrs'] as $n => $v) {
$params[$n] = $v;
}
}
// handle simpleContent
if (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') {
$this->debug('in buildVal, handling simpleContent');
if (isset($this->message[$pos]['type'])) {
$params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
} else {
$parent = $this->message[$pos]['parent'];
if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
$params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
} else {
$params['!'] = $this->message[$pos]['cdata'];
}
}
}
return is_array($params) ? $params : array();
} else {
$this->debug('in buildVal, no children, building scalar');
$cdata = isset($this->message[$pos]['cdata']) ? $this->message[$pos]['cdata'] : '';
if (isset($this->message[$pos]['type'])) {
return $this->decodeSimple($cdata, $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
}
$parent = $this->message[$pos]['parent'];
if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
return $this->decodeSimple($cdata, $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
}
return $this->message[$pos]['cdata'];
}
}
}
?> | 10npsite | trunk/Index/Lib/Order/chinabank/lib/class.soap_parser.php | PHP | asf20 | 24,261 |
<?php
/*
$Id: nusoapmime.php,v 1.7 2005/07/27 19:24:42 snichol Exp $
NuSOAP - Web Services Toolkit for PHP
Copyright (c) 2002 NuSphere Corporation
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you have any questions or comments, please email:
Dietrich Ayala
dietrich@ganx4.com
http://dietrich.ganx4.com/nusoap
NuSphere Corporation
http://www.nusphere.com
*/
/*require_once('nusoap.php');*/
/* PEAR Mail_MIME library */
require_once('Mail/mimeDecode.php');
require_once('Mail/mimePart.php');
/**
* soapclientmime client supporting MIME attachments defined at
* http://www.w3.org/TR/SOAP-attachments. It depends on the PEAR Mail_MIME library.
*
* @author Scott Nichol <snichol@sourceforge.net>
* @author Thanks to Guillaume and Henning Reich for posting great attachment code to the mail list
* @version $Id: nusoapmime.php,v 1.7 2005/07/27 19:24:42 snichol Exp $
* @access public
*/
class soapclientmime extends soapclientw {
/**
* @var array Each array element in the return is an associative array with keys
* data, filename, contenttype, cid
* @access private
*/
var $requestAttachments = array();
/**
* @var array Each array element in the return is an associative array with keys
* data, filename, contenttype, cid
* @access private
*/
var $responseAttachments;
/**
* @var string
* @access private
*/
var $mimeContentType;
/**
* adds a MIME attachment to the current request.
*
* If the $data parameter contains an empty string, this method will read
* the contents of the file named by the $filename parameter.
*
* If the $cid parameter is false, this method will generate the cid.
*
* @param string $data The data of the attachment
* @param string $filename The filename of the attachment (default is empty string)
* @param string $contenttype The MIME Content-Type of the attachment (default is application/octet-stream)
* @param string $cid The content-id (cid) of the attachment (default is false)
* @return string The content-id (cid) of the attachment
* @access public
*/
function addAttachment($data, $filename = '', $contenttype = 'application/octet-stream', $cid = false) {
if (! $cid) {
$cid = md5(uniqid(time()));
}
$info['data'] = $data;
$info['filename'] = $filename;
$info['contenttype'] = $contenttype;
$info['cid'] = $cid;
$this->requestAttachments[] = $info;
return $cid;
}
/**
* clears the MIME attachments for the current request.
*
* @access public
*/
function clearAttachments() {
$this->requestAttachments = array();
}
/**
* gets the MIME attachments from the current response.
*
* Each array element in the return is an associative array with keys
* data, filename, contenttype, cid. These keys correspond to the parameters
* for addAttachment.
*
* @return array The attachments.
* @access public
*/
function getAttachments() {
return $this->responseAttachments;
}
/**
* gets the HTTP body for the current request.
*
* @param string $soapmsg The SOAP payload
* @return string The HTTP body, which includes the SOAP payload
* @access private
*/
function getHTTPBody($soapmsg) {
if (count($this->requestAttachments) > 0) {
$params['content_type'] = 'multipart/related; type=text/xml';
$mimeMessage =& new Mail_mimePart('', $params);
unset($params);
$params['content_type'] = 'text/xml';
$params['encoding'] = '8bit';
$params['charset'] = $this->soap_defencoding;
$mimeMessage->addSubpart($soapmsg, $params);
foreach ($this->requestAttachments as $att) {
unset($params);
$params['content_type'] = $att['contenttype'];
$params['encoding'] = 'base64';
$params['disposition'] = 'attachment';
$params['dfilename'] = $att['filename'];
$params['cid'] = $att['cid'];
if ($att['data'] == '' && $att['filename'] <> '') {
if ($fd = fopen($att['filename'], 'rb')) {
$data = fread($fd, filesize($att['filename']));
fclose($fd);
} else {
$data = '';
}
$mimeMessage->addSubpart($data, $params);
} else {
$mimeMessage->addSubpart($att['data'], $params);
}
}
$output = $mimeMessage->encode();
$mimeHeaders = $output['headers'];
foreach ($mimeHeaders as $k => $v) {
$this->debug("MIME header $k: $v");
if (strtolower($k) == 'content-type') {
// PHP header() seems to strip leading whitespace starting
// the second line, so force everything to one line
$this->mimeContentType = str_replace("\r\n", " ", $v);
}
}
return $output['body'];
}
return parent::getHTTPBody($soapmsg);
}
/**
* gets the HTTP content type for the current request.
*
* Note: getHTTPBody must be called before this.
*
* @return string the HTTP content type for the current request.
* @access private
*/
function getHTTPContentType() {
if (count($this->requestAttachments) > 0) {
return $this->mimeContentType;
}
return parent::getHTTPContentType();
}
/**
* gets the HTTP content type charset for the current request.
* returns false for non-text content types.
*
* Note: getHTTPBody must be called before this.
*
* @return string the HTTP content type charset for the current request.
* @access private
*/
function getHTTPContentTypeCharset() {
if (count($this->requestAttachments) > 0) {
return false;
}
return parent::getHTTPContentTypeCharset();
}
/**
* processes SOAP message returned from server
*
* @param array $headers The HTTP headers
* @param string $data unprocessed response data from server
* @return mixed value of the message, decoded into a PHP type
* @access private
*/
function parseResponse($headers, $data) {
$this->debug('Entering parseResponse() for payload of length ' . strlen($data) . ' and type of ' . $headers['content-type']);
$this->responseAttachments = array();
if (strstr($headers['content-type'], 'multipart/related')) {
$this->debug('Decode multipart/related');
$input = '';
foreach ($headers as $k => $v) {
$input .= "$k: $v\r\n";
}
$params['input'] = $input . "\r\n" . $data;
$params['include_bodies'] = true;
$params['decode_bodies'] = true;
$params['decode_headers'] = true;
$structure = Mail_mimeDecode::decode($params);
foreach ($structure->parts as $part) {
if (!isset($part->disposition)) {
$this->debug('Have root part of type ' . $part->headers['content-type']);
$return = parent::parseResponse($part->headers, $part->body);
} else {
$this->debug('Have an attachment of type ' . $part->headers['content-type']);
$info['data'] = $part->body;
$info['filename'] = isset($part->d_parameters['filename']) ? $part->d_parameters['filename'] : '';
$info['contenttype'] = $part->headers['content-type'];
$info['cid'] = $part->headers['content-id'];
$this->responseAttachments[] = $info;
}
}
if (isset($return)) {
return $return;
}
$this->setError('No root part found in multipart/related content');
return;
}
$this->debug('Not multipart/related');
return parent::parseResponse($headers, $data);
}
}
/**
* nusoapservermime server supporting MIME attachments defined at
* http://www.w3.org/TR/SOAP-attachments. It depends on the PEAR Mail_MIME library.
*
* @author Scott Nichol <snichol@sourceforge.net>
* @author Thanks to Guillaume and Henning Reich for posting great attachment code to the mail list
* @version $Id: nusoapmime.php,v 1.7 2005/07/27 19:24:42 snichol Exp $
* @access public
*/
class nusoapservermime extends soap_server {
/**
* @var array Each array element in the return is an associative array with keys
* data, filename, contenttype, cid
* @access private
*/
var $requestAttachments = array();
/**
* @var array Each array element in the return is an associative array with keys
* data, filename, contenttype, cid
* @access private
*/
var $responseAttachments;
/**
* @var string
* @access private
*/
var $mimeContentType;
/**
* adds a MIME attachment to the current response.
*
* If the $data parameter contains an empty string, this method will read
* the contents of the file named by the $filename parameter.
*
* If the $cid parameter is false, this method will generate the cid.
*
* @param string $data The data of the attachment
* @param string $filename The filename of the attachment (default is empty string)
* @param string $contenttype The MIME Content-Type of the attachment (default is application/octet-stream)
* @param string $cid The content-id (cid) of the attachment (default is false)
* @return string The content-id (cid) of the attachment
* @access public
*/
function addAttachment($data, $filename = '', $contenttype = 'application/octet-stream', $cid = false) {
if (! $cid) {
$cid = md5(uniqid(time()));
}
$info['data'] = $data;
$info['filename'] = $filename;
$info['contenttype'] = $contenttype;
$info['cid'] = $cid;
$this->responseAttachments[] = $info;
return $cid;
}
/**
* clears the MIME attachments for the current response.
*
* @access public
*/
function clearAttachments() {
$this->responseAttachments = array();
}
/**
* gets the MIME attachments from the current request.
*
* Each array element in the return is an associative array with keys
* data, filename, contenttype, cid. These keys correspond to the parameters
* for addAttachment.
*
* @return array The attachments.
* @access public
*/
function getAttachments() {
return $this->requestAttachments;
}
/**
* gets the HTTP body for the current response.
*
* @param string $soapmsg The SOAP payload
* @return string The HTTP body, which includes the SOAP payload
* @access private
*/
function getHTTPBody($soapmsg) {
if (count($this->responseAttachments) > 0) {
$params['content_type'] = 'multipart/related; type=text/xml';
$mimeMessage =& new Mail_mimePart('', $params);
unset($params);
$params['content_type'] = 'text/xml';
$params['encoding'] = '8bit';
$params['charset'] = $this->soap_defencoding;
$mimeMessage->addSubpart($soapmsg, $params);
foreach ($this->responseAttachments as $att) {
unset($params);
$params['content_type'] = $att['contenttype'];
$params['encoding'] = 'base64';
$params['disposition'] = 'attachment';
$params['dfilename'] = $att['filename'];
$params['cid'] = $att['cid'];
if ($att['data'] == '' && $att['filename'] <> '') {
if ($fd = fopen($att['filename'], 'rb')) {
$data = fread($fd, filesize($att['filename']));
fclose($fd);
} else {
$data = '';
}
$mimeMessage->addSubpart($data, $params);
} else {
$mimeMessage->addSubpart($att['data'], $params);
}
}
$output = $mimeMessage->encode();
$mimeHeaders = $output['headers'];
foreach ($mimeHeaders as $k => $v) {
$this->debug("MIME header $k: $v");
if (strtolower($k) == 'content-type') {
// PHP header() seems to strip leading whitespace starting
// the second line, so force everything to one line
$this->mimeContentType = str_replace("\r\n", " ", $v);
}
}
return $output['body'];
}
return parent::getHTTPBody($soapmsg);
}
/**
* gets the HTTP content type for the current response.
*
* Note: getHTTPBody must be called before this.
*
* @return string the HTTP content type for the current response.
* @access private
*/
function getHTTPContentType() {
if (count($this->responseAttachments) > 0) {
return $this->mimeContentType;
}
return parent::getHTTPContentType();
}
/**
* gets the HTTP content type charset for the current response.
* returns false for non-text content types.
*
* Note: getHTTPBody must be called before this.
*
* @return string the HTTP content type charset for the current response.
* @access private
*/
function getHTTPContentTypeCharset() {
if (count($this->responseAttachments) > 0) {
return false;
}
return parent::getHTTPContentTypeCharset();
}
/**
* processes SOAP message received from client
*
* @param array $headers The HTTP headers
* @param string $data unprocessed request data from client
* @return mixed value of the message, decoded into a PHP type
* @access private
*/
function parseRequest($headers, $data) {
$this->debug('Entering parseRequest() for payload of length ' . strlen($data) . ' and type of ' . $headers['content-type']);
$this->requestAttachments = array();
if (strstr($headers['content-type'], 'multipart/related')) {
$this->debug('Decode multipart/related');
$input = '';
foreach ($headers as $k => $v) {
$input .= "$k: $v\r\n";
}
$params['input'] = $input . "\r\n" . $data;
$params['include_bodies'] = true;
$params['decode_bodies'] = true;
$params['decode_headers'] = true;
$structure = Mail_mimeDecode::decode($params);
foreach ($structure->parts as $part) {
if (!isset($part->disposition)) {
$this->debug('Have root part of type ' . $part->headers['content-type']);
$return = parent::parseRequest($part->headers, $part->body);
} else {
$this->debug('Have an attachment of type ' . $part->headers['content-type']);
$info['data'] = $part->body;
$info['filename'] = isset($part->d_parameters['filename']) ? $part->d_parameters['filename'] : '';
$info['contenttype'] = $part->headers['content-type'];
$info['cid'] = $part->headers['content-id'];
$this->requestAttachments[] = $info;
}
}
if (isset($return)) {
return $return;
}
$this->setError('No root part found in multipart/related content');
return;
}
$this->debug('Not multipart/related');
return parent::parseRequest($headers, $data);
}
}
?>
| 10npsite | trunk/Index/Lib/Order/chinabank/lib/nusoapmime.php | PHP | asf20 | 14,878 |
<?php
/**
格式化显示错误提示
author: jroam
*/
function formatalt($str)
{
if($str=="") return "";
//定义消息数组
$arr=array(
"E12041025"=>"商户不支持此信用卡",
"E12041026"=>"信用卡日交易次数限制",
"E12041030"=>"商户交易号重复",
"E12041029"=>"超出日交易限额",
"E12041036"=>"超出预授权金额浮动范围",
"E12041042"=>"此卡不允许做此交易",
"E12041006"=>"信用卡格式错误",
"E12041008"=>"交易金额格式错误",
"E12041013"=>"商户号错误",
"E12041024"=>"MOTO不支持此信用卡",
"E12041010"=>"持卡人证件格式错误",
"E12041009 "=>"持卡人姓名格式错误",
"E12041011"=>"持卡人电话格式错误",
"E12041023"=>"超出单笔交易限额",
"E12042000"=>"银行不允许此交易",
"E12041027"=>"信用卡日交易有效期错误次数限制",
"E12041033"=>"金额原交易不符",
"E12042010"=>"无效交易",
);
foreach($arr as $k=>$v)
{
$str=str_replace($k,$v,$str);
}
return $str;
}
?> | 10npsite | trunk/Index/Lib/Order/chinabank/lib/userfunction.php | PHP | asf20 | 1,065 |
<?php
/**
* caches instances of the wsdl class
*
* @author Scott Nichol <snichol@computer.org>
* @author Ingo Fischer <ingo@apollon.de>
* @version $Id: class.wsdlcache.php,v 1.5 2005/05/20 17:58:17 snichol Exp $
* @access public
*/
class wsdlcache {
/**
* @var resource
* @access private
*/
var $fplock;
/**
* @var integer
* @access private
*/
var $cache_lifetime;
/**
* @var string
* @access private
*/
var $cache_dir;
/**
* @var string
* @access public
*/
var $debug_str = '';
/**
* constructor
*
* @param string $cache_dir directory for cache-files
* @param integer $cache_lifetime lifetime for caching-files in seconds or 0 for unlimited
* @access public
*/
function wsdlcache($cache_dir='.', $cache_lifetime=0) {
$this->fplock = array();
$this->cache_dir = $cache_dir != '' ? $cache_dir : '.';
$this->cache_lifetime = $cache_lifetime;
}
/**
* creates the filename used to cache a wsdl instance
*
* @param string $wsdl The URL of the wsdl instance
* @return string The filename used to cache the instance
* @access private
*/
function createFilename($wsdl) {
return $this->cache_dir.'/wsdlcache-' . md5($wsdl);
}
/**
* adds debug data to the class level debug string
*
* @param string $string debug data
* @access private
*/
function debug($string){
$this->debug_str .= get_class($this).": $string\n";
}
/**
* gets a wsdl instance from the cache
*
* @param string $wsdl The URL of the wsdl instance
* @return object wsdl The cached wsdl instance, null if the instance is not in the cache
* @access public
*/
function get($wsdl) {
$filename = $this->createFilename($wsdl);
if ($this->obtainMutex($filename, "r")) {
// check for expired WSDL that must be removed from the cache
if ($this->cache_lifetime > 0) {
if (file_exists($filename) && (time() - filemtime($filename) > $this->cache_lifetime)) {
unlink($filename);
$this->debug("Expired $wsdl ($filename) from cache");
$this->releaseMutex($filename);
return null;
}
}
// see what there is to return
$fp = @fopen($filename, "r");
if ($fp) {
$s = implode("", @file($filename));
fclose($fp);
$this->debug("Got $wsdl ($filename) from cache");
} else {
$s = null;
$this->debug("$wsdl ($filename) not in cache");
}
$this->releaseMutex($filename);
return (!is_null($s)) ? unserialize($s) : null;
} else {
$this->debug("Unable to obtain mutex for $filename in get");
}
return null;
}
/**
* obtains the local mutex
*
* @param string $filename The Filename of the Cache to lock
* @param string $mode The open-mode ("r" or "w") or the file - affects lock-mode
* @return boolean Lock successfully obtained ?!
* @access private
*/
function obtainMutex($filename, $mode) {
if (isset($this->fplock[md5($filename)])) {
$this->debug("Lock for $filename already exists");
return false;
}
$this->fplock[md5($filename)] = fopen($filename.".lock", "w");
if ($mode == "r") {
return flock($this->fplock[md5($filename)], LOCK_SH);
} else {
return flock($this->fplock[md5($filename)], LOCK_EX);
}
}
/**
* adds a wsdl instance to the cache
*
* @param object wsdl $wsdl_instance The wsdl instance to add
* @return boolean WSDL successfully cached
* @access public
*/
function put($wsdl_instance) {
$filename = $this->createFilename($wsdl_instance->wsdl);
$s = serialize($wsdl_instance);
if ($this->obtainMutex($filename, "w")) {
$fp = fopen($filename, "w");
fputs($fp, $s);
fclose($fp);
$this->debug("Put $wsdl_instance->wsdl ($filename) in cache");
$this->releaseMutex($filename);
return true;
} else {
$this->debug("Unable to obtain mutex for $filename in put");
}
return false;
}
/**
* releases the local mutex
*
* @param string $filename The Filename of the Cache to lock
* @return boolean Lock successfully released
* @access private
*/
function releaseMutex($filename) {
$ret = flock($this->fplock[md5($filename)], LOCK_UN);
fclose($this->fplock[md5($filename)]);
unset($this->fplock[md5($filename)]);
if (! $ret) {
$this->debug("Not able to release lock for $filename");
}
return $ret;
}
/**
* removes a wsdl instance from the cache
*
* @param string $wsdl The URL of the wsdl instance
* @return boolean Whether there was an instance to remove
* @access public
*/
function remove($wsdl) {
$filename = $this->createFilename($wsdl);
// ignore errors obtaining mutex
$this->obtainMutex($filename, "w");
$ret = unlink($filename);
$this->debug("Removed ($ret) $wsdl ($filename) from cache");
$this->releaseMutex($filename);
return $ret;
}
}
?>
| 10npsite | trunk/Index/Lib/Order/chinabank/lib/class.wsdlcache.php | PHP | asf20 | 4,874 |
<?php
/**
*
* soapclient higher level class for easy usage.
*
* usage:
*
* // instantiate client with server info
* $soapclient = new soapclient( string path [ ,boolean wsdl] );
*
* // call method, get results
* echo $soapclient->call( string methodname [ ,array parameters] );
*
* // bye bye client
* unset($soapclient);
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: class.soapclient.php,v 1.52 2005/07/27 19:24:42 snichol Exp $
* @access public
*/
class soapclientw extends nusoap_base {
var $username = '';
var $password = '';
var $authtype = '';
var $certRequest = array();
var $requestHeaders = false; // SOAP headers in request (text)
var $responseHeaders = ''; // SOAP headers from response (incomplete namespace resolution) (text)
var $document = ''; // SOAP body response portion (incomplete namespace resolution) (text)
var $endpoint;
var $forceEndpoint = ''; // overrides WSDL endpoint
var $proxyhost = '';
var $proxyport = '';
var $proxyusername = '';
var $proxypassword = '';
var $xml_encoding = ''; // character set encoding of incoming (response) messages
var $http_encoding = false;
var $timeout = 0; // HTTP connection timeout
var $response_timeout = 30; // HTTP response timeout
var $endpointType = ''; // soap|wsdl, empty for WSDL initialization error
var $persistentConnection = false;
var $defaultRpcParams = false; // This is no longer used
var $request = ''; // HTTP request
var $response = ''; // HTTP response
var $responseData = ''; // SOAP payload of response
var $cookies = array(); // Cookies from response or for request
var $decode_utf8 = true; // toggles whether the parser decodes element content w/ utf8_decode()
var $operations = array(); // WSDL operations, empty for WSDL initialization error
/*
* fault related variables
*/
/**
* @var fault
* @access public
*/
var $fault;
/**
* @var faultcode
* @access public
*/
var $faultcode;
/**
* @var faultstring
* @access public
*/
var $faultstring;
/**
* @var faultdetail
* @access public
*/
var $faultdetail;
/**
* constructor
*
* @param mixed $endpoint SOAP server or WSDL URL (string), or wsdl instance (object)
* @param bool $wsdl optional, set to true if using WSDL
* @param int $portName optional portName in WSDL document
* @param string $proxyhost
* @param string $proxyport
* @param string $proxyusername
* @param string $proxypassword
* @param integer $timeout set the connection timeout
* @param integer $response_timeout set the response timeout
* @access public
*/
function soapclientw($endpoint,$wsdl = false,$proxyhost = false,$proxyport = false,$proxyusername = false, $proxypassword = false, $timeout = 0, $response_timeout = 30){
parent::nusoap_base();
$this->endpoint = $endpoint;
$this->proxyhost = $proxyhost;
$this->proxyport = $proxyport;
$this->proxyusername = $proxyusername;
$this->proxypassword = $proxypassword;
$this->timeout = $timeout;
$this->response_timeout = $response_timeout;
// make values
if($wsdl){
if (is_object($endpoint) && (get_class($endpoint) == 'wsdl')) {
$this->wsdl = $endpoint;
$this->endpoint = $this->wsdl->wsdl;
$this->wsdlFile = $this->endpoint;
$this->debug('existing wsdl instance created from ' . $this->endpoint);
} else {
$this->wsdlFile = $this->endpoint;
// instantiate wsdl object and parse wsdl file
$this->debug('instantiating wsdl class with doc: '.$endpoint);
$this->wsdl =& new wsdl($this->wsdlFile,$this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword,$this->timeout,$this->response_timeout);
}
$this->appendDebug($this->wsdl->getDebug());
$this->wsdl->clearDebug();
// catch errors
if($errstr = $this->wsdl->getError()){
$this->debug('got wsdl error: '.$errstr);
$this->setError('wsdl error: '.$errstr);
} elseif($this->operations = $this->wsdl->getOperations()){
$this->debug( 'got '.count($this->operations).' operations from wsdl '.$this->wsdlFile);
$this->endpointType = 'wsdl';
} else {
$this->debug( 'getOperations returned false');
$this->setError('no operations defined in the WSDL document!');
}
} else {
$this->debug("instantiate SOAP with endpoint at $endpoint");
$this->endpointType = 'soap';
}
}
/**
* calls method, returns PHP native type
*
* @param string $method SOAP server URL or path
* @param mixed $params An array, associative or simple, of the parameters
* for the method call, or a string that is the XML
* for the call. For rpc style, this call will
* wrap the XML in a tag named after the method, as
* well as the SOAP Envelope and Body. For document
* style, this will only wrap with the Envelope and Body.
* IMPORTANT: when using an array with document style,
* in which case there
* is really one parameter, the root of the fragment
* used in the call, which encloses what programmers
* normally think of parameters. A parameter array
* *must* include the wrapper.
* @param string $namespace optional method namespace (WSDL can override)
* @param string $soapAction optional SOAPAction value (WSDL can override)
* @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers
* @param boolean $rpcParams optional (no longer used)
* @param string $style optional (rpc|document) the style to use when serializing parameters (WSDL can override)
* @param string $use optional (encoded|literal) the use when serializing parameters (WSDL can override)
* @return mixed response from SOAP call
* @access public
*/
function call($operation,$params=array(),$namespace='http://tempuri.org',$soapAction='',$headers=false,$rpcParams=null,$style='rpc',$use='encoded'){
$this->operation = $operation;
$this->fault = false;
$this->setError('');
$this->request = '';
$this->response = '';
$this->responseData = '';
$this->faultstring = '';
$this->faultcode = '';
$this->opData = array();
$this->debug("call: operation=$operation, namespace=$namespace, soapAction=$soapAction, rpcParams=$rpcParams, style=$style, use=$use, endpointType=$this->endpointType");
$this->appendDebug('params=' . $this->varDump($params));
$this->appendDebug('headers=' . $this->varDump($headers));
if ($headers) {
$this->requestHeaders = $headers;
}
// serialize parameters
if($this->endpointType == 'wsdl' && $opData = $this->getOperationData($operation)){
// use WSDL for operation
$this->opData = $opData;
$this->debug("found operation");
$this->appendDebug('opData=' . $this->varDump($opData));
if (isset($opData['soapAction'])) {
$soapAction = $opData['soapAction'];
}
if (! $this->forceEndpoint) {
$this->endpoint = $opData['endpoint'];
} else {
$this->endpoint = $this->forceEndpoint;
}
$namespace = isset($opData['input']['namespace']) ? $opData['input']['namespace'] : $namespace;
$style = $opData['style'];
$use = $opData['input']['use'];
// add ns to ns array
if($namespace != '' && !isset($this->wsdl->namespaces[$namespace])){
$nsPrefix = 'ns' . rand(1000, 9999);
$this->wsdl->namespaces[$nsPrefix] = $namespace;
}
$nsPrefix = $this->wsdl->getPrefixFromNamespace($namespace);
// serialize payload
if (is_string($params)) {
$this->debug("serializing param string for WSDL operation $operation");
$payload = $params;
} elseif (is_array($params)) {
$this->debug("serializing param array for WSDL operation $operation");
$payload = $this->wsdl->serializeRPCParameters($operation,'input',$params);
} else {
$this->debug('params must be array or string');
$this->setError('params must be array or string');
return false;
}
$usedNamespaces = $this->wsdl->usedNamespaces;
if (isset($opData['input']['encodingStyle'])) {
$encodingStyle = $opData['input']['encodingStyle'];
} else {
$encodingStyle = '';
}
$this->appendDebug($this->wsdl->getDebug());
$this->wsdl->clearDebug();
if ($errstr = $this->wsdl->getError()) {
$this->debug('got wsdl error: '.$errstr);
$this->setError('wsdl error: '.$errstr);
return false;
}
} elseif($this->endpointType == 'wsdl') {
// operation not in WSDL
$this->appendDebug($this->wsdl->getDebug());
$this->wsdl->clearDebug();
$this->setError( 'operation '.$operation.' not present.');
$this->debug("operation '$operation' not present.");
return false;
} else {
// no WSDL
//$this->namespaces['ns1'] = $namespace;
$nsPrefix = 'ns' . rand(1000, 9999);
// serialize
$payload = '';
if (is_string($params)) {
$this->debug("serializing param string for operation $operation");
$payload = $params;
} elseif (is_array($params)) {
$this->debug("serializing param array for operation $operation");
foreach($params as $k => $v){
$payload .= $this->serialize_val($v,$k,false,false,false,false,$use);
}
} else {
$this->debug('params must be array or string');
$this->setError('params must be array or string');
return false;
}
$usedNamespaces = array();
if ($use == 'encoded') {
$encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
} else {
$encodingStyle = '';
}
}
// wrap RPC calls with method element
if ($style == 'rpc') {
if ($use == 'literal') {
$this->debug("wrapping RPC request with literal method element");
if ($namespace) {
$payload = "<$operation xmlns=\"$namespace\">" . $payload . "</$operation>";
} else {
$payload = "<$operation>" . $payload . "</$operation>";
}
} else {
$this->debug("wrapping RPC request with encoded method element");
if ($namespace) {
$payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" .
$payload .
"</$nsPrefix:$operation>";
} else {
$payload = "<$operation>" .
$payload .
"</$operation>";
}
}
}
// serialize envelope
$soapmsg = $this->serializeEnvelope($payload,$this->requestHeaders,$usedNamespaces,$style,$use,$encodingStyle);
$this->debug("endpoint=$this->endpoint, soapAction=$soapAction, namespace=$namespace, style=$style, use=$use, encodingStyle=$encodingStyle");
$this->debug('SOAP message length=' . strlen($soapmsg) . ' contents (max 1000 bytes)=' . substr($soapmsg, 0, 1000));
// send
$return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout);
if($errstr = $this->getError()){
$this->debug('Error: '.$errstr);
return false;
} else {
$this->return = $return;
$this->debug('sent message successfully and got a(n) '.gettype($return));
$this->appendDebug('return=' . $this->varDump($return));
// fault?
if(is_array($return) && isset($return['faultcode'])){
$this->debug('got fault');
$this->setError($return['faultcode'].': '.$return['faultstring']);
$this->fault = true;
foreach($return as $k => $v){
$this->$k = $v;
$this->debug("$k = $v<br>");
}
return $return;
} elseif ($style == 'document') {
// NOTE: if the response is defined to have multiple parts (i.e. unwrapped),
// we are only going to return the first part here...sorry about that
return $return;
} else {
// array of return values
if(is_array($return)){
// multiple 'out' parameters, which we return wrapped up
// in the array
if(sizeof($return) > 1){
return $return;
}
// single 'out' parameter (normally the return value)
$return = array_shift($return);
$this->debug('return shifted value: ');
$this->appendDebug($this->varDump($return));
return $return;
// nothing returned (ie, echoVoid)
} else {
return "";
}
}
}
}
/**
* get available data pertaining to an operation
*
* @param string $operation operation name
* @return array array of data pertaining to the operation
* @access public
*/
function getOperationData($operation){
if(isset($this->operations[$operation])){
return $this->operations[$operation];
}
$this->debug("No data for operation: $operation");
}
/**
* send the SOAP message
*
* Note: if the operation has multiple return values
* the return value of this method will be an array
* of those values.
*
* @param string $msg a SOAPx4 soapmsg object
* @param string $soapaction SOAPAction value
* @param integer $timeout set connection timeout in seconds
* @param integer $response_timeout set response timeout in seconds
* @return mixed native PHP types.
* @access private
*/
function send($msg, $soapaction = '', $timeout=0, $response_timeout=30) {
$this->checkCookies();
// detect transport
switch(true){
// http(s)
case ereg('^http',$this->endpoint):
$this->debug('transporting via HTTP');
if($this->persistentConnection == true && is_object($this->persistentConnection)){
$http =& $this->persistentConnection;
} else {
$http = new soap_transport_http($this->endpoint);
if ($this->persistentConnection) {
$http->usePersistentConnection();
}
}
$http->setContentType($this->getHTTPContentType(), $this->getHTTPContentTypeCharset());
$http->setSOAPAction($soapaction);
if($this->proxyhost && $this->proxyport){
$http->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword);
}
if($this->authtype != '') {
$http->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest);
}
if($this->http_encoding != ''){
$http->setEncoding($this->http_encoding);
}
$this->debug('sending message, length='.strlen($msg));
if(ereg('^http:',$this->endpoint)){
//if(strpos($this->endpoint,'http:')){
$this->responseData = $http->send($msg,$timeout,$response_timeout,$this->cookies);
} elseif(ereg('^https',$this->endpoint)){
//} elseif(strpos($this->endpoint,'https:')){
//if(phpversion() == '4.3.0-dev'){
//$response = $http->send($msg,$timeout,$response_timeout);
//$this->request = $http->outgoing_payload;
//$this->response = $http->incoming_payload;
//} else
$this->responseData = $http->sendHTTPS($msg,$timeout,$response_timeout,$this->cookies);
} else {
$this->setError('no http/s in endpoint url');
}
$this->request = $http->outgoing_payload;
$this->response = $http->incoming_payload;
$this->appendDebug($http->getDebug());
$this->UpdateCookies($http->incoming_cookies);
// save transport object if using persistent connections
if ($this->persistentConnection) {
$http->clearDebug();
if (!is_object($this->persistentConnection)) {
$this->persistentConnection = $http;
}
}
if($err = $http->getError()){
$this->setError('HTTP Error: '.$err);
return false;
} elseif($this->getError()){
return false;
} else {
$this->debug('got response, length='. strlen($this->responseData).' type='.$http->incoming_headers['content-type']);
return $this->parseResponse($http->incoming_headers, $this->responseData);
}
break;
default:
$this->setError('no transport found, or selected transport is not yet supported!');
return false;
break;
}
}
/**
* processes SOAP message returned from server
*
* @param array $headers The HTTP headers
* @param string $data unprocessed response data from server
* @return mixed value of the message, decoded into a PHP type
* @access private
*/
function parseResponse($headers, $data) {
$this->debug('Entering parseResponse() for data of length ' . strlen($data) . ' and type ' . $headers['content-type']);
if (!strstr($headers['content-type'], 'text/xml')) {
$this->setError('Response not of type text/xml');
return false;
}
if (strpos($headers['content-type'], '=')) {
$enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1));
$this->debug('Got response encoding: ' . $enc);
if(eregi('^(ISO-8859-1|US-ASCII|UTF-8)$',$enc)){
$this->xml_encoding = strtoupper($enc);
} else {
$this->xml_encoding = 'US-ASCII';
}
} else {
// should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
$this->xml_encoding = 'ISO-8859-1';
}
$this->debug('Use encoding: ' . $this->xml_encoding . ' when creating soap_parser');
$parser = new soap_parser($data,$this->xml_encoding,$this->operation,$this->decode_utf8);
// add parser debug data to our debug
$this->appendDebug($parser->getDebug());
// if parse errors
if($errstr = $parser->getError()){
$this->setError( $errstr);
// destroy the parser object
unset($parser);
return false;
} else {
// get SOAP headers
$this->responseHeaders = $parser->getHeaders();
// get decoded message
$return = $parser->get_response();
// add document for doclit support
$this->document = $parser->document;
// destroy the parser object
unset($parser);
// return decode message
return $return;
}
}
/**
* sets the SOAP endpoint, which can override WSDL
*
* @param $endpoint string The endpoint URL to use, or empty string or false to prevent override
* @access public
*/
function setEndpoint($endpoint) {
$this->forceEndpoint = $endpoint;
}
/**
* set the SOAP headers
*
* @param $headers mixed String of XML with SOAP header content, or array of soapval objects for SOAP headers
* @access public
*/
function setHeaders($headers){
$this->requestHeaders = $headers;
}
/**
* get the SOAP response headers (namespace resolution incomplete)
*
* @return string
* @access public
*/
function getHeaders(){
return $this->responseHeaders;
}
/**
* set proxy info here
*
* @param string $proxyhost
* @param string $proxyport
* @param string $proxyusername
* @param string $proxypassword
* @access public
*/
function setHTTPProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') {
$this->proxyhost = $proxyhost;
$this->proxyport = $proxyport;
$this->proxyusername = $proxyusername;
$this->proxypassword = $proxypassword;
}
/**
* if authenticating, set user credentials here
*
* @param string $username
* @param string $password
* @param string $authtype (basic|digest|certificate)
* @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
* @access public
*/
function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) {
$this->username = $username;
$this->password = $password;
$this->authtype = $authtype;
$this->certRequest = $certRequest;
}
/**
* use HTTP encoding
*
* @param string $enc
* @access public
*/
function setHTTPEncoding($enc='gzip, deflate'){
$this->http_encoding = $enc;
}
/**
* use HTTP persistent connections if possible
*
* @access public
*/
function useHTTPPersistentConnection(){
$this->persistentConnection = true;
}
/**
* gets the default RPC parameter setting.
* If true, default is that call params are like RPC even for document style.
* Each call() can override this value.
*
* This is no longer used.
*
* @return boolean
* @access public
* @deprecated
*/
function getDefaultRpcParams() {
return $this->defaultRpcParams;
}
/**
* sets the default RPC parameter setting.
* If true, default is that call params are like RPC even for document style
* Each call() can override this value.
*
* This is no longer used.
*
* @param boolean $rpcParams
* @access public
* @deprecated
*/
function setDefaultRpcParams($rpcParams) {
$this->defaultRpcParams = $rpcParams;
}
/**
* dynamically creates an instance of a proxy class,
* allowing user to directly call methods from wsdl
*
* @return object soap_proxy object
* @access public
*/
function getProxy(){
$r = rand();
$evalStr = $this->_getProxyClassCode($r);
//$this->debug("proxy class: $evalStr";
// eval the class
eval($evalStr);
// instantiate proxy object
eval("\$proxy = new soap_proxy_$r('');");
// transfer current wsdl data to the proxy thereby avoiding parsing the wsdl twice
$proxy->endpointType = 'wsdl';
$proxy->wsdlFile = $this->wsdlFile;
$proxy->wsdl = $this->wsdl;
$proxy->operations = $this->operations;
$proxy->defaultRpcParams = $this->defaultRpcParams;
// transfer other state
$proxy->username = $this->username;
$proxy->password = $this->password;
$proxy->authtype = $this->authtype;
$proxy->proxyhost = $this->proxyhost;
$proxy->proxyport = $this->proxyport;
$proxy->proxyusername = $this->proxyusername;
$proxy->proxypassword = $this->proxypassword;
$proxy->timeout = $this->timeout;
$proxy->response_timeout = $this->response_timeout;
$proxy->http_encoding = $this->http_encoding;
$proxy->persistentConnection = $this->persistentConnection;
$proxy->requestHeaders = $this->requestHeaders;
$proxy->soap_defencoding = $this->soap_defencoding;
$proxy->endpoint = $this->endpoint;
$proxy->forceEndpoint = $this->forceEndpoint;
return $proxy;
}
/**
* dynamically creates proxy class code
*
* @return string PHP/NuSOAP code for the proxy class
* @access private
*/
function _getProxyClassCode($r) {
if ($this->endpointType != 'wsdl') {
$evalStr = 'A proxy can only be created for a WSDL client';
$this->setError($evalStr);
return $evalStr;
}
$evalStr = '';
foreach ($this->operations as $operation => $opData) {
if ($operation != '') {
// create param string and param comment string
if (sizeof($opData['input']['parts']) > 0) {
$paramStr = '';
$paramArrayStr = '';
$paramCommentStr = '';
foreach ($opData['input']['parts'] as $name => $type) {
$paramStr .= "\$$name, ";
$paramArrayStr .= "'$name' => \$$name, ";
$paramCommentStr .= "$type \$$name, ";
}
$paramStr = substr($paramStr, 0, strlen($paramStr)-2);
$paramArrayStr = substr($paramArrayStr, 0, strlen($paramArrayStr)-2);
$paramCommentStr = substr($paramCommentStr, 0, strlen($paramCommentStr)-2);
} else {
$paramStr = '';
$paramCommentStr = 'void';
}
$opData['namespace'] = !isset($opData['namespace']) ? 'http://testuri.com' : $opData['namespace'];
$evalStr .= "// $paramCommentStr
function " . str_replace('.', '__', $operation) . "($paramStr) {
\$params = array($paramArrayStr);
return \$this->call('$operation', \$params, '".$opData['namespace']."', '".(isset($opData['soapAction']) ? $opData['soapAction'] : '')."');
}
";
unset($paramStr);
unset($paramCommentStr);
}
}
$evalStr = 'class soap_proxy_'.$r.' extends soapclientw {
'.$evalStr.'
}';
return $evalStr;
}
/**
* dynamically creates proxy class code
*
* @return string PHP/NuSOAP code for the proxy class
* @access public
*/
function getProxyClassCode() {
$r = rand();
return $this->_getProxyClassCode($r);
}
/**
* gets the HTTP body for the current request.
*
* @param string $soapmsg The SOAP payload
* @return string The HTTP body, which includes the SOAP payload
* @access private
*/
function getHTTPBody($soapmsg) {
return $soapmsg;
}
/**
* gets the HTTP content type for the current request.
*
* Note: getHTTPBody must be called before this.
*
* @return string the HTTP content type for the current request.
* @access private
*/
function getHTTPContentType() {
return 'text/xml';
}
/**
* gets the HTTP content type charset for the current request.
* returns false for non-text content types.
*
* Note: getHTTPBody must be called before this.
*
* @return string the HTTP content type charset for the current request.
* @access private
*/
function getHTTPContentTypeCharset() {
return $this->soap_defencoding;
}
/*
* whether or not parser should decode utf8 element content
*
* @return always returns true
* @access public
*/
function decodeUTF8($bool){
$this->decode_utf8 = $bool;
return true;
}
/**
* adds a new Cookie into $this->cookies array
*
* @param string $name Cookie Name
* @param string $value Cookie Value
* @return if cookie-set was successful returns true, else false
* @access public
*/
function setCookie($name, $value) {
if (strlen($name) == 0) {
return false;
}
$this->cookies[] = array('name' => $name, 'value' => $value);
return true;
}
/**
* gets all Cookies
*
* @return array with all internal cookies
* @access public
*/
function getCookies() {
return $this->cookies;
}
/**
* checks all Cookies and delete those which are expired
*
* @return always return true
* @access private
*/
function checkCookies() {
if (sizeof($this->cookies) == 0) {
return true;
}
$this->debug('checkCookie: check ' . sizeof($this->cookies) . ' cookies');
$curr_cookies = $this->cookies;
$this->cookies = array();
foreach ($curr_cookies as $cookie) {
if (! is_array($cookie)) {
$this->debug('Remove cookie that is not an array');
continue;
}
if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) {
if (strtotime($cookie['expires']) > time()) {
$this->cookies[] = $cookie;
} else {
$this->debug('Remove expired cookie ' . $cookie['name']);
}
} else {
$this->cookies[] = $cookie;
}
}
$this->debug('checkCookie: '.sizeof($this->cookies).' cookies left in array');
return true;
}
/**
* updates the current cookies with a new set
*
* @param array $cookies new cookies with which to update current ones
* @return always return true
* @access private
*/
function UpdateCookies($cookies) {
if (sizeof($this->cookies) == 0) {
// no existing cookies: take whatever is new
if (sizeof($cookies) > 0) {
$this->debug('Setting new cookie(s)');
$this->cookies = $cookies;
}
return true;
}
if (sizeof($cookies) == 0) {
// no new cookies: keep what we've got
return true;
}
// merge
foreach ($cookies as $newCookie) {
if (!is_array($newCookie)) {
continue;
}
if ((!isset($newCookie['name'])) || (!isset($newCookie['value']))) {
continue;
}
$newName = $newCookie['name'];
$found = false;
for ($i = 0; $i < count($this->cookies); $i++) {
$cookie = $this->cookies[$i];
if (!is_array($cookie)) {
continue;
}
if (!isset($cookie['name'])) {
continue;
}
if ($newName != $cookie['name']) {
continue;
}
$newDomain = isset($newCookie['domain']) ? $newCookie['domain'] : 'NODOMAIN';
$domain = isset($cookie['domain']) ? $cookie['domain'] : 'NODOMAIN';
if ($newDomain != $domain) {
continue;
}
$newPath = isset($newCookie['path']) ? $newCookie['path'] : 'NOPATH';
$path = isset($cookie['path']) ? $cookie['path'] : 'NOPATH';
if ($newPath != $path) {
continue;
}
$this->cookies[$i] = $newCookie;
$found = true;
$this->debug('Update cookie ' . $newName . '=' . $newCookie['value']);
break;
}
if (! $found) {
$this->debug('Add cookie ' . $newName . '=' . $newCookie['value']);
$this->cookies[] = $newCookie;
}
}
return true;
}
}
?>
| 10npsite | trunk/Index/Lib/Order/chinabank/lib/class.soapclient.php | PHP | asf20 | 28,502 |
<?php
/**
* Contains information for a SOAP fault.
* Mainly used for returning faults from deployed functions
* in a server instance.
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: class.soap_fault.php,v 1.12 2005/07/27 19:24:42 snichol Exp $
* @access public
*/
class soap_fault extends nusoap_base {
/**
* The fault code (client|server)
* @var string
* @access private
*/
var $faultcode;
/**
* The fault actor
* @var string
* @access private
*/
var $faultactor;
/**
* The fault string, a description of the fault
* @var string
* @access private
*/
var $faultstring;
/**
* The fault detail, typically a string or array of string
* @var mixed
* @access private
*/
var $faultdetail;
/**
* constructor
*
* @param string $faultcode (client | server)
* @param string $faultactor only used when msg routed between multiple actors
* @param string $faultstring human readable error message
* @param mixed $faultdetail detail, typically a string or array of string
*/
function soap_fault($faultcode,$faultactor='',$faultstring='',$faultdetail=''){
parent::nusoap_base();
$this->faultcode = $faultcode;
$this->faultactor = $faultactor;
$this->faultstring = $faultstring;
$this->faultdetail = $faultdetail;
}
/**
* serialize a fault
*
* @return string The serialization of the fault instance.
* @access public
*/
function serialize(){
$ns_string = '';
foreach($this->namespaces as $k => $v){
$ns_string .= "\n xmlns:$k=\"$v\"";
}
$return_msg =
'<?xml version="1.0" encoding="'.$this->soap_defencoding.'"?>'.
'<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"'.$ns_string.">\n".
'<SOAP-ENV:Body>'.
'<SOAP-ENV:Fault>'.
$this->serialize_val($this->faultcode, 'faultcode').
$this->serialize_val($this->faultactor, 'faultactor').
$this->serialize_val($this->faultstring, 'faultstring').
$this->serialize_val($this->faultdetail, 'detail').
'</SOAP-ENV:Fault>'.
'</SOAP-ENV:Body>'.
'</SOAP-ENV:Envelope>';
return $return_msg;
}
}
?> | 10npsite | trunk/Index/Lib/Order/chinabank/lib/class.soap_fault.php | PHP | asf20 | 2,208 |
<?php
/**
* transport class for sending/receiving data via HTTP and HTTPS
* NOTE: PHP must be compiled with the CURL extension for HTTPS support
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: class.soap_transport_http.php,v 1.57 2005/07/27 19:24:42 snichol Exp $
* @access public
*/
class soap_transport_http extends nusoap_base {
var $url = '';
var $uri = '';
var $digest_uri = '';
var $scheme = '';
var $host = '';
var $port = '';
var $path = '';
var $request_method = 'POST';
var $protocol_version = '1.0';
var $encoding = '';
var $outgoing_headers = array();
var $incoming_headers = array();
var $incoming_cookies = array();
var $outgoing_payload = '';
var $incoming_payload = '';
var $useSOAPAction = true;
var $persistentConnection = false;
var $ch = false; // cURL handle
var $username = '';
var $password = '';
var $authtype = '';
var $digestRequest = array();
var $certRequest = array(); // keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional)
// cainfofile: certificate authority file, e.g. '$pathToPemFiles/rootca.pem'
// sslcertfile: SSL certificate file, e.g. '$pathToPemFiles/mycert.pem'
// sslkeyfile: SSL key file, e.g. '$pathToPemFiles/mykey.pem'
// passphrase: SSL key password/passphrase
// verifypeer: default is 1
// verifyhost: default is 1
/**
* constructor
*/
function soap_transport_http($url){
parent::nusoap_base();
$this->setURL($url);
ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev);
$this->outgoing_headers['User-Agent'] = $this->title.'/'.$this->version.' ('.$rev[1].')';
$this->debug('set User-Agent: ' . $this->outgoing_headers['User-Agent']);
}
function setURL($url) {
$this->url = $url;
$u = parse_url($url);
foreach($u as $k => $v){
$this->debug("$k = $v");
$this->$k = $v;
}
// add any GET params to path
if(isset($u['query']) && $u['query'] != ''){
$this->path .= '?' . $u['query'];
}
// set default port
if(!isset($u['port'])){
if($u['scheme'] == 'https'){
$this->port = 443;
} else {
$this->port = 80;
}
}
$this->uri = $this->path;
$this->digest_uri = $this->uri;
// build headers
if (!isset($u['port'])) {
$this->outgoing_headers['Host'] = $this->host;
} else {
$this->outgoing_headers['Host'] = $this->host.':'.$this->port;
}
$this->debug('set Host: ' . $this->outgoing_headers['Host']);
if (isset($u['user']) && $u['user'] != '') {
$this->setCredentials(urldecode($u['user']), isset($u['pass']) ? urldecode($u['pass']) : '');
}
}
function connect($connection_timeout=0,$response_timeout=30){
// For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like
// "regular" socket.
// TODO: disabled for now because OpenSSL must be *compiled* in (not just
// loaded), and until PHP5 stream_get_wrappers is not available.
// if ($this->scheme == 'https') {
// if (version_compare(phpversion(), '4.3.0') >= 0) {
// if (extension_loaded('openssl')) {
// $this->scheme = 'ssl';
// $this->debug('Using SSL over OpenSSL');
// }
// }
// }
$this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port");
if ($this->scheme == 'http' || $this->scheme == 'ssl') {
// use persistent connection
if($this->persistentConnection && isset($this->fp) && is_resource($this->fp)){
if (!feof($this->fp)) {
$this->debug('Re-use persistent connection');
return true;
}
fclose($this->fp);
$this->debug('Closed persistent connection at EOF');
}
// munge host if using OpenSSL
if ($this->scheme == 'ssl') {
$host = 'ssl://' . $this->host;
} else {
$host = $this->host;
}
$this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout);
// open socket
if($connection_timeout > 0){
$this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str, $connection_timeout);
} else {
$this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str);
}
// test pointer
if(!$this->fp) {
$msg = 'Couldn\'t open socket connection to server ' . $this->url;
if ($this->errno) {
$msg .= ', Error ('.$this->errno.'): '.$this->error_str;
} else {
$msg .= ' prior to connect(). This is often a problem looking up the host name.';
}
$this->debug($msg);
$this->setError($msg);
return false;
}
// set response timeout
$this->debug('set response timeout to ' . $response_timeout);
socket_set_timeout( $this->fp, $response_timeout);
$this->debug('socket connected');
return true;
} else if ($this->scheme == 'https') {
if (!extension_loaded('curl')) {
$this->setError('CURL Extension, or OpenSSL extension w/ PHP version >= 4.3 is required for HTTPS');
return false;
}
$this->debug('connect using https');
// init CURL
$this->ch = curl_init();
// set url
$hostURL = ($this->port != '') ? "https://$this->host:$this->port" : "https://$this->host";
// add path
$hostURL .= $this->path;
curl_setopt($this->ch, CURLOPT_URL, $hostURL);
// follow location headers (re-directs)
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1);
// ask for headers in the response output
curl_setopt($this->ch, CURLOPT_HEADER, 1);
// ask for the response output as the return value
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
// encode
// We manage this ourselves through headers and encoding
// if(function_exists('gzuncompress')){
// curl_setopt($this->ch, CURLOPT_ENCODING, 'deflate');
// }
// persistent connection
if ($this->persistentConnection) {
// The way we send data, we cannot use persistent connections, since
// there will be some "junk" at the end of our request.
//curl_setopt($this->ch, CURL_HTTP_VERSION_1_1, true);
$this->persistentConnection = false;
$this->outgoing_headers['Connection'] = 'close';
$this->debug('set Connection: ' . $this->outgoing_headers['Connection']);
}
// set timeout
if ($connection_timeout != 0) {
curl_setopt($this->ch, CURLOPT_TIMEOUT, $connection_timeout);
}
// TODO: cURL has added a connection timeout separate from the response timeout
//if ($connection_timeout != 0) {
// curl_setopt($this->ch, CURLOPT_CONNECTIONTIMEOUT, $connection_timeout);
//}
//if ($response_timeout != 0) {
// curl_setopt($this->ch, CURLOPT_TIMEOUT, $response_timeout);
//}
// recent versions of cURL turn on peer/host checking by default,
// while PHP binaries are not compiled with a default location for the
// CA cert bundle, so disable peer/host checking.
//curl_setopt($this->ch, CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt');
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 0);
// support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo)
if ($this->authtype == 'certificate') {
if (isset($this->certRequest['cainfofile'])) {
curl_setopt($this->ch, CURLOPT_CAINFO, $this->certRequest['cainfofile']);
}
if (isset($this->certRequest['verifypeer'])) {
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $this->certRequest['verifypeer']);
} else {
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 1);
}
if (isset($this->certRequest['verifyhost'])) {
curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, $this->certRequest['verifyhost']);
} else {
curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 1);
}
if (isset($this->certRequest['sslcertfile'])) {
curl_setopt($this->ch, CURLOPT_SSLCERT, $this->certRequest['sslcertfile']);
}
if (isset($this->certRequest['sslkeyfile'])) {
curl_setopt($this->ch, CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']);
}
if (isset($this->certRequest['passphrase'])) {
curl_setopt($this->ch, CURLOPT_SSLKEYPASSWD , $this->certRequest['passphrase']);
}
}
$this->debug('cURL connection set up');
return true;
} else {
$this->setError('Unknown scheme ' . $this->scheme);
$this->debug('Unknown scheme ' . $this->scheme);
return false;
}
}
/**
* send the SOAP message via HTTP
*
* @param string $data message data
* @param integer $timeout set connection timeout in seconds
* @param integer $response_timeout set response timeout in seconds
* @param array $cookies cookies to send
* @return string data
* @access public
*/
function send($data, $timeout=0, $response_timeout=30, $cookies=NULL) {
$this->debug('entered send() with data of length: '.strlen($data));
$this->tryagain = true;
$tries = 0;
while ($this->tryagain) {
$this->tryagain = false;
if ($tries++ < 2) {
// make connnection
if (!$this->connect($timeout, $response_timeout)){
return false;
}
// send request
if (!$this->sendRequest($data, $cookies)){
return false;
}
// get response
$respdata = $this->getResponse();
} else {
$this->setError('Too many tries to get an OK response');
}
}
$this->debug('end of send()');
return $respdata;
}
/**
* send the SOAP message via HTTPS 1.0 using CURL
*
* @param string $msg message data
* @param integer $timeout set connection timeout in seconds
* @param integer $response_timeout set response timeout in seconds
* @param array $cookies cookies to send
* @return string data
* @access public
*/
function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) {
return $this->send($data, $timeout, $response_timeout, $cookies);
}
/**
* if authenticating, set user credentials here
*
* @param string $username
* @param string $password
* @param string $authtype (basic, digest, certificate)
* @param array $digestRequest (keys must be nonce, nc, realm, qop)
* @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
* @access public
*/
function setCredentials($username, $password, $authtype = 'basic', $digestRequest = array(), $certRequest = array()) {
$this->debug("Set credentials for authtype $authtype");
// cf. RFC 2617
if ($authtype == 'basic') {
$this->outgoing_headers['Authorization'] = 'Basic '.base64_encode(str_replace(':','',$username).':'.$password);
} elseif ($authtype == 'digest') {
if (isset($digestRequest['nonce'])) {
$digestRequest['nc'] = isset($digestRequest['nc']) ? $digestRequest['nc']++ : 1;
// calculate the Digest hashes (calculate code based on digest implementation found at: http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html)
// A1 = unq(username-value) ":" unq(realm-value) ":" passwd
$A1 = $username. ':' . (isset($digestRequest['realm']) ? $digestRequest['realm'] : '') . ':' . $password;
// H(A1) = MD5(A1)
$HA1 = md5($A1);
// A2 = Method ":" digest-uri-value
$A2 = 'POST:' . $this->digest_uri;
// H(A2)
$HA2 = md5($A2);
// KD(secret, data) = H(concat(secret, ":", data))
// if qop == auth:
// request-digest = <"> < KD ( H(A1), unq(nonce-value)
// ":" nc-value
// ":" unq(cnonce-value)
// ":" unq(qop-value)
// ":" H(A2)
// ) <">
// if qop is missing,
// request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <">
$unhashedDigest = '';
$nonce = isset($digestRequest['nonce']) ? $digestRequest['nonce'] : '';
$cnonce = $nonce;
if ($digestRequest['qop'] != '') {
$unhashedDigest = $HA1 . ':' . $nonce . ':' . sprintf("%08d", $digestRequest['nc']) . ':' . $cnonce . ':' . $digestRequest['qop'] . ':' . $HA2;
} else {
$unhashedDigest = $HA1 . ':' . $nonce . ':' . $HA2;
}
$hashedDigest = md5($unhashedDigest);
$this->outgoing_headers['Authorization'] = 'Digest username="' . $username . '", realm="' . $digestRequest['realm'] . '", nonce="' . $nonce . '", uri="' . $this->digest_uri . '", cnonce="' . $cnonce . '", nc=' . sprintf("%08x", $digestRequest['nc']) . ', qop="' . $digestRequest['qop'] . '", response="' . $hashedDigest . '"';
}
} elseif ($authtype == 'certificate') {
$this->certRequest = $certRequest;
}
$this->username = $username;
$this->password = $password;
$this->authtype = $authtype;
$this->digestRequest = $digestRequest;
if (isset($this->outgoing_headers['Authorization'])) {
$this->debug('set Authorization: ' . substr($this->outgoing_headers['Authorization'], 0, 12) . '...');
} else {
$this->debug('Authorization header not set');
}
}
/**
* set the soapaction value
*
* @param string $soapaction
* @access public
*/
function setSOAPAction($soapaction) {
$this->outgoing_headers['SOAPAction'] = '"' . $soapaction . '"';
$this->debug('set SOAPAction: ' . $this->outgoing_headers['SOAPAction']);
}
/**
* use http encoding
*
* @param string $enc encoding style. supported values: gzip, deflate, or both
* @access public
*/
function setEncoding($enc='gzip, deflate') {
if (function_exists('gzdeflate')) {
$this->protocol_version = '1.1';
$this->outgoing_headers['Accept-Encoding'] = $enc;
$this->debug('set Accept-Encoding: ' . $this->outgoing_headers['Accept-Encoding']);
if (!isset($this->outgoing_headers['Connection'])) {
$this->outgoing_headers['Connection'] = 'close';
$this->persistentConnection = false;
$this->debug('set Connection: ' . $this->outgoing_headers['Connection']);
}
set_magic_quotes_runtime(0);
// deprecated
$this->encoding = $enc;
}
}
/**
* set proxy info here
*
* @param string $proxyhost
* @param string $proxyport
* @param string $proxyusername
* @param string $proxypassword
* @access public
*/
function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') {
$this->uri = $this->url;
$this->host = $proxyhost;
$this->port = $proxyport;
if ($proxyusername != '' && $proxypassword != '') {
$this->outgoing_headers['Proxy-Authorization'] = ' Basic '.base64_encode($proxyusername.':'.$proxypassword);
$this->debug('set Proxy-Authorization: ' . $this->outgoing_headers['Proxy-Authorization']);
}
}
/**
* decode a string that is encoded w/ "chunked' transfer encoding
* as defined in RFC2068 19.4.6
*
* @param string $buffer
* @param string $lb
* @returns string
* @access public
* @deprecated
*/
function decodeChunked($buffer, $lb){
// length := 0
$length = 0;
$new = '';
// read chunk-size, chunk-extension (if any) and CRLF
// get the position of the linebreak
$chunkend = strpos($buffer, $lb);
if ($chunkend == FALSE) {
$this->debug('no linebreak found in decodeChunked');
return $new;
}
$temp = substr($buffer,0,$chunkend);
$chunk_size = hexdec( trim($temp) );
$chunkstart = $chunkend + strlen($lb);
// while (chunk-size > 0) {
while ($chunk_size > 0) {
$this->debug("chunkstart: $chunkstart chunk_size: $chunk_size");
$chunkend = strpos( $buffer, $lb, $chunkstart + $chunk_size);
// Just in case we got a broken connection
if ($chunkend == FALSE) {
$chunk = substr($buffer,$chunkstart);
// append chunk-data to entity-body
$new .= $chunk;
$length += strlen($chunk);
break;
}
// read chunk-data and CRLF
$chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart);
// append chunk-data to entity-body
$new .= $chunk;
// length := length + chunk-size
$length += strlen($chunk);
// read chunk-size and CRLF
$chunkstart = $chunkend + strlen($lb);
$chunkend = strpos($buffer, $lb, $chunkstart) + strlen($lb);
if ($chunkend == FALSE) {
break; //Just in case we got a broken connection
}
$temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);
$chunk_size = hexdec( trim($temp) );
$chunkstart = $chunkend;
}
return $new;
}
/*
* Writes payload, including HTTP headers, to $this->outgoing_payload.
*/
function buildPayload($data, $cookie_str = '') {
// add content-length header
$this->outgoing_headers['Content-Length'] = strlen($data);
$this->debug('set Content-Length: ' . $this->outgoing_headers['Content-Length']);
// start building outgoing payload:
$req = "$this->request_method $this->uri HTTP/$this->protocol_version";
$this->debug("HTTP request: $req");
$this->outgoing_payload = "$req\r\n";
// loop thru headers, serializing
foreach($this->outgoing_headers as $k => $v){
$hdr = $k.': '.$v;
$this->debug("HTTP header: $hdr");
$this->outgoing_payload .= "$hdr\r\n";
}
// add any cookies
if ($cookie_str != '') {
$hdr = 'Cookie: '.$cookie_str;
$this->debug("HTTP header: $hdr");
$this->outgoing_payload .= "$hdr\r\n";
}
// header/body separator
$this->outgoing_payload .= "\r\n";
// add data
$this->outgoing_payload .= $data;
}
function sendRequest($data, $cookies = NULL) {
// build cookie string
$cookie_str = $this->getCookiesForRequest($cookies, (($this->scheme == 'ssl') || ($this->scheme == 'https')));
// build payload
$this->buildPayload($data, $cookie_str);
if ($this->scheme == 'http' || $this->scheme == 'ssl') {
// send payload
if(!fputs($this->fp, $this->outgoing_payload, strlen($this->outgoing_payload))) {
$this->setError('couldn\'t write message data to socket');
$this->debug('couldn\'t write message data to socket');
return false;
}
$this->debug('wrote data to socket, length = ' . strlen($this->outgoing_payload));
return true;
} else if ($this->scheme == 'https') {
// set payload
// TODO: cURL does say this should only be the verb, and in fact it
// turns out that the URI and HTTP version are appended to this, which
// some servers refuse to work with
//curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $this->outgoing_payload);
foreach($this->outgoing_headers as $k => $v){
$curl_headers[] = "$k: $v";
}
if ($cookie_str != '') {
$curl_headers[] = 'Cookie: ' . $cookie_str;
}
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $curl_headers);
if ($this->request_method == "POST") {
curl_setopt($this->ch, CURLOPT_POST, 1);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data);
} else {
}
$this->debug('set cURL payload');
return true;
}
}
function getResponse(){
$this->incoming_payload = '';
if ($this->scheme == 'http' || $this->scheme == 'ssl') {
// loop until headers have been retrieved
$data = '';
while (!isset($lb)){
// We might EOF during header read.
if(feof($this->fp)) {
$this->incoming_payload = $data;
$this->debug('found no headers before EOF after length ' . strlen($data));
$this->debug("received before EOF:\n" . $data);
$this->setError('server failed to send headers');
return false;
}
$tmp = fgets($this->fp, 256);
$tmplen = strlen($tmp);
$this->debug("read line of $tmplen bytes: " . trim($tmp));
if ($tmplen == 0) {
$this->incoming_payload = $data;
$this->debug('socket read of headers timed out after length ' . strlen($data));
$this->debug("read before timeout: " . $data);
$this->setError('socket read of headers timed out');
return false;
}
$data .= $tmp;
$pos = strpos($data,"\r\n\r\n");
if($pos > 1){
$lb = "\r\n";
} else {
$pos = strpos($data,"\n\n");
if($pos > 1){
$lb = "\n";
}
}
// remove 100 header
if(isset($lb) && ereg('^HTTP/1.1 100',$data)){
unset($lb);
$data = '';
}//
}
// store header data
$this->incoming_payload .= $data;
$this->debug('found end of headers after length ' . strlen($data));
// process headers
$header_data = trim(substr($data,0,$pos));
$header_array = explode($lb,$header_data);
$this->incoming_headers = array();
$this->incoming_cookies = array();
foreach($header_array as $header_line){
$arr = explode(':',$header_line, 2);
if(count($arr) > 1){
$header_name = strtolower(trim($arr[0]));
$this->incoming_headers[$header_name] = trim($arr[1]);
if ($header_name == 'set-cookie') {
// TODO: allow multiple cookies from parseCookie
$cookie = $this->parseCookie(trim($arr[1]));
if ($cookie) {
$this->incoming_cookies[] = $cookie;
$this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']);
} else {
$this->debug('did not find cookie in ' . trim($arr[1]));
}
}
} else if (isset($header_name)) {
// append continuation line to previous header
$this->incoming_headers[$header_name] .= $lb . ' ' . $header_line;
}
}
// loop until msg has been received
if (isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked') {
$content_length = 2147483647; // ignore any content-length header
$chunked = true;
$this->debug("want to read chunked content");
} elseif (isset($this->incoming_headers['content-length'])) {
$content_length = $this->incoming_headers['content-length'];
$chunked = false;
$this->debug("want to read content of length $content_length");
} else {
$content_length = 2147483647;
$chunked = false;
$this->debug("want to read content to EOF");
}
$data = '';
do {
if ($chunked) {
$tmp = fgets($this->fp, 256);
$tmplen = strlen($tmp);
$this->debug("read chunk line of $tmplen bytes");
if ($tmplen == 0) {
$this->incoming_payload = $data;
$this->debug('socket read of chunk length timed out after length ' . strlen($data));
$this->debug("read before timeout:\n" . $data);
$this->setError('socket read of chunk length timed out');
return false;
}
$content_length = hexdec(trim($tmp));
$this->debug("chunk length $content_length");
}
$strlen = 0;
while (($strlen < $content_length) && (!feof($this->fp))) {
$readlen = min(8192, $content_length - $strlen);
$tmp = fread($this->fp, $readlen);
$tmplen = strlen($tmp);
$this->debug("read buffer of $tmplen bytes");
if (($tmplen == 0) && (!feof($this->fp))) {
$this->incoming_payload = $data;
$this->debug('socket read of body timed out after length ' . strlen($data));
$this->debug("read before timeout:\n" . $data);
$this->setError('socket read of body timed out');
return false;
}
$strlen += $tmplen;
$data .= $tmp;
}
if ($chunked && ($content_length > 0)) {
$tmp = fgets($this->fp, 256);
$tmplen = strlen($tmp);
$this->debug("read chunk terminator of $tmplen bytes");
if ($tmplen == 0) {
$this->incoming_payload = $data;
$this->debug('socket read of chunk terminator timed out after length ' . strlen($data));
$this->debug("read before timeout:\n" . $data);
$this->setError('socket read of chunk terminator timed out');
return false;
}
}
} while ($chunked && ($content_length > 0) && (!feof($this->fp)));
if (feof($this->fp)) {
$this->debug('read to EOF');
}
$this->debug('read body of length ' . strlen($data));
$this->incoming_payload .= $data;
$this->debug('received a total of '.strlen($this->incoming_payload).' bytes of data from server');
// close filepointer
if(
(isset($this->incoming_headers['connection']) && strtolower($this->incoming_headers['connection']) == 'close') ||
(! $this->persistentConnection) || feof($this->fp)){
fclose($this->fp);
$this->fp = false;
$this->debug('closed socket');
}
// connection was closed unexpectedly
if($this->incoming_payload == ''){
$this->setError('no response from server');
return false;
}
// decode transfer-encoding
// if(isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked'){
// if(!$data = $this->decodeChunked($data, $lb)){
// $this->setError('Decoding of chunked data failed');
// return false;
// }
//print "<pre>\nde-chunked:\n---------------\n$data\n\n---------------\n</pre>";
// set decoded payload
// $this->incoming_payload = $header_data.$lb.$lb.$data;
// }
} else if ($this->scheme == 'https') {
// send and receive
$this->debug('send and receive with cURL');
$this->incoming_payload = curl_exec($this->ch);
$data = $this->incoming_payload;
$cErr = curl_error($this->ch);
if ($cErr != '') {
$err = 'cURL ERROR: '.curl_errno($this->ch).': '.$cErr.'<br>';
// TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE
foreach(curl_getinfo($this->ch) as $k => $v){
$err .= "$k: $v<br>";
}
$this->debug($err);
$this->setError($err);
curl_close($this->ch);
return false;
} else {
//echo '<pre>';
//var_dump(curl_getinfo($this->ch));
//echo '</pre>';
}
// close curl
$this->debug('No cURL error, closing cURL');
curl_close($this->ch);
// remove 100 header(s)
while (ereg('^HTTP/1.1 100',$data)) {
if ($pos = strpos($data,"\r\n\r\n")) {
$data = ltrim(substr($data,$pos));
} elseif($pos = strpos($data,"\n\n") ) {
$data = ltrim(substr($data,$pos));
}
}
// separate content from HTTP headers
if ($pos = strpos($data,"\r\n\r\n")) {
$lb = "\r\n";
} elseif( $pos = strpos($data,"\n\n")) {
$lb = "\n";
} else {
$this->debug('no proper separation of headers and document');
$this->setError('no proper separation of headers and document');
return false;
}
$header_data = trim(substr($data,0,$pos));
$header_array = explode($lb,$header_data);
$data = ltrim(substr($data,$pos));
$this->debug('found proper separation of headers and document');
$this->debug('cleaned data, stringlen: '.strlen($data));
// clean headers
foreach ($header_array as $header_line) {
$arr = explode(':',$header_line,2);
if(count($arr) > 1){
$header_name = strtolower(trim($arr[0]));
$this->incoming_headers[$header_name] = trim($arr[1]);
if ($header_name == 'set-cookie') {
// TODO: allow multiple cookies from parseCookie
$cookie = $this->parseCookie(trim($arr[1]));
if ($cookie) {
$this->incoming_cookies[] = $cookie;
$this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']);
} else {
$this->debug('did not find cookie in ' . trim($arr[1]));
}
}
} else if (isset($header_name)) {
// append continuation line to previous header
$this->incoming_headers[$header_name] .= $lb . ' ' . $header_line;
}
}
}
$arr = explode(' ', $header_array[0], 3);
$http_version = $arr[0];
$http_status = intval($arr[1]);
$http_reason = count($arr) > 2 ? $arr[2] : '';
// see if we need to resend the request with http digest authentication
if (isset($this->incoming_headers['location']) && $http_status == 301) {
$this->debug("Got 301 $http_reason with Location: " . $this->incoming_headers['location']);
$this->setURL($this->incoming_headers['location']);
$this->tryagain = true;
return false;
}
// see if we need to resend the request with http digest authentication
if (isset($this->incoming_headers['www-authenticate']) && $http_status == 401) {
$this->debug("Got 401 $http_reason with WWW-Authenticate: " . $this->incoming_headers['www-authenticate']);
if (strstr($this->incoming_headers['www-authenticate'], "Digest ")) {
$this->debug('Server wants digest authentication');
// remove "Digest " from our elements
$digestString = str_replace('Digest ', '', $this->incoming_headers['www-authenticate']);
// parse elements into array
$digestElements = explode(',', $digestString);
foreach ($digestElements as $val) {
$tempElement = explode('=', trim($val), 2);
$digestRequest[$tempElement[0]] = str_replace("\"", '', $tempElement[1]);
}
// should have (at least) qop, realm, nonce
if (isset($digestRequest['nonce'])) {
$this->setCredentials($this->username, $this->password, 'digest', $digestRequest);
$this->tryagain = true;
return false;
}
}
$this->debug('HTTP authentication failed');
$this->setError('HTTP authentication failed');
return false;
}
if (
($http_status >= 300 && $http_status <= 307) ||
($http_status >= 400 && $http_status <= 417) ||
($http_status >= 501 && $http_status <= 505)
) {
$this->setError("Unsupported HTTP response status $http_status $http_reason (soapclientw->response has contents of the response)");
return false;
}
// decode content-encoding
if(isset($this->incoming_headers['content-encoding']) && $this->incoming_headers['content-encoding'] != ''){
if(strtolower($this->incoming_headers['content-encoding']) == 'deflate' || strtolower($this->incoming_headers['content-encoding']) == 'gzip'){
// if decoding works, use it. else assume data wasn't gzencoded
if(function_exists('gzinflate')){
//$timer->setMarker('starting decoding of gzip/deflated content');
// IIS 5 requires gzinflate instead of gzuncompress (similar to IE 5 and gzdeflate v. gzcompress)
// this means there are no Zlib headers, although there should be
$this->debug('The gzinflate function exists');
$datalen = strlen($data);
if ($this->incoming_headers['content-encoding'] == 'deflate') {
if ($degzdata = @gzinflate($data)) {
$data = $degzdata;
$this->debug('The payload has been inflated to ' . strlen($data) . ' bytes');
if (strlen($data) < $datalen) {
// test for the case that the payload has been compressed twice
$this->debug('The inflated payload is smaller than the gzipped one; try again');
if ($degzdata = @gzinflate($data)) {
$data = $degzdata;
$this->debug('The payload has been inflated again to ' . strlen($data) . ' bytes');
}
}
} else {
$this->debug('Error using gzinflate to inflate the payload');
$this->setError('Error using gzinflate to inflate the payload');
}
} elseif ($this->incoming_headers['content-encoding'] == 'gzip') {
if ($degzdata = @gzinflate(substr($data, 10))) { // do our best
$data = $degzdata;
$this->debug('The payload has been un-gzipped to ' . strlen($data) . ' bytes');
if (strlen($data) < $datalen) {
// test for the case that the payload has been compressed twice
$this->debug('The un-gzipped payload is smaller than the gzipped one; try again');
if ($degzdata = @gzinflate(substr($data, 10))) {
$data = $degzdata;
$this->debug('The payload has been un-gzipped again to ' . strlen($data) . ' bytes');
}
}
} else {
$this->debug('Error using gzinflate to un-gzip the payload');
$this->setError('Error using gzinflate to un-gzip the payload');
}
}
//$timer->setMarker('finished decoding of gzip/deflated content');
//print "<xmp>\nde-inflated:\n---------------\n$data\n-------------\n</xmp>";
// set decoded payload
$this->incoming_payload = $header_data.$lb.$lb.$data;
} else {
$this->debug('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.');
$this->setError('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.');
}
} else {
$this->debug('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']);
$this->setError('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']);
}
} else {
$this->debug('No Content-Encoding header');
}
if(strlen($data) == 0){
$this->debug('no data after headers!');
$this->setError('no data present after HTTP headers');
return false;
}
return $data;
}
function setContentType($type, $charset = false) {
$this->outgoing_headers['Content-Type'] = $type . ($charset ? '; charset=' . $charset : '');
$this->debug('set Content-Type: ' . $this->outgoing_headers['Content-Type']);
}
function usePersistentConnection(){
if (isset($this->outgoing_headers['Accept-Encoding'])) {
return false;
}
$this->protocol_version = '1.1';
$this->persistentConnection = true;
$this->outgoing_headers['Connection'] = 'Keep-Alive';
$this->debug('set Connection: ' . $this->outgoing_headers['Connection']);
return true;
}
/**
* parse an incoming Cookie into it's parts
*
* @param string $cookie_str content of cookie
* @return array with data of that cookie
* @access private
*/
/*
* TODO: allow a Set-Cookie string to be parsed into multiple cookies
*/
function parseCookie($cookie_str) {
$cookie_str = str_replace('; ', ';', $cookie_str) . ';';
$data = split(';', $cookie_str);
$value_str = $data[0];
$cookie_param = 'domain=';
$start = strpos($cookie_str, $cookie_param);
if ($start > 0) {
$domain = substr($cookie_str, $start + strlen($cookie_param));
$domain = substr($domain, 0, strpos($domain, ';'));
} else {
$domain = '';
}
$cookie_param = 'expires=';
$start = strpos($cookie_str, $cookie_param);
if ($start > 0) {
$expires = substr($cookie_str, $start + strlen($cookie_param));
$expires = substr($expires, 0, strpos($expires, ';'));
} else {
$expires = '';
}
$cookie_param = 'path=';
$start = strpos($cookie_str, $cookie_param);
if ( $start > 0 ) {
$path = substr($cookie_str, $start + strlen($cookie_param));
$path = substr($path, 0, strpos($path, ';'));
} else {
$path = '/';
}
$cookie_param = ';secure;';
if (strpos($cookie_str, $cookie_param) !== FALSE) {
$secure = true;
} else {
$secure = false;
}
$sep_pos = strpos($value_str, '=');
if ($sep_pos) {
$name = substr($value_str, 0, $sep_pos);
$value = substr($value_str, $sep_pos + 1);
$cookie= array( 'name' => $name,
'value' => $value,
'domain' => $domain,
'path' => $path,
'expires' => $expires,
'secure' => $secure
);
return $cookie;
}
return false;
}
/**
* sort out cookies for the current request
*
* @param array $cookies array with all cookies
* @param boolean $secure is the send-content secure or not?
* @return string for Cookie-HTTP-Header
* @access private
*/
function getCookiesForRequest($cookies, $secure=false) {
$cookie_str = '';
if ((! is_null($cookies)) && (is_array($cookies))) {
foreach ($cookies as $cookie) {
if (! is_array($cookie)) {
continue;
}
$this->debug("check cookie for validity: ".$cookie['name'].'='.$cookie['value']);
if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) {
if (strtotime($cookie['expires']) <= time()) {
$this->debug('cookie has expired');
continue;
}
}
if ((isset($cookie['domain'])) && (! empty($cookie['domain']))) {
$domain = preg_quote($cookie['domain']);
if (! preg_match("'.*$domain$'i", $this->host)) {
$this->debug('cookie has different domain');
continue;
}
}
if ((isset($cookie['path'])) && (! empty($cookie['path']))) {
$path = preg_quote($cookie['path']);
if (! preg_match("'^$path.*'i", $this->path)) {
$this->debug('cookie is for a different path');
continue;
}
}
if ((! $secure) && (isset($cookie['secure'])) && ($cookie['secure'])) {
$this->debug('cookie is secure, transport is not');
continue;
}
$cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; ';
$this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']);
}
}
return $cookie_str;
}
}
?> | 10npsite | trunk/Index/Lib/Order/chinabank/lib/class.soap_transport_http.php | PHP | asf20 | 37,124 |
<?php
/**
* parses a WSDL file, allows access to it's data, other utility methods
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: class.wsdl.php,v 1.56 2005/08/04 01:27:42 snichol Exp $
* @access public
*/
class wsdl extends nusoap_base {
// URL or filename of the root of this WSDL
var $wsdl;
// define internal arrays of bindings, ports, operations, messages, etc.
var $schemas = array();
var $currentSchema;
var $message = array();
var $complexTypes = array();
var $messages = array();
var $currentMessage;
var $currentOperation;
var $portTypes = array();
var $currentPortType;
var $bindings = array();
var $currentBinding;
var $ports = array();
var $currentPort;
var $opData = array();
var $status = '';
var $documentation = false;
var $endpoint = '';
// array of wsdl docs to import
var $import = array();
// parser vars
var $parser;
var $position = 0;
var $depth = 0;
var $depth_array = array();
// for getting wsdl
var $proxyhost = '';
var $proxyport = '';
var $proxyusername = '';
var $proxypassword = '';
var $timeout = 0;
var $response_timeout = 30;
/**
* constructor
*
* @param string $wsdl WSDL document URL
* @param string $proxyhost
* @param string $proxyport
* @param string $proxyusername
* @param string $proxypassword
* @param integer $timeout set the connection timeout
* @param integer $response_timeout set the response timeout
* @access public
*/
function wsdl($wsdl = '',$proxyhost=false,$proxyport=false,$proxyusername=false,$proxypassword=false,$timeout=0,$response_timeout=30){
parent::nusoap_base();
$this->wsdl = $wsdl;
$this->proxyhost = $proxyhost;
$this->proxyport = $proxyport;
$this->proxyusername = $proxyusername;
$this->proxypassword = $proxypassword;
$this->timeout = $timeout;
$this->response_timeout = $response_timeout;
// parse wsdl file
if ($wsdl != "") {
$this->debug('initial wsdl URL: ' . $wsdl);
$this->parseWSDL($wsdl);
}
// imports
// TODO: handle imports more properly, grabbing them in-line and nesting them
$imported_urls = array();
$imported = 1;
while ($imported > 0) {
$imported = 0;
// Schema imports
foreach ($this->schemas as $ns => $list) {
foreach ($list as $xs) {
$wsdlparts = parse_url($this->wsdl); // this is bogusly simple!
foreach ($xs->imports as $ns2 => $list2) {
for ($ii = 0; $ii < count($list2); $ii++) {
if (! $list2[$ii]['loaded']) {
$this->schemas[$ns]->imports[$ns2][$ii]['loaded'] = true;
$url = $list2[$ii]['location'];
if ($url != '') {
$urlparts = parse_url($url);
if (!isset($urlparts['host'])) {
$url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' .$wsdlparts['port'] : '') .
substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
}
if (! in_array($url, $imported_urls)) {
$this->parseWSDL($url);
$imported++;
$imported_urls[] = $url;
}
} else {
$this->debug("Unexpected scenario: empty URL for unloaded import");
}
}
}
}
}
}
// WSDL imports
$wsdlparts = parse_url($this->wsdl); // this is bogusly simple!
foreach ($this->import as $ns => $list) {
for ($ii = 0; $ii < count($list); $ii++) {
if (! $list[$ii]['loaded']) {
$this->import[$ns][$ii]['loaded'] = true;
$url = $list[$ii]['location'];
if ($url != '') {
$urlparts = parse_url($url);
if (!isset($urlparts['host'])) {
$url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') .
substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
}
if (! in_array($url, $imported_urls)) {
$this->parseWSDL($url);
$imported++;
$imported_urls[] = $url;
}
} else {
$this->debug("Unexpected scenario: empty URL for unloaded import");
}
}
}
}
}
// add new data to operation data
foreach($this->bindings as $binding => $bindingData) {
if (isset($bindingData['operations']) && is_array($bindingData['operations'])) {
foreach($bindingData['operations'] as $operation => $data) {
$this->debug('post-parse data gathering for ' . $operation);
$this->bindings[$binding]['operations'][$operation]['input'] =
isset($this->bindings[$binding]['operations'][$operation]['input']) ?
array_merge($this->bindings[$binding]['operations'][$operation]['input'], $this->portTypes[ $bindingData['portType'] ][$operation]['input']) :
$this->portTypes[ $bindingData['portType'] ][$operation]['input'];
$this->bindings[$binding]['operations'][$operation]['output'] =
isset($this->bindings[$binding]['operations'][$operation]['output']) ?
array_merge($this->bindings[$binding]['operations'][$operation]['output'], $this->portTypes[ $bindingData['portType'] ][$operation]['output']) :
$this->portTypes[ $bindingData['portType'] ][$operation]['output'];
if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ])){
$this->bindings[$binding]['operations'][$operation]['input']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ];
}
if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ])){
$this->bindings[$binding]['operations'][$operation]['output']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ];
}
if (isset($bindingData['style'])) {
$this->bindings[$binding]['operations'][$operation]['style'] = $bindingData['style'];
}
$this->bindings[$binding]['operations'][$operation]['transport'] = isset($bindingData['transport']) ? $bindingData['transport'] : '';
$this->bindings[$binding]['operations'][$operation]['documentation'] = isset($this->portTypes[ $bindingData['portType'] ][$operation]['documentation']) ? $this->portTypes[ $bindingData['portType'] ][$operation]['documentation'] : '';
$this->bindings[$binding]['operations'][$operation]['endpoint'] = isset($bindingData['endpoint']) ? $bindingData['endpoint'] : '';
}
}
}
}
/**
* parses the wsdl document
*
* @param string $wsdl path or URL
* @access private
*/
function parseWSDL($wsdl = '')
{
if ($wsdl == '') {
$this->debug('no wsdl passed to parseWSDL()!!');
$this->setError('no wsdl passed to parseWSDL()!!');
return false;
}
// parse $wsdl for url format
$wsdl_props = parse_url($wsdl);
if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'http' || $wsdl_props['scheme'] == 'https')) {
$this->debug('getting WSDL http(s) URL ' . $wsdl);
// get wsdl
$tr = new soap_transport_http($wsdl);
$tr->request_method = 'GET';
$tr->useSOAPAction = false;
if($this->proxyhost && $this->proxyport){
$tr->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword);
}
$tr->setEncoding('gzip, deflate');
$wsdl_string = $tr->send('', $this->timeout, $this->response_timeout);
//$this->debug("WSDL request\n" . $tr->outgoing_payload);
//$this->debug("WSDL response\n" . $tr->incoming_payload);
$this->appendDebug($tr->getDebug());
// catch errors
if($err = $tr->getError() ){
$errstr = 'HTTP ERROR: '.$err;
$this->debug($errstr);
$this->setError($errstr);
unset($tr);
return false;
}
unset($tr);
$this->debug("got WSDL URL");
} else {
// $wsdl is not http(s), so treat it as a file URL or plain file path
if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'file') && isset($wsdl_props['path'])) {
$path = isset($wsdl_props['host']) ? ($wsdl_props['host'] . ':' . $wsdl_props['path']) : $wsdl_props['path'];
} else {
$path = $wsdl;
}
$this->debug('getting WSDL file ' . $path);
if ($fp = @fopen($path, 'r')) {
$wsdl_string = '';
while ($data = fread($fp, 32768)) {
$wsdl_string .= $data;
}
fclose($fp);
} else {
$errstr = "Bad path to WSDL file $path";
$this->debug($errstr);
$this->setError($errstr);
return false;
}
}
$this->debug('Parse WSDL');
// end new code added
// Create an XML parser.
$this->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($this->parser, XML_OPTION_CASE_FOLDING, 0);
// Set the object for the parser.
xml_set_object($this->parser, $this);
// Set the element handlers for the parser.
xml_set_element_handler($this->parser, 'start_element', 'end_element');
xml_set_character_data_handler($this->parser, 'character_data');
// Parse the XML file.
if (!xml_parse($this->parser, $wsdl_string, true)) {
// Display an error message.
$errstr = sprintf(
'XML error parsing WSDL from %s on line %d: %s',
$wsdl,
xml_get_current_line_number($this->parser),
xml_error_string(xml_get_error_code($this->parser))
);
$this->debug($errstr);
$this->debug("XML payload:\n" . $wsdl_string);
$this->setError($errstr);
return false;
}
// free the parser
xml_parser_free($this->parser);
$this->debug('Parsing WSDL done');
// catch wsdl parse errors
if($this->getError()){
return false;
}
return true;
}
/**
* start-element handler
*
* @param string $parser XML parser object
* @param string $name element name
* @param string $attrs associative array of attributes
* @access private
*/
function start_element($parser, $name, $attrs)
{
if ($this->status == 'schema') {
$this->currentSchema->schemaStartElement($parser, $name, $attrs);
$this->appendDebug($this->currentSchema->getDebug());
$this->currentSchema->clearDebug();
} elseif (ereg('schema$', $name)) {
$this->debug('Parsing WSDL schema');
// $this->debug("startElement for $name ($attrs[name]). status = $this->status (".$this->getLocalPart($name).")");
$this->status = 'schema';
$this->currentSchema = new xmlschema('', '', $this->namespaces);
$this->currentSchema->schemaStartElement($parser, $name, $attrs);
$this->appendDebug($this->currentSchema->getDebug());
$this->currentSchema->clearDebug();
} else {
// position in the total number of elements, starting from 0
$pos = $this->position++;
$depth = $this->depth++;
// set self as current value for this depth
$this->depth_array[$depth] = $pos;
$this->message[$pos] = array('cdata' => '');
// process attributes
if (count($attrs) > 0) {
// register namespace declarations
foreach($attrs as $k => $v) {
if (ereg("^xmlns", $k)) {
if ($ns_prefix = substr(strrchr($k, ':'), 1)) {
$this->namespaces[$ns_prefix] = $v;
} else {
$this->namespaces['ns' . (count($this->namespaces) + 1)] = $v;
}
if ($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema') {
$this->XMLSchemaVersion = $v;
$this->namespaces['xsi'] = $v . '-instance';
}
}
}
// expand each attribute prefix to its namespace
foreach($attrs as $k => $v) {
$k = strpos($k, ':') ? $this->expandQname($k) : $k;
if ($k != 'location' && $k != 'soapAction' && $k != 'namespace') {
$v = strpos($v, ':') ? $this->expandQname($v) : $v;
}
$eAttrs[$k] = $v;
}
$attrs = $eAttrs;
} else {
$attrs = array();
}
// get element prefix, namespace and name
if (ereg(':', $name)) {
// get ns prefix
$prefix = substr($name, 0, strpos($name, ':'));
// get ns
$namespace = isset($this->namespaces[$prefix]) ? $this->namespaces[$prefix] : '';
// get unqualified name
$name = substr(strstr($name, ':'), 1);
}
// process attributes, expanding any prefixes to namespaces
// find status, register data
switch ($this->status) {
case 'message':
if ($name == 'part') {
if (isset($attrs['type'])) {
$this->debug("msg " . $this->currentMessage . ": found part $attrs[name]: " . implode(',', $attrs));
$this->messages[$this->currentMessage][$attrs['name']] = $attrs['type'];
}
if (isset($attrs['element'])) {
$this->debug("msg " . $this->currentMessage . ": found part $attrs[name]: " . implode(',', $attrs));
$this->messages[$this->currentMessage][$attrs['name']] = $attrs['element'];
}
}
break;
case 'portType':
switch ($name) {
case 'operation':
$this->currentPortOperation = $attrs['name'];
$this->debug("portType $this->currentPortType operation: $this->currentPortOperation");
if (isset($attrs['parameterOrder'])) {
$this->portTypes[$this->currentPortType][$attrs['name']]['parameterOrder'] = $attrs['parameterOrder'];
}
break;
case 'documentation':
$this->documentation = true;
break;
// merge input/output data
default:
$m = isset($attrs['message']) ? $this->getLocalPart($attrs['message']) : '';
$this->portTypes[$this->currentPortType][$this->currentPortOperation][$name]['message'] = $m;
break;
}
break;
case 'binding':
switch ($name) {
case 'binding':
// get ns prefix
if (isset($attrs['style'])) {
$this->bindings[$this->currentBinding]['prefix'] = $prefix;
}
$this->bindings[$this->currentBinding] = array_merge($this->bindings[$this->currentBinding], $attrs);
break;
case 'header':
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs;
break;
case 'operation':
if (isset($attrs['soapAction'])) {
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['soapAction'] = $attrs['soapAction'];
}
if (isset($attrs['style'])) {
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['style'] = $attrs['style'];
}
if (isset($attrs['name'])) {
$this->currentOperation = $attrs['name'];
$this->debug("current binding operation: $this->currentOperation");
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['name'] = $attrs['name'];
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['binding'] = $this->currentBinding;
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['endpoint'] = isset($this->bindings[$this->currentBinding]['endpoint']) ? $this->bindings[$this->currentBinding]['endpoint'] : '';
}
break;
case 'input':
$this->opStatus = 'input';
break;
case 'output':
$this->opStatus = 'output';
break;
case 'body':
if (isset($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus])) {
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = array_merge($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus], $attrs);
} else {
$this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = $attrs;
}
break;
}
break;
case 'service':
switch ($name) {
case 'port':
$this->currentPort = $attrs['name'];
$this->debug('current port: ' . $this->currentPort);
$this->ports[$this->currentPort]['binding'] = $this->getLocalPart($attrs['binding']);
break;
case 'address':
$this->ports[$this->currentPort]['location'] = $attrs['location'];
$this->ports[$this->currentPort]['bindingType'] = $namespace;
$this->bindings[ $this->ports[$this->currentPort]['binding'] ]['bindingType'] = $namespace;
$this->bindings[ $this->ports[$this->currentPort]['binding'] ]['endpoint'] = $attrs['location'];
break;
}
break;
}
// set status
switch ($name) {
case 'import':
if (isset($attrs['location'])) {
$this->import[$attrs['namespace']][] = array('location' => $attrs['location'], 'loaded' => false);
$this->debug('parsing import ' . $attrs['namespace']. ' - ' . $attrs['location'] . ' (' . count($this->import[$attrs['namespace']]).')');
} else {
$this->import[$attrs['namespace']][] = array('location' => '', 'loaded' => true);
if (! $this->getPrefixFromNamespace($attrs['namespace'])) {
$this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace'];
}
$this->debug('parsing import ' . $attrs['namespace']. ' - [no location] (' . count($this->import[$attrs['namespace']]).')');
}
break;
//wait for schema
//case 'types':
// $this->status = 'schema';
// break;
case 'message':
$this->status = 'message';
$this->messages[$attrs['name']] = array();
$this->currentMessage = $attrs['name'];
break;
case 'portType':
$this->status = 'portType';
$this->portTypes[$attrs['name']] = array();
$this->currentPortType = $attrs['name'];
break;
case "binding":
if (isset($attrs['name'])) {
// get binding name
if (strpos($attrs['name'], ':')) {
$this->currentBinding = $this->getLocalPart($attrs['name']);
} else {
$this->currentBinding = $attrs['name'];
}
$this->status = 'binding';
$this->bindings[$this->currentBinding]['portType'] = $this->getLocalPart($attrs['type']);
$this->debug("current binding: $this->currentBinding of portType: " . $attrs['type']);
}
break;
case 'service':
$this->serviceName = $attrs['name'];
$this->status = 'service';
$this->debug('current service: ' . $this->serviceName);
break;
case 'definitions':
foreach ($attrs as $name => $value) {
$this->wsdl_info[$name] = $value;
}
break;
}
}
}
/**
* end-element handler
*
* @param string $parser XML parser object
* @param string $name element name
* @access private
*/
function end_element($parser, $name){
// unset schema status
if (/*ereg('types$', $name) ||*/ ereg('schema$', $name)) {
$this->status = "";
$this->appendDebug($this->currentSchema->getDebug());
$this->currentSchema->clearDebug();
$this->schemas[$this->currentSchema->schemaTargetNamespace][] = $this->currentSchema;
$this->debug('Parsing WSDL schema done');
}
if ($this->status == 'schema') {
$this->currentSchema->schemaEndElement($parser, $name);
} else {
// bring depth down a notch
$this->depth--;
}
// end documentation
if ($this->documentation) {
//TODO: track the node to which documentation should be assigned; it can be a part, message, etc.
//$this->portTypes[$this->currentPortType][$this->currentPortOperation]['documentation'] = $this->documentation;
$this->documentation = false;
}
}
/**
* element content handler
*
* @param string $parser XML parser object
* @param string $data element content
* @access private
*/
function character_data($parser, $data)
{
$pos = isset($this->depth_array[$this->depth]) ? $this->depth_array[$this->depth] : 0;
if (isset($this->message[$pos]['cdata'])) {
$this->message[$pos]['cdata'] .= $data;
}
if ($this->documentation) {
$this->documentation .= $data;
}
}
function getBindingData($binding)
{
if (is_array($this->bindings[$binding])) {
return $this->bindings[$binding];
}
}
/**
* returns an assoc array of operation names => operation data
*
* @param string $bindingType eg: soap, smtp, dime (only soap is currently supported)
* @return array
* @access public
*/
function getOperations($bindingType = 'soap')
{
$ops = array();
if ($bindingType == 'soap') {
$bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
}
// loop thru ports
foreach($this->ports as $port => $portData) {
// binding type of port matches parameter
if ($portData['bindingType'] == $bindingType) {
//$this->debug("getOperations for port $port");
//$this->debug("port data: " . $this->varDump($portData));
//$this->debug("bindings: " . $this->varDump($this->bindings[ $portData['binding'] ]));
// merge bindings
if (isset($this->bindings[ $portData['binding'] ]['operations'])) {
$ops = array_merge ($ops, $this->bindings[ $portData['binding'] ]['operations']);
}
}
}
return $ops;
}
/**
* returns an associative array of data necessary for calling an operation
*
* @param string $operation , name of operation
* @param string $bindingType , type of binding eg: soap
* @return array
* @access public
*/
function getOperationData($operation, $bindingType = 'soap')
{
if ($bindingType == 'soap') {
$bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
}
// loop thru ports
foreach($this->ports as $port => $portData) {
// binding type of port matches parameter
if ($portData['bindingType'] == $bindingType) {
// get binding
//foreach($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
foreach(array_keys($this->bindings[ $portData['binding'] ]['operations']) as $bOperation) {
// note that we could/should also check the namespace here
if ($operation == $bOperation) {
$opData = $this->bindings[ $portData['binding'] ]['operations'][$operation];
return $opData;
}
}
}
}
}
/**
* returns an associative array of data necessary for calling an operation
*
* @param string $soapAction soapAction for operation
* @param string $bindingType type of binding eg: soap
* @return array
* @access public
*/
function getOperationDataForSoapAction($soapAction, $bindingType = 'soap') {
if ($bindingType == 'soap') {
$bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
}
// loop thru ports
foreach($this->ports as $port => $portData) {
// binding type of port matches parameter
if ($portData['bindingType'] == $bindingType) {
// loop through operations for the binding
foreach ($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
if ($opData['soapAction'] == $soapAction) {
return $opData;
}
}
}
}
}
/**
* returns an array of information about a given type
* returns false if no type exists by the given name
*
* typeDef = array(
* 'elements' => array(), // refs to elements array
* 'restrictionBase' => '',
* 'phpType' => '',
* 'order' => '(sequence|all)',
* 'attrs' => array() // refs to attributes array
* )
*
* @param $type string the type
* @param $ns string namespace (not prefix) of the type
* @return mixed
* @access public
* @see xmlschema
*/
function getTypeDef($type, $ns) {
$this->debug("in getTypeDef: type=$type, ns=$ns");
if ((! $ns) && isset($this->namespaces['tns'])) {
$ns = $this->namespaces['tns'];
$this->debug("in getTypeDef: type namespace forced to $ns");
}
if (isset($this->schemas[$ns])) {
$this->debug("in getTypeDef: have schema for namespace $ns");
for ($i = 0; $i < count($this->schemas[$ns]); $i++) {
$xs = &$this->schemas[$ns][$i];
$t = $xs->getTypeDef($type);
$this->appendDebug($xs->getDebug());
$xs->clearDebug();
if ($t) {
if (!isset($t['phpType'])) {
// get info for type to tack onto the element
$uqType = substr($t['type'], strrpos($t['type'], ':') + 1);
$ns = substr($t['type'], 0, strrpos($t['type'], ':'));
$etype = $this->getTypeDef($uqType, $ns);
if ($etype) {
$this->debug("found type for [element] $type:");
$this->debug($this->varDump($etype));
if (isset($etype['phpType'])) {
$t['phpType'] = $etype['phpType'];
}
if (isset($etype['elements'])) {
$t['elements'] = $etype['elements'];
}
if (isset($etype['attrs'])) {
$t['attrs'] = $etype['attrs'];
}
}
}
return $t;
}
}
} else {
$this->debug("in getTypeDef: do not have schema for namespace $ns");
}
return false;
}
/**
* prints html description of services
*
* @access private
*/
function webDescription(){
global $HTTP_SERVER_VARS;
if (isset($_SERVER)) {
$PHP_SELF = $_SERVER['PHP_SELF'];
} elseif (isset($HTTP_SERVER_VARS)) {
$PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
} else {
$this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
}
$b = '
<html><head><title>NuSOAP: '.$this->serviceName.'</title>
<style type="text/css">
body { font-family: arial; color: #000000; background-color: #ffffff; margin: 0px 0px 0px 0px; }
p { font-family: arial; color: #000000; margin-top: 0px; margin-bottom: 12px; }
pre { background-color: silver; padding: 5px; font-family: Courier New; font-size: x-small; color: #000000;}
ul { margin-top: 10px; margin-left: 20px; }
li { list-style-type: none; margin-top: 10px; color: #000000; }
.content{
margin-left: 0px; padding-bottom: 2em; }
.nav {
padding-top: 10px; padding-bottom: 10px; padding-left: 15px; font-size: .70em;
margin-top: 10px; margin-left: 0px; color: #000000;
background-color: #ccccff; width: 20%; margin-left: 20px; margin-top: 20px; }
.title {
font-family: arial; font-size: 26px; color: #ffffff;
background-color: #999999; width: 105%; margin-left: 0px;
padding-top: 10px; padding-bottom: 10px; padding-left: 15px;}
.hidden {
position: absolute; visibility: hidden; z-index: 200; left: 250px; top: 100px;
font-family: arial; overflow: hidden; width: 600;
padding: 20px; font-size: 10px; background-color: #999999;
layer-background-color:#FFFFFF; }
a,a:active { color: charcoal; font-weight: bold; }
a:visited { color: #666666; font-weight: bold; }
a:hover { color: cc3300; font-weight: bold; }
</style>
<script language="JavaScript" type="text/javascript">
<!--
// POP-UP CAPTIONS...
function lib_bwcheck(){ //Browsercheck (needed)
this.ver=navigator.appVersion
this.agent=navigator.userAgent
this.dom=document.getElementById?1:0
this.opera5=this.agent.indexOf("Opera 5")>-1
this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0;
this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
this.ie=this.ie4||this.ie5||this.ie6
this.mac=this.agent.indexOf("Mac")>-1
this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0;
this.ns4=(document.layers && !this.dom)?1:0;
this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5)
return this
}
var bw = new lib_bwcheck()
//Makes crossbrowser object.
function makeObj(obj){
this.evnt=bw.dom? document.getElementById(obj):bw.ie4?document.all[obj]:bw.ns4?document.layers[obj]:0;
if(!this.evnt) return false
this.css=bw.dom||bw.ie4?this.evnt.style:bw.ns4?this.evnt:0;
this.wref=bw.dom||bw.ie4?this.evnt:bw.ns4?this.css.document:0;
this.writeIt=b_writeIt;
return this
}
// A unit of measure that will be added when setting the position of a layer.
//var px = bw.ns4||window.opera?"":"px";
function b_writeIt(text){
if (bw.ns4){this.wref.write(text);this.wref.close()}
else this.wref.innerHTML = text
}
//Shows the messages
var oDesc;
function popup(divid){
if(oDesc = new makeObj(divid)){
oDesc.css.visibility = "visible"
}
}
function popout(){ // Hides message
if(oDesc) oDesc.css.visibility = "hidden"
}
//-->
</script>
</head>
<body>
<div class=content>
<br><br>
<div class=title>'.$this->serviceName.'</div>
<div class=nav>
<p>View the <a href="'.$PHP_SELF.'?wsdl">WSDL</a> for the service.
Click on an operation name to view it's details.</p>
<ul>';
foreach($this->getOperations() as $op => $data){
$b .= "<li><a href='#' onclick=\"popout();popup('$op')\">$op</a></li>";
// create hidden div
$b .= "<div id='$op' class='hidden'>
<a href='#' onclick='popout()'><font color='#ffffff'>Close</font></a><br><br>";
foreach($data as $donnie => $marie){ // loop through opdata
if($donnie == 'input' || $donnie == 'output'){ // show input/output data
$b .= "<font color='white'>".ucfirst($donnie).':</font><br>';
foreach($marie as $captain => $tenille){ // loop through data
if($captain == 'parts'){ // loop thru parts
$b .= " $captain:<br>";
//if(is_array($tenille)){
foreach($tenille as $joanie => $chachi){
$b .= " $joanie: $chachi<br>";
}
//}
} else {
$b .= " $captain: $tenille<br>";
}
}
} else {
$b .= "<font color='white'>".ucfirst($donnie).":</font> $marie<br>";
}
}
$b .= '</div>';
}
$b .= '
<ul>
</div>
</div></body></html>';
return $b;
}
/**
* serialize the parsed wsdl
*
* @param mixed $debug whether to put debug=1 in endpoint URL
* @return string serialization of WSDL
* @access public
*/
function serialize($debug = 0)
{
$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$xml .= "\n<definitions";
foreach($this->namespaces as $k => $v) {
$xml .= " xmlns:$k=\"$v\"";
}
// 10.9.02 - add poulter fix for wsdl and tns declarations
if (isset($this->namespaces['wsdl'])) {
$xml .= " xmlns=\"" . $this->namespaces['wsdl'] . "\"";
}
if (isset($this->namespaces['tns'])) {
$xml .= " targetNamespace=\"" . $this->namespaces['tns'] . "\"";
}
$xml .= '>';
// imports
if (sizeof($this->import) > 0) {
foreach($this->import as $ns => $list) {
foreach ($list as $ii) {
if ($ii['location'] != '') {
$xml .= '<import location="' . $ii['location'] . '" namespace="' . $ns . '" />';
} else {
$xml .= '<import namespace="' . $ns . '" />';
}
}
}
}
// types
if (count($this->schemas)>=1) {
$xml .= "\n<types>";
foreach ($this->schemas as $ns => $list) {
foreach ($list as $xs) {
$xml .= $xs->serializeSchema();
}
}
$xml .= '</types>';
}
// messages
if (count($this->messages) >= 1) {
foreach($this->messages as $msgName => $msgParts) {
$xml .= "\n<message name=\"" . $msgName . '">';
if(is_array($msgParts)){
foreach($msgParts as $partName => $partType) {
// print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'<br>';
if (strpos($partType, ':')) {
$typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType));
} elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) {
// print 'checking typemap: '.$this->XMLSchemaVersion.'<br>';
$typePrefix = 'xsd';
} else {
foreach($this->typemap as $ns => $types) {
if (isset($types[$partType])) {
$typePrefix = $this->getPrefixFromNamespace($ns);
}
}
if (!isset($typePrefix)) {
die("$partType has no namespace!");
}
}
$ns = $this->getNamespaceFromPrefix($typePrefix);
$typeDef = $this->getTypeDef($this->getLocalPart($partType), $ns);
if ($typeDef['typeClass'] == 'element') {
$elementortype = 'element';
} else {
$elementortype = 'type';
}
$xml .= '<part name="' . $partName . '" ' . $elementortype . '="' . $typePrefix . ':' . $this->getLocalPart($partType) . '" />';
}
}
$xml .= '</message>';
}
}
// bindings & porttypes
if (count($this->bindings) >= 1) {
$binding_xml = '';
$portType_xml = '';
foreach($this->bindings as $bindingName => $attrs) {
$binding_xml .= "\n<binding name=\"" . $bindingName . '" type="tns:' . $attrs['portType'] . '">';
$binding_xml .= '<soap:binding style="' . $attrs['style'] . '" transport="' . $attrs['transport'] . '"/>';
$portType_xml .= "\n<portType name=\"" . $attrs['portType'] . '">';
foreach($attrs['operations'] as $opName => $opParts) {
$binding_xml .= '<operation name="' . $opName . '">';
$binding_xml .= '<soap:operation soapAction="' . $opParts['soapAction'] . '" style="'. $opParts['style'] . '"/>';
if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') {
$enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"';
} else {
$enc_style = '';
}
$binding_xml .= '<input><soap:body use="' . $opParts['input']['use'] . '" namespace="' . $opParts['input']['namespace'] . '"' . $enc_style . '/></input>';
if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') {
$enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"';
} else {
$enc_style = '';
}
$binding_xml .= '<output><soap:body use="' . $opParts['output']['use'] . '" namespace="' . $opParts['output']['namespace'] . '"' . $enc_style . '/></output>';
$binding_xml .= '</operation>';
$portType_xml .= '<operation name="' . $opParts['name'] . '"';
if (isset($opParts['parameterOrder'])) {
$portType_xml .= ' parameterOrder="' . $opParts['parameterOrder'] . '"';
}
$portType_xml .= '>';
if(isset($opParts['documentation']) && $opParts['documentation'] != '') {
$portType_xml .= '<documentation>' . htmlspecialchars($opParts['documentation']) . '</documentation>';
}
$portType_xml .= '<input message="tns:' . $opParts['input']['message'] . '"/>';
$portType_xml .= '<output message="tns:' . $opParts['output']['message'] . '"/>';
$portType_xml .= '</operation>';
}
$portType_xml .= '</portType>';
$binding_xml .= '</binding>';
}
$xml .= $portType_xml . $binding_xml;
}
// services
$xml .= "\n<service name=\"" . $this->serviceName . '">';
if (count($this->ports) >= 1) {
foreach($this->ports as $pName => $attrs) {
$xml .= '<port name="' . $pName . '" binding="tns:' . $attrs['binding'] . '">';
$xml .= '<soap:address location="' . $attrs['location'] . ($debug ? '?debug=1' : '') . '"/>';
$xml .= '</port>';
}
}
$xml .= '</service>';
return $xml . "\n</definitions>";
}
/**
* serialize PHP values according to a WSDL message definition
*
* TODO
* - multi-ref serialization
* - validate PHP values against type definitions, return errors if invalid
*
* @param string $operation operation name
* @param string $direction (input|output)
* @param mixed $parameters parameter value(s)
* @return mixed parameters serialized as XML or false on error (e.g. operation not found)
* @access public
*/
function serializeRPCParameters($operation, $direction, $parameters)
{
$this->debug("in serializeRPCParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion");
$this->appendDebug('parameters=' . $this->varDump($parameters));
if ($direction != 'input' && $direction != 'output') {
$this->debug('The value of the \$direction argument needs to be either "input" or "output"');
$this->setError('The value of the \$direction argument needs to be either "input" or "output"');
return false;
}
if (!$opData = $this->getOperationData($operation)) {
$this->debug('Unable to retrieve WSDL data for operation: ' . $operation);
$this->setError('Unable to retrieve WSDL data for operation: ' . $operation);
return false;
}
$this->debug('opData:');
$this->appendDebug($this->varDump($opData));
// Get encoding style for output and set to current
$encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
$encodingStyle = $opData['output']['encodingStyle'];
$enc_style = $encodingStyle;
}
// set input params
$xml = '';
if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
$use = $opData[$direction]['use'];
$this->debug('have ' . count($opData[$direction]['parts']) . ' part(s) to serialize');
if (is_array($parameters)) {
$parametersArrayType = $this->isArraySimpleOrStruct($parameters);
$this->debug('have ' . count($parameters) . ' parameter(s) provided as ' . $parametersArrayType . ' to serialize');
foreach($opData[$direction]['parts'] as $name => $type) {
$this->debug('serializing part "'.$name.'" of type "'.$type.'"');
// Track encoding style
if (isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
$encodingStyle = $opData[$direction]['encodingStyle'];
$enc_style = $encodingStyle;
} else {
$enc_style = false;
}
// NOTE: add error handling here
// if serializeType returns false, then catch global error and fault
if ($parametersArrayType == 'arraySimple') {
$p = array_shift($parameters);
$this->debug('calling serializeType w/indexed param');
$xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
} elseif (isset($parameters[$name])) {
$this->debug('calling serializeType w/named param');
$xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
} else {
// TODO: only send nillable
$this->debug('calling serializeType w/null param');
$xml .= $this->serializeType($name, $type, null, $use, $enc_style);
}
}
} else {
$this->debug('no parameters passed.');
}
}
$this->debug("serializeRPCParameters returning: $xml");
return $xml;
}
/**
* serialize a PHP value according to a WSDL message definition
*
* TODO
* - multi-ref serialization
* - validate PHP values against type definitions, return errors if invalid
*
* @param string $ type name
* @param mixed $ param value
* @return mixed new param or false if initial value didn't validate
* @access public
* @deprecated
*/
function serializeParameters($operation, $direction, $parameters)
{
$this->debug("in serializeParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion");
$this->appendDebug('parameters=' . $this->varDump($parameters));
if ($direction != 'input' && $direction != 'output') {
$this->debug('The value of the \$direction argument needs to be either "input" or "output"');
$this->setError('The value of the \$direction argument needs to be either "input" or "output"');
return false;
}
if (!$opData = $this->getOperationData($operation)) {
$this->debug('Unable to retrieve WSDL data for operation: ' . $operation);
$this->setError('Unable to retrieve WSDL data for operation: ' . $operation);
return false;
}
$this->debug('opData:');
$this->appendDebug($this->varDump($opData));
// Get encoding style for output and set to current
$encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
$encodingStyle = $opData['output']['encodingStyle'];
$enc_style = $encodingStyle;
}
// set input params
$xml = '';
if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
$use = $opData[$direction]['use'];
$this->debug("use=$use");
$this->debug('got ' . count($opData[$direction]['parts']) . ' part(s)');
if (is_array($parameters)) {
$parametersArrayType = $this->isArraySimpleOrStruct($parameters);
$this->debug('have ' . $parametersArrayType . ' parameters');
foreach($opData[$direction]['parts'] as $name => $type) {
$this->debug('serializing part "'.$name.'" of type "'.$type.'"');
// Track encoding style
if(isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
$encodingStyle = $opData[$direction]['encodingStyle'];
$enc_style = $encodingStyle;
} else {
$enc_style = false;
}
// NOTE: add error handling here
// if serializeType returns false, then catch global error and fault
if ($parametersArrayType == 'arraySimple') {
$p = array_shift($parameters);
$this->debug('calling serializeType w/indexed param');
$xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
} elseif (isset($parameters[$name])) {
$this->debug('calling serializeType w/named param');
$xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
} else {
// TODO: only send nillable
$this->debug('calling serializeType w/null param');
$xml .= $this->serializeType($name, $type, null, $use, $enc_style);
}
}
} else {
$this->debug('no parameters passed.');
}
}
$this->debug("serializeParameters returning: $xml");
return $xml;
}
/**
* serializes a PHP value according a given type definition
*
* @param string $name name of value (part or element)
* @param string $type XML schema type of value (type or element)
* @param mixed $value a native PHP value (parameter value)
* @param string $use use for part (encoded|literal)
* @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
* @param boolean $unqualified a kludge for what should be XML namespace form handling
* @return string value serialized as an XML string
* @access private
*/
function serializeType($name, $type, $value, $use='encoded', $encodingStyle=false, $unqualified=false)
{
$this->debug("in serializeType: name=$name, type=$type, use=$use, encodingStyle=$encodingStyle, unqualified=" . ($unqualified ? "unqualified" : "qualified"));
$this->appendDebug("value=" . $this->varDump($value));
if($use == 'encoded' && $encodingStyle) {
$encodingStyle = ' SOAP-ENV:encodingStyle="' . $encodingStyle . '"';
}
// if a soapval has been supplied, let its type override the WSDL
if (is_object($value) && get_class($value) == 'soapval') {
if ($value->type_ns) {
$type = $value->type_ns . ':' . $value->type;
$forceType = true;
$this->debug("in serializeType: soapval overrides type to $type");
} elseif ($value->type) {
$type = $value->type;
$forceType = true;
$this->debug("in serializeType: soapval overrides type to $type");
} else {
$forceType = false;
$this->debug("in serializeType: soapval does not override type");
}
$attrs = $value->attributes;
$value = $value->value;
$this->debug("in serializeType: soapval overrides value to $value");
if ($attrs) {
if (!is_array($value)) {
$value['!'] = $value;
}
foreach ($attrs as $n => $v) {
$value['!' . $n] = $v;
}
$this->debug("in serializeType: soapval provides attributes");
}
} else {
$forceType = false;
}
$xml = '';
if (strpos($type, ':')) {
$uqType = substr($type, strrpos($type, ':') + 1);
$ns = substr($type, 0, strrpos($type, ':'));
$this->debug("in serializeType: got a prefixed type: $uqType, $ns");
if ($this->getNamespaceFromPrefix($ns)) {
$ns = $this->getNamespaceFromPrefix($ns);
$this->debug("in serializeType: expanded prefixed type: $uqType, $ns");
}
if($ns == $this->XMLSchemaVersion || $ns == 'http://schemas.xmlsoap.org/soap/encoding/'){
$this->debug('in serializeType: type namespace indicates XML Schema or SOAP Encoding type');
if ($unqualified && $use == 'literal') {
$elementNS = " xmlns=\"\"";
} else {
$elementNS = '';
}
if (is_null($value)) {
if ($use == 'literal') {
// TODO: depends on minOccurs
$xml = "<$name$elementNS/>";
} else {
// TODO: depends on nillable, which should be checked before calling this method
$xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>";
}
$this->debug("in serializeType: returning: $xml");
return $xml;
}
if ($uqType == 'boolean') {
if ((is_string($value) && $value == 'false') || (! $value)) {
$value = 'false';
} else {
$value = 'true';
}
}
if ($uqType == 'string' && gettype($value) == 'string') {
$value = $this->expandEntities($value);
}
if (($uqType == 'long' || $uqType == 'unsignedLong') && gettype($value) == 'double') {
$value = sprintf("%.0lf", $value);
}
// it's a scalar
// TODO: what about null/nil values?
// check type isn't a custom type extending xmlschema namespace
if (!$this->getTypeDef($uqType, $ns)) {
if ($use == 'literal') {
if ($forceType) {
$xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value</$name>";
} else {
$xml = "<$name$elementNS>$value</$name>";
}
} else {
$xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value</$name>";
}
$this->debug("in serializeType: returning: $xml");
return $xml;
}
$this->debug('custom type extends XML Schema or SOAP Encoding namespace (yuck)');
} else if ($ns == 'http://xml.apache.org/xml-soap') {
$this->debug('in serializeType: appears to be Apache SOAP type');
if ($uqType == 'Map') {
$tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap');
if (! $tt_prefix) {
$this->debug('in serializeType: Add namespace for Apache SOAP type');
$tt_prefix = 'ns' . rand(1000, 9999);
$this->namespaces[$tt_prefix] = 'http://xml.apache.org/xml-soap';
// force this to be added to usedNamespaces
$tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap');
}
$contents = '';
foreach($value as $k => $v) {
$this->debug("serializing map element: key $k, value $v");
$contents .= '<item>';
$contents .= $this->serialize_val($k,'key',false,false,false,false,$use);
$contents .= $this->serialize_val($v,'value',false,false,false,false,$use);
$contents .= '</item>';
}
if ($use == 'literal') {
if ($forceType) {
$xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\">$contents</$name>";
} else {
$xml = "<$name>$contents</$name>";
}
} else {
$xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\"$encodingStyle>$contents</$name>";
}
$this->debug("in serializeType: returning: $xml");
return $xml;
}
$this->debug('in serializeType: Apache SOAP type, but only support Map');
}
} else {
// TODO: should the type be compared to types in XSD, and the namespace
// set to XSD if the type matches?
$this->debug("in serializeType: No namespace for type $type");
$ns = '';
$uqType = $type;
}
if(!$typeDef = $this->getTypeDef($uqType, $ns)){
$this->setError("$type ($uqType) is not a supported type.");
$this->debug("in serializeType: $type ($uqType) is not a supported type.");
return false;
} else {
$this->debug("in serializeType: found typeDef");
$this->appendDebug('typeDef=' . $this->varDump($typeDef));
}
$phpType = $typeDef['phpType'];
$this->debug("in serializeType: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: " . (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '') );
// if php type == struct, map value to the <all> element names
if ($phpType == 'struct') {
if (isset($typeDef['typeClass']) && $typeDef['typeClass'] == 'element') {
$elementName = $uqType;
if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
$elementNS = " xmlns=\"$ns\"";
} else {
$elementNS = " xmlns=\"\"";
}
} else {
$elementName = $name;
if ($unqualified) {
$elementNS = " xmlns=\"\"";
} else {
$elementNS = '';
}
}
if (is_null($value)) {
if ($use == 'literal') {
// TODO: depends on minOccurs
$xml = "<$elementName$elementNS/>";
} else {
$xml = "<$elementName$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>";
}
$this->debug("in serializeType: returning: $xml");
return $xml;
}
if (is_object($value)) {
$value = get_object_vars($value);
}
if (is_array($value)) {
$elementAttrs = $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType);
if ($use == 'literal') {
if ($forceType) {
$xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">";
} else {
$xml = "<$elementName$elementNS$elementAttrs>";
}
} else {
$xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>";
}
$xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle);
$xml .= "</$elementName>";
} else {
$this->debug("in serializeType: phpType is struct, but value is not an array");
$this->setError("phpType is struct, but value is not an array: see debug output for details");
$xml = '';
}
} elseif ($phpType == 'array') {
if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
$elementNS = " xmlns=\"$ns\"";
} else {
if ($unqualified) {
$elementNS = " xmlns=\"\"";
} else {
$elementNS = '';
}
}
if (is_null($value)) {
if ($use == 'literal') {
// TODO: depends on minOccurs
$xml = "<$name$elementNS/>";
} else {
$xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" .
$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .
":Array\" " .
$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .
':arrayType="' .
$this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) .
':' .
$this->getLocalPart($typeDef['arrayType'])."[0]\"/>";
}
$this->debug("in serializeType: returning: $xml");
return $xml;
}
if (isset($typeDef['multidimensional'])) {
$nv = array();
foreach($value as $v) {
$cols = ',' . sizeof($v);
$nv = array_merge($nv, $v);
}
$value = $nv;
} else {
$cols = '';
}
if (is_array($value) && sizeof($value) >= 1) {
$rows = sizeof($value);
$contents = '';
foreach($value as $k => $v) {
$this->debug("serializing array element: $k, $v of type: $typeDef[arrayType]");
//if (strpos($typeDef['arrayType'], ':') ) {
if (!in_array($typeDef['arrayType'],$this->typemap['http://www.w3.org/2001/XMLSchema'])) {
$contents .= $this->serializeType('item', $typeDef['arrayType'], $v, $use);
} else {
$contents .= $this->serialize_val($v, 'item', $typeDef['arrayType'], null, $this->XMLSchemaVersion, false, $use);
}
}
} else {
$rows = 0;
$contents = null;
}
// TODO: for now, an empty value will be serialized as a zero element
// array. Revisit this when coding the handling of null/nil values.
if ($use == 'literal') {
$xml = "<$name$elementNS>"
.$contents
."</$name>";
} else {
$xml = "<$name$elementNS xsi:type=\"".$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/').':Array" '.
$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/')
.':arrayType="'
.$this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType']))
.":".$this->getLocalPart($typeDef['arrayType'])."[$rows$cols]\">"
.$contents
."</$name>";
}
} elseif ($phpType == 'scalar') {
if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
$elementNS = " xmlns=\"$ns\"";
} else {
if ($unqualified) {
$elementNS = " xmlns=\"\"";
} else {
$elementNS = '';
}
}
if ($use == 'literal') {
if ($forceType) {
$xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value</$name>";
} else {
$xml = "<$name$elementNS>$value</$name>";
}
} else {
$xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value</$name>";
}
}
$this->debug("in serializeType: returning: $xml");
return $xml;
}
/**
* serializes the attributes for a complexType
*
* @param array $typeDef our internal representation of an XML schema type (or element)
* @param mixed $value a native PHP value (parameter value)
* @param string $ns the namespace of the type
* @param string $uqType the local part of the type
* @return string value serialized as an XML string
* @access private
*/
function serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType) {
$xml = '';
if (isset($typeDef['attrs']) && is_array($typeDef['attrs'])) {
$this->debug("serialize attributes for XML Schema type $ns:$uqType");
if (is_array($value)) {
$xvalue = $value;
} elseif (is_object($value)) {
$xvalue = get_object_vars($value);
} else {
$this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
$xvalue = array();
}
foreach ($typeDef['attrs'] as $aName => $attrs) {
if (isset($xvalue['!' . $aName])) {
$xname = '!' . $aName;
$this->debug("value provided for attribute $aName with key $xname");
} elseif (isset($xvalue[$aName])) {
$xname = $aName;
$this->debug("value provided for attribute $aName with key $xname");
} elseif (isset($attrs['default'])) {
$xname = '!' . $aName;
$xvalue[$xname] = $attrs['default'];
$this->debug('use default value of ' . $xvalue[$aName] . ' for attribute ' . $aName);
} else {
$xname = '';
$this->debug("no value provided for attribute $aName");
}
if ($xname) {
$xml .= " $aName=\"" . $this->expandEntities($xvalue[$xname]) . "\"";
}
}
} else {
$this->debug("no attributes to serialize for XML Schema type $ns:$uqType");
}
if (isset($typeDef['extensionBase'])) {
$ns = $this->getPrefix($typeDef['extensionBase']);
$uqType = $this->getLocalPart($typeDef['extensionBase']);
if ($this->getNamespaceFromPrefix($ns)) {
$ns = $this->getNamespaceFromPrefix($ns);
}
if ($typeDef = $this->getTypeDef($uqType, $ns)) {
$this->debug("serialize attributes for extension base $ns:$uqType");
$xml .= $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType);
} else {
$this->debug("extension base $ns:$uqType is not a supported type");
}
}
return $xml;
}
/**
* serializes the elements for a complexType
*
* @param array $typeDef our internal representation of an XML schema type (or element)
* @param mixed $value a native PHP value (parameter value)
* @param string $ns the namespace of the type
* @param string $uqType the local part of the type
* @param string $use use for part (encoded|literal)
* @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
* @return string value serialized as an XML string
* @access private
*/
function serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use='encoded', $encodingStyle=false) {
$xml = '';
if (isset($typeDef['elements']) && is_array($typeDef['elements'])) {
$this->debug("in serializeComplexTypeElements, serialize elements for XML Schema type $ns:$uqType");
if (is_array($value)) {
$xvalue = $value;
} elseif (is_object($value)) {
$xvalue = get_object_vars($value);
} else {
$this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
$xvalue = array();
}
// toggle whether all elements are present - ideally should validate against schema
if (count($typeDef['elements']) != count($xvalue)){
$optionals = true;
}
foreach ($typeDef['elements'] as $eName => $attrs) {
if (!isset($xvalue[$eName])) {
if (isset($attrs['default'])) {
$xvalue[$eName] = $attrs['default'];
$this->debug('use default value of ' . $xvalue[$eName] . ' for element ' . $eName);
}
}
// if user took advantage of a minOccurs=0, then only serialize named parameters
if (isset($optionals)
&& (!isset($xvalue[$eName]))
&& ( (!isset($attrs['nillable'])) || $attrs['nillable'] != 'true')
){
if (isset($attrs['minOccurs']) && $attrs['minOccurs'] <> '0') {
$this->debug("apparent error: no value provided for element $eName with minOccurs=" . $attrs['minOccurs']);
}
// do nothing
$this->debug("no value provided for complexType element $eName and element is not nillable, so serialize nothing");
} else {
// get value
if (isset($xvalue[$eName])) {
$v = $xvalue[$eName];
} else {
$v = null;
}
if (isset($attrs['form'])) {
$unqualified = ($attrs['form'] == 'unqualified');
} else {
$unqualified = false;
}
if (isset($attrs['maxOccurs']) && ($attrs['maxOccurs'] == 'unbounded' || $attrs['maxOccurs'] > 1) && isset($v) && is_array($v) && $this->isArraySimpleOrStruct($v) == 'arraySimple') {
$vv = $v;
foreach ($vv as $k => $v) {
if (isset($attrs['type']) || isset($attrs['ref'])) {
// serialize schema-defined type
$xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
} else {
// serialize generic type (can this ever really happen?)
$this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
$xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
}
}
} else {
if (isset($attrs['type']) || isset($attrs['ref'])) {
// serialize schema-defined type
$xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
} else {
// serialize generic type (can this ever really happen?)
$this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
$xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
}
}
}
}
} else {
$this->debug("no elements to serialize for XML Schema type $ns:$uqType");
}
if (isset($typeDef['extensionBase'])) {
$ns = $this->getPrefix($typeDef['extensionBase']);
$uqType = $this->getLocalPart($typeDef['extensionBase']);
if ($this->getNamespaceFromPrefix($ns)) {
$ns = $this->getNamespaceFromPrefix($ns);
}
if ($typeDef = $this->getTypeDef($uqType, $ns)) {
$this->debug("serialize elements for extension base $ns:$uqType");
$xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle);
} else {
$this->debug("extension base $ns:$uqType is not a supported type");
}
}
return $xml;
}
/**
* adds an XML Schema complex type to the WSDL types
*
* @param string name
* @param string typeClass (complexType|simpleType|attribute)
* @param string phpType: currently supported are array and struct (php assoc array)
* @param string compositor (all|sequence|choice)
* @param string restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
* @param array elements = array ( name => array(name=>'',type=>'') )
* @param array attrs = array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'xsd:string[]'))
* @param string arrayType: namespace:name (xsd:string)
* @see xmlschema
* @access public
*/
function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType='') {
if (count($elements) > 0) {
foreach($elements as $n => $e){
// expand each element
foreach ($e as $k => $v) {
$k = strpos($k,':') ? $this->expandQname($k) : $k;
$v = strpos($v,':') ? $this->expandQname($v) : $v;
$ee[$k] = $v;
}
$eElements[$n] = $ee;
}
$elements = $eElements;
}
if (count($attrs) > 0) {
foreach($attrs as $n => $a){
// expand each attribute
foreach ($a as $k => $v) {
$k = strpos($k,':') ? $this->expandQname($k) : $k;
$v = strpos($v,':') ? $this->expandQname($v) : $v;
$aa[$k] = $v;
}
$eAttrs[$n] = $aa;
}
$attrs = $eAttrs;
}
$restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
$arrayType = strpos($arrayType,':') ? $this->expandQname($arrayType) : $arrayType;
$typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
$this->schemas[$typens][0]->addComplexType($name,$typeClass,$phpType,$compositor,$restrictionBase,$elements,$attrs,$arrayType);
}
/**
* adds an XML Schema simple type to the WSDL types
*
* @param string $name
* @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
* @param string $typeClass (should always be simpleType)
* @param string $phpType (should always be scalar)
* @param array $enumeration array of values
* @see xmlschema
* @access public
*/
function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
$restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
$typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
$this->schemas[$typens][0]->addSimpleType($name, $restrictionBase, $typeClass, $phpType, $enumeration);
}
/**
* adds an element to the WSDL types
*
* @param array $attrs attributes that must include name and type
* @see xmlschema
* @access public
*/
function addElement($attrs) {
$typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
$this->schemas[$typens][0]->addElement($attrs);
}
/**
* register an operation with the server
*
* @param string $name operation (method) name
* @param array $in assoc array of input values: key = param name, value = param type
* @param array $out assoc array of output values: key = param name, value = param type
* @param string $namespace optional The namespace for the operation
* @param string $soapaction optional The soapaction for the operation
* @param string $style (rpc|document) optional The style for the operation Note: when 'document' is specified, parameter and return wrappers are created for you automatically
* @param string $use (encoded|literal) optional The use for the parameters (cannot mix right now)
* @param string $documentation optional The description to include in the WSDL
* @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
* @access public
*/
function addOperation($name, $in = false, $out = false, $namespace = false, $soapaction = false, $style = 'rpc', $use = 'encoded', $documentation = '', $encodingStyle = ''){
if ($use == 'encoded' && $encodingStyle == '') {
$encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
}
if ($style == 'document') {
$elements = array();
foreach ($in as $n => $t) {
$elements[$n] = array('name' => $n, 'type' => $t);
}
$this->addComplexType($name . 'RequestType', 'complexType', 'struct', 'all', '', $elements);
$this->addElement(array('name' => $name, 'type' => $name . 'RequestType'));
$in = array('parameters' => 'tns:' . $name);
$elements = array();
foreach ($out as $n => $t) {
$elements[$n] = array('name' => $n, 'type' => $t);
}
$this->addComplexType($name . 'ResponseType', 'complexType', 'struct', 'all', '', $elements);
$this->addElement(array('name' => $name . 'Response', 'type' => $name . 'ResponseType'));
$out = array('parameters' => 'tns:' . $name . 'Response');
}
// get binding
$this->bindings[ $this->serviceName . 'Binding' ]['operations'][$name] =
array(
'name' => $name,
'binding' => $this->serviceName . 'Binding',
'endpoint' => $this->endpoint,
'soapAction' => $soapaction,
'style' => $style,
'input' => array(
'use' => $use,
'namespace' => $namespace,
'encodingStyle' => $encodingStyle,
'message' => $name . 'Request',
'parts' => $in),
'output' => array(
'use' => $use,
'namespace' => $namespace,
'encodingStyle' => $encodingStyle,
'message' => $name . 'Response',
'parts' => $out),
'namespace' => $namespace,
'transport' => 'http://schemas.xmlsoap.org/soap/http',
'documentation' => $documentation);
// add portTypes
// add messages
if($in)
{
foreach($in as $pName => $pType)
{
if(strpos($pType,':')) {
$pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
}
$this->messages[$name.'Request'][$pName] = $pType;
}
} else {
$this->messages[$name.'Request']= '0';
}
if($out)
{
foreach($out as $pName => $pType)
{
if(strpos($pType,':')) {
$pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
}
$this->messages[$name.'Response'][$pName] = $pType;
}
} else {
$this->messages[$name.'Response']= '0';
}
return true;
}
}
?> | 10npsite | trunk/Index/Lib/Order/chinabank/lib/class.wsdl.php | PHP | asf20 | 70,349 |
<?php
/**
*
* soap_server allows the user to create a SOAP server
* that is capable of receiving messages and returning responses
*
* NOTE: WSDL functionality is experimental
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: class.soap_server.php,v 1.48 2005/08/04 01:27:42 snichol Exp $
* @access public
*/
class soap_server extends nusoap_base {
/**
* HTTP headers of request
* @var array
* @access private
*/
var $headers = array();
/**
* HTTP request
* @var string
* @access private
*/
var $request = '';
/**
* SOAP headers from request (incomplete namespace resolution; special characters not escaped) (text)
* @var string
* @access public
*/
var $requestHeaders = '';
/**
* SOAP body request portion (incomplete namespace resolution; special characters not escaped) (text)
* @var string
* @access public
*/
var $document = '';
/**
* SOAP payload for request (text)
* @var string
* @access public
*/
var $requestSOAP = '';
/**
* requested method namespace URI
* @var string
* @access private
*/
var $methodURI = '';
/**
* name of method requested
* @var string
* @access private
*/
var $methodname = '';
/**
* method parameters from request
* @var array
* @access private
*/
var $methodparams = array();
/**
* SOAP Action from request
* @var string
* @access private
*/
var $SOAPAction = '';
/**
* character set encoding of incoming (request) messages
* @var string
* @access public
*/
var $xml_encoding = '';
/**
* toggles whether the parser decodes element content w/ utf8_decode()
* @var boolean
* @access public
*/
var $decode_utf8 = true;
/**
* HTTP headers of response
* @var array
* @access public
*/
var $outgoing_headers = array();
/**
* HTTP response
* @var string
* @access private
*/
var $response = '';
/**
* SOAP headers for response (text)
* @var string
* @access public
*/
var $responseHeaders = '';
/**
* SOAP payload for response (text)
* @var string
* @access private
*/
var $responseSOAP = '';
/**
* method return value to place in response
* @var mixed
* @access private
*/
var $methodreturn = false;
/**
* whether $methodreturn is a string of literal XML
* @var boolean
* @access public
*/
var $methodreturnisliteralxml = false;
/**
* SOAP fault for response (or false)
* @var mixed
* @access private
*/
var $fault = false;
/**
* text indication of result (for debugging)
* @var string
* @access private
*/
var $result = 'successful';
/**
* assoc array of operations => opData; operations are added by the register()
* method or by parsing an external WSDL definition
* @var array
* @access private
*/
var $operations = array();
/**
* wsdl instance (if one)
* @var mixed
* @access private
*/
var $wsdl = false;
/**
* URL for WSDL (if one)
* @var mixed
* @access private
*/
var $externalWSDLURL = false;
/**
* whether to append debug to response as XML comment
* @var boolean
* @access public
*/
var $debug_flag = false;
/**
* constructor
* the optional parameter is a path to a WSDL file that you'd like to bind the server instance to.
*
* @param mixed $wsdl file path or URL (string), or wsdl instance (object)
* @access public
*/
function soap_server($wsdl=false){
parent::nusoap_base();
// turn on debugging?
global $debug;
global $HTTP_SERVER_VARS;
if (isset($_SERVER)) {
$this->debug("_SERVER is defined:");
$this->appendDebug($this->varDump($_SERVER));
} elseif (isset($HTTP_SERVER_VARS)) {
$this->debug("HTTP_SERVER_VARS is defined:");
$this->appendDebug($this->varDump($HTTP_SERVER_VARS));
} else {
$this->debug("Neither _SERVER nor HTTP_SERVER_VARS is defined.");
}
if (isset($debug)) {
$this->debug("In soap_server, set debug_flag=$debug based on global flag");
$this->debug_flag = $debug;
} elseif (isset($_SERVER['QUERY_STRING'])) {
$qs = explode('&', $_SERVER['QUERY_STRING']);
foreach ($qs as $v) {
if (substr($v, 0, 6) == 'debug=') {
$this->debug("In soap_server, set debug_flag=" . substr($v, 6) . " based on query string #1");
$this->debug_flag = substr($v, 6);
}
}
} elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
$qs = explode('&', $HTTP_SERVER_VARS['QUERY_STRING']);
foreach ($qs as $v) {
if (substr($v, 0, 6) == 'debug=') {
$this->debug("In soap_server, set debug_flag=" . substr($v, 6) . " based on query string #2");
$this->debug_flag = substr($v, 6);
}
}
}
// wsdl
if($wsdl){
$this->debug("In soap_server, WSDL is specified");
if (is_object($wsdl) && (get_class($wsdl) == 'wsdl')) {
$this->wsdl = $wsdl;
$this->externalWSDLURL = $this->wsdl->wsdl;
$this->debug('Use existing wsdl instance from ' . $this->externalWSDLURL);
} else {
$this->debug('Create wsdl from ' . $wsdl);
$this->wsdl = new wsdl($wsdl);
$this->externalWSDLURL = $wsdl;
}
$this->appendDebug($this->wsdl->getDebug());
$this->wsdl->clearDebug();
if($err = $this->wsdl->getError()){
die('WSDL ERROR: '.$err);
}
}
}
/**
* processes request and returns response
*
* @param string $data usually is the value of $HTTP_RAW_POST_DATA
* @access public
*/
function service($data){
global $HTTP_SERVER_VARS;
if (isset($_SERVER['QUERY_STRING'])) {
$qs = $_SERVER['QUERY_STRING'];
} elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
$qs = $HTTP_SERVER_VARS['QUERY_STRING'];
} else {
$qs = '';
}
$this->debug("In service, query string=$qs");
if (ereg('wsdl', $qs) ){
$this->debug("In service, this is a request for WSDL");
if($this->externalWSDLURL){
if (strpos($this->externalWSDLURL,"://")!==false) { // assume URL
header('Location: '.$this->externalWSDLURL);
} else { // assume file
header("Content-Type: text/xml\r\n");
$fp = fopen($this->externalWSDLURL, 'r');
fpassthru($fp);
}
} elseif ($this->wsdl) {
header("Content-Type: text/xml; charset=ISO-8859-1\r\n");
print $this->wsdl->serialize($this->debug_flag);
if ($this->debug_flag) {
$this->debug('wsdl:');
$this->appendDebug($this->varDump($this->wsdl));
print $this->getDebugAsXMLComment();
}
} else {
header("Content-Type: text/html; charset=ISO-8859-1\r\n");
print "This service does not provide WSDL";
}
} elseif ($data == '' && $this->wsdl) {
$this->debug("In service, there is no data, so return Web description");
print $this->wsdl->webDescription();
} else {
$this->debug("In service, invoke the request");
$this->parse_request($data);
if (! $this->fault) {
$this->invoke_method();
}
if (! $this->fault) {
$this->serialize_return();
}
$this->send_response();
}
}
/**
* parses HTTP request headers.
*
* The following fields are set by this function (when successful)
*
* headers
* request
* xml_encoding
* SOAPAction
*
* @access private
*/
function parse_http_headers() {
global $HTTP_SERVER_VARS;
$this->request = '';
$this->SOAPAction = '';
if(function_exists('getallheaders')){
$this->debug("In parse_http_headers, use getallheaders");
$headers = getallheaders();
foreach($headers as $k=>$v){
$k = strtolower($k);
$this->headers[$k] = $v;
$this->request .= "$k: $v\r\n";
$this->debug("$k: $v");
}
// get SOAPAction header
if(isset($this->headers['soapaction'])){
$this->SOAPAction = str_replace('"','',$this->headers['soapaction']);
}
// get the character encoding of the incoming request
if(isset($this->headers['content-type']) && strpos($this->headers['content-type'],'=')){
$enc = str_replace('"','',substr(strstr($this->headers["content-type"],'='),1));
if(eregi('^(ISO-8859-1|US-ASCII|UTF-8)$',$enc)){
$this->xml_encoding = strtoupper($enc);
} else {
$this->xml_encoding = 'US-ASCII';
}
} else {
// should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
$this->xml_encoding = 'ISO-8859-1';
}
} elseif(isset($_SERVER) && is_array($_SERVER)){
$this->debug("In parse_http_headers, use _SERVER");
foreach ($_SERVER as $k => $v) {
if (substr($k, 0, 5) == 'HTTP_') {
$k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5));
} else {
$k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k);
}
if ($k == 'soapaction') {
// get SOAPAction header
$k = 'SOAPAction';
$v = str_replace('"', '', $v);
$v = str_replace('\\', '', $v);
$this->SOAPAction = $v;
} else if ($k == 'content-type') {
// get the character encoding of the incoming request
if (strpos($v, '=')) {
$enc = substr(strstr($v, '='), 1);
$enc = str_replace('"', '', $enc);
$enc = str_replace('\\', '', $enc);
if (eregi('^(ISO-8859-1|US-ASCII|UTF-8)$', $enc)) {
$this->xml_encoding = strtoupper($enc);
} else {
$this->xml_encoding = 'US-ASCII';
}
} else {
// should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
$this->xml_encoding = 'ISO-8859-1';
}
}
$this->headers[$k] = $v;
$this->request .= "$k: $v\r\n";
$this->debug("$k: $v");
}
} elseif (is_array($HTTP_SERVER_VARS)) {
$this->debug("In parse_http_headers, use HTTP_SERVER_VARS");
foreach ($HTTP_SERVER_VARS as $k => $v) {
if (substr($k, 0, 5) == 'HTTP_') {
$k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5));
} else {
$k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k);
}
if ($k == 'soapaction') {
// get SOAPAction header
$k = 'SOAPAction';
$v = str_replace('"', '', $v);
$v = str_replace('\\', '', $v);
$this->SOAPAction = $v;
} else if ($k == 'content-type') {
// get the character encoding of the incoming request
if (strpos($v, '=')) {
$enc = substr(strstr($v, '='), 1);
$enc = str_replace('"', '', $enc);
$enc = str_replace('\\', '', $enc);
if (eregi('^(ISO-8859-1|US-ASCII|UTF-8)$', $enc)) {
$this->xml_encoding = strtoupper($enc);
} else {
$this->xml_encoding = 'US-ASCII';
}
} else {
// should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
$this->xml_encoding = 'ISO-8859-1';
}
}
$this->headers[$k] = $v;
$this->request .= "$k: $v\r\n";
$this->debug("$k: $v");
}
} else {
$this->debug("In parse_http_headers, HTTP headers not accessible");
$this->setError("HTTP headers not accessible");
}
}
/**
* parses a request
*
* The following fields are set by this function (when successful)
*
* headers
* request
* xml_encoding
* SOAPAction
* request
* requestSOAP
* methodURI
* methodname
* methodparams
* requestHeaders
* document
*
* This sets the fault field on error
*
* @param string $data XML string
* @access private
*/
function parse_request($data='') {
$this->debug('entering parse_request()');
$this->parse_http_headers();
$this->debug('got character encoding: '.$this->xml_encoding);
// uncompress if necessary
if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] != '') {
$this->debug('got content encoding: ' . $this->headers['content-encoding']);
if ($this->headers['content-encoding'] == 'deflate' || $this->headers['content-encoding'] == 'gzip') {
// if decoding works, use it. else assume data wasn't gzencoded
if (function_exists('gzuncompress')) {
if ($this->headers['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
$data = $degzdata;
} elseif ($this->headers['content-encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))) {
$data = $degzdata;
} else {
$this->fault('Client', 'Errors occurred when trying to decode the data');
return;
}
} else {
$this->fault('Client', 'This Server does not support compressed data');
return;
}
}
}
$this->request .= "\r\n".$data;
$data = $this->parseRequest($this->headers, $data);
$this->requestSOAP = $data;
$this->debug('leaving parse_request');
}
/**
* invokes a PHP function for the requested SOAP method
*
* The following fields are set by this function (when successful)
*
* methodreturn
*
* Note that the PHP function that is called may also set the following
* fields to affect the response sent to the client
*
* responseHeaders
* outgoing_headers
*
* This sets the fault field on error
*
* @access private
*/
function invoke_method() {
$this->debug('in invoke_method, methodname=' . $this->methodname . ' methodURI=' . $this->methodURI . ' SOAPAction=' . $this->SOAPAction);
if ($this->wsdl) {
if ($this->opData = $this->wsdl->getOperationData($this->methodname)) {
$this->debug('in invoke_method, found WSDL operation=' . $this->methodname);
$this->appendDebug('opData=' . $this->varDump($this->opData));
} elseif ($this->opData = $this->wsdl->getOperationDataForSoapAction($this->SOAPAction)) {
// Note: hopefully this case will only be used for doc/lit, since rpc services should have wrapper element
$this->debug('in invoke_method, found WSDL soapAction=' . $this->SOAPAction . ' for operation=' . $this->opData['name']);
$this->appendDebug('opData=' . $this->varDump($this->opData));
$this->methodname = $this->opData['name'];
} else {
$this->debug('in invoke_method, no WSDL for operation=' . $this->methodname);
$this->fault('Client', "Operation '" . $this->methodname . "' is not defined in the WSDL for this service");
return;
}
} else {
$this->debug('in invoke_method, no WSDL to validate method');
}
// if a . is present in $this->methodname, we see if there is a class in scope,
// which could be referred to. We will also distinguish between two deliminators,
// to allow methods to be called a the class or an instance
$class = '';
$method = '';
if (strpos($this->methodname, '..') > 0) {
$delim = '..';
} else if (strpos($this->methodname, '.') > 0) {
$delim = '.';
} else {
$delim = '';
}
if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1 &&
class_exists(substr($this->methodname, 0, strpos($this->methodname, $delim)))) {
// get the class and method name
$class = substr($this->methodname, 0, strpos($this->methodname, $delim));
$method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim));
$this->debug("in invoke_method, class=$class method=$method delim=$delim");
}
// does method exist?
if ($class == '') {
if (!function_exists($this->methodname)) {
$this->debug("in invoke_method, function '$this->methodname' not found!");
$this->result = 'fault: method not found';
$this->fault('Client',"method '$this->methodname' not defined in service");
return;
}
} else {
$method_to_compare = (substr(phpversion(), 0, 2) == '4.') ? strtolower($method) : $method;
if (!in_array($method_to_compare, get_class_methods($class))) {
$this->debug("in invoke_method, method '$this->methodname' not found in class '$class'!");
$this->result = 'fault: method not found';
$this->fault('Client',"method '$this->methodname' not defined in service");
return;
}
}
// evaluate message, getting back parameters
// verify that request parameters match the method's signature
if(! $this->verify_method($this->methodname,$this->methodparams)){
// debug
$this->debug('ERROR: request not verified against method signature');
$this->result = 'fault: request failed validation against method signature';
// return fault
$this->fault('Client',"Operation '$this->methodname' not defined in service.");
return;
}
// if there are parameters to pass
$this->debug('in invoke_method, params:');
$this->appendDebug($this->varDump($this->methodparams));
$this->debug("in invoke_method, calling '$this->methodname'");
if (!function_exists('call_user_func_array')) {
if ($class == '') {
$this->debug('in invoke_method, calling function using eval()');
$funcCall = "\$this->methodreturn = $this->methodname(";
} else {
if ($delim == '..') {
$this->debug('in invoke_method, calling class method using eval()');
$funcCall = "\$this->methodreturn = ".$class."::".$method."(";
} else {
$this->debug('in invoke_method, calling instance method using eval()');
// generate unique instance name
$instname = "\$inst_".time();
$funcCall = $instname." = new ".$class."(); ";
$funcCall .= "\$this->methodreturn = ".$instname."->".$method."(";
}
}
if ($this->methodparams) {
foreach ($this->methodparams as $param) {
if (is_array($param)) {
$this->fault('Client', 'NuSOAP does not handle complexType parameters correctly when using eval; call_user_func_array must be available');
return;
}
$funcCall .= "\"$param\",";
}
$funcCall = substr($funcCall, 0, -1);
}
$funcCall .= ');';
$this->debug('in invoke_method, function call: '.$funcCall);
@eval($funcCall);
} else {
if ($class == '') {
$this->debug('in invoke_method, calling function using call_user_func_array()');
$call_arg = "$this->methodname"; // straight assignment changes $this->methodname to lower case after call_user_func_array()
} elseif ($delim == '..') {
$this->debug('in invoke_method, calling class method using call_user_func_array()');
$call_arg = array ($class, $method);
} else {
$this->debug('in invoke_method, calling instance method using call_user_func_array()');
$instance = new $class ();
$call_arg = array(&$instance, $method);
}
$this->methodreturn = call_user_func_array($call_arg, $this->methodparams);
}
$this->debug('in invoke_method, methodreturn:');
$this->appendDebug($this->varDump($this->methodreturn));
$this->debug("in invoke_method, called method $this->methodname, received $this->methodreturn of type ".gettype($this->methodreturn));
}
/**
* serializes the return value from a PHP function into a full SOAP Envelope
*
* The following fields are set by this function (when successful)
*
* responseSOAP
*
* This sets the fault field on error
*
* @access private
*/
function serialize_return() {
$this->debug('Entering serialize_return methodname: ' . $this->methodname . ' methodURI: ' . $this->methodURI);
// if fault
if (isset($this->methodreturn) && (get_class($this->methodreturn) == 'soap_fault')) {
$this->debug('got a fault object from method');
$this->fault = $this->methodreturn;
return;
} elseif ($this->methodreturnisliteralxml) {
$return_val = $this->methodreturn;
// returned value(s)
} else {
$this->debug('got a(n) '.gettype($this->methodreturn).' from method');
$this->debug('serializing return value');
if($this->wsdl){
// weak attempt at supporting multiple output params
if(sizeof($this->opData['output']['parts']) > 1){
$opParams = $this->methodreturn;
} else {
// TODO: is this really necessary?
$opParams = array($this->methodreturn);
}
$return_val = $this->wsdl->serializeRPCParameters($this->methodname,'output',$opParams);
$this->appendDebug($this->wsdl->getDebug());
$this->wsdl->clearDebug();
if($errstr = $this->wsdl->getError()){
$this->debug('got wsdl error: '.$errstr);
$this->fault('Server', 'unable to serialize result');
return;
}
} else {
if (isset($this->methodreturn)) {
$return_val = $this->serialize_val($this->methodreturn, 'return');
} else {
$return_val = '';
$this->debug('in absence of WSDL, assume void return for backward compatibility');
}
}
}
$this->debug('return value:');
$this->appendDebug($this->varDump($return_val));
$this->debug('serializing response');
if ($this->wsdl) {
$this->debug('have WSDL for serialization: style is ' . $this->opData['style']);
if ($this->opData['style'] == 'rpc') {
$this->debug('style is rpc for serialization: use is ' . $this->opData['output']['use']);
if ($this->opData['output']['use'] == 'literal') {
$payload = '<'.$this->methodname.'Response xmlns="'.$this->methodURI.'">'.$return_val.'</'.$this->methodname."Response>";
} else {
$payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
}
} else {
$this->debug('style is not rpc for serialization: assume document');
$payload = $return_val;
}
} else {
$this->debug('do not have WSDL for serialization: assume rpc/encoded');
$payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
}
$this->result = 'successful';
if($this->wsdl){
//if($this->debug_flag){
$this->appendDebug($this->wsdl->getDebug());
// }
if (isset($opData['output']['encodingStyle'])) {
$encodingStyle = $opData['output']['encodingStyle'];
} else {
$encodingStyle = '';
}
// Added: In case we use a WSDL, return a serialized env. WITH the usedNamespaces.
$this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders,$this->wsdl->usedNamespaces,$this->opData['style'],$encodingStyle);
} else {
$this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders);
}
$this->debug("Leaving serialize_return");
}
/**
* sends an HTTP response
*
* The following fields are set by this function (when successful)
*
* outgoing_headers
* response
*
* @access private
*/
function send_response() {
$this->debug('Enter send_response');
if ($this->fault) {
$payload = $this->fault->serialize();
$this->outgoing_headers[] = "HTTP/1.0 500 Internal Server Error";
$this->outgoing_headers[] = "Status: 500 Internal Server Error";
} else {
$payload = $this->responseSOAP;
// Some combinations of PHP+Web server allow the Status
// to come through as a header. Since OK is the default
// just do nothing.
// $this->outgoing_headers[] = "HTTP/1.0 200 OK";
// $this->outgoing_headers[] = "Status: 200 OK";
}
// add debug data if in debug mode
if(isset($this->debug_flag) && $this->debug_flag){
$payload .= $this->getDebugAsXMLComment();
}
$this->outgoing_headers[] = "Server: $this->title Server v$this->version";
ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev);
$this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".$rev[1].")";
// Let the Web server decide about this
//$this->outgoing_headers[] = "Connection: Close\r\n";
$payload = $this->getHTTPBody($payload);
$type = $this->getHTTPContentType();
$charset = $this->getHTTPContentTypeCharset();
$this->outgoing_headers[] = "Content-Type: $type" . ($charset ? '; charset=' . $charset : '');
//begin code to compress payload - by John
// NOTE: there is no way to know whether the Web server will also compress
// this data.
if (strlen($payload) > 1024 && isset($this->headers) && isset($this->headers['accept-encoding'])) {
if (strstr($this->headers['accept-encoding'], 'gzip')) {
if (function_exists('gzencode')) {
if (isset($this->debug_flag) && $this->debug_flag) {
$payload .= "<!-- Content being gzipped -->";
}
$this->outgoing_headers[] = "Content-Encoding: gzip";
$payload = gzencode($payload);
} else {
if (isset($this->debug_flag) && $this->debug_flag) {
$payload .= "<!-- Content will not be gzipped: no gzencode -->";
}
}
} elseif (strstr($this->headers['accept-encoding'], 'deflate')) {
// Note: MSIE requires gzdeflate output (no Zlib header and checksum),
// instead of gzcompress output,
// which conflicts with HTTP 1.1 spec (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5)
if (function_exists('gzdeflate')) {
if (isset($this->debug_flag) && $this->debug_flag) {
$payload .= "<!-- Content being deflated -->";
}
$this->outgoing_headers[] = "Content-Encoding: deflate";
$payload = gzdeflate($payload);
} else {
if (isset($this->debug_flag) && $this->debug_flag) {
$payload .= "<!-- Content will not be deflated: no gzcompress -->";
}
}
}
}
//end code
$this->outgoing_headers[] = "Content-Length: ".strlen($payload);
reset($this->outgoing_headers);
foreach($this->outgoing_headers as $hdr){
header($hdr, false);
}
print $payload;
$this->response = join("\r\n",$this->outgoing_headers)."\r\n\r\n".$payload;
}
/**
* takes the value that was created by parsing the request
* and compares to the method's signature, if available.
*
* @param string $operation The operation to be invoked
* @param array $request The array of parameter values
* @return boolean Whether the operation was found
* @access private
*/
function verify_method($operation,$request){
if(isset($this->wsdl) && is_object($this->wsdl)){
if($this->wsdl->getOperationData($operation)){
return true;
}
} elseif(isset($this->operations[$operation])){
return true;
}
return false;
}
/**
* processes SOAP message received from client
*
* @param array $headers The HTTP headers
* @param string $data unprocessed request data from client
* @return mixed value of the message, decoded into a PHP type
* @access private
*/
function parseRequest($headers, $data) {
$this->debug('Entering parseRequest() for data of length ' . strlen($data) . ' and type ' . $headers['content-type']);
if (!strstr($headers['content-type'], 'text/xml')) {
$this->setError('Request not of type text/xml');
return false;
}
if (strpos($headers['content-type'], '=')) {
$enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1));
$this->debug('Got response encoding: ' . $enc);
if(eregi('^(ISO-8859-1|US-ASCII|UTF-8)$',$enc)){
$this->xml_encoding = strtoupper($enc);
} else {
$this->xml_encoding = 'US-ASCII';
}
} else {
// should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
$this->xml_encoding = 'ISO-8859-1';
}
$this->debug('Use encoding: ' . $this->xml_encoding . ' when creating soap_parser');
// parse response, get soap parser obj
$parser = new soap_parser($data,$this->xml_encoding,'',$this->decode_utf8);
// parser debug
$this->debug("parser debug: \n".$parser->getDebug());
// if fault occurred during message parsing
if($err = $parser->getError()){
$this->result = 'fault: error in msg parsing: '.$err;
$this->fault('Client',"error in msg parsing:\n".$err);
// else successfully parsed request into soapval object
} else {
// get/set methodname
$this->methodURI = $parser->root_struct_namespace;
$this->methodname = $parser->root_struct_name;
$this->debug('methodname: '.$this->methodname.' methodURI: '.$this->methodURI);
$this->debug('calling parser->get_response()');
$this->methodparams = $parser->get_response();
// get SOAP headers
$this->requestHeaders = $parser->getHeaders();
// add document for doclit support
$this->document = $parser->document;
}
}
/**
* gets the HTTP body for the current response.
*
* @param string $soapmsg The SOAP payload
* @return string The HTTP body, which includes the SOAP payload
* @access private
*/
function getHTTPBody($soapmsg) {
return $soapmsg;
}
/**
* gets the HTTP content type for the current response.
*
* Note: getHTTPBody must be called before this.
*
* @return string the HTTP content type for the current response.
* @access private
*/
function getHTTPContentType() {
return 'text/xml';
}
/**
* gets the HTTP content type charset for the current response.
* returns false for non-text content types.
*
* Note: getHTTPBody must be called before this.
*
* @return string the HTTP content type charset for the current response.
* @access private
*/
function getHTTPContentTypeCharset() {
return $this->soap_defencoding;
}
/**
* add a method to the dispatch map (this has been replaced by the register method)
*
* @param string $methodname
* @param string $in array of input values
* @param string $out array of output values
* @access public
* @deprecated
*/
function add_to_map($methodname,$in,$out){
$this->operations[$methodname] = array('name' => $methodname,'in' => $in,'out' => $out);
}
/**
* register a service function with the server
*
* @param string $name the name of the PHP function, class.method or class..method
* @param array $in assoc array of input values: key = param name, value = param type
* @param array $out assoc array of output values: key = param name, value = param type
* @param mixed $namespace the element namespace for the method or false
* @param mixed $soapaction the soapaction for the method or false
* @param mixed $style optional (rpc|document) or false Note: when 'document' is specified, parameter and return wrappers are created for you automatically
* @param mixed $use optional (encoded|literal) or false
* @param string $documentation optional Description to include in WSDL
* @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
* @access public
*/
function register($name,$in=array(),$out=array(),$namespace=false,$soapaction=false,$style=false,$use=false,$documentation='',$encodingStyle=''){
global $HTTP_SERVER_VARS;
if($this->externalWSDLURL){
die('You cannot bind to an external WSDL file, and register methods outside of it! Please choose either WSDL or no WSDL.');
}
if (! $name) {
die('You must specify a name when you register an operation');
}
if (!is_array($in)) {
die('You must provide an array for operation inputs');
}
if (!is_array($out)) {
die('You must provide an array for operation outputs');
}
if(false == $namespace) {
}
if(false == $soapaction) {
if (isset($_SERVER)) {
$SERVER_NAME = $_SERVER['SERVER_NAME'];
$SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
} elseif (isset($HTTP_SERVER_VARS)) {
$SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME'];
$SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME'];
} else {
$this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
}
$soapaction = "http://$SERVER_NAME$SCRIPT_NAME/$name";
}
if(false == $style) {
$style = "rpc";
}
if(false == $use) {
$use = "encoded";
}
if ($use == 'encoded' && $encodingStyle = '') {
$encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
}
$this->operations[$name] = array(
'name' => $name,
'in' => $in,
'out' => $out,
'namespace' => $namespace,
'soapaction' => $soapaction,
'style' => $style);
if($this->wsdl){
$this->wsdl->addOperation($name,$in,$out,$namespace,$soapaction,$style,$use,$documentation,$encodingStyle);
}
return true;
}
/**
* Specify a fault to be returned to the client.
* This also acts as a flag to the server that a fault has occured.
*
* @param string $faultcode
* @param string $faultstring
* @param string $faultactor
* @param string $faultdetail
* @access public
*/
function fault($faultcode,$faultstring,$faultactor='',$faultdetail=''){
if ($faultdetail == '' && $this->debug_flag) {
$faultdetail = $this->getDebug();
}
$this->fault = new soap_fault($faultcode,$faultactor,$faultstring,$faultdetail);
$this->fault->soap_defencoding = $this->soap_defencoding;
}
/**
* Sets up wsdl object.
* Acts as a flag to enable internal WSDL generation
*
* @param string $serviceName, name of the service
* @param mixed $namespace optional 'tns' service namespace or false
* @param mixed $endpoint optional URL of service endpoint or false
* @param string $style optional (rpc|document) WSDL style (also specified by operation)
* @param string $transport optional SOAP transport
* @param mixed $schemaTargetNamespace optional 'types' targetNamespace for service schema or false
*/
function configureWSDL($serviceName,$namespace = false,$endpoint = false,$style='rpc', $transport = 'http://schemas.xmlsoap.org/soap/http', $schemaTargetNamespace = false)
{
global $HTTP_SERVER_VARS;
if (isset($_SERVER)) {
$SERVER_NAME = $_SERVER['SERVER_NAME'];
$SERVER_PORT = $_SERVER['SERVER_PORT'];
$SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
$HTTPS = $_SERVER['HTTPS'];
} elseif (isset($HTTP_SERVER_VARS)) {
$SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME'];
$SERVER_PORT = $HTTP_SERVER_VARS['SERVER_PORT'];
$SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME'];
$HTTPS = $HTTP_SERVER_VARS['HTTPS'];
} else {
$this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
}
if ($SERVER_PORT == 80) {
$SERVER_PORT = '';
} else {
$SERVER_PORT = ':' . $SERVER_PORT;
}
if(false == $namespace) {
$namespace = "http://$SERVER_NAME/soap/$serviceName";
}
if(false == $endpoint) {
if ($HTTPS == '1' || $HTTPS == 'on') {
$SCHEME = 'https';
} else {
$SCHEME = 'http';
}
$endpoint = "$SCHEME://$SERVER_NAME$SERVER_PORT$SCRIPT_NAME";
}
if(false == $schemaTargetNamespace) {
$schemaTargetNamespace = $namespace;
}
$this->wsdl = new wsdl;
$this->wsdl->serviceName = $serviceName;
$this->wsdl->endpoint = $endpoint;
$this->wsdl->namespaces['tns'] = $namespace;
$this->wsdl->namespaces['soap'] = 'http://schemas.xmlsoap.org/wsdl/soap/';
$this->wsdl->namespaces['wsdl'] = 'http://schemas.xmlsoap.org/wsdl/';
if ($schemaTargetNamespace != $namespace) {
$this->wsdl->namespaces['types'] = $schemaTargetNamespace;
}
$this->wsdl->schemas[$schemaTargetNamespace][0] = new xmlschema('', '', $this->wsdl->namespaces);
$this->wsdl->schemas[$schemaTargetNamespace][0]->schemaTargetNamespace = $schemaTargetNamespace;
$this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/soap/encoding/'][0] = array('location' => '', 'loaded' => true);
$this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/wsdl/'][0] = array('location' => '', 'loaded' => true);
$this->wsdl->bindings[$serviceName.'Binding'] = array(
'name'=>$serviceName.'Binding',
'style'=>$style,
'transport'=>$transport,
'portType'=>$serviceName.'PortType');
$this->wsdl->ports[$serviceName.'Port'] = array(
'binding'=>$serviceName.'Binding',
'location'=>$endpoint,
'bindingType'=>'http://schemas.xmlsoap.org/wsdl/soap/');
}
}
?> | 10npsite | trunk/Index/Lib/Order/chinabank/lib/class.soap_server.php | PHP | asf20 | 36,568 |
<?php
/**
* For creating serializable abstractions of native PHP types. This class
* allows element name/namespace, XSD type, and XML attributes to be
* associated with a value. This is extremely useful when WSDL is not
* used, but is also useful when WSDL is used with polymorphic types, including
* xsd:anyType and user-defined types.
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: class.soap_val.php,v 1.9 2005/07/27 19:24:42 snichol Exp $
* @access public
*/
class soapval extends nusoap_base {
/**
* The XML element name
*
* @var string
* @access private
*/
var $name;
/**
* The XML type name (string or false)
*
* @var mixed
* @access private
*/
var $type;
/**
* The PHP value
*
* @var mixed
* @access private
*/
var $value;
/**
* The XML element namespace (string or false)
*
* @var mixed
* @access private
*/
var $element_ns;
/**
* The XML type namespace (string or false)
*
* @var mixed
* @access private
*/
var $type_ns;
/**
* The XML element attributes (array or false)
*
* @var mixed
* @access private
*/
var $attributes;
/**
* constructor
*
* @param string $name optional name
* @param mixed $type optional type name
* @param mixed $value optional value
* @param mixed $element_ns optional namespace of value
* @param mixed $type_ns optional namespace of type
* @param mixed $attributes associative array of attributes to add to element serialization
* @access public
*/
function soapval($name='soapval',$type=false,$value=-1,$element_ns=false,$type_ns=false,$attributes=false) {
parent::nusoap_base();
$this->name = $name;
$this->type = $type;
$this->value = $value;
$this->element_ns = $element_ns;
$this->type_ns = $type_ns;
$this->attributes = $attributes;
}
/**
* return serialized value
*
* @param string $use The WSDL use value (encoded|literal)
* @return string XML data
* @access public
*/
function serialize($use='encoded') {
return $this->serialize_val($this->value,$this->name,$this->type,$this->element_ns,$this->type_ns,$this->attributes,$use);
}
/**
* decodes a soapval object into a PHP native type
*
* @return mixed
* @access public
*/
function decode(){
return $this->value;
}
}
?> | 10npsite | trunk/Index/Lib/Order/chinabank/lib/class.soap_val.php | PHP | asf20 | 2,393 |
<?php
/*
$Id: class.nusoap_base.php,v 1.43 2005/08/04 01:27:42 snichol Exp $
NuSOAP - Web Services Toolkit for PHP
Copyright (c) 2002 NuSphere Corporation
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you have any questions or comments, please email:
Dietrich Ayala
dietrich@ganx4.com
http://dietrich.ganx4.com/nusoap
NuSphere Corporation
http://www.nusphere.com
*/
/* load classes
// necessary classes
require_once('class.soapclientw.php');
require_once('class.soap_val.php');
require_once('class.soap_parser.php');
require_once('class.soap_fault.php');
// transport classes
require_once('class.soap_transport_http.php');
// optional add-on classes
require_once('class.xmlschema.php');
require_once('class.wsdl.php');
// server class
require_once('class.soap_server.php');*/
// class variable emulation
// cf. http://www.webkreator.com/php/techniques/php-static-class-variables.html
$GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel = 9;
/**
*
* nusoap_base
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: class.nusoap_base.php,v 1.43 2005/08/04 01:27:42 snichol Exp $
* @access public
*/
class nusoap_base {
/**
* Identification for HTTP headers.
*
* @var string
* @access private
*/
var $title = 'NuSOAP';
/**
* Version for HTTP headers.
*
* @var string
* @access private
*/
var $version = '0.7.2';
/**
* CVS revision for HTTP headers.
*
* @var string
* @access private
*/
var $revision = '$Revision: 1.43 $';
/**
* Current error string (manipulated by getError/setError)
*
* @var string
* @access private
*/
var $error_str = '';
/**
* Current debug string (manipulated by debug/appendDebug/clearDebug/getDebug/getDebugAsXMLComment)
*
* @var string
* @access private
*/
var $debug_str = '';
/**
* toggles automatic encoding of special characters as entities
* (should always be true, I think)
*
* @var boolean
* @access private
*/
var $charencoding = true;
/**
* the debug level for this instance
*
* @var integer
* @access private
*/
var $debugLevel;
/**
* set schema version
*
* @var string
* @access public
*/
var $XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema';
/**
* charset encoding for outgoing messages
*
* @var string
* @access public
*/
var $soap_defencoding = 'ISO-8859-1';
//var $soap_defencoding = 'UTF-8';
/**
* namespaces in an array of prefix => uri
*
* this is "seeded" by a set of constants, but it may be altered by code
*
* @var array
* @access public
*/
var $namespaces = array(
'SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/',
'xsd' => 'http://www.w3.org/2001/XMLSchema',
'xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/'
);
/**
* namespaces used in the current context, e.g. during serialization
*
* @var array
* @access private
*/
var $usedNamespaces = array();
/**
* XML Schema types in an array of uri => (array of xml type => php type)
* is this legacy yet?
* no, this is used by the xmlschema class to verify type => namespace mappings.
* @var array
* @access public
*/
var $typemap = array(
'http://www.w3.org/2001/XMLSchema' => array(
'string'=>'string','boolean'=>'boolean','float'=>'double','double'=>'double','decimal'=>'double',
'duration'=>'','dateTime'=>'string','time'=>'string','date'=>'string','gYearMonth'=>'',
'gYear'=>'','gMonthDay'=>'','gDay'=>'','gMonth'=>'','hexBinary'=>'string','base64Binary'=>'string',
// abstract "any" types
'anyType'=>'string','anySimpleType'=>'string',
// derived datatypes
'normalizedString'=>'string','token'=>'string','language'=>'','NMTOKEN'=>'','NMTOKENS'=>'','Name'=>'','NCName'=>'','ID'=>'',
'IDREF'=>'','IDREFS'=>'','ENTITY'=>'','ENTITIES'=>'','integer'=>'integer','nonPositiveInteger'=>'integer',
'negativeInteger'=>'integer','long'=>'integer','int'=>'integer','short'=>'integer','byte'=>'integer','nonNegativeInteger'=>'integer',
'unsignedLong'=>'','unsignedInt'=>'','unsignedShort'=>'','unsignedByte'=>'','positiveInteger'=>''),
'http://www.w3.org/2000/10/XMLSchema' => array(
'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double',
'float'=>'double','dateTime'=>'string',
'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'),
'http://www.w3.org/1999/XMLSchema' => array(
'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double',
'float'=>'double','dateTime'=>'string',
'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'),
'http://soapinterop.org/xsd' => array('SOAPStruct'=>'struct'),
'http://schemas.xmlsoap.org/soap/encoding/' => array('base64'=>'string','array'=>'array','Array'=>'array'),
'http://xml.apache.org/xml-soap' => array('Map')
);
/**
* XML entities to convert
*
* @var array
* @access public
* @deprecated
* @see expandEntities
*/
var $xmlEntities = array('quot' => '"','amp' => '&',
'lt' => '<','gt' => '>','apos' => "'");
/**
* constructor
*
* @access public
*/
function nusoap_base() {
$this->debugLevel = $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel;
}
/**
* gets the global debug level, which applies to future instances
*
* @return integer Debug level 0-9, where 0 turns off
* @access public
*/
function getGlobalDebugLevel() {
return $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel;
}
/**
* sets the global debug level, which applies to future instances
*
* @param int $level Debug level 0-9, where 0 turns off
* @access public
*/
function setGlobalDebugLevel($level) {
$GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel = $level;
}
/**
* gets the debug level for this instance
*
* @return int Debug level 0-9, where 0 turns off
* @access public
*/
function getDebugLevel() {
return $this->debugLevel;
}
/**
* sets the debug level for this instance
*
* @param int $level Debug level 0-9, where 0 turns off
* @access public
*/
function setDebugLevel($level) {
$this->debugLevel = $level;
}
/**
* adds debug data to the instance debug string with formatting
*
* @param string $string debug data
* @access private
*/
function debug($string){
if ($this->debugLevel > 0) {
$this->appendDebug($this->getmicrotime().' '.get_class($this).": $string\n");
}
}
/**
* adds debug data to the instance debug string without formatting
*
* @param string $string debug data
* @access public
*/
function appendDebug($string){
if ($this->debugLevel > 0) {
// it would be nice to use a memory stream here to use
// memory more efficiently
$this->debug_str .= $string;
}
}
/**
* clears the current debug data for this instance
*
* @access public
*/
function clearDebug() {
// it would be nice to use a memory stream here to use
// memory more efficiently
$this->debug_str = '';
}
/**
* gets the current debug data for this instance
*
* @return debug data
* @access public
*/
function &getDebug() {
// it would be nice to use a memory stream here to use
// memory more efficiently
return $this->debug_str;
}
/**
* gets the current debug data for this instance as an XML comment
* this may change the contents of the debug data
*
* @return debug data as an XML comment
* @access public
*/
function &getDebugAsXMLComment() {
// it would be nice to use a memory stream here to use
// memory more efficiently
while (strpos($this->debug_str, '--')) {
$this->debug_str = str_replace('--', '- -', $this->debug_str);
}
return "<!--\n" . $this->debug_str . "\n-->";
}
/**
* expands entities, e.g. changes '<' to '<'.
*
* @param string $val The string in which to expand entities.
* @access private
*/
function expandEntities($val) {
if ($this->charencoding) {
$val = str_replace('&', '&', $val);
$val = str_replace("'", ''', $val);
$val = str_replace('"', '"', $val);
$val = str_replace('<', '<', $val);
$val = str_replace('>', '>', $val);
}
return $val;
}
/**
* returns error string if present
*
* @return mixed error string or false
* @access public
*/
function getError(){
if($this->error_str != ''){
return $this->error_str;
}
return false;
}
/**
* sets error string
*
* @return boolean $string error string
* @access private
*/
function setError($str){
$this->error_str = $str;
}
/**
* detect if array is a simple array or a struct (associative array)
*
* @param mixed $val The PHP array
* @return string (arraySimple|arrayStruct)
* @access private
*/
function isArraySimpleOrStruct($val) {
$keyList = array_keys($val);
foreach ($keyList as $keyListValue) {
if (!is_int($keyListValue)) {
return 'arrayStruct';
}
}
return 'arraySimple';
}
/**
* serializes PHP values in accordance w/ section 5. Type information is
* not serialized if $use == 'literal'.
*
* @param mixed $val The value to serialize
* @param string $name The name (local part) of the XML element
* @param string $type The XML schema type (local part) for the element
* @param string $name_ns The namespace for the name of the XML element
* @param string $type_ns The namespace for the type of the element
* @param array $attributes The attributes to serialize as name=>value pairs
* @param string $use The WSDL "use" (encoded|literal)
* @return string The serialized element, possibly with child elements
* @access public
*/
function serialize_val($val,$name=false,$type=false,$name_ns=false,$type_ns=false,$attributes=false,$use='encoded'){
$this->debug("in serialize_val: name=$name, type=$type, name_ns=$name_ns, type_ns=$type_ns, use=$use");
$this->appendDebug('value=' . $this->varDump($val));
$this->appendDebug('attributes=' . $this->varDump($attributes));
if(is_object($val) && get_class($val) == 'soapval'){
return $val->serialize($use);
}
// force valid name if necessary
if (is_numeric($name)) {
$name = '__numeric_' . $name;
} elseif (! $name) {
$name = 'noname';
}
// if name has ns, add ns prefix to name
$xmlns = '';
if($name_ns){
$prefix = 'nu'.rand(1000,9999);
$name = $prefix.':'.$name;
$xmlns .= " xmlns:$prefix=\"$name_ns\"";
}
// if type is prefixed, create type prefix
if($type_ns != '' && $type_ns == $this->namespaces['xsd']){
// need to fix this. shouldn't default to xsd if no ns specified
// w/o checking against typemap
$type_prefix = 'xsd';
} elseif($type_ns){
$type_prefix = 'ns'.rand(1000,9999);
$xmlns .= " xmlns:$type_prefix=\"$type_ns\"";
}
// serialize attributes if present
$atts = '';
if($attributes){
foreach($attributes as $k => $v){
$atts .= " $k=\"".$this->expandEntities($v).'"';
}
}
// serialize null value
if (is_null($val)) {
if ($use == 'literal') {
// TODO: depends on minOccurs
return "<$name$xmlns $atts/>";
} else {
if (isset($type) && isset($type_prefix)) {
$type_str = " xsi:type=\"$type_prefix:$type\"";
} else {
$type_str = '';
}
return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>";
}
}
// serialize if an xsd built-in primitive type
if($type != '' && isset($this->typemap[$this->XMLSchemaVersion][$type])){
if (is_bool($val)) {
if ($type == 'boolean') {
$val = $val ? 'true' : 'false';
} elseif (! $val) {
$val = 0;
}
} else if (is_string($val)) {
$val = $this->expandEntities($val);
}
if ($use == 'literal') {
return "<$name$xmlns $atts>$val</$name>";
} else {
return "<$name$xmlns $atts xsi:type=\"xsd:$type\">$val</$name>";
}
}
// detect type and serialize
$xml = '';
switch(true) {
case (is_bool($val) || $type == 'boolean'):
if ($type == 'boolean') {
$val = $val ? 'true' : 'false';
} elseif (! $val) {
$val = 0;
}
if ($use == 'literal') {
$xml .= "<$name$xmlns $atts>$val</$name>";
} else {
$xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val</$name>";
}
break;
case (is_int($val) || is_long($val) || $type == 'int'):
if ($use == 'literal') {
$xml .= "<$name$xmlns $atts>$val</$name>";
} else {
$xml .= "<$name$xmlns xsi:type=\"xsd:int\"$atts>$val</$name>";
}
break;
case (is_float($val)|| is_double($val) || $type == 'float'):
if ($use == 'literal') {
$xml .= "<$name$xmlns $atts>$val</$name>";
} else {
$xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val</$name>";
}
break;
case (is_string($val) || $type == 'string'):
$val = $this->expandEntities($val);
if ($use == 'literal') {
$xml .= "<$name$xmlns $atts>$val</$name>";
} else {
$xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val</$name>";
}
break;
case is_object($val):
if (! $name) {
$name = get_class($val);
$this->debug("In serialize_val, used class name $name as element name");
} else {
$this->debug("In serialize_val, do not override name $name for element name for class " . get_class($val));
}
foreach(get_object_vars($val) as $k => $v){
$pXml = isset($pXml) ? $pXml.$this->serialize_val($v,$k,false,false,false,false,$use) : $this->serialize_val($v,$k,false,false,false,false,$use);
}
$xml .= '<'.$name.'>'.$pXml.'</'.$name.'>';
break;
break;
case (is_array($val) || $type):
// detect if struct or array
$valueType = $this->isArraySimpleOrStruct($val);
if($valueType=='arraySimple' || ereg('^ArrayOf',$type)){
$i = 0;
if(is_array($val) && count($val)> 0){
foreach($val as $v){
if(is_object($v) && get_class($v) == 'soapval'){
$tt_ns = $v->type_ns;
$tt = $v->type;
} elseif (is_array($v)) {
$tt = $this->isArraySimpleOrStruct($v);
} else {
$tt = gettype($v);
}
$array_types[$tt] = 1;
// TODO: for literal, the name should be $name
$xml .= $this->serialize_val($v,'item',false,false,false,false,$use);
++$i;
}
if(count($array_types) > 1){
$array_typename = 'xsd:anyType';
} elseif(isset($tt) && isset($this->typemap[$this->XMLSchemaVersion][$tt])) {
if ($tt == 'integer') {
$tt = 'int';
}
$array_typename = 'xsd:'.$tt;
} elseif(isset($tt) && $tt == 'arraySimple'){
$array_typename = 'SOAP-ENC:Array';
} elseif(isset($tt) && $tt == 'arrayStruct'){
$array_typename = 'unnamed_struct_use_soapval';
} else {
// if type is prefixed, create type prefix
if ($tt_ns != '' && $tt_ns == $this->namespaces['xsd']){
$array_typename = 'xsd:' . $tt;
} elseif ($tt_ns) {
$tt_prefix = 'ns' . rand(1000, 9999);
$array_typename = "$tt_prefix:$tt";
$xmlns .= " xmlns:$tt_prefix=\"$tt_ns\"";
} else {
$array_typename = $tt;
}
}
$array_type = $i;
if ($use == 'literal') {
$type_str = '';
} else if (isset($type) && isset($type_prefix)) {
$type_str = " xsi:type=\"$type_prefix:$type\"";
} else {
$type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"".$array_typename."[$array_type]\"";
}
// empty array
} else {
if ($use == 'literal') {
$type_str = '';
} else if (isset($type) && isset($type_prefix)) {
$type_str = " xsi:type=\"$type_prefix:$type\"";
} else {
$type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"xsd:anyType[0]\"";
}
}
// TODO: for array in literal, there is no wrapper here
$xml = "<$name$xmlns$type_str$atts>".$xml."</$name>";
} else {
// got a struct
if(isset($type) && isset($type_prefix)){
$type_str = " xsi:type=\"$type_prefix:$type\"";
} else {
$type_str = '';
}
if ($use == 'literal') {
$xml .= "<$name$xmlns $atts>";
} else {
$xml .= "<$name$xmlns$type_str$atts>";
}
foreach($val as $k => $v){
// Apache Map
if ($type == 'Map' && $type_ns == 'http://xml.apache.org/xml-soap') {
$xml .= '<item>';
$xml .= $this->serialize_val($k,'key',false,false,false,false,$use);
$xml .= $this->serialize_val($v,'value',false,false,false,false,$use);
$xml .= '</item>';
} else {
$xml .= $this->serialize_val($v,$k,false,false,false,false,$use);
}
}
$xml .= "</$name>";
}
break;
default:
$xml .= 'not detected, got '.gettype($val).' for '.$val;
break;
}
return $xml;
}
/**
* serializes a message
*
* @param string $body the XML of the SOAP body
* @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers
* @param array $namespaces optional the namespaces used in generating the body and headers
* @param string $style optional (rpc|document)
* @param string $use optional (encoded|literal)
* @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
* @return string the message
* @access public
*/
function serializeEnvelope($body,$headers=false,$namespaces=array(),$style='rpc',$use='encoded',$encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'){
// TODO: add an option to automatically run utf8_encode on $body and $headers
// if $this->soap_defencoding is UTF-8. Not doing this automatically allows
// one to send arbitrary UTF-8 characters, not just characters that map to ISO-8859-1
$this->debug("In serializeEnvelope length=" . strlen($body) . " body (max 1000 characters)=" . substr($body, 0, 1000) . " style=$style use=$use encodingStyle=$encodingStyle");
$this->debug("headers:");
$this->appendDebug($this->varDump($headers));
$this->debug("namespaces:");
$this->appendDebug($this->varDump($namespaces));
// serialize namespaces
$ns_string = '';
foreach(array_merge($this->namespaces,$namespaces) as $k => $v){
$ns_string .= " xmlns:$k=\"$v\"";
}
if($encodingStyle) {
$ns_string = " SOAP-ENV:encodingStyle=\"$encodingStyle\"$ns_string";
}
// serialize headers
if($headers){
if (is_array($headers)) {
$xml = '';
foreach ($headers as $header) {
$xml .= $this->serialize_val($header, false, false, false, false, false, $use);
}
$headers = $xml;
$this->debug("In serializeEnvelope, serialzied array of headers to $headers");
}
$headers = "<SOAP-ENV:Header>".$headers."</SOAP-ENV:Header>";
}
// serialize envelope
return
'<?xml version="1.0" encoding="'.$this->soap_defencoding .'"?'.">".
'<SOAP-ENV:Envelope'.$ns_string.">".
$headers.
"<SOAP-ENV:Body>".
$body.
"</SOAP-ENV:Body>".
"</SOAP-ENV:Envelope>";
}
/**
* formats a string to be inserted into an HTML stream
*
* @param string $str The string to format
* @return string The formatted string
* @access public
* @deprecated
*/
function formatDump($str){
$str = htmlspecialchars($str);
return nl2br($str);
}
/**
* contracts (changes namespace to prefix) a qualified name
*
* @param string $qname qname
* @return string contracted qname
* @access private
*/
function contractQname($qname){
// get element namespace
//$this->xdebug("Contract $qname");
if (strrpos($qname, ':')) {
// get unqualified name
$name = substr($qname, strrpos($qname, ':') + 1);
// get ns
$ns = substr($qname, 0, strrpos($qname, ':'));
$p = $this->getPrefixFromNamespace($ns);
if ($p) {
return $p . ':' . $name;
}
return $qname;
} else {
return $qname;
}
}
/**
* expands (changes prefix to namespace) a qualified name
*
* @param string $string qname
* @return string expanded qname
* @access private
*/
function expandQname($qname){
// get element prefix
if(strpos($qname,':') && !ereg('^http://',$qname)){
// get unqualified name
$name = substr(strstr($qname,':'),1);
// get ns prefix
$prefix = substr($qname,0,strpos($qname,':'));
if(isset($this->namespaces[$prefix])){
return $this->namespaces[$prefix].':'.$name;
} else {
return $qname;
}
} else {
return $qname;
}
}
/**
* returns the local part of a prefixed string
* returns the original string, if not prefixed
*
* @param string $str The prefixed string
* @return string The local part
* @access public
*/
function getLocalPart($str){
if($sstr = strrchr($str,':')){
// get unqualified name
return substr( $sstr, 1 );
} else {
return $str;
}
}
/**
* returns the prefix part of a prefixed string
* returns false, if not prefixed
*
* @param string $str The prefixed string
* @return mixed The prefix or false if there is no prefix
* @access public
*/
function getPrefix($str){
if($pos = strrpos($str,':')){
// get prefix
return substr($str,0,$pos);
}
return false;
}
/**
* pass it a prefix, it returns a namespace
*
* @param string $prefix The prefix
* @return mixed The namespace, false if no namespace has the specified prefix
* @access public
*/
function getNamespaceFromPrefix($prefix){
if (isset($this->namespaces[$prefix])) {
return $this->namespaces[$prefix];
}
//$this->setError("No namespace registered for prefix '$prefix'");
return false;
}
/**
* returns the prefix for a given namespace (or prefix)
* or false if no prefixes registered for the given namespace
*
* @param string $ns The namespace
* @return mixed The prefix, false if the namespace has no prefixes
* @access public
*/
function getPrefixFromNamespace($ns) {
foreach ($this->namespaces as $p => $n) {
if ($ns == $n || $ns == $p) {
$this->usedNamespaces[$p] = $n;
return $p;
}
}
return false;
}
/**
* returns the time in ODBC canonical form with microseconds
*
* @return string The time in ODBC canonical form with microseconds
* @access public
*/
function getmicrotime() {
if (function_exists('gettimeofday')) {
$tod = gettimeofday();
$sec = $tod['sec'];
$usec = $tod['usec'];
} else {
$sec = time();
$usec = 0;
}
return strftime('%Y-%m-%d %H:%M:%S', $sec) . '.' . sprintf('%06d', $usec);
}
/**
* Returns a string with the output of var_dump
*
* @param mixed $data The variable to var_dump
* @return string The output of var_dump
* @access public
*/
function varDump($data) {
ob_start();
var_dump($data);
$ret_val = ob_get_contents();
ob_end_clean();
return $ret_val;
}
}
// XML Schema Datatype Helper Functions
//xsd:dateTime helpers
/**
* convert unix timestamp to ISO 8601 compliant date string
*
* @param string $timestamp Unix time stamp
* @access public
*/
function timestamp_to_iso8601($timestamp,$utc=true){
$datestr = date('Y-m-d\TH:i:sO',$timestamp);
if($utc){
$eregStr =
'([0-9]{4})-'. // centuries & years CCYY-
'([0-9]{2})-'. // months MM-
'([0-9]{2})'. // days DD
'T'. // separator T
'([0-9]{2}):'. // hours hh:
'([0-9]{2}):'. // minutes mm:
'([0-9]{2})(\.[0-9]*)?'. // seconds ss.ss...
'(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
if(ereg($eregStr,$datestr,$regs)){
return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',$regs[1],$regs[2],$regs[3],$regs[4],$regs[5],$regs[6]);
}
return false;
} else {
return $datestr;
}
}
/**
* convert ISO 8601 compliant date string to unix timestamp
*
* @param string $datestr ISO 8601 compliant date string
* @access public
*/
function iso8601_to_timestamp($datestr){
$eregStr =
'([0-9]{4})-'. // centuries & years CCYY-
'([0-9]{2})-'. // months MM-
'([0-9]{2})'. // days DD
'T'. // separator T
'([0-9]{2}):'. // hours hh:
'([0-9]{2}):'. // minutes mm:
'([0-9]{2})(\.[0-9]+)?'. // seconds ss.ss...
'(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
if(ereg($eregStr,$datestr,$regs)){
// not utc
if($regs[8] != 'Z'){
$op = substr($regs[8],0,1);
$h = substr($regs[8],1,2);
$m = substr($regs[8],strlen($regs[8])-2,2);
if($op == '-'){
$regs[4] = $regs[4] + $h;
$regs[5] = $regs[5] + $m;
} elseif($op == '+'){
$regs[4] = $regs[4] - $h;
$regs[5] = $regs[5] - $m;
}
}
return strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z");
} else {
return false;
}
}
/**
* sleeps some number of microseconds
*
* @param string $usec the number of microseconds to sleep
* @access public
* @deprecated
*/
function usleepWindows($usec)
{
$start = gettimeofday();
do
{
$stop = gettimeofday();
$timePassed = 1000000 * ($stop['sec'] - $start['sec'])
+ $stop['usec'] - $start['usec'];
}
while ($timePassed < $usec);
}
?> | 10npsite | trunk/Index/Lib/Order/chinabank/lib/class.nusoap_base.php | PHP | asf20 | 26,697 |
<?php
/*
+----------------------------------------------------------------------+
| Sofee Framework For PHP4 |
+----------------------------------------------------------------------+
| Copyright (c) 2004-2005 The Sofee Development Team |
+----------------------------------------------------------------------+
| This source file is subject to the GNU Lesser Public License (LGPL), |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.fsf.org/copyleft/lesser.html |
| If you did not receive a copy of the LGPL and are unable to |
| obtain it through the world-wide-web, you can get it by writing the |
| Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, |
| MA 02111-1307, USA. |
+----------------------------------------------------------------------+
| Author: Justin Wu <ezdevelop@gmail.com> |
+----------------------------------------------------------------------+
*/
/* $Id: SofeeXmlParser.php,v 1.3 2005/05/30 06:30:14 wenlong Exp $ */
/**
* Sofee XML Parser class - This is an XML parser based on PHP's "xml" extension.
*
* The SofeeXmlParser class provides a very simple and easily usable toolset to convert XML
* to an array that can be processed with array iterators.
*
* @package SofeeFramework
* @access public
* @version $Revision: 1.1 $
* @author Justin Wu <wenlong@php.net>
* @homepage http://www.sofee.cn
* @copyright Copyright (c) 2004-2005 Sofee Development Team.(http://www.sofee.cn)
* @since 2005-05-30
* @see PEAR:XML_Parser | SimpleXML extension
*/
class SofeeXmlParser {
/**
* XML parser handle
*
* @var resource
* @see xml_parser_create()
*/
var $parser;
/**
* source encoding
*
* @var string
*/
var $srcenc;
/**
* target encoding
*
* @var string
*/
var $dstenc;
/**
* the original struct
*
* @access private
* @var array1
*/
var $_struct = array();
/**
* Constructor
*
* @access public
* @param mixed [$srcenc] source encoding
* @param mixed [$dstenc] target encoding
* @return void
* @since
*/
function SofeeXmlParser($srcenc = null, $dstenc = null) {
$this->srcenc = $srcenc;
$this->dstenc = $dstenc;
// initialize the variable.
$this->parser = null;
$this->_struct = array();
}
/**
* Free the resources
*
* @access public
* @return void
**/
function free() {
if (isset($this->parser) && is_resource($this->parser)) {
xml_parser_free($this->parser);
unset($this->parser);
}
}
/**
* Parses the XML file
*
* @access public
* @param string [$file] the XML file name
* @return void
* @since
*/
function parseFile($file) {
$data = @file_get_contents($file) or die("Can't open file $file for reading!");
$this->parseString($data);
}
/**
* Parses a string.
*
* @access public
* @param string [$data] XML data
* @return void
*/
function parseString($data) {
if ($this->srcenc === null) {
$this->parser = @xml_parser_create() or die('Unable to create XML parser resource.');
} else {
$this->parser = @xml_parser_create($this->srcenc) or die('Unable to create XML parser resource with '. $this->srcenc .' encoding.');
}
if ($this->dstenc !== null) {
@xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->dstenc) or die('Invalid target encoding');
}
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); // lowercase tags
xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1); // skip empty tags
if (!xml_parse_into_struct($this->parser, $data, &$this->_struct)) {
printf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($this->parser)),
xml_get_current_line_number($this->parser)
);
$this->free();
exit();
}
$this->_count = count($this->_struct);
$this->free();
}
/**
* return the data struction
*
* @access public
* @return array
*/
function getTree() {
$i = 0;
$tree = array();
$tree = $this->addNode(
$tree,
$this->_struct[$i]['tag'],
(isset($this->_struct[$i]['value'])) ? $this->_struct[$i]['value'] : '',
(isset($this->_struct[$i]['attributes'])) ? $this->_struct[$i]['attributes'] : '',
$this->getChild($i)
);
unset($this->_struct);
return ($tree);
}
/**
* recursion the children node data
*
* @access public
* @param integer [$i] the last struct index
* @return array
*/
function getChild(&$i) {
// contain node data
$children = array();
// loop
while (++$i < $this->_count) {
// node tag name
$tagname = $this->_struct[$i]['tag'];
$value = isset($this->_struct[$i]['value']) ? $this->_struct[$i]['value'] : '';
$attributes = isset($this->_struct[$i]['attributes']) ? $this->_struct[$i]['attributes'] : '';
switch ($this->_struct[$i]['type']) {
case 'open':
// node has more children
$child = $this->getChild($i);
// append the children data to the current node
$children = $this->addNode($children, $tagname, $value, $attributes, $child);
break;
case 'complete':
// at end of current branch
$children = $this->addNode($children, $tagname, $value, $attributes);
break;
case 'cdata':
// node has CDATA after one of it's children
$children['value'] .= $value;
break;
case 'close':
// end of node, return collected data
return $children;
break;
}
}
//return $children;
}
/**
* Appends some values to an array
*
* @access public
* @param array [$target]
* @param string [$key]
* @param string [$value]
* @param array [$attributes]
* @param array [$child] the children
* @return void
* @since
*/
function addNode($target, $key, $value = '', $attributes = '', $child = '') {
if (!isset($target[$key]['value']) && !isset($target[$key][0])) {
if ($child != '') {
$target[$key] = $child;
}
if ($attributes != '') {
foreach ($attributes as $k => $v) {
$target[$key][$k] = $v;
}
}
$target[$key]['value'] = $value;
} else {
if (!isset($target[$key][0])) {
// is string or other
$oldvalue = $target[$key];
$target[$key] = array();
$target[$key][0] = $oldvalue;
$index = 1;
} else {
// is array
$index = count($target[$key]);
}
if ($child != '') {
$target[$key][$index] = $child;
}
if ($attributes != '') {
foreach ($attributes as $k => $v) {
$target[$key][$index][$k] = $v;
}
}
$target[$key][$index]['value'] = $value;
}
return $target;
}
}
?> | 10npsite | trunk/Index/Lib/Order/chinabank/lib/SofeeXmlParser.php | PHP | asf20 | 7,051 |
<?php
/**
* parses an XML Schema, allows access to it's data, other utility methods
* no validation... yet.
* very experimental and limited. As is discussed on XML-DEV, I'm one of the people
* that just doesn't have time to read the spec(s) thoroughly, and just have a couple of trusty
* tutorials I refer to :)
*
* @author Dietrich Ayala <dietrich@ganx4.com>
* @version $Id: class.xmlschema.php,v 1.39 2005/08/04 01:27:42 snichol Exp $
* @access public
*/
class XMLSchema extends nusoap_base {
// files
var $schema = '';
var $xml = '';
// namespaces
var $enclosingNamespaces;
// schema info
var $schemaInfo = array();
var $schemaTargetNamespace = '';
// types, elements, attributes defined by the schema
var $attributes = array();
var $complexTypes = array();
var $complexTypeStack = array();
var $currentComplexType = null;
var $elements = array();
var $elementStack = array();
var $currentElement = null;
var $simpleTypes = array();
var $simpleTypeStack = array();
var $currentSimpleType = null;
// imports
var $imports = array();
// parser vars
var $parser;
var $position = 0;
var $depth = 0;
var $depth_array = array();
var $message = array();
var $defaultNamespace = array();
/**
* constructor
*
* @param string $schema schema document URI
* @param string $xml xml document URI
* @param string $namespaces namespaces defined in enclosing XML
* @access public
*/
function XMLSchema($schema='',$xml='',$namespaces=array()){
parent::nusoap_base();
$this->debug('xmlschema class instantiated, inside constructor');
// files
$this->schema = $schema;
$this->xml = $xml;
// namespaces
$this->enclosingNamespaces = $namespaces;
$this->namespaces = array_merge($this->namespaces, $namespaces);
// parse schema file
if($schema != ''){
$this->debug('initial schema file: '.$schema);
$this->parseFile($schema, 'schema');
}
// parse xml file
if($xml != ''){
$this->debug('initial xml file: '.$xml);
$this->parseFile($xml, 'xml');
}
}
/**
* parse an XML file
*
* @param string $xml, path/URL to XML file
* @param string $type, (schema | xml)
* @return boolean
* @access public
*/
function parseFile($xml,$type){
// parse xml file
if($xml != ""){
$xmlStr = @join("",@file($xml));
if($xmlStr == ""){
$msg = 'Error reading XML from '.$xml;
$this->setError($msg);
$this->debug($msg);
return false;
} else {
$this->debug("parsing $xml");
$this->parseString($xmlStr,$type);
$this->debug("done parsing $xml");
return true;
}
}
return false;
}
/**
* parse an XML string
*
* @param string $xml path or URL
* @param string $type, (schema|xml)
* @access private
*/
function parseString($xml,$type){
// parse xml string
if($xml != ""){
// Create an XML parser.
$this->parser = xml_parser_create();
// Set the options for parsing the XML data.
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
// Set the object for the parser.
xml_set_object($this->parser, $this);
// Set the element handlers for the parser.
if($type == "schema"){
xml_set_element_handler($this->parser, 'schemaStartElement','schemaEndElement');
xml_set_character_data_handler($this->parser,'schemaCharacterData');
} elseif($type == "xml"){
xml_set_element_handler($this->parser, 'xmlStartElement','xmlEndElement');
xml_set_character_data_handler($this->parser,'xmlCharacterData');
}
// Parse the XML file.
if(!xml_parse($this->parser,$xml,true)){
// Display an error message.
$errstr = sprintf('XML error parsing XML schema on line %d: %s',
xml_get_current_line_number($this->parser),
xml_error_string(xml_get_error_code($this->parser))
);
$this->debug($errstr);
$this->debug("XML payload:\n" . $xml);
$this->setError($errstr);
}
xml_parser_free($this->parser);
} else{
$this->debug('no xml passed to parseString()!!');
$this->setError('no xml passed to parseString()!!');
}
}
/**
* start-element handler
*
* @param string $parser XML parser object
* @param string $name element name
* @param string $attrs associative array of attributes
* @access private
*/
function schemaStartElement($parser, $name, $attrs) {
// position in the total number of elements, starting from 0
$pos = $this->position++;
$depth = $this->depth++;
// set self as current value for this depth
$this->depth_array[$depth] = $pos;
$this->message[$pos] = array('cdata' => '');
if ($depth > 0) {
$this->defaultNamespace[$pos] = $this->defaultNamespace[$this->depth_array[$depth - 1]];
} else {
$this->defaultNamespace[$pos] = false;
}
// get element prefix
if($prefix = $this->getPrefix($name)){
// get unqualified name
$name = $this->getLocalPart($name);
} else {
$prefix = '';
}
// loop thru attributes, expanding, and registering namespace declarations
if(count($attrs) > 0){
foreach($attrs as $k => $v){
// if ns declarations, add to class level array of valid namespaces
if(ereg("^xmlns",$k)){
//$this->xdebug("$k: $v");
//$this->xdebug('ns_prefix: '.$this->getPrefix($k));
if($ns_prefix = substr(strrchr($k,':'),1)){
//$this->xdebug("Add namespace[$ns_prefix] = $v");
$this->namespaces[$ns_prefix] = $v;
} else {
$this->defaultNamespace[$pos] = $v;
if (! $this->getPrefixFromNamespace($v)) {
$this->namespaces['ns'.(count($this->namespaces)+1)] = $v;
}
}
if($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema'){
$this->XMLSchemaVersion = $v;
$this->namespaces['xsi'] = $v.'-instance';
}
}
}
foreach($attrs as $k => $v){
// expand each attribute
$k = strpos($k,':') ? $this->expandQname($k) : $k;
$v = strpos($v,':') ? $this->expandQname($v) : $v;
$eAttrs[$k] = $v;
}
$attrs = $eAttrs;
} else {
$attrs = array();
}
// find status, register data
switch($name){
case 'all': // (optional) compositor content for a complexType
case 'choice':
case 'group':
case 'sequence':
//$this->xdebug("compositor $name for currentComplexType: $this->currentComplexType and currentElement: $this->currentElement");
$this->complexTypes[$this->currentComplexType]['compositor'] = $name;
//if($name == 'all' || $name == 'sequence'){
// $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
//}
break;
case 'attribute': // complexType attribute
//$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']);
$this->xdebug("parsing attribute:");
$this->appendDebug($this->varDump($attrs));
if (!isset($attrs['form'])) {
$attrs['form'] = $this->schemaInfo['attributeFormDefault'];
}
if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) {
$v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
if (!strpos($v, ':')) {
// no namespace in arrayType attribute value...
if ($this->defaultNamespace[$pos]) {
// ...so use the default
$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'] = $this->defaultNamespace[$pos] . ':' . $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
}
}
}
if(isset($attrs['name'])){
$this->attributes[$attrs['name']] = $attrs;
$aname = $attrs['name'];
} elseif(isset($attrs['ref']) && $attrs['ref'] == 'http://schemas.xmlsoap.org/soap/encoding/:arrayType'){
if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) {
$aname = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
} else {
$aname = '';
}
} elseif(isset($attrs['ref'])){
$aname = $attrs['ref'];
$this->attributes[$attrs['ref']] = $attrs;
}
if($this->currentComplexType){ // This should *always* be
$this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs;
}
// arrayType attribute
if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']) || $this->getLocalPart($aname) == 'arrayType'){
$this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
$prefix = $this->getPrefix($aname);
if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])){
$v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
} else {
$v = '';
}
if(strpos($v,'[,]')){
$this->complexTypes[$this->currentComplexType]['multidimensional'] = true;
}
$v = substr($v,0,strpos($v,'[')); // clip the []
if(!strpos($v,':') && isset($this->typemap[$this->XMLSchemaVersion][$v])){
$v = $this->XMLSchemaVersion.':'.$v;
}
$this->complexTypes[$this->currentComplexType]['arrayType'] = $v;
}
break;
case 'complexContent': // (optional) content for a complexType
break;
case 'complexType':
array_push($this->complexTypeStack, $this->currentComplexType);
if(isset($attrs['name'])){
$this->xdebug('processing named complexType '.$attrs['name']);
//$this->currentElement = false;
$this->currentComplexType = $attrs['name'];
$this->complexTypes[$this->currentComplexType] = $attrs;
$this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';
// This is for constructs like
// <complexType name="ListOfString" base="soap:Array">
// <sequence>
// <element name="string" type="xsd:string"
// minOccurs="0" maxOccurs="unbounded" />
// </sequence>
// </complexType>
if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){
$this->xdebug('complexType is unusual array');
$this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
} else {
$this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
}
}else{
$this->xdebug('processing unnamed complexType for element '.$this->currentElement);
$this->currentComplexType = $this->currentElement . '_ContainedType';
//$this->currentElement = false;
$this->complexTypes[$this->currentComplexType] = $attrs;
$this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';
// This is for constructs like
// <complexType name="ListOfString" base="soap:Array">
// <sequence>
// <element name="string" type="xsd:string"
// minOccurs="0" maxOccurs="unbounded" />
// </sequence>
// </complexType>
if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){
$this->xdebug('complexType is unusual array');
$this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
} else {
$this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
}
}
break;
case 'element':
array_push($this->elementStack, $this->currentElement);
// elements defined as part of a complex type should
// not really be added to $this->elements, but for some
// reason, they are
if (!isset($attrs['form'])) {
$attrs['form'] = $this->schemaInfo['elementFormDefault'];
}
if(isset($attrs['type'])){
$this->xdebug("processing typed element ".$attrs['name']." of type ".$attrs['type']);
if (! $this->getPrefix($attrs['type'])) {
if ($this->defaultNamespace[$pos]) {
$attrs['type'] = $this->defaultNamespace[$pos] . ':' . $attrs['type'];
$this->xdebug('used default namespace to make type ' . $attrs['type']);
}
}
// This is for constructs like
// <complexType name="ListOfString" base="soap:Array">
// <sequence>
// <element name="string" type="xsd:string"
// minOccurs="0" maxOccurs="unbounded" />
// </sequence>
// </complexType>
if ($this->currentComplexType && $this->complexTypes[$this->currentComplexType]['phpType'] == 'array') {
$this->xdebug('arrayType for unusual array is ' . $attrs['type']);
$this->complexTypes[$this->currentComplexType]['arrayType'] = $attrs['type'];
}
$this->currentElement = $attrs['name'];
$this->elements[ $attrs['name'] ] = $attrs;
$this->elements[ $attrs['name'] ]['typeClass'] = 'element';
$ename = $attrs['name'];
} elseif(isset($attrs['ref'])){
$this->xdebug("processing element as ref to ".$attrs['ref']);
$this->currentElement = "ref to ".$attrs['ref'];
$ename = $this->getLocalPart($attrs['ref']);
} else {
$this->xdebug("processing untyped element ".$attrs['name']);
$this->currentElement = $attrs['name'];
$this->elements[ $attrs['name'] ] = $attrs;
$this->elements[ $attrs['name'] ]['typeClass'] = 'element';
$attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['name'] . '_ContainedType';
$this->elements[ $attrs['name'] ]['type'] = $attrs['type'];
$ename = $attrs['name'];
}
if(isset($ename) && $this->currentComplexType){
$this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs;
}
break;
case 'enumeration': // restriction value list member
$this->xdebug('enumeration ' . $attrs['value']);
if ($this->currentSimpleType) {
$this->simpleTypes[$this->currentSimpleType]['enumeration'][] = $attrs['value'];
} elseif ($this->currentComplexType) {
$this->complexTypes[$this->currentComplexType]['enumeration'][] = $attrs['value'];
}
break;
case 'extension': // simpleContent or complexContent type extension
$this->xdebug('extension ' . $attrs['base']);
if ($this->currentComplexType) {
$this->complexTypes[$this->currentComplexType]['extensionBase'] = $attrs['base'];
}
break;
case 'import':
if (isset($attrs['schemaLocation'])) {
//$this->xdebug('import namespace ' . $attrs['namespace'] . ' from ' . $attrs['schemaLocation']);
$this->imports[$attrs['namespace']][] = array('location' => $attrs['schemaLocation'], 'loaded' => false);
} else {
//$this->xdebug('import namespace ' . $attrs['namespace']);
$this->imports[$attrs['namespace']][] = array('location' => '', 'loaded' => true);
if (! $this->getPrefixFromNamespace($attrs['namespace'])) {
$this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace'];
}
}
break;
case 'list': // simpleType value list
break;
case 'restriction': // simpleType, simpleContent or complexContent value restriction
$this->xdebug('restriction ' . $attrs['base']);
if($this->currentSimpleType){
$this->simpleTypes[$this->currentSimpleType]['type'] = $attrs['base'];
} elseif($this->currentComplexType){
$this->complexTypes[$this->currentComplexType]['restrictionBase'] = $attrs['base'];
if(strstr($attrs['base'],':') == ':Array'){
$this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
}
}
break;
case 'schema':
$this->schemaInfo = $attrs;
$this->schemaInfo['schemaVersion'] = $this->getNamespaceFromPrefix($prefix);
if (isset($attrs['targetNamespace'])) {
$this->schemaTargetNamespace = $attrs['targetNamespace'];
}
if (!isset($attrs['elementFormDefault'])) {
$this->schemaInfo['elementFormDefault'] = 'unqualified';
}
if (!isset($attrs['attributeFormDefault'])) {
$this->schemaInfo['attributeFormDefault'] = 'unqualified';
}
break;
case 'simpleContent': // (optional) content for a complexType
break;
case 'simpleType':
array_push($this->simpleTypeStack, $this->currentSimpleType);
if(isset($attrs['name'])){
$this->xdebug("processing simpleType for name " . $attrs['name']);
$this->currentSimpleType = $attrs['name'];
$this->simpleTypes[ $attrs['name'] ] = $attrs;
$this->simpleTypes[ $attrs['name'] ]['typeClass'] = 'simpleType';
$this->simpleTypes[ $attrs['name'] ]['phpType'] = 'scalar';
} else {
$this->xdebug('processing unnamed simpleType for element '.$this->currentElement);
$this->currentSimpleType = $this->currentElement . '_ContainedType';
//$this->currentElement = false;
$this->simpleTypes[$this->currentSimpleType] = $attrs;
$this->simpleTypes[$this->currentSimpleType]['phpType'] = 'scalar';
}
break;
case 'union': // simpleType type list
break;
default:
//$this->xdebug("do not have anything to do for element $name");
}
}
/**
* end-element handler
*
* @param string $parser XML parser object
* @param string $name element name
* @access private
*/
function schemaEndElement($parser, $name) {
// bring depth down a notch
$this->depth--;
// position of current element is equal to the last value left in depth_array for my depth
if(isset($this->depth_array[$this->depth])){
$pos = $this->depth_array[$this->depth];
}
// get element prefix
if ($prefix = $this->getPrefix($name)){
// get unqualified name
$name = $this->getLocalPart($name);
} else {
$prefix = '';
}
// move on...
if($name == 'complexType'){
$this->xdebug('done processing complexType ' . ($this->currentComplexType ? $this->currentComplexType : '(unknown)'));
$this->currentComplexType = array_pop($this->complexTypeStack);
//$this->currentElement = false;
}
if($name == 'element'){
$this->xdebug('done processing element ' . ($this->currentElement ? $this->currentElement : '(unknown)'));
$this->currentElement = array_pop($this->elementStack);
}
if($name == 'simpleType'){
$this->xdebug('done processing simpleType ' . ($this->currentSimpleType ? $this->currentSimpleType : '(unknown)'));
$this->currentSimpleType = array_pop($this->simpleTypeStack);
}
}
/**
* element content handler
*
* @param string $parser XML parser object
* @param string $data element content
* @access private
*/
function schemaCharacterData($parser, $data){
$pos = $this->depth_array[$this->depth - 1];
$this->message[$pos]['cdata'] .= $data;
}
/**
* serialize the schema
*
* @access public
*/
function serializeSchema(){
$schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion);
$xml = '';
// imports
if (sizeof($this->imports) > 0) {
foreach($this->imports as $ns => $list) {
foreach ($list as $ii) {
if ($ii['location'] != '') {
$xml .= " <$schemaPrefix:import location=\"" . $ii['location'] . '" namespace="' . $ns . "\" />\n";
} else {
$xml .= " <$schemaPrefix:import namespace=\"" . $ns . "\" />\n";
}
}
}
}
// complex types
foreach($this->complexTypes as $typeName => $attrs){
$contentStr = '';
// serialize child elements
if(isset($attrs['elements']) && (count($attrs['elements']) > 0)){
foreach($attrs['elements'] as $element => $eParts){
if(isset($eParts['ref'])){
$contentStr .= " <$schemaPrefix:element ref=\"$element\"/>\n";
} else {
$contentStr .= " <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\"";
foreach ($eParts as $aName => $aValue) {
// handle, e.g., abstract, default, form, minOccurs, maxOccurs, nillable
if ($aName != 'name' && $aName != 'type') {
$contentStr .= " $aName=\"$aValue\"";
}
}
$contentStr .= "/>\n";
}
}
// compositor wraps elements
if (isset($attrs['compositor']) && ($attrs['compositor'] != '')) {
$contentStr = " <$schemaPrefix:$attrs[compositor]>\n".$contentStr." </$schemaPrefix:$attrs[compositor]>\n";
}
}
// attributes
if(isset($attrs['attrs']) && (count($attrs['attrs']) >= 1)){
foreach($attrs['attrs'] as $attr => $aParts){
$contentStr .= " <$schemaPrefix:attribute";
foreach ($aParts as $a => $v) {
if ($a == 'ref' || $a == 'type') {
$contentStr .= " $a=\"".$this->contractQName($v).'"';
} elseif ($a == 'http://schemas.xmlsoap.org/wsdl/:arrayType') {
$this->usedNamespaces['wsdl'] = $this->namespaces['wsdl'];
$contentStr .= ' wsdl:arrayType="'.$this->contractQName($v).'"';
} else {
$contentStr .= " $a=\"$v\"";
}
}
$contentStr .= "/>\n";
}
}
// if restriction
if (isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != ''){
$contentStr = " <$schemaPrefix:restriction base=\"".$this->contractQName($attrs['restrictionBase'])."\">\n".$contentStr." </$schemaPrefix:restriction>\n";
// complex or simple content
if ((isset($attrs['elements']) && count($attrs['elements']) > 0) || (isset($attrs['attrs']) && count($attrs['attrs']) > 0)){
$contentStr = " <$schemaPrefix:complexContent>\n".$contentStr." </$schemaPrefix:complexContent>\n";
}
}
// finalize complex type
if($contentStr != ''){
$contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." </$schemaPrefix:complexType>\n";
} else {
$contentStr = " <$schemaPrefix:complexType name=\"$typeName\"/>\n";
}
$xml .= $contentStr;
}
// simple types
if(isset($this->simpleTypes) && count($this->simpleTypes) > 0){
foreach($this->simpleTypes as $typeName => $eParts){
$xml .= " <$schemaPrefix:simpleType name=\"$typeName\">\n <$schemaPrefix:restriction base=\"".$this->contractQName($eParts['type'])."\"/>\n";
if (isset($eParts['enumeration'])) {
foreach ($eParts['enumeration'] as $e) {
$xml .= " <$schemaPrefix:enumeration value=\"$e\"/>\n";
}
}
$xml .= " </$schemaPrefix:simpleType>";
}
}
// elements
if(isset($this->elements) && count($this->elements) > 0){
foreach($this->elements as $element => $eParts){
$xml .= " <$schemaPrefix:element name=\"$element\" type=\"".$this->contractQName($eParts['type'])."\"/>\n";
}
}
// attributes
if(isset($this->attributes) && count($this->attributes) > 0){
foreach($this->attributes as $attr => $aParts){
$xml .= " <$schemaPrefix:attribute name=\"$attr\" type=\"".$this->contractQName($aParts['type'])."\"\n/>";
}
}
// finish 'er up
$el = "<$schemaPrefix:schema targetNamespace=\"$this->schemaTargetNamespace\"\n";
foreach (array_diff($this->usedNamespaces, $this->enclosingNamespaces) as $nsp => $ns) {
$el .= " xmlns:$nsp=\"$ns\"\n";
}
$xml = $el . ">\n".$xml."</$schemaPrefix:schema>\n";
return $xml;
}
/**
* adds debug data to the clas level debug string
*
* @param string $string debug data
* @access private
*/
function xdebug($string){
$this->debug('<' . $this->schemaTargetNamespace . '> '.$string);
}
/**
* get the PHP type of a user defined type in the schema
* PHP type is kind of a misnomer since it actually returns 'struct' for assoc. arrays
* returns false if no type exists, or not w/ the given namespace
* else returns a string that is either a native php type, or 'struct'
*
* @param string $type, name of defined type
* @param string $ns, namespace of type
* @return mixed
* @access public
* @deprecated
*/
function getPHPType($type,$ns){
if(isset($this->typemap[$ns][$type])){
//print "found type '$type' and ns $ns in typemap<br>";
return $this->typemap[$ns][$type];
} elseif(isset($this->complexTypes[$type])){
//print "getting type '$type' and ns $ns from complexTypes array<br>";
return $this->complexTypes[$type]['phpType'];
}
return false;
}
/**
* returns an associative array of information about a given type
* returns false if no type exists by the given name
*
* For a complexType typeDef = array(
* 'restrictionBase' => '',
* 'phpType' => '',
* 'compositor' => '(sequence|all)',
* 'elements' => array(), // refs to elements array
* 'attrs' => array() // refs to attributes array
* ... and so on (see addComplexType)
* )
*
* For simpleType or element, the array has different keys.
*
* @param string
* @return mixed
* @access public
* @see addComplexType
* @see addSimpleType
* @see addElement
*/
function getTypeDef($type){
//$this->debug("in getTypeDef for type $type");
if(isset($this->complexTypes[$type])){
$this->xdebug("in getTypeDef, found complexType $type");
return $this->complexTypes[$type];
} elseif(isset($this->simpleTypes[$type])){
$this->xdebug("in getTypeDef, found simpleType $type");
if (!isset($this->simpleTypes[$type]['phpType'])) {
// get info for type to tack onto the simple type
// TODO: can this ever really apply (i.e. what is a simpleType really?)
$uqType = substr($this->simpleTypes[$type]['type'], strrpos($this->simpleTypes[$type]['type'], ':') + 1);
$ns = substr($this->simpleTypes[$type]['type'], 0, strrpos($this->simpleTypes[$type]['type'], ':'));
$etype = $this->getTypeDef($uqType);
if ($etype) {
$this->xdebug("in getTypeDef, found type for simpleType $type:");
$this->xdebug($this->varDump($etype));
if (isset($etype['phpType'])) {
$this->simpleTypes[$type]['phpType'] = $etype['phpType'];
}
if (isset($etype['elements'])) {
$this->simpleTypes[$type]['elements'] = $etype['elements'];
}
}
}
return $this->simpleTypes[$type];
} elseif(isset($this->elements[$type])){
$this->xdebug("in getTypeDef, found element $type");
if (!isset($this->elements[$type]['phpType'])) {
// get info for type to tack onto the element
$uqType = substr($this->elements[$type]['type'], strrpos($this->elements[$type]['type'], ':') + 1);
$ns = substr($this->elements[$type]['type'], 0, strrpos($this->elements[$type]['type'], ':'));
$etype = $this->getTypeDef($uqType);
if ($etype) {
$this->xdebug("in getTypeDef, found type for element $type:");
$this->xdebug($this->varDump($etype));
if (isset($etype['phpType'])) {
$this->elements[$type]['phpType'] = $etype['phpType'];
}
if (isset($etype['elements'])) {
$this->elements[$type]['elements'] = $etype['elements'];
}
} elseif ($ns == 'http://www.w3.org/2001/XMLSchema') {
$this->xdebug("in getTypeDef, element $type is an XSD type");
$this->elements[$type]['phpType'] = 'scalar';
}
}
return $this->elements[$type];
} elseif(isset($this->attributes[$type])){
$this->xdebug("in getTypeDef, found attribute $type");
return $this->attributes[$type];
} elseif (ereg('_ContainedType$', $type)) {
$this->xdebug("in getTypeDef, have an untyped element $type");
$typeDef['typeClass'] = 'simpleType';
$typeDef['phpType'] = 'scalar';
$typeDef['type'] = 'http://www.w3.org/2001/XMLSchema:string';
return $typeDef;
}
$this->xdebug("in getTypeDef, did not find $type");
return false;
}
/**
* returns a sample serialization of a given type, or false if no type by the given name
*
* @param string $type, name of type
* @return mixed
* @access public
* @deprecated
*/
function serializeTypeDef($type){
//print "in sTD() for type $type<br>";
if($typeDef = $this->getTypeDef($type)){
$str .= '<'.$type;
if(is_array($typeDef['attrs'])){
foreach($attrs as $attName => $data){
$str .= " $attName=\"{type = ".$data['type']."}\"";
}
}
$str .= " xmlns=\"".$this->schema['targetNamespace']."\"";
if(count($typeDef['elements']) > 0){
$str .= ">";
foreach($typeDef['elements'] as $element => $eData){
$str .= $this->serializeTypeDef($element);
}
$str .= "</$type>";
} elseif($typeDef['typeClass'] == 'element') {
$str .= "></$type>";
} else {
$str .= "/>";
}
return $str;
}
return false;
}
/**
* returns HTML form elements that allow a user
* to enter values for creating an instance of the given type.
*
* @param string $name, name for type instance
* @param string $type, name of type
* @return string
* @access public
* @deprecated
*/
function typeToForm($name,$type){
// get typedef
if($typeDef = $this->getTypeDef($type)){
// if struct
if($typeDef['phpType'] == 'struct'){
$buffer .= '<table>';
foreach($typeDef['elements'] as $child => $childDef){
$buffer .= "
<tr><td align='right'>$childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):</td>
<td><input type='text' name='parameters[".$name."][$childDef[name]]'></td></tr>";
}
$buffer .= '</table>';
// if array
} elseif($typeDef['phpType'] == 'array'){
$buffer .= '<table>';
for($i=0;$i < 3; $i++){
$buffer .= "
<tr><td align='right'>array item (type: $typeDef[arrayType]):</td>
<td><input type='text' name='parameters[".$name."][]'></td></tr>";
}
$buffer .= '</table>';
// if scalar
} else {
$buffer .= "<input type='text' name='parameters[$name]'>";
}
} else {
$buffer .= "<input type='text' name='parameters[$name]'>";
}
return $buffer;
}
/**
* adds a complex type to the schema
*
* example: array
*
* addType(
* 'ArrayOfstring',
* 'complexType',
* 'array',
* '',
* 'SOAP-ENC:Array',
* array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'string[]'),
* 'xsd:string'
* );
*
* example: PHP associative array ( SOAP Struct )
*
* addType(
* 'SOAPStruct',
* 'complexType',
* 'struct',
* 'all',
* array('myVar'=> array('name'=>'myVar','type'=>'string')
* );
*
* @param name
* @param typeClass (complexType|simpleType|attribute)
* @param phpType: currently supported are array and struct (php assoc array)
* @param compositor (all|sequence|choice)
* @param restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
* @param elements = array ( name = array(name=>'',type=>'') )
* @param attrs = array(
* array(
* 'ref' => "http://schemas.xmlsoap.org/soap/encoding/:arrayType",
* "http://schemas.xmlsoap.org/wsdl/:arrayType" => "string[]"
* )
* )
* @param arrayType: namespace:name (http://www.w3.org/2001/XMLSchema:string)
* @access public
* @see getTypeDef
*/
function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType=''){
$this->complexTypes[$name] = array(
'name' => $name,
'typeClass' => $typeClass,
'phpType' => $phpType,
'compositor'=> $compositor,
'restrictionBase' => $restrictionBase,
'elements' => $elements,
'attrs' => $attrs,
'arrayType' => $arrayType
);
$this->xdebug("addComplexType $name:");
$this->appendDebug($this->varDump($this->complexTypes[$name]));
}
/**
* adds a simple type to the schema
*
* @param string $name
* @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
* @param string $typeClass (should always be simpleType)
* @param string $phpType (should always be scalar)
* @param array $enumeration array of values
* @access public
* @see xmlschema
* @see getTypeDef
*/
function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
$this->simpleTypes[$name] = array(
'name' => $name,
'typeClass' => $typeClass,
'phpType' => $phpType,
'type' => $restrictionBase,
'enumeration' => $enumeration
);
$this->xdebug("addSimpleType $name:");
$this->appendDebug($this->varDump($this->simpleTypes[$name]));
}
/**
* adds an element to the schema
*
* @param array $attrs attributes that must include name and type
* @see xmlschema
* @access public
*/
function addElement($attrs) {
if (! $this->getPrefix($attrs['type'])) {
$attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type'];
}
$this->elements[ $attrs['name'] ] = $attrs;
$this->elements[ $attrs['name'] ]['typeClass'] = 'element';
$this->xdebug("addElement " . $attrs['name']);
$this->appendDebug($this->varDump($this->elements[ $attrs['name'] ]));
}
}
?> | 10npsite | trunk/Index/Lib/Order/chinabank/lib/class.xmlschema.php | PHP | asf20 | 33,539 |
<? require "../../../global.php"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require_once('./lib/chinabank.MotoClient.php');
require_once('./lib/userfunction.php');
// 消费
$motoClient = new MotoClient();
$cardid =trim($_POST["cardid"]); // 信用卡卡号
$month =trim($_POST["month"]); // 月
$year =trim($_POST["year"]); // 年
$year_month = $year.$month;
$cvv =trim($_POST["cvv"]); // 年
$money =trim($_POST["money"]); // 金额 单位元
$name =trim($_POST["name"]); // 持卡人姓名
$idcard =trim($_POST["idcard"]); // 证件号
$type1 =trim($_POST["type1"]); //支付款项类型
$orderid=trim($_POST[ "orderid" ]);
if($idcard=="")
{
$idcard="999999";
}
//初始化支付信息,当支付列表里没有支付信息时添加一条新的支付记录
preg_match("/^[a-zA-Z][0-9]+/",$orderid,$orderAr);
$orderidl=$orderAr[0];
$payflag=str_replace($orderidl,"",$orderid);
require RootDir."/inc/dabase_mysql.php";
$mydb=new YYBDB();
$sql="select orderno from ".$SystemConest[7]."orderpaylist where orderno='".$orderidl."'";
$res=$mydb->db_query($sql);
if($mydb->db_num_rows($res)<1)
{
$sql="insert into ".$SystemConest[7]."orderpaylist (tourid,orderno,paytype,earnbizhong) value(".$_REQUEST['productid'].",'$orderidl','chinabank','RMB')";
$mydb->db_query($sql);
}
$result = $motoClient->consume( $_POST[ "orderid" ], $cardid, $year_month, $money*100, array("name"=>$name, "idcard"=>$idcard, "cvv2"=>$cvv, 'mobile'=>'139','type1'=>$type1, 'note'=>'nothing'));
//echo $result[$motoClient->MOTO_SEARCH_AMOUNT] . "<br />";
//print_a("RESULT Array", $result);
//echo "oid: {$result[$motoClient->MOTO_KEY_OID]},<br/> authcode: {$result[$motoClient->MOTO_KEY_AUTHID]},<br/>";
echo "result: {".formatalt($result[result])."}<br/>";
if($result[result]==0 and !strstr($result[result],"E"))//当返回0时交易流程成功,但要调用查询才能知道是否交易成功
{
//当返回0时,表示是实时的,可以调用查询马上得到结果
/**
result:0可以成功查询到此交易,$rsearch[$motoClient->MOTO_SEARCH_STATECODE]==0支付成功
*/
$rsearch = $motoClient->search($orderid);
if($rsearch[result]==0 and $rsearch[$motoClient->MOTO_SEARCH_STATECODE]==0)
{
//更改数据库里的订单状态
require RootDir."/inc/dabase_mysql.php";
$mydb=new YYBDB();
$sql2="earnestmoney=".$money.",paytimeearnestmoney=".time().",paytype='chinabank',earnbizhong='RMB',isconfim=1";
$paytype="dj";
if($payflag!="")
{
if($payflag=="je2")
{
$sql2=",balance=".$money.",paytimebalance=".time().",balancepaytye='chinabank',balancebizhong='RMB',balanceisconfim=1";
$paytype="je2";
}
if($payflag=="je3")
{
$sql2=",je3=".$money.",je3paytime=".time().",je3paytype='chinabank',je3bizhong='RMB',je3isconfim=1";
$paytype="je3";
}
if($payflag=="je4")
{
$sql2=",je4=".$money.",je4paytime=".time().",je4paytype='chinabank',je4bizhong='RMB',je4isconfim=1";
$paytype="je4";
}
}
$sql="update ".$SystemConest[7]."orderpaylist set
".$sql2."
where orderno='".$orderidl."'";
$mydb->db_query($sql);
$res=$mydb->db_query("select * from ".$SystemConest[7]."tourorder where orderno='".$orderidl."'");
$rs=$mydb->db_fetch_array($res);
//支付成功,执行发送邮件操作
echo "<iframe src='/".Q."SendMail_sendMailInfo_type_paysuss_orderno_".$orderidl."_paytype_".$paytype."_email_".$rs["nuseremail"]."'
frameborder=0 scrolling=no width=1 height=1></iframe>";
unset($rs);
require RootDir."/inc/Uifunction.php";
$url="/".Q."paytype_showpaysucctocustomer_orderno_".$orderidl."_moneynum_".$money."_bizhong_RMB_paytype_chinabank_djorwk_$paytype";
gourl($url,1);
}
}
elseif($result[result]==1)
{
echo "<br>您的卡是非实时交易卡,请稍后请进入<a href='http://usa.dreams-travel.com/user/dsztourorder_searchone'>订单查询页面查询</a><br>";
}
else
{
//支付失败时
echo "你的信用卡不能在本系统支付,或者你的信用卡设置了密码,或者卡号不对,所以不能支付!<br>请换一张信用卡或者换一种支付方式!";
}
?>
| 10npsite | trunk/Index/Lib/Order/chinabank/ChinaBankPay.php | PHP | asf20 | 4,532 |
<?php require "../../../../global.php";
require RootDir."/inc/Uifunction.php";
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<?php
/**
*功能:付完款后跳转的页面(页面跳转同步通知页面)
*版本:3.1
*日期:2010-10-29
'说明:
'以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
'该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
///////////页面功能说明///////////////
//该页面可在本机电脑测试
//该页面称作“页面跳转同步通知页面”,是由支付宝服务器同步调用,可当作是支付完成后的提示信息页,如“您的某某某订单,多少金额已支付成功”。
//可放入HTML等美化页面的代码和订单交易完成后的数据库更新程序代码
//该页面可以使用PHP开发工具调试,也可以使用写文本函数log_result进行调试,该函数已被默认关闭,见alipay_notify.php中的函数return_verify
//TRADE_FINISHED(表示交易已经成功结束,为普通即时到帐的交易状态成功标识);
//TRADE_SUCCESS(表示交易已经成功结束,为高级即时到帐的交易状态成功标识);
///////////////////////////////////
require_once("class/alipay_notify.php");
require_once("alipay_config.php");
//构造通知函数信息
$alipay = new alipay_notify($partner,$key,$sign_type,$_input_charset,$transport);
//计算得出通知验证结果
$verify_result = $alipay->return_verify();
if($verify_result) {//验证成功
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//请在这里加上商户的业务逻辑程序代码
//——请根据您的业务逻辑来编写程序(以下代码仅作参考)——
//获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表
$dingdan = $_GET['out_trade_no']; //获取订单号 这里是映射的订单号
$total_fee = $_GET['total_fee']; //获取总价格
$extra_common_param=$_GET["extra_common_param"];//获取自定义的参数,这里是价格的列表 多个用逗号分隔
$body =$_REQUEST["body"];//获取支付类型
//初始化参数
$dingdanno= getsubstr($dingdan, "/^H[\d]+/");
$jetype=getkuohaostr($dingdan, "/\(([a-z])/");//如果是a表示支付的是定金,如果是b支付的是余额
if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
//判断该笔订单是否在商户网站中已经做过处理(可参考“集成教程”中“3.4返回数据处理”)
//如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
//如果有做过处理,不执行商户的业务程序
//支付成功,更新订单数据库的内容
/**
$sql="select * from ".DQ."onlingpayorder where onlingpayorder1='".$dingdan."'";
$res=$mydb->query($sql);
if($rs=$mydb->db_fetch_array($res)){
$realorder=$rs["onlingpayorder2"];
}
if($realorder=="") die("参数错误");
preg_match("/[t|h][\d]{7}j[\d]{1}/",$realorder,$orderlist);//获取订单号列表
$pAmounts=preg_replace("/^[\w]+\^/","",$realorder);
$pAmountsarr=explode(",", $pAmounts);
$i=0;
*/
if($jetype="a"){
$sql2="pay3=".$pAmountsarr[$i].",pay4=".time().",pay5='支付宝',pay6=1";
}
if($jetype=="b"){
$sql2="pay7=".$pAmountsarr[$i].",pay8=".time().",pay9='支付宝',pay10=1";
}
$sql="update ".$SystemConest[7]."pay set ".$sql2." where pay1='".$dingdanno."'";
$mydb->db_query($sql);
//$dingdanlist.=$orderno."|".$SystemConest[7]."|".$payflag.",";
//支付成功,执行发送邮件操作
$dingdan=substr($dingdan, 0,-1);
echo "<iframe src='/sendmail/paysusshotel-orderno-".$dingdanno."' frameborder=0 scrolling=no width=1 height=1></iframe>";
unset($rs);
$url="/pay/showpaysuss-orderlist-".$dingdanl."";
gourl($url,1);
}
else {
echo "trade_status=".$_GET['trade_status'];
}
//——请根据您的业务逻辑来编写程序(以上代码仅作参考)——
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
else {
//验证失败
//如要调试,请看alipay_notify.php页面的return_verify函数,比对sign和mysign的值是否相等,或者检查$veryfy_result有没有返回true
echo "支付失败!请重新检查或联系我们!";
}
?>
<title>支付宝即时支付</title>
<style type="text/css">
.font_content{
font-family:"宋体";
font-size:14px;
color:#FF6600;
}
.font_title{
font-family:"宋体";
font-size:16px;
color:#FF0000;
font-weight:bold;
}
table{
border: 1px solid #CCCCCC;
}
</style></head>
<body>
<table align="center" width="350" cellpadding="5" cellspacing="0">
<tr>
<td align="center" class="font_title" colspan="2">梦之旅支付宝付款通知返回</td>
</tr>
<tr>
<td class="font_content" align="right">支付宝交易号:</td>
<td class="font_content" align="left"><?php echo $_GET['trade_no']; ?></td>
</tr>
<tr>
<td class="font_content" align="right">订单号:</td>
<td class="font_content" align="left"><?php echo $dingdan; ?></td>
</tr>
<tr>
<td class="font_content" align="right">付款总金额:</td>
<td class="font_content" align="left"><?php echo $_GET['total_fee']; ?></td>
</tr>
<tr>
<td class="font_content" align="right">商品标题:</td>
<td class="font_content" align="left"><?php echo $_GET['subject']; ?></td>
</tr>
<tr>
<td class="font_content" align="right">商品描述:</td>
<td class="font_content" align="left"><?php echo $_GET['body']; ?></td>
</tr>
<tr>
<td class="font_content" align="right">买家账号:</td>
<td class="font_content" align="left"><?php echo $_GET['buyer_email']; ?></td>
</tr>
<tr>
<td class="font_content" align="right">交易状态:</td>
<td class="font_content" align="left"><?php echo $_GET['trade_status']; ?></td>
</tr>
</table>
</body>
</html> | 10npsite | trunk/Index/Lib/Order/alipay_php_utf8/return_url.php | PHP | asf20 | 7,147 |
<?php
/**
*功能:支付宝接口公用函数
*详细:该页面是请求、通知返回两个文件所调用的公用函数核心处理文件,不需要修改
*版本:3.1
*修改日期:2010-10-29
'说明:
'以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
'该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
/**生成签名结果
*$array要签名的数组
*return 签名结果字符串
*/
function build_mysign($sort_array,$key,$sign_type = "MD5") {
$prestr = create_linkstring($sort_array); //把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
$prestr = $prestr.$key; //把拼接后的字符串再与安全校验码直接连接起来
$mysgin = sign($prestr,$sign_type); //把最终的字符串签名,获得签名结果
return $mysgin;
}
/********************************************************************************/
/**把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
*$array 需要拼接的数组
*return 拼接完成以后的字符串
*/
function create_linkstring($array) {
$arg = "";
while (list ($key, $val) = each ($array)) {
$arg.=$key."=".$val."&";
}
$arg = substr($arg,0,count($arg)-2); //去掉最后一个&字符
return $arg;
}
/********************************************************************************/
/**除去数组中的空值和签名参数
*$parameter 签名参数组
*return 去掉空值与签名参数后的新签名参数组
*/
function para_filter($parameter) {
$para = array();
while (list ($key, $val) = each ($parameter)) {
if($key == "sign" || $key == "sign_type" || $val == "")continue;
else $para[$key] = $parameter[$key];
}
return $para;
}
/********************************************************************************/
/**对数组排序
*$array 排序前的数组
*return 排序后的数组
*/
function arg_sort($array) {
ksort($array);
reset($array);
return $array;
}
/********************************************************************************/
/**签名字符串
*$prestr 需要签名的字符串
*return 签名结果
*/
function sign($prestr,$sign_type) {
$sign='';
if($sign_type == 'MD5') {
$sign = md5($prestr);
}elseif($sign_type =='DSA') {
//DSA 签名方法待后续开发
die("DSA 签名方法待后续开发,请先使用MD5签名方式");
}else {
die("支付宝暂不支持".$sign_type."类型的签名方式");
}
return $sign;
}
/********************************************************************************/
// 日志消息,把支付宝返回的参数记录下来
// 请注意服务器是否开通fopen配置
function log_result($word) {
$fp = fopen("log.txt","a");
flock($fp, LOCK_EX) ;
fwrite($fp,"执行日期:".strftime("%Y%m%d%H%M%S",time())."\n".$word."\n");
flock($fp, LOCK_UN);
fclose($fp);
}
/********************************************************************************/
/**实现多种字符编码方式
*$input 需要编码的字符串
*$_output_charset 输出的编码格式
*$_input_charset 输入的编码格式
*return 编码后的字符串
*/
function charset_encode($input,$_output_charset ,$_input_charset) {
$output = "";
if(!isset($_output_charset) )$_output_charset = $_input_charset;
if($_input_charset == $_output_charset || $input ==null ) {
$output = $input;
} elseif (function_exists("mb_convert_encoding")) {
$output = mb_convert_encoding($input,$_output_charset,$_input_charset);
} elseif(function_exists("iconv")) {
$output = iconv($_input_charset,$_output_charset,$input);
} else die("sorry, you have no libs support for charset change.");
return $output;
}
/********************************************************************************/
/**实现多种字符解码方式
*$input 需要解码的字符串
*$_output_charset 输出的解码格式
*$_input_charset 输入的解码格式
*return 解码后的字符串
*/
function charset_decode($input,$_input_charset ,$_output_charset) {
$output = "";
if(!isset($_input_charset) )$_input_charset = $_input_charset ;
if($_input_charset == $_output_charset || $input ==null ) {
$output = $input;
} elseif (function_exists("mb_convert_encoding")) {
$output = mb_convert_encoding($input,$_output_charset,$_input_charset);
} elseif(function_exists("iconv")) {
$output = iconv($_input_charset,$_output_charset,$input);
} else die("sorry, you have no libs support for charset changes.");
return $output;
}
/*********************************************************************************/
/**用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数
注意:由于低版本的PHP配置环境不支持远程XML解析,因此必须服务器、本地电脑中装有支持DOMDocument、SSL的PHP配置环境。建议本地调试时使用PHP开发软件
*$partner 合作身份者ID
*return 时间戳字符串
*/
function query_timestamp($partner) {
$URL = "https://mapi.alipay.com/gateway.do?service=query_timestamp&partner=".$partner;
$encrypt_key = "";
//若要使用防钓鱼,请取消下面的4行注释
// $doc = new DOMDocument();
// $doc->load($URL);
// $itemEncrypt_key = $doc->getElementsByTagName( "encrypt_key" );
// $encrypt_key = $itemEncrypt_key->item(0)->nodeValue;
// return $encrypt_key;
}
?> | 10npsite | trunk/Index/Lib/Order/alipay_php_utf8/class/alipay_function.php | PHP | asf20 | 5,860 |
<?php
/**
*类名:alipay_service
*功能:支付宝外部服务接口控制
*详细:该页面是请求参数核心处理文件,不需要修改
*版本:3.1
*修改日期:2010-10-29
'说明:
'以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
'该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
require_once("alipay_function.php");
class alipay_service {
var $gateway; //网关地址
var $_key; //安全校验码
var $mysign; //签名结果
var $sign_type; //签名类型
var $parameter; //需要签名的参数数组
var $_input_charset; //字符编码格式
/**构造函数
*从配置文件及入口文件中初始化变量
*$parameter 需要签名的参数数组
*$key 安全校验码
*$sign_type 签名类型
*/
function alipay_service($parameter,$key,$sign_type) {
$this->gateway = "https://www.alipay.com/cooperate/gateway.do?";
$this->_key = $key;
$this->sign_type = $sign_type;
$this->parameter = para_filter($parameter);
//设定_input_charset的值,为空值的情况下默认为GBK
if($parameter['_input_charset'] == '')
$this->parameter['_input_charset'] = 'GBK';
$this->_input_charset = $this->parameter['_input_charset'];
//获得签名结果
$sort_array = arg_sort($this->parameter); //得到从字母a到z排序后的签名参数数组
$this->mysign = build_mysign($sort_array,$this->_key,$this->sign_type);
}
/********************************************************************************/
/**构造表单提交HTML
*return 表单提交HTML文本
*/
function build_form() {
//GET方式传递
$sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='".$this->gateway."_input_charset=".$this->parameter['_input_charset']."' method='get'>";
//POST方式传递(GET与POST二必选一)
//$sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='".$this->gateway."_input_charset=".$this->parameter['_input_charset']."' method='post'>";
while (list ($key, $val) = each ($this->parameter)) {
$sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
}
$sHtml = $sHtml."<input type='hidden' name='sign' value='".$this->mysign."'/>";
$sHtml = $sHtml."<input type='hidden' name='sign_type' value='".$this->sign_type."'/>";
//submit按钮控件请不要含有name属性
$sHtml = $sHtml."<input type='submit' value='支付宝确认付款'></form>";
$sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";
return $sHtml;
}
/********************************************************************************/
}
?> | 10npsite | trunk/Index/Lib/Order/alipay_php_utf8/class/alipay_service.php | PHP | asf20 | 3,005 |
<?php
/*
*类名:alipay_notify
*功能:付款过程中服务器通知类
*详细:该页面是通知返回核心处理文件,不需要修改
*版本:3.1
*修改日期:2010-10-29
'说明:
'以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
'该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
////////////////////注意/////////////////////////
//调试通知返回时,可查看或改写log日志的写入TXT里的数据,来检查通知返回是否正常
/////////////////////////////////////////////////
require_once("alipay_function.php");
class alipay_notify {
var $gateway; //网关地址
var $_key; //安全校验码
var $partner; //合作伙伴ID
var $sign_type; //签名方式 系统默认
var $mysign; //签名结果
var $_input_charset; //字符编码格式
var $transport; //访问模式
/**构造函数
*从配置文件中初始化变量
*$partner 合作身份者ID
*$key 安全校验码
*$sign_type 签名类型
*$_input_charset 字符编码格式
*$transport 访问模式
*/
function alipay_notify($partner,$key,$sign_type,$_input_charset = "GBK",$transport= "https") {
$this->transport = $transport;
if($this->transport == "https") {
$this->gateway = "https://www.alipay.com/cooperate/gateway.do?";
}else {
$this->gateway = "http://notify.alipay.com/trade/notify_query.do?";
}
$this->partner = $partner;
$this->_key = $key;
$this->mysign = "";
$this->sign_type = $sign_type;
$this->_input_charset = $_input_charset;
}
/********************************************************************************/
/**对notify_url的认证
*返回的验证结果:true/false
*/
function notify_verify() {
//获取远程服务器ATN结果,验证是否是支付宝服务器发来的请求
if($this->transport == "https") {
$veryfy_url = $this->gateway. "service=notify_verify" ."&partner=" .$this->partner. "¬ify_id=".$_POST["notify_id"];
} else {
$veryfy_url = $this->gateway. "partner=".$this->partner."¬ify_id=".$_POST["notify_id"];
}
$veryfy_result = $this->get_verify($veryfy_url);
//生成签名结果
if(empty($_POST)) { //判断POST来的数组是否为空
return false;
}
else {
$post = para_filter($_POST); //对所有POST返回的参数去空
$sort_post = arg_sort($post); //对所有POST反馈回来的数据排序
$this->mysign = build_mysign($sort_post,$this->_key,$this->sign_type); //生成签名结果
//写日志记录
log_result("veryfy_result=".$veryfy_result."\n notify_url_log:sign=".$_POST["sign"]."&mysign=".$this->mysign.",".create_linkstring($sort_post));
//判断veryfy_result是否为ture,生成的签名结果mysign与获得的签名结果sign是否一致
//$veryfy_result的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
//mysign与sign不等,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关
if (preg_match("/true$/i",$veryfy_result) && $this->mysign == $_POST["sign"]) {
return true;
} else {
return false;
}
}
}
/********************************************************************************/
/**对return_url的认证
*return 验证结果:true/false
*/
function return_verify() {
//获取远程服务器ATN结果,验证是否是支付宝服务器发来的请求
if($this->transport == "https") {
$veryfy_url = $this->gateway. "service=notify_verify" ."&partner=" .$this->partner. "¬ify_id=".$_GET["notify_id"];
} else {
$veryfy_url = $this->gateway. "partner=".$this->partner."¬ify_id=".$_GET["notify_id"];
}
$veryfy_result = $this->get_verify($veryfy_url);
//生成签名结果
if(empty($_GET)) { //判断GET来的数组是否为空
return false;
}
else {
$get = para_filter($_GET); //对所有GET反馈回来的数据去空
$sort_get = arg_sort($get); //对所有GET反馈回来的数据排序
$this->mysign = build_mysign($sort_get,$this->_key,$this->sign_type); //生成签名结果
//写日志记录
//log_result("veryfy_result=".$veryfy_result."\n return_url_log:sign=".$_GET["sign"]."&mysign=".$this->mysign."&".create_linkstring($sort_get));
//判断veryfy_result是否为ture,生成的签名结果mysign与获得的签名结果sign是否一致
//$veryfy_result的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
//mysign与sign不等,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关
if (preg_match("/true$/i",$veryfy_result) && $this->mysign == $_GET["sign"]) {
return true;
}else {
return false;
}
}
}
/********************************************************************************/
/**获取远程服务器ATN结果
*$url 指定URL路径地址
*return 服务器ATN结果集
*/
function get_verify($url,$time_out = "60") {
$urlarr = parse_url($url);
$errno = "";
$errstr = "";
$transports = "";
if($urlarr["scheme"] == "https") {
$transports = "ssl://";
$urlarr["port"] = "443";
} else {
$transports = "tcp://";
$urlarr["port"] = "80";
}
$fp=@fsockopen($transports . $urlarr['host'],$urlarr['port'],$errno,$errstr,$time_out);
if(!$fp) {
die("ERROR: $errno - $errstr<br />\n");
} else {
fputs($fp, "POST ".$urlarr["path"]." HTTP/1.1\r\n");
fputs($fp, "Host: ".$urlarr["host"]."\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($urlarr["query"])."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $urlarr["query"] . "\r\n\r\n");
while(!feof($fp)) {
$info[]=@fgets($fp, 1024);
}
fclose($fp);
$info = implode(",",$info);
return $info;
}
}
/********************************************************************************/
}
?>
| 10npsite | trunk/Index/Lib/Order/alipay_php_utf8/class/alipay_notify.php | PHP | asf20 | 6,866 |
<?php
/*
*功能:快速付款入口模板页
*详细:该页面是针对不涉及到购物车流程、充值流程等业务流程,只需要实现买家能够快速付款给卖家的付款功能。
*版本:3.1
*日期:2010-10-29
*说明:
*以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
*该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
require_once("alipay_config.php");
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML XMLNS:CC><HEAD><TITLE>支付宝 - 网上支付 安全快速!</TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<META content=网上购物/网上支付/安全支付/安全购物/购物,安全/支付,安全/支付宝/安全,支付/安全,购物/支付,
name=description 在线 付款,收款 网上,贸易 网上贸易.>
<META content=网上购物/网上支付/安全支付/安全购物/购物,安全/支付,安全/支付宝/安全,支付/安全,购物/支付, name=keywords
在线 付款,收款 网上,贸易 网上贸易.><LINK href="images/layout.css"
type=text/css rel=stylesheet>
<SCRIPT language=JavaScript>
<!--
//校验输入框 -->
function CheckForm()
{
if (document.alipayment.aliorder.value.length == 0) {
alert("请输入商品名称.");
document.alipayment.aliorder.focus();
return false;
}
if (document.alipayment.alimoney.value.length == 0) {
alert("请输入付款金额.");
document.alipayment.alimoney.focus();
return false;
}
var reg = new RegExp(/^\d*\.?\d{0,2}$/);
if (! reg.test(document.alipayment.alimoney.value))
{
alert("请正确输入付款金额");
document.alipayment.alimoney.focus();
return false;
}
if (Number(document.alipayment.alimoney.value) < 0.01) {
alert("付款金额金额最小是0.01.");
document.alipayment.alimoney.focus();
return false;
}
}
<!--
//控制文字显示-->
function glowit(which){
if (document.all.glowtext[which].filters[0].strength==2)
document.all.glowtext[which].filters[0].strength=1
else
document.all.glowtext[which].filters[0].strength=2
}
function glowit2(which){
if (document.all.glowtext.filters[0].strength==2)
document.all.glowtext.filters[0].strength=1
else
document.all.glowtext.filters[0].strength=2
}
function startglowing(){
if (document.all.glowtext&&glowtext.length){
for (i=0;i<glowtext.length;i++)
eval('setInterval("glowit('+i+')",150)')
}
else if (glowtext)
setInterval("glowit2(0)",150)
}
if (document.all)
window.onload=startglowing
</SCRIPT>
</HEAD>
<style>
<!--
#glowtext{
filter:glow(color=red,strength=2);
width:100%;
}
-->
</style>
<BODY text=#000000 bgColor=#ffffff leftMargin=0 topMargin=4>
<CENTER>
<TABLE cellSpacing=0 cellPadding=0 width=760 border=0>
<TBODY>
<TR>
<TD class=title>支付宝即时到帐付款快速通道</TD>
</TR></TBODY>
</TABLE><BR>
<FORM name=alipayment onSubmit="return CheckForm();" action=alipayto.php
method=post target="_blank">
<table>
<tr>
<td>
<TABLE cellSpacing=0 cellPadding=0 width=740 border=0>
<TR>
<TD class=form-left>收款方: </TD>
<TD class=form-star>* </TD>
<TD class=form-right><?php echo $mainname; ?></TD>
</TR>
<TR>
<TD colspan="3" align="center"><HR width=600 SIZE=2 color="#999999"></TD>
</TR>
<TR>
<TD class=form-left>标题: </TD>
<TD class=form-star>* </TD>
<TD class=form-right><INPUT size=30 name=aliorder maxlength="200"><span>如:7月5日定货款。</span></TD>
</TR>
<TR>
<TD class=form-left>订单号:</TD>
<TD class=form-star> </TD>
<TD class=form-right><INPUT size=30 name=out_trade_no id="out_trade_no" maxlength="200"></TD>
</TR>
<TR>
<TD class=form-left>付款金额: </TD>
<TD class=form-star>*</TD>
<TD class=form-right><INPUT maxLength=10 size=30 name=alimoney onFocus="if(Number(this.value)==0){this.value='';}" value="00.00"/>
<span>如:112.21</span></TD>
</TR>
<TR>
<TD class=form-left>备注:</TD>
<TD class=form-star></TD>
<TD class=form-right><TEXTAREA name=alibody rows=2 cols=40 wrap="physical"></TEXTAREA><BR>
(如联系方法,商品要求、数量等。100汉字内)</TD>
</TR>
<TR>
<TD class=form-left>支付方式:</TD>
<TD class=form-star></TD>
<TD class=form-right>
<table>
<tr>
<td><input type="radio" name="pay_bank" value="directPay" checked><img src="images/alipay_1.gif" border="0"/></td>
</tr>
</table>
</TD>
</TR>
<TR>
<TD class=form-left></TD>
<TD class=form-star></TD>
<TD class=form-right><INPUT type=image
src="images/button_sure.gif" value=确认订单
name=nextstep></TD>
</TR>
</TABLE>
</td>
<td vAlign=top width=205 style="font-size:12px;font-family:'宋体'">
<span id="glowtext">小贴士:</span>
<fieldset>
<P class=STYLE1>本通道为<a href="<?php echo $show_url; ?>" target="_blank"><strong><?php echo $mainname; ?></strong></a>客户专用,采用支付宝付款。请在支付前与本网站达成一致。</P>
<P class="style2">请务必与<a href="<?php echo $show_url; ?>" target="_blank"><strong><?php echo $mainname; ?></strong></a>确认好订单和货款后,再付款。可以在快速付款通道里的“标题”、“订单金额”、“付款方”和备注中填入相应的订单信息。</P>
<P class="style2 style3"> </P>
</fieldset>
</td>
</tr>
</table>
</FORM>
<TABLE cellSpacing=1 width=760 border=0>
<TR>
<TD><FONT class=note-help>如果您点击“购买”按钮,即表示您已经接受“支付宝服务协议”,同意向卖家购买此物品。
<BR>
您有责任查阅完整的物品登录资料,包括卖家的说明和接受的付款方式。卖家必须承担物品信息正确登录的责任!
</FONT>
</TD>
</TR>
</TABLE>
<TABLE cellSpacing=0 cellPadding=0 width=760 align=center border=0>
<TR align=middle>
<TD class="txt12 lh15"><A href="http://china.alibaba.com/"
target=_blank>阿里巴巴旗下公司</A> | 支付宝版权所有 2004-2012</TD>
</TR>
<TR align=middle>
<TD class="txt12 lh15"><IMG alt="支付宝通过“国际权威安全认证” "
src="images/logo_vbvv.gif" border=0><BR>支付宝通过“国际权威安全
认证”
</TD>
</TR>
</TABLE>
</BODY></HTML>
| 10npsite | trunk/Index/Lib/Order/alipay_php_utf8/index.php | PHP | asf20 | 7,012 |
<?php
/**
*功能:支付宝主动通知调用的页面(服务器异步通知页面)
*版本:3.1
*日期:2010-10-29
'说明:
'以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
'该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
///////////页面功能说明///////////////
//创建该页面文件时,请留心该页面文件中无任何HTML代码及空格。
//该页面不能在本机电脑测试,请到服务器上做测试。请确保外部可以访问该页面。
//该页面调试工具请使用写文本函数log_result,该函数已被默认关闭,见alipay_notify.php中的函数notify_verify
//TRADE_FINISHED(表示交易已经成功结束,通用即时到帐反馈的交易状态成功标志);
//TRADE_SUCCESS(表示交易已经成功结束,高级即时到帐反馈的交易状态成功标志);
//该服务器异步通知页面面主要功能是:对于返回页面(return_url.php)做补单处理。如果没有收到该页面返回的 success 信息,支付宝会在24小时内按一定的时间策略重发通知
/////////////////////////////////////
require_once("class/alipay_notify.php");
require_once("alipay_config.php");
$alipay = new alipay_notify($partner,$key,$sign_type,$_input_charset,$transport); //构造通知函数信息
$verify_result = $alipay->notify_verify(); //计算得出通知验证结果
if($verify_result) {//验证成功
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//请在这里加上商户的业务逻辑程序代
//——请根据您的业务逻辑来编写程序(以下代码仅作参考)——
//获取支付宝的通知返回参数,可参考技术文档中服务器异步通知参数列表
$dingdan = $_POST['out_trade_no']; //获取支付宝传递过来的订单号
$total = $_POST['total_fee']; //获取支付宝传递过来的总价格
if($_POST['trade_status'] == 'TRADE_FINISHED' ||$_POST['trade_status'] == 'TRADE_SUCCESS') { //交易成功结束
//判断该笔订单是否在商户网站中已经做过处理(可参考“集成教程”中“3.4返回数据处理”)
//如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
//如果有做过处理,不执行商户的业务程序
echo "success"; //请不要修改或删除
//调试用,写文本函数记录程序运行情况是否正常
//log_result("这里写入想要调试的代码变量值,或其他运行的结果记录");
}
else {
echo "success"; //其他状态判断。普通即时到帐中,其他状态不用判断,直接打印success。
//调试用,写文本函数记录程序运行情况是否正常
//log_result ("这里写入想要调试的代码变量值,或其他运行的结果记录");
}
//——请根据您的业务逻辑来编写程序(以上代码仅作参考)——
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
else {
//验证失败
echo "fail";
//调试用,写文本函数记录程序运行情况是否正常
//log_result ("这里写入想要调试的代码变量值,或其他运行的结果记录");
}
?> | 10npsite | trunk/Index/Lib/Order/alipay_php_utf8/notify_url.php | PHP | asf20 | 3,640 |
<? require "../../../../global.php";?>
<?php
/**
*功能:设置商品有关信息(确认订单支付宝在线购买入口页)
*详细:该页面是接口入口页面,生成支付时的URL
*版本:3.1
*修改日期:2010-10-29
'说明:
'以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
'该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
////////////////////注意/////////////////////////
//如果您在接口集成过程中遇到问题,
//您可以到商户服务中心(https://b.alipay.com/support/helperApply.htm?action=consultationApply),提交申请集成协助,我们会有专业的技术工程师主动联系您协助解决,
//您也可以到支付宝论坛(http://club.alipay.com/read-htm-tid-8681712.html)寻找相关解决方案
//要传递的参数要么不允许为空,要么就不要出现在数组与隐藏控件或URL链接里。
/////////////////////////////////////////////////
require_once("alipay_config.php");
require_once("class/alipay_service.php");
//以下参数是需要通过下单时的订单数据传入进来获得
//必填参数
$out_trade_no = $_REQUEST['out_trade_no']; //$_POST['out_trade_no']请与贵网站订单系统中的唯一订单号匹配
$subject = $_REQUEST['aliorder']; //订单名称,显示在支付宝收银台里的“商品名称”里,显示在支付宝的交易管理的“商品名称”的列表里。
$body = $_REQUEST['alibody']."(".$_REQUEST["paymoneytype"].")"; //订单描述、订单详细、订单备注,显示在支付宝收银台里的“商品描述”里
$total_fee = $_REQUEST['alimoney']; //订单总金额,显示在支付宝收银台里的“应付总额”里
$dingjiallnumlist=$_REQUEST["dingjiallnumlist"];//各个订单的订金金额列表,多个用逗号分隔
$jetype=$_REQUEST["jetype"];//支付金额的类型,a为定金,b为余额
//扩展功能参数——默认支付方式
$pay_mode = $_POST['pay_bank'];
if ($pay_mode == "directPay") {
$paymethod = "directPay"; //默认支付方式,四个值可选:bankPay(网银); cartoon(卡通); directPay(余额); CASH(网点支付)
$defaultbank = "";
}
else {
$paymethod = "bankPay"; //默认支付方式,四个值可选:bankPay(网银); cartoon(卡通); directPay(余额); CASH(网点支付)
$defaultbank = $pay_mode; //默认网银代号,代号列表见http://club.alipay.com/read.php?tid=8681379
}
//初始化支付信息,当支付列表里没有支付信息时添加一条新的支付记录
require RootDir."/inc/dabase_mysql.php";
$mydb=new YYBDB();
$orderlist=explode(",",$out_trade_no);
$alimoneylistarr=explode(",",$dingjiallnumlist);
$i=0;
foreach ($orderlist as $v){
$sql="select pay1 from ".$SystemConest[7]."pay where pay1='".$v."'";
$res=$mydb->db_query($sql);
if($mydb->db_num_rows($res)<1){
$sql="insert into ".$SystemConest[7]."pay (pay1,pay3,pay5) value('".$v."',573,".$alimoneylistarr[$i].",'支付宝')";
$mydb->db_query($sql);
}
$i++;
}
//构建映射表,把真实订单号存入数据库里,再生成一个简短的订单号供支付
$out_trade_no=$out_trade_no."(".$jetype.rand(10, 99).")";//产生一个随机数,供支付多次
/**
require RootDir."/inc/dabase_mysql.php";
$mydb=new YYBDB();
$sql="select * from ".DQ."onlingpayorder where onlingpayorder2='".$pAttach."'";
$res=$mydb->db_query($sql);
if($rs=$mydb->db_fetch_array($res)){
$newordern=$rs["onlingpayorder1"];
}
else{
//生成新的订单号用于向第三方支付
$newordern="M".date("ydmhis").rand(10, 99);
$sql="insert into ".DQ."onlingpayorder (onlingpayorder1,onlingpayorder2) value('".$newordern."','".$pAttach."')";
$mydb->db_query($sql);
}
*/
//扩展功能参数——防钓鱼
//请慎重选择是否开启防钓鱼功能
//exter_invoke_ip、anti_phishing_key一旦被使用过,那么它们就会成为必填参数
//开启防钓鱼功能后,服务器、本机电脑必须支持远程XML解析,请配置好该环境。
//若要使用防钓鱼功能,请打开class文件夹中alipay_function.php文件,找到该文件最下方的query_timestamp函数,根据注释对该函数进行修改
//建议使用POST方式请求数据
$anti_phishing_key = ''; //防钓鱼时间戳
$exter_invoke_ip = ''; //获取客户端的IP地址,建议:编写获取客户端IP地址的程序
//如:
//$exter_invoke_ip = '202.1.1.1';
//$anti_phishing_key = query_timestamp($partner); //获取防钓鱼时间戳函数
//扩展功能参数——其他
$extra_common_param = $alimoneylistarr; //自定义参数,可存放任何内容(除=、&等特殊字符外),不会显示在页面上 这里放入的是价格的参数列表
$buyer_email = ''; //默认买家支付宝账号
//扩展功能参数——分润(若要使用,请按照注释要求的格式赋值)
$royalty_type = ""; //提成类型,该值为固定值:10,不需要修改
$royalty_parameters = "";
//提成信息集,与需要结合商户网站自身情况动态获取每笔交易的各分润收款账号、各分润金额、各分润说明。最多只能设置10条
//各分润金额的总和须小于等于total_fee
//提成信息集格式为:收款方Email_1^金额1^备注1|收款方Email_2^金额2^备注2
//如:
//royalty_type = "10"
//royalty_parameters = "111@126.com^0.01^分润备注一|222@126.com^0.01^分润备注二"
///
//构造要请求的参数数组,无需改动
$parameter = array(
"service" => "create_direct_pay_by_user", //接口名称,不需要修改
"payment_type" => "1", //交易类型,不需要修改
//获取配置文件(alipay_config.php)中的值
"partner" => $partner,
"seller_email" => $seller_email,
"return_url" => $return_url,
"notify_url" => $notify_url,
"_input_charset" => $_input_charset,
"show_url" => $show_url,
//从订单数据中动态获取到的必填参数
"out_trade_no" => $out_trade_no,
"subject" => $subject,
"body" => $body,
"total_fee" => $total_fee,
//扩展功能参数——网银提前
"paymethod" => $paymethod,
"defaultbank" => $defaultbank,
//扩展功能参数——防钓鱼
"anti_phishing_key" => $anti_phishing_key,
"exter_invoke_ip" => $exter_invoke_ip,
//扩展功能参数——自定义参数
"buyer_email" => $buyer_email,
"extra_common_param"=> $extra_common_param,
//扩展功能参数——分润
"royalty_type" => $royalty_type,
"royalty_parameters"=> $royalty_parameters
);
//构造请求函数
$alipay = new alipay_service($parameter,$key,$sign_type);
$sHtmlText = $alipay->build_form();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>支付宝即时支付</title>
<style type="text/css">
.font_content{
font-family:"宋体";
font-size:14px;
color:#FF6600;
}
.font_title{
font-family:"宋体";
font-size:16px;
color:#FF0000;
font-weight:bold;
}
table{
border: 1px solid #CCCCCC;
}
</style>
</head>
<body>
<div style="">正在跳转.....</div>
<table style="display:none" align="center" width="350" cellpadding="5" cellspacing="0">
<tr>
<td align="center" class="font_title" colspan="2">订单确认</td>
</tr>
<tr>
<td class="font_content" align="right">订单号:</td>
<td class="font_content" align="left"><?php echo $out_trade_no; ?></td>
</tr>
<tr>
<td class="font_content" align="right">付款总金额:</td>
<td class="font_content" align="left"><?php echo $total_fee; ?></td>
</tr>
<tr>
<td align="center" colspan="2"><?php echo $sHtmlText; ?></td>
</tr>
</table>
</body>
</html>
| 10npsite | trunk/Index/Lib/Order/alipay_php_utf8/alipayto.php | PHP | asf20 | 8,508 |
<?php
/**
*功能:设置帐户有关信息及返回路径(基础配置页面)
*版本:3.1
*日期:2010-10-29
'说明:
'以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
'该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
/** 提示:如何获取安全校验码和合作身份者ID
1.访问支付宝商户服务中心(b.alipay.com),然后用您的签约支付宝账号登陆.
2.访问“技术服务”→“下载技术集成文档”(https://b.alipay.com/support/helperApply.htm?action=selfIntegration)
3.在“自助集成帮助”中,点击“合作者身份(Partner ID)查询”、“安全校验码(Key)查询”
安全校验码查看时,输入支付密码后,页面呈灰色的现象,怎么办?
解决方法:
1、检查浏览器配置,不让浏览器做弹框屏蔽设置
2、更换浏览器或电脑,重新登录查询。
*/
//↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//合作身份者ID,以2088开头的16位纯数字
//$partner = "2088102877500134";
//安全检验码,以数字和字母组成的32位字符
//$key = "ka1b4cvquz2o9yoek8pbuytf4c2qwswx";
//签约支付宝账号或卖家支付宝帐户
//$seller_email = "office@dreams-travel.com";
//合作身份者ID,以2088开头的16位纯数字
$partner = "2088701788739916";
//安全检验码,以数字和字母组成的32位字符
$key = "zthsg2knlwt2nn99c3yan5zi3fspmzaf";
//签约支付宝账号或卖家支付宝帐户
$seller_email = "cw@dreams-travel.com";
//交易过程中服务器通知的页面 要用 http://格式的完整路径,不允许加?id=123这类自定义参数
$notify_url = "http://".$_SERVER['SERVER_NAME']."/Lib/Order/alipay_php_utf8/notify_url.php";
//付完款后跳转的页面 要用 http://格式的完整路径,不允许加?id=123这类自定义参数
$return_url = "http://".$_SERVER['SERVER_NAME']."/Lib/Order/alipay_php_utf8/return_url.php";
//网站商品的展示地址,不允许加?id=123这类自定义参数
$show_url = "http://".$_SERVER['SERVER_NAME'];
//收款方名称,如:公司名称、网站名称、收款人姓名等
$mainname = "梦之旅";
//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
//签名方式 不需修改
$sign_type = "MD5";
//字符编码格式 目前支持 GBK 或 utf-8
$_input_charset = "utf-8";
//访问模式,根据自己的服务器是否支持ssl访问,若支持请选择https;若不支持请选择http
$transport = "http";
?> | 10npsite | trunk/Index/Lib/Order/alipay_php_utf8/alipay_config.php | PHP | asf20 | 2,816 |
<?
//支付失败处理页面
?> | 10npsite | trunk/Index/Lib/Order/IPSRMBphp/demo/failurl.php | PHP | asf20 | 34 |
<?php
header("Content-type:text/html; charset=utf-8");
//提交地址
//$form_url = 'https://pay.ips.net.cn/ipayment.aspx'; //测试
$form_url = 'https://pay.ips.com.cn/ipayment.aspx'; //正式
//商户号
$Mer_code = "014740";
//商户证书:登陆http://merchant.ips.com.cn/商户后台下载的商户证书内容
$Mer_key = "36451620901856065970269330053246181842887948974683586506701057676567422219322046647065958403072037230625137727476541950060891824";
//商户订单编号
$Billno = $_POST['Billno'];
//订单金额(保留2位小数)
$Amount = number_format($_POST['Amount'], 2, '.', '');
//订单日期
$Date = date("Ymd");
//币种
$Currency_Type = $_POST['Currency_Type'];
//支付卡种
$Gateway_Type = "01";
//语言
$Lang = "GB";
//支付结果成功返回的商户URL
$Merchanturl = "http://".$_SERVER['SERVER_NAME']."/Lib/Order/IPSRMBphp/demo/OrderReturn.php";
//支付结果失败返回的商户URL
$FailUrl = "http://".$_SERVER['SERVER_NAME']."/Lib/Order/IPSRMBphp/demo/failurl.php";
//支付结果错误返回的商户URL
$ErrorUrl = $FailUrl;//暂时和失败返回同一个地址
//商户数据包
$Attach = $_POST['Attach'];
//显示金额
$DispAmount = $Amount;
//订单支付接口加密方式
$OrderEncodeType = 2;
//交易返回接口加密方式
$RetEncodeType =12;
//返回方式
$Rettype = 0;//暂不启用无server to server
//Server to Server 返回页面URL
$ServerUrl = "";//
require "../../../../global.php";
require RootDir."/inc/dabase_mysql.php";
$mydb=new YYBDB();
$sql="select orderno from ".$SystemConest[7]."orderpaylist where orderno='".$Billno."'";
$res=$mydb->db_query($sql);
if($mydb->db_num_rows($res)<1)
{
$sql="insert into ".$SystemConest[7]."orderpaylist (tourid,orderno,paytype,earnbizhong) value(".$_REQUEST['productid'].",'$Billno','环讯','RMB')";
$mydb->db_query($sql);
}
//订单支付接口的Md5摘要,原文=订单号+金额+日期+支付币种+商户证书
$SignMD5 = md5($Billno . $Amount . $Date . $Currency_Type . $Mer_key);
?>
<html>
<head>
<title>跳转......</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form action="<?php echo $form_url ?>" method="post" id="frm1">
<input type="hidden" name="Mer_code" value="<?php echo $Mer_code ?>">
<input type="hidden" name="Billno" value="<?php echo $Billno ?>">
<input type="hidden" name="Amount" value="<?php echo $Amount ?>" >
<input type="hidden" name="Date" value="<?php echo $Date ?>">
<input type="hidden" name="Currency_Type" value="<?php echo $Currency_Type ?>">
<input type="hidden" name="Gateway_Type" value="<?php echo $Gateway_Type ?>">
<input type="hidden" name="Lang" value="<?php echo $Lang ?>">
<input type="hidden" name="Merchanturl" value="<?php echo $Merchanturl ?>">
<input type="hidden" name="FailUrl" value="<?php echo $FailUrl ?>">
<input type="hidden" name="ErrorUrl" value="<?php echo $ErrorUrl ?>">
<input type="hidden" name="Attach" value="<?php echo $Attach ?>">
<input type="hidden" name="DispAmount" value="<?php echo $DispAmount ?>">
<input type="hidden" name="OrderEncodeType" value="<?php echo $OrderEncodeType ?>">
<input type="hidden" name="RetEncodeType" value="<?php echo $RetEncodeType ?>">
<input type="hidden" name="Rettype" value="<?php echo $Rettype ?>">
<input type="hidden" name="ServerUrl" value="<?php echo $ServerUrl ?>">
<input type="hidden" name="SignMD5" value="<?php echo $SignMD5 ?>">
</form>
<script language="javascript">
document.getElementById("frm1").submit();
</script>
</body>
</html>
| 10npsite | trunk/Index/Lib/Order/IPSRMBphp/demo/redirect.php | PHP | asf20 | 3,786 |
<?php
require "../../../../global.php";
//----------------------------------------------------
// 接收数据
// Receive the data
//----------------------------------------------------
$billno = $_GET['billno'];
$amount = $_GET['amount'];
$mydate = $_GET['date'];
$succ = $_GET['succ'];
$msg = $_GET['msg'];
$attach = $_GET['attach'];
$ipsbillno = $_GET['ipsbillno'];
$retEncodeType = $_GET['retencodetype'];
$currency_type = $_GET['Currency_type'];
$signature = $_GET['signature'];
//'----------------------------------------------------
//' Md5摘要认证
//' verify md5
//'----------------------------------------------------
$content = $billno . $amount . $mydate . $succ . $ipsbillno . $currency_type;
//请在该字段中放置商户登陆merchant.ips.com.cn下载的证书
$cert = '36451620901856065970269330053246181842887948974683586506701057676567422219322046647065958403072037230625137727476541950060891824';
$signature_1ocal = md5($content . $cert);
if ($signature_1ocal == $signature)
{
//----------------------------------------------------
// 判断交易是否成功
// See the successful flag of this transaction
//----------------------------------------------------
if ($succ == 'Y')
{
/**----------------------------------------------------
*比较返回的订单号和金额与您数据库中的金额是否相符
*compare the billno and amount from ips with the data recorded in your datebase
*----------------------------------------------------
if(不等)
echo "从IPS返回的数据和本地记录的不符合,失败!"
exit
else
'----------------------------------------------------
'交易成功,处理您的数据库
'The transaction is successful. update your database.
'----------------------------------------------------
end if
**/
//更新商户数据库内容
require RootDir."/inc/dabase_mysql.php";
$mydb=new YYBDB();
preg_match("/^[a-zA-Z][0-9]+/",$billno,$orderAr);
$billnol=$orderAr[0];
$payflag=str_replace($billnol,"",$billno);
//定金支付条件
$sql2="earnestmoney=".$amount.",paytimeearnestmoney=".time().",earnbizhong='".$currency_type."',paytype='环讯',isconfim=1";
$paytype="dj";
if($payflag!="")
{
if($payflag=="je2")//第二次支付条件
{
$sql2="balance=".$amount.",paytimebalance=".time().",balancebizhong='".$currency_type."',balancepaytye='环讯',balanceisconfim=1";
$paytype="je2";
}
if($payflag=="je3")
{
$sql2="je3=".$amount.",je3paytime=".time().",je3bizhong='".$currency_type."',je3paytype='环讯',je3isconfim=1";
$paytype="je3";
}
if($payflag=="je4")
{
$sql2="je4=".$amount.",je4paytime=".time().",je4bizhong='".$currency_type."',je4paytype='环讯',je4isconfim=1";
$paytype="je4";
}
}
$sql="update ".$SystemConest[7]."orderpaylist set ".$sql2." where orderno='".$billnol."'";
$mydb->db_query($sql);
$res=$mydb->db_query("select * from ".$SystemConest[7]."tourorder where orderno='".$billnol."'");
$rs=$mydb->db_fetch_array($res);
//支付成功,执行发送邮件操作
echo "<iframe src='/dszSendMail_sendMailInfo_type_paysuss_orderno_".$billnol."_paytype_网银在线支付_djorwk_".$paytype."_email_".$rs["nuseremail"]."'
frameborder=0 scrolling=no width=1 height=1></iframe>";
unset($rs);
//这里可以写支付后的返回给用户的界面
require RootDir."/inc/Uifunction.php";
$url="/".Q."paytype_showpaysucctocustomer_orderno_".$billnol."_moneynum_".$amount."_bizhong_RMB_paytype_网银在线支付";
gourl($url,1);
}
else
{
echo '交易失败!';
exit;
}
}
else
{
echo '签名不正确!';
exit;
}
?>
| 10npsite | trunk/Index/Lib/Order/IPSRMBphp/demo/OrderReturn.php | PHP | asf20 | 3,846 |
<?php
?> | 10npsite | trunk/Index/Lib/Action/globalAction.class.php | PHP | asf20 | 16 |
<?php
/**
* 公共资源服务
* Created by Tinico
*/
class apiAction extends Action {
private $dao;
public function _initialize() {
parent::_initialize();
$this->dao = M('classsys');
}
public function district() {
$dist = intval($_GET['dist']);
$field = array(
'classsys0' => 'id',
'classsys1' => 'name',
'classsys2' => 'parent',
'classsys4' => 'order'
);
$condition['classsys3'] = 590;
$condition['classsys0'] = $dist;
M('classsys')->
}
//查找节点路径
public function getRoot($nodeId, &$path) {
//查找父ID
$node = $this->dao
->field(array('classsys0'=>'id'))
->where('classsys0='.$nodeId)
->find();
$parentId = $node['classsys2'];
//父ID为0或空时即是根节点
if(empty($parentId))
return empty($path) ? $node['id'];
else
return getRoot($parentId);
}
}
?> | 10npsite | trunk/Index/Lib/Action/Inn/apiAction.class.php | PHP | asf20 | 1,132 |
<?php
/**
* 订单表
* @author Administrator
*
*/
class orderformAction extends Action{
/**
* 生成订单号
* @param $data 参数数组
* @return 成功返回订单号,失败返回false
*/
function addorder($data){
if(!$data) return false;
$mr=M("orderform");
//========计算订单号
//获取最近的一个订单号
$rs=$mr->order("orderform0 desc")->where("orderform3 like 'H1%'")->getField("orderform3");
$orderno=$rs;
if($orderno==""){
$orderno="H10000001";
}else{
$orderno=preg_replace("/^H1[0]*/", "", $orderno);
$orderno=$orderno+1;
$temp="0000000";
$orderno="H1".preg_replace("/[0]{".strlen($orderno)."}$/", $orderno, $temp);
}
$data["orderform3"]=$orderno;
$rs=$mr->add($data);
return $rs?$orderno:false;
}
}
?> | 10npsite | trunk/Index/Lib/Action/Inn/orderformAction.class.php | PHP | asf20 | 843 |
<?php
/**
* 客栈列表
*/
class listAction extends globalAction {
private $dao;
public function _initialize() {
parent::_initialize();
parent::_loginRequire();
$this->dao = D('Inn');
}
public function index() {
$innList = $this->dao
->field($this->dao->_map_flip)
->where(array(
$this->dao->_map['menuId'] => 585,
$this->dao->_map['uid'] => __USERID__
))
->order(array(
$this->dao->_map['display_order'] => 'desc'
))
->select();
//字段附加
if($innList) {
$innCount = count($innList);
$InnCooperationDao = D('InnCooperation');
$InnTypeDao = D('InnType');
for($i = 0; $i < $innCount; $i++) {
//合作方式
$InnCooperation = $InnCooperationDao
->field($InnCooperationDao->_map_flip)
->where(array(
$InnCooperationDao->_map['menuId'] => 600,
$InnCooperationDao->_map['id'] => intval($innList[$i]['cooperation'])
))
->find();
$innList[$i]['cooperation'] = $InnCooperation['name'];
//客栈类别
$InnType = $InnTypeDao
->field($InnTypeDao->_map_flip)
->where(array(
$InnTypeDao->_map['menuId'] => 606,
$InnTypeDao->_map['id'] => intval($innList[$i]['type'])
))
->find();
$innList[$i]['type'] = $InnType['name'];
}
}
$this->assign('innList', $innList);
$this->display();
}
} | 10npsite | trunk/Index/Lib/Action/Inn/listAction.class.php | PHP | asf20 | 1,867 |
<?php
/**
* 点评管理
*/
class ReviewsAction extends globalAction {
private $reviewsDao, $innDao, $myInn;
public function _initialize() {
parent::_initialize();
parent::_loginRequire();
$this->reviewsDao = D('InnReviews');
$this->innDao = D('Inn');
$field = array(
$this->innDao->_map['id'] => 'id',
$this->innDao->_map['name'] => 'name'
);
$myInnList = $this->innDao
->field($field)
->where(array(
$this->innDao->_map['menuId'] => 585,
$this->innDao->_map['uid'] => __USERID__
))
->select();
if(!empty($myInnList)) {
$this->myInn = makearray($myInnList, 'id', 'name');
$this->assign('myInn', $this->myInn);
}
}
public function index() {
$conditions[$this->reviewsDao->_map['menu_id']] = 604;
$conditions[$this->reviewsDao->_map['product_id']] = array('in',array_keys($this->myInn));
$reviewsList = $this->reviewsDao
->field($this->reviewsDao->_map_flip)
->where($conditions)
->order($this->reviewsDao->_map['msg_time'])
->select();
$this->assign('reviewsList', $reviewsList);
$this->display();
}
public function details() {
$rv_id = intval($_GET['id']);
if(empty($rv_id)) parent::_message('error', '未指定点评内容ID');
$conditions[$this->reviewsDao->_map['rv_id']] = $rv_id;
$conditions[$this->reviewsDao->_map['menu_id']] = 604;
$conditions[$this->reviewsDao->_map['product_id']] = array('in',array_keys($this->myInn));
$reviews = $this->reviewsDao
->field($this->reviewsDao->_map_flip)
->where($conditions)
->find();
$this->assign('reviews', $reviews);
$this->display();
}
} | 10npsite | trunk/Index/Lib/Action/Inn/reviewsAction.class.php | PHP | asf20 | 2,013 |
<?php
class hotelAction extends globalAction{
public function _initialize() {
parent::_initialize();
$this->assign('moduleTitle', '客栈');
}
public function test(){
echo GROUP_NAME;
}
/**
* 获取推荐客栈栏目 暂以排序值排
*/
public function gettuijianhotel(){
$imr=M("hotel");
$sqlrs="select hotel0,hotel1,hotel15 from ".DQ."hotel where hotel23=1212 order by hotel25 desc,hotel0 desc limit 0,20";
$rstujname=$imr->query($sqlrs);
$this->assign("rs",$rstujname);
$temp= $this->fetch("hotel:gettuijianhotel");
return $temp;
}
/**
* 获取本月最热门的客栈 暂以人气值排
*/
public function getrenqipaihang(){
$imr=M("hotel");
$sqlrs="select hotel0,hotel1 from ".DQ."hotel where hotel23=1212 order by hotel26 desc,hotel0 desc limit 0,20";
$rshotname=$imr->query($sqlrs);
$this->assign("rs",$rshotname);
$temp= $this->fetch("hotel:getrenqipaihang");
return $temp;
}
/**
* 查看酒店的具体的信息
*
*/
function view(){
$id=$_REQUEST["id"];//酒店id
if(!is_numeric($id)) die("请从正确的地址进入");
$hmr=M("hotel");
$cmr=A("Inn/classsys");
$picmr=A("Inn/pic");
$sql="select * from ".DQ."hotel where hotel0=".$id;
$rs=$hmr->cache(true)->query($sql);
//调用基础设施中文值
if($rs[0]["hotel20"]!=""){
$this->assign("jichushes",$cmr->getidtoname($rs[0]["hotel20"],1));
}
//调用客栈等级图片地址
if($rs[0]["hotel6"]!=""){
$this->assign("dengjipic",$cmr->getidtoname($rs[0]["hotel6"],7));
}
//获取房型信息
$sql="select * from ".DQ."hotelroom where hotelroom2=".$id." order by hotelroom18 desc";
$fangxinrs=$hmr->cache(true)->query($sql);
if($fangxinrs) $this->assign("fangxinrs",$fangxinrs);
//获取房型图片
$picrs=$picmr->getpiclist($rs[0]["hotel0"]);
if($picrs) $this->assign("picrs",$picrs);
//获取周边客栈
$zhoubianhotel=$this->getzhoubianhotel($rs[0]["hotel0"],$rs[0]["hotel5"]);
$this->assign("zhoubianhotel",$zhoubianhotel);
//获取评论列表
$plmr=A("Inn/pinglun");
$pinglunlist=$plmr->getpinglunlist($rs[0]["hotel0"]);
$totalpf=$plmr->getonehotelpingf($rs[0]["hotel0"]);
//获取这个客栈的每一项的评分
$everypl=$plmr->getpinglunhotelev($rs[0]["hotel0"]);
//获取猜你喜欢酒店客栈
$cnxhh=$this->getxihuanhotellist($rs[0]["hotel5"], $rs[0]["hotel0"]);
$this->assign("everypl",$everypl);
$this->assign("totalpf",$totalpf);
$this->assign("pinglunlist",$pinglunlist);
$this->assign("cnxhh",$cnxhh);
//获取回复列表
$mel=A("Inn/messagesys");
$messl=$mel->getmlistofhotel($rs[0]["hotel0"]);
$this->assign("messl",$messl);
//获取客栈类别信息
$sql="select * from ".DQ."classsys where classsys0=".$rs[0]["hotel4"];
$clsrs=M()->query($sql);
$this->assign("clsrs",$clsrs[0]);
$this->assign("rs",$rs[0]);
$this->display();
}
/**
* 每执行一次就给一个客栈增加人气值1
*/
function addrenqi(){
$hid=$_REQUEST["hid"];//酒店id值
if(!is_numeric($hid)) die("dopass");
$mr=M("hotel");
if($mr->where('hotel0='.$hid)->setInc('hotel26',1)){
echo "dook";
} else{
echo "dopass";
}
}
/**
* 添加客栈特色内容
*/
function addteshe(){
$hid=$_REQUEST["hid"];//酒店id值
$teshecontent=$_REQUEST["teshecontent"];
if(!is_numeric($hid)) die("dopass");
$temp=getsubstr($teshecontent,"/^[\s,,.。'\"]+$/");
if($temp!="" or $teshecontent=="") die("dopass");
$sql="update ".DQ."hotel set hotel27=concat(hotel27,',".$teshecontent."') where hotel0=".$hid;
$mr=M("hotel");
$rs=$mr->execute($sql);
if($rs){
echo "dook";
} else{
echo "dopass";
}
}
/**
* 通过cookie获取浏览过的客栈名称
*/
function getbrowerhotebycookie(){
$arr=unserialize($_COOKIE["browerhotel"]);
$this->assign("rs",$arr);
$this->display();
}
/**
* 把浏览过的一个酒店地址添加到cookie值里
*/
function addbrowerhoteltocookie(){
$hid=$_REQUEST["hid"];//酒店id
$hname=$_REQUEST["hname"];//酒店名称
if(!is_numeric($hid)) die("dopass");
if($hname=="") die("dopass");
$arr=unserialize($_COOKIE["browerhotel"]);
$arr[$hid]=$hname;
setcookie("browerhotel",serialize($arr),time()+13600,"/","");
}
/**
* 获取周边酒店列表,查找同类别下的其它客栈
*/
function getzhoubianhotel($hid,$cid){
if(!is_numeric($hid) or !is_numeric($cid)) return null;
$mr=M("hotel");
$sql="select hotel0,hotel1 from ".DQ."hotel where hotel5=".$cid." and hotel0<>".$hid."
order by hotel25 desc,hotel28 desc limit 0,10";
$rs=$mr->query($sql);
return $rs?$rs:null;
}
/**
* 获取猜你喜欢的酒店列表,规则暂时是同市下面的随机几个客栈
* @param $cid
*/
function getxihuanhotellist($cid,$hid){
if(!is_numeric($cid)) return "";
if(!is_numeric($hid)) return "";
$sql="select hotel0,hotel1,hotel15 from ".DQ."hotel where hotel5 in
(select classsys0 from ".DQ."classsys where classsys2=
(select classsys2 from ".DQ."classsys where classsys0=$cid))
and hotel0<>$hid limit 0,10
";
$mr=M("hotel");
$rs=$mr->query($sql);
return ($rs)?$rs:"";
}
/**
* 酒店列表页
*/
function hotellist(){
//城市列表
$innAreaDao = D('InnArea');
$innAreaProvince = S('innAreaProvince');
if(empty($innAreaProvince)) {
$innAreaProvince = $innAreaDao
->field($innAreaDao->_map_flip)
->where(array(
$innAreaDao->_map['menuId']=>590,
$innAreaDao->_map['parent']=>0
))
->order($innAreaDao->_map['order'])
->select();
S('innAreaProvince', $innAreaProvince);
}
$innCity = S('innCity');
if(empty($innCity)) {
$innCity = array();
$provinceCount = count($innAreaProvince);
for($i=0; $i<$provinceCount; $i++) {
$provinceId = $innAreaProvince[$i]['id'];
$innCity[$provinceId] = $innAreaDao
->field($innAreaDao->_map_flip)
->where(array(
$innAreaDao->_map['menuId']=>590,
$innAreaDao->_map['parent']=>$provinceId
))
->order($innAreaDao->_map['order'])
->select();
}
S('innCity', $innCity);
}
$this->assign('innAreaProvince', $innAreaProvince);
$this->assign('innCity', $innCity);
//客栈类型列表
$innTypeDao = D('InnType');
$innType = $innTypeDao
->field($innTypeDao->_map_flip)
->where(array(
$innTypeDao->_map['menuId']=>606,
$innTypeDao->_map['parent']=>0
))
->select();
$innTypeList = makearray($innType, 'id', 'name');
$this->assign('innType', $innType);
$this->assign('innTypeList', $innTypeList);
//客栈等级列表
$innClassDao = D('InnClass');
$innClass = $innClassDao
->field($innClassDao->_map_flip)
->where(array(
$innClassDao->_map['menuId']=>598,
$innClassDao->_map['parent']=>0
))
->select();
$this->assign('innClass', $innClass);
//客栈主题列表
$innSubjectDao = D('InnSubject');
$innSubject = $innSubjectDao
->field($innSubjectDao->_map_flip)
->where(array(
$innSubjectDao->_map['menuId']=>613,
$innSubjectDao->_map['parent']=>0
))
->select();
$this->assign('innSubject', $innSubject);
//推荐方式列表
$innRecommendDao = D('InnRecommend');
$innRecommend = $innRecommendDao
->field($innRecommendDao->_map_flip)
->where(array(
$innRecommendDao->_map['menuId']=>614,
$innRecommendDao->_map['parent']=>0
))
->select();
$this->assign('innRecommend', $innRecommend);
//预定方式列表
$innBookTypeDao = D('InnBookType');
$innBookType = $innBookTypeDao
->field($innBookTypeDao->_map_flip)
->where(array(
$innBookTypeDao->_map['menuId']=>615,
$innBookTypeDao->_map['parent']=>0
))
->select();
$this->assign('innBookType', $innBookType);
/***********************************************************************
* 解析筛选条件,构造筛选URL
**********************************************************************/
$innDao = D('Inn');
$title = '';//网页标题
$keyword = '';//网页关键字
$description = '';//网页介绍
$baseUrl = __ACTION__;//基础URL
$condition = array();//查询条件
$condition[$innDao->_map['menuId']] = 585;//客栈数据标志
$condition[$innDao->_map['status']] = 1212;//审核标志
//查询城市
$city = $_GET['c'];
if(!empty($city)) {
$baseUrl .= '-c-'.$city;
$condition[$innDao->_map['area']] = $city;
}
//查询关键字
$keyword = $_GET['k'];
if(!empty($keyword)) {
$baseUrl .= '-k-'.$keyword;
$condition[$innDao->_map['name']] = array('like', '%'.$keyword.'%');
}
$this->assign('baseUrl', $baseUrl);
//分析快捷筛选条件
$baseParam = array();
if(!empty($_GET['s'])) {
$baseParam = preg_split('/_/',$_GET['s']);
}
$this->assign('baseParam', $baseParam);
//分析客栈类型
if(!empty($baseParam[0])) {
$condition[$innDao->_map['type']] = $baseParam[0];
foreach($innType as $row) {
if($row['id'] == $baseParam[0]) {
$title = $row['name'] . $title;
break;
}
}
}
//分析客栈级别
if(!empty($baseParam[1])) {
$condition[$innDao->_map['class']] = $baseParam[1];
foreach($innClass as $row) {
if($row['id'] == $baseParam[1]) {
$title = $row['name'] . $title;
break;
}
}
}
//分析客栈主题
if(!empty($baseParam[2])) {
$condition[$innDao->_map['subject']] = $baseParam[2];
foreach($innSubject as $row) {
if($row['id'] == $baseParam[2]) {
$title = $row['name'] . $title;
break;
}
}
}
//分析客栈推荐方式
if(!empty($baseParam[3])) {
$condition[$innDao->_map['recommend']] = $baseParam[3];
foreach($innRecommend as $row) {
if($row['id'] == $baseParam[3]) {
$title = $row['name'] . $title;
break;
}
}
}
//分析客栈预定方式
if(!empty($baseParam[4])) {
$condition[$innDao->_map['booktype']] = $baseParam[4];
foreach($innBookType as $row) {
if($row['id'] == $baseParam[4]) {
$title .= '-支持' . $row['name'];
break;
}
}
}
if(!empty($title)) $this->assign('detailTitle', $title);
//$condition[$innDao->_map['area']] = 585;
//分页
import("ORG.Util.Page");
$innCount = $innDao->where($condition)->count();
$Page = new Page($innCount, 6);
$Page->setConfig('header','间客栈');
$Page->setConfig('prev','上一页');
$Page->setConfig('next','下一页');
$Page->setConfig('first','首页');
$Page->setConfig('last','末页');
$Page->setConfig('theme','<li><a>(%totalRow%)</a>%linkPage%</li> <li class="f1">%first% %upPage% %downPage% %end%</li>');
$this->assign('pageBar', $Page->show());
//取数据
$innList = $innDao
->field($innDao->_map_flip)
->where($condition)
->limit($Page->firstRow.','.$Page->listRows)
->select();
//分析评分和最低价
$InnRoom = D('InnRoom');
$plmr=A("Inn/pinglun");
for($i = 0; $i < $innCount; $i++) {
//评分
$innList[$i]['score'] = $plmr->getonehotelpingf($innList[$i]['id']);
//最低价
$minprice = $InnRoom
->field("min(".$InnRoom->_map['minprice'].") as minprice")
->where($InnRoom->_map['innId'] . '=' . $innList[$i]['id'])
->find();
$innList[$i]['minprice'] = $minprice['minprice'];
}
$this->assign('innList', $innList);
/***********************************************************************
* 取推荐客栈2条
**********************************************************************/
$recommendCondition[$innDao->_map['status']] = 1212;
if(!empty($condition[$innDao->_map['area']]))
$recommendCondition[$innDao->_map['area']] = $condition[$innDao->_map['area']];
//取数据
$recommendInnList = $innDao
->field($innDao->_map_flip)
->where($recommendCondition)
->order('RAND()')//TODO 推荐度排序字段
->limit(2)
->select();
//分析评分和最低价
$plmr=A("Inn/pinglun");
for($i = 0; $i < count($recommendInnList); $i++) {
$recommendInnList[$i]['score'] = $plmr->getonehotelpingf($recommendInnList[$i]['id']);
$minprice = $InnRoom
->field("min(".$InnRoom->_map['minprice'].") as minprice")
->where($InnRoom->_map['innId'] . '=' . $recommendInnList[$i]['id'])
->find();
$recommendInnList[$i]['minprice'] = $minprice['minprice'];
}
$this->assign('recommendInnList', $recommendInnList);
/***********************************************************************
* 取相关线路
**********************************************************************/
//分析城市名
$cityName = '';
if(!empty($city)) {
$cityData = $innAreaDao
->field($innAreaDao->_map_flip)
->where(array(
$innAreaDao->_map['menuId']=>590,
$innAreaDao->_map['id']=>$city
))
->find();
$cityName = $cityData['name'];
$this->assign('cityName', $cityName);
}
$hoteltour = S('hoteltour' . $city);
if(empty($hoteltour)) {
global $SYS_config;
$lead = urlencode( iconv("UTF-8", "gb2312", $cityName) );
$url = $SYS_config["Gettourxoldurl"]."/xdreams.asp"
. "?lead={$lead}&tourtype=zhoubian&format=hotelListSide&limit=9";
$hoteltour = file_get_contents($url);
$hoteltour = iconv('GB2312', 'UTF-8', $hoteltour);
S('hoteltour' . $city , $hoteltour, 3600);
}
if(!empty($hoteltour)) $this->assign('hoteltour', $hoteltour);
/***********************************************************************
* 取相关景点游记、图片
**********************************************************************/
//远程获取数据
$parseArray = C('TMPL_PARSE_STRING');
$url = $parseArray['__UCHOME__'];
$url .= '/user.php?m=Json&a=BlogList&limit=15&keyword=中国'.$cityName;
$data = uc_fopen($url);
if(!empty($data) && ($bloglist = json_decode($data)) && ($bloglist=object2array($bloglist))) {
$topBlogList = array_slice($bloglist, 0, 2);//游记头两条
$otherBlogList = array_slice($bloglist, 2, 7);//其他游记
$picBlogList = array_slice($bloglist, 9, 6);//相关景点图片
if(!empty($topBlogList)) $this->assign('topBlogList', $topBlogList);
if(!empty($otherBlogList)) $this->assign('otherBlogList', $otherBlogList);
if(!empty($picBlogList)) $this->assign('picBlogList', $picBlogList);
}
/***********************************************************************
* 取相相关统计数据
**********************************************************************/
if(!($innStat = S('innStat'))) {
$innStat["checkin"] = rand(100,999);
$innStat["inncount"] = rand(100,999);
$innStat["vister"] = rand(100,999);
$innStat["subject"] = rand(100,999);
$innStat["order"] = rand(100,999);
$innStat["time"] = time();
S('innStat', $innStat);
}
//更新统计
if($innStat["time"] < time() - 5) {
$innStat["checkin"] += rand(0,3);
//$innStat["inncount"] = rand(100,999);
$innStat["vister"] += rand(-50,50);
$innStat["subject"] += rand(0,3);
$innStat["order"] += rand(0,3);
$innStat["time"] = time();
S('innStat', $innStat);
}
$this->assign('innStat', $innStat);
$this->display();
}
}
?> | 10npsite | trunk/Index/Lib/Action/Inn/hotelAction.class.php | PHP | asf20 | 17,969 |
<?php
/**
* 会员订单管理
*/
class mybookAction extends globalAction {
private $orderDao, $orderViewDao;
public function _initialize() {
parent::_initialize();
parent::_loginRequire();
$this->orderDao = D('Order');
$this->orderViewDao = $this->orderDao->switchModel("View",array("viewFields"));
C('SHOW_PAGE_TRACE', false);
}
public function index() {
/***********************************************************************
* 构建筛选条件
**********************************************************************/
$conditions[$this->orderDao->_map['uid']] = array('eq', __USERID__);
//没有被删除
$conditions[$this->orderDao->_map['isDel']] = array('exp', 'is null');
//订单号以H1开头的才是客栈订单
$conditions[$this->orderDao->_map['orderNum']] = array('like', 'h1%');
//用户搜索项目
if(!empty($_REQUEST['contact']))
$conditions[$this->orderDao->_map['contact']] = array('like', "%{$_REQUEST['contact']}%");
if(!empty($_REQUEST['mobile']))
$conditions[$this->orderDao->_map['textContent']] = array('like', "%{$_REQUEST['mobile']}%");
if(!empty($_REQUEST['email']))
$conditions[$this->orderDao->_map['email']] = array('like', "%{$_REQUEST['email']}%");
if(!empty($_REQUEST['orderNum']))
$conditions[$this->orderDao->_map['orderNum']] = array('like', "%{$_REQUEST['orderNum']}%");
if($_REQUEST['selectType']=='uncheckin') {
$conditions[$this->orderDao->_map['checkinDate']] = array('EGT', strtotime(date('Y-m-d')));
$conditions[$this->orderDao->_map['status']] = array('neq', 2);//2表示拒绝入住
$order[$this->orderDao->_map['checkinDate']] = 'asc';
} else {
$order[$this->orderDao->_map['orderTime']] = 'desc';
}
import('ORG.Util.Page');
$count = $this->orderDao->where($conditions)->count();
$Page = new Page($count,10);
$pageBar = $Page->show();
$this->assign('pageBar', $pageBar);
$orderList = $this->orderViewDao
->where($conditions)
->order($order)
->limit($Page->firstRow.','.$Page->listRows)
->select();
$this->assign('orderList', $orderList);
C('TOKEN_ON',false);
$this->display();
}
public function details() {
$orderId = intval($_GET['id']);
$orderDetails = $this->getOrder($orderId);
$this->assign('orderDetails', $orderDetails);
$this->display();
}
private function getOrder($orderId) {
if(empty($orderId)) {
parent::_message('error','订单ID错误!');
}
//订单ID
$conditions[$this->orderDao->_map['id']] = array('eq', $orderId);
//属于客栈老板其下的客栈
$conditions[$this->orderDao->_map['uid']] = array('eq', __USERID__);
//没有被删除
$conditions[$this->orderDao->_map['isDel']] = array('exp', 'is null');
//订单号以H1开头的才是客栈订单
$conditions[$this->orderDao->_map['orderNum']] = array('like', 'h1%');
$orderDetails = $this->orderViewDao
->where($conditions)
->find();
if(empty($orderDetails)) {
parent::_message('error','没有找到此订单!');
}
return $orderDetails;
}
} | 10npsite | trunk/Index/Lib/Action/Inn/mybookAction.class.php | PHP | asf20 | 3,579 |
<?php
/**
* 价格设置
*/
class PriceAction extends globalAction {
private $dao, $inn, $prices;
public function _initialize() {
parent::_initialize();
parent::_loginRequire();
//客栈管理权限验证
$innId = intval($_GET['innId']);
if(empty($innId)) parent::_message('error', '未指定客栈!');
$innDao = D('Inn');
$this->inn = $innDao
->field($innDao->_map_flip)
->where(array(
$innDao->_map['id'] => $innId,
$innDao->_map['menuId'] => 585,
$innDao->_map['uid'] => __USERID__
))
->find();
if(empty($this->inn)) parent::_message('error','您无权管理此客栈');
$this->assign('inn', $this->inn);
//获取价格时间段
$this->dao = D('InnBatPrice');
if(!empty($_POST['add'])) return;//当添加时间段的时候无需获取时间段列表
$this->prices = $this->dao
->field($this->dao->_map_flip)
->where(array(
$this->dao->_map['innId'] => $innId,
$this->dao->_map['menuId'] => 612
))
->select();
$this->assign('prices', $this->prices);
}
public function index() {
//获取当前查看的时间段设置
$priceID = intval($_GET['pid']);
if(!empty($priceID)) {
foreach($this->prices as $price) {
if($price['id'] == $priceID) {
$priceList = $this->unPackPrices($price['price_data']);
//查找房型列表
$roomDao = D('InnRoom');
$roomList = $roomDao
->field($roomDao->_map_flip)
->where(array(
$roomDao->_map['menuId'] => 601,
$roomDao->_map['innId'] => $this->inn['id']
))
->order(array(
$roomDao->_map['display_order'] => 'asc'
))
->select();
$roomCount = count($roomList);
for($i=0; $i < $roomCount; $i++) {
$roomId = $roomList[$i]['id'];
$roomList[$i]['priceSet'] = $priceList[$roomId];
}
$this->assign('roomList', $roomList);
$this->assign('price', $price);
break;
}
}
}
$this->display();
}
public function dayprice() {
$roomid = intval($_GET['roomid']);
if(empty($roomid)) parent::_message('error', '未指定房型!');
//查找房型
$roomDao = D('InnRoom');
$room = $roomDao
->field($roomDao->_map_flip)
->where(array(
$roomDao->_map['id'] => $roomid,
$roomDao->_map['menuId'] => 601,
$roomDao->_map['innId'] => $this->inn['id']
))
->find();
if(empty($room)) parent::_message('error', '未找到房型!');
$this->assign('room', $room);
$this->display();
}
public function op() {
if(!empty($_POST['add'])) {
$_POST['innId'] = $this->inn['id'];
if($this->dao->create()) {
$result = $this->dao->add();
if(false !== $result) {
redirect( C('TMPL_PARSE_STRING.__KZURL__') . '/price/index-innId-' . $this->inn['id'] . '-pid-' . $result);
} else {
parent::_message('error', '添加失败!请联系管理员!', $_SERVER['HTTP_REFERER']);
}
} else {
parent::_message('error', implode('<br />', $this->dao->getError()), $_SERVER['HTTP_REFERER']);
}
} elseif(!empty($_POST['modify'])) {
$_POST['innId'] = $this->inn['id'];
$_POST['price_data'] = $this->packPrices($_POST['prices']);
if($this->dao->create()) {
//防止偷取别人的价格信息
$result = $this->dao->where(array(
$this->dao->_map['id'] => intval($_POST['id']),
$this->dao->_map['innId'] => intval($_POST['innId'])
))->save();
if(false !== $result) {
//远程触发[自动计算房型最低价]
global $SYS_config, $SystemConest;
$uri = $SYS_config['siteurl'].'/'.$SystemConest[1].'/u.php/hotelroom/updateroomminprice/hid/'.$this->inn['id'];
@file_get_contents($uri);
redirect( C('TMPL_PARSE_STRING.__KZURL__') . '/price/index-innId-' . $this->inn['id'] . '-pid-' . $_POST['id']);
} else {
parent::_message('error', '保存失败!请联系管理员!', $_SERVER['HTTP_REFERER']);
}
} else {
parent::_message('error', implode('<br />', $this->dao->getError()), $_SERVER['HTTP_REFERER']);
}
} elseif(!empty($_GET['delete'])) {
$priceID = intval($_GET['delete']);
$this->dao->where(array(
$this->dao->_map['id'] => $priceID,
$this->dao->_map['innId'] => $this->inn['id']
))->delete();
redirect( C('TMPL_PARSE_STRING.__KZURL__') . '/price/index-innId-' . $this->inn['id']);
}
}
public function do_delete() {
$this->dao->delete($this->dateSetData['id']);
redirect( C('TMPL_PARSE_STRING.__KZURL__') . '/DateSet/index-innid-' . $this->inn['id']);
}
/**
* 打包价格数据
* @param $prices array(
* '房型ID'=>array(
* '价格属性代码'=>'价格'
* ...
* )...)
*/
private function packPrices($prices) {
$price_data = array();
foreach($prices as $roomId => $price) {
if(empty($price)) continue;
$roomPrice = '{id:'.$roomId.'}';
foreach($price as $key => $val) {
$roomPrice .= '{'.$key.':'.$val.'}';
}
$price_data[] = $roomPrice;
}
return implode(',', $price_data);
}
/**
* 解包价格数据
* @param $price_data String
*/
private function unPackPrices($price_data) {
$priceList = array();
if(!empty($price_data)) {
$prices = explode(',', $price_data);
foreach($prices as $price) {
preg_match_all('/\{(\w+\:\w+)\}/', $price, $matches);
$attr = array();
foreach($matches[1] as $val) {
$keyval = explode(':', $val);
$attr[$keyval[0]] = $keyval[1];
}
$priceList[$attr['id']] = $attr;
}
}
return $priceList;
}
} | 10npsite | trunk/Index/Lib/Action/Inn/priceAction.class.php | PHP | asf20 | 7,212 |
<?php
class IndexAction extends globalAction{
private $innDao;
public function _initialize() {
parent::_initialize();
$this->innDao = D('Inn');
}
function index() {
/***********************************************************************
* 特卖客栈
**********************************************************************/
$condition = array();//查询条件
$condition[$this->innDao->_map['menuId']] = 585;//客栈数据标志
$condition[$this->innDao->_map['status']] = 1212;//审核标志
$order = array();
$order[$this->innDao->_map['display_order']] = 'asc';
$innSpecialList = $this->innDao->unionField()
->where($condition)
->limit(5)
->order($order)
->select();
$this->assign("innSpecialList",$innSpecialList);
/***********************************************************************
* 客栈排行榜
**********************************************************************/
$condition = array();//查询条件
$condition[$this->innDao->_map['menuId']] = 585;//客栈数据标志
$condition[$this->innDao->_map['status']] = 1212;//审核标志
$order = array();
$order[$this->innDao->_map['display_order']] = 'desc';
$innTopList = $this->innDao->unionField()
->where($condition)
->limit(5)
->order($order)
->select();
$this->assign("innTopList",$innTopList);
/***********************************************************************
* 最新加入客栈
**********************************************************************/
$condition = array();//查询条件
$condition[$this->innDao->_map['menuId']] = 585;//客栈数据标志
$condition[$this->innDao->_map['status']] = 1212;//审核标志
$order = array();
$order[$this->innDao->_map['addTime']] = 'desc';
$innNewList = $this->innDao->unionField()
->where($condition)
->limit(8)
->order($order)
->select();
$this->assign("innNewList",$innNewList);
/***********************************************************************
* 热门客栈
**********************************************************************/
$condition = array();//查询条件
$condition[$this->innDao->_map['menuId']] = 585;//客栈数据标志
$condition[$this->innDao->_map['status']] = 1212;//审核标志
$order = array();
$order[$this->innDao->_map['hot']] = 'desc';
$innHotList = $this->innDao->unionField()
->where($condition)
->limit(8)
->order($order)
->select();
$this->assign("innHotList",$innHotList);
/***********************************************************************
* 推荐客栈
**********************************************************************/
$condition = array();//查询条件
$condition[$this->innDao->_map['menuId']] = 585;//客栈数据标志
$condition[$this->innDao->_map['status']] = 1212;//审核标志
$order = array();
$order[$this->innDao->_map['hot']] = 'desc';
$innRecommendList = $this->innDao->unionField()
->where($condition)
->limit(8)
->order($order)
->select();
$this->assign("innRecommendList",$innRecommendList);
/***********************************************************************
* 热门城市
**********************************************************************/
//获取热门客栈所在城市
$field = array();
$field[$this->innDao->_map['area']] = 'city';
$condition = array();//查询条件
$condition[$this->innDao->_map['menuId']] = 585;//客栈数据标志
$condition[$this->innDao->_map['status']] = 1212;//审核标志
$order = array();
$order[$this->innDao->_map['hot']] = 'desc';
$citys_id = $this->innDao
->Distinct(true)
->field($field)
->where($condition)
->limit(15)
->order($order)
->select();
//将city_id压入数组
$citys_id_range = array();
foreach($citys_id as $city_id) {
$citys_id_range[] = $city_id['city'];
}
//获取城市详情
$areaDao = D('InnArea');
$cityHotList = $areaDao
->field($areaDao->_map_flip)
->where(array(
$areaDao->_map['id'] => array('in', $citys_id_range)
))
->select();
$this->assign("cityHotList",$cityHotList);
/***********************************************************************
* 客栈搜索框处理
**********************************************************************/
//城市列表
$innAreaDao = D('InnArea');
$innCity = S('innCity');
if(empty($innCity)) {
$innCity = $innAreaDao
->field($innAreaDao->_map_flip)
->where(array(
$innAreaDao->_map['menuId']=>590,
$innAreaDao->_map['mainCity']=>1212
))
->order($innAreaDao->_map['order'])
->select();
S('innCity', $innCity);
}
$this->assign('innCity', $innCity);
//客栈类型列表
$innTypeDao = D('InnType');
$innTypeList = $innTypeDao
->field($innTypeDao->_map_flip)
->where(array(
$innTypeDao->_map['menuId']=>606,
$innTypeDao->_map['parent']=>0
))
->select();
$this->assign('innTypeList', $innTypeList);
/***********************************************************************
* 取相相关统计数据
**********************************************************************/
//初始化统计数据
if(!($innStat = S('innStat'))) {
$innStat["checkin"] = rand(100,999);
$innStat["inncount"] = $this->innDao->where(array($this->innDao->_map['status']=>1212))->count();
$innStat["vister"] = rand(100,999);
$innStat["subject"] = rand(100,999);
$innStat["order"] = rand(100,999);
$innStat["time"] = time();
S('innStat', $innStat);
}
//定期更新统计数据
if($innStat["time"] < time() - 5*60) {
$innStat["checkin"] += rand(0,3);
$innStat["inncount"] = $this->innDao->where(array($this->innDao->_map['status']=>1212))->count();
$innStat["vister"] += rand(-50,50);
$innStat["subject"] += rand(0,3);
$innStat["order"] += rand(0,3);
$innStat["time"] = time();
S('innStat', $innStat);
}
$this->assign('innStat', $innStat);
$this->display();
}
}
?> | 10npsite | trunk/Index/Lib/Action/Inn/IndexAction.class.php | PHP | asf20 | 7,390 |
<?php
/**
* 公共模块库
一些公共的功能写入此,供其它模块调用
* @author jroam
*
*/
class commonAction extends Action{
function top(){
$hmoemr=A("Home/public");
echo "dfdf";
}
/**
* 显示google地图
*/
function showgooglemap(){
$zbz=$_REQUEST["zbz"];//google地图坐标值
$hotelname=$_REQUEST["hname"];
$widthpx=$_REQUEST["widthpx"];//地图宽度
$heightpx=$_REQUEST["heightpx"];
//验证坐标值格式
if(getsubstr($zbz,"/^[\d\.]+,[\d\.]+$/")=="") die;
if(!is_numeric($widthpx)) $widthpx=400;
if(!is_numeric($heightpx))$heightpx=300;
$this->assign("zbz",$zbz);
$this->assign("hname",$hotelname);
$this->assign("heightpx",$heightpx);
$this->assign("widthpx",$widthpx);
$this->display();
}
/**
* 实时获取每个房间的剩余房间数和价格等
*
*/
function checkdateyoux(){
$startdate=$_REQUEST["startdate"];//入住日期,由于url中的分隔符是-所以这里替换为_
$enddate=$_REQUEST["enddate"];//离店日期 同上
$hid=$_REQUEST["hid"];//客栈id
$rid=$_REQUEST["rid"];//房间id
$croomnum=$_REQUEST["n"];//选择的房间数量
//检查并格式化时间
if(getsubstr($startdate, "/^[\d]{4}_[\d]{1,2}_[\d]{1,2}$/")=="") die("入住时间格式错误");
if(getsubstr($enddate, "/^[\d]{4}_[\d]{1,2}_[\d]{1,2}$/")=="") die("离店时间格式错误");
if(!is_numeric($rid)) die("请从正确的地址进入");
$startdate=str_replace("_", "-", $startdate);
$enddate=str_replace("_", "-", $enddate);
$numstart=strtotime($startdate);
$numend=strtotime($enddate);
$mr=M();
//获取这个房间这段时间的批量值
$sql="select * from ".DQ."price where price4=".$hid." and price3=612 and price13<=".$numstart." and price14>=".$numend."
and price19<>''
";
$rs=$mr->query($sql);
$returnarr=array();//格式化后的数组
if($rs){
foreach ($rs as $v){
$price19=$v["price19"];
$p19arr=explode(",",$price19);
foreach($p19arr as $v2){
if(strstr($v2, "{id:$rid}")!=""){
$returnarr["mzlj"]=getkuohaostr($v2, "/\{mzlj\:([\d\.]+)+\}/");//本站价
$returnarr["tiqianyudin"]=getkuohaostr($v2, "/\{tiqianyudin\:([\d\.])+\}/");//提前预定天数
$returnarr["zfbl"]=getkuohaostr($v2, "/\{zfbl\:([\d\.])+\}/");//定金支付比例
$returnarr["kucunshu"]=getkuohaostr($v2, "/\{kucunshu\:([\d\.]+)\}/");//库存数
break;
}
}
}
}
$temp=24*3600;
//去获取单独设置的每一天的数据
$sql="select hotelroom0,hotelroom12 from ".DQ."hotelroom where hotelroom0=".$rid;
$rs=$mr->query($sql);
for($i=$numend-$temp;$i>=$numstart;$i-=$temp){
$tstr="". date("Y-m-d",$i)." ,";
if($croomnum>$returnarr["kucunshu"]){
$tstr.="满房";
}
else {
$tstr.="房价:".$returnarr["mzlj"]."元 * ".$croomnum."间";
echo "{".$returnarr["mzlj"]*$croomnum."}";
}
$tstr.="<br>";
echo $tstr;
}
//$this->display();
}
Public function verify(){
import("ORG.Util.Image");
Image::buildImageVerify();
}
}
?> | 10npsite | trunk/Index/Lib/Action/Inn/commonAction.class.php | PHP | asf20 | 3,215 |
<?php
/**
* 留言管理类
* @author jroam
*
*/
class messagesysAction extends Action{
/**
* 获取某一个客栈的留言列表
*/
function getmlistofhotel($hid){
if(!is_numeric($hid)) die("");
$sql="select * from ".DQ."messagesys where messagesys10=".$hid." and messagesys11=1212 order by messagesys8 desc limit 20";
$mr=M("messagesys");
$rs=$mr->query($sql);
$this->assign("rs",$rs);
return $this->fetch("messagesys:getmlistofhotel");
}
/**
* 保存添加的留言信息
*/
function addmessage(){
$content=$_REQUEST["c"];//留言内容
$hid=$_REQUEST["hid"];
$uid=__USERID__;//登陆后的用户名
if(!is_numeric($uid)) die("dopass");//用户没有登陆的话,不能添加
if(strlen($content)<3) die("dopass");//内容没有不能添加
$data["messagesys7"]=608;
$data["messagesys5"]=$content;
$data["messagesys8"]=time();
$data["messagesys9"]=$uid;
$data["messagesys10"]=$hid;
$data["messagesys11"]=1213;
$mr=M("messagesys");
if($mr->data($data)->add()){
echo "dook";
}else{
echo "dopass";
}
}
}
?> | 10npsite | trunk/Index/Lib/Action/Inn/messagesysAction.class.php | PHP | asf20 | 1,155 |
<?php
/**
* 客栈申请
*/
class applyAction extends globalAction {
public function index() {
$this->display();
}
public function agreement() {
$this->display();
}
public function getChildType() {
$typeId = intval($_GET['typeId']);
if(empty($typeId)) die();
//客栈类型
$InnTypeDao = D('InnType');
$InnTypeList = $InnTypeDao
->field($InnTypeDao->_map_flip)
->where(array(
$InnTypeDao->_map['menuId'] => 606,
$InnTypeDao->_map['parent'] => $typeId,
))
->order($InnTypeDao->_map['order'])
->select();
die(json_encode(makearray($InnTypeList, 'id', 'name')));
}
public function details() {
//客栈类型
$InnTypeDao = D('InnType');
$InnTypeList = $InnTypeDao
->field($InnTypeDao->_map_flip)
->where(array(
$InnTypeDao->_map['menuId'] => 606,
$InnTypeDao->_map['parent'] => 0,
))
->order($InnTypeDao->_map['order'])
->select();
$this->assign('InnTypeList',makearray($InnTypeList, 'id', 'name'));
//客栈等级
$InnClassDao = D('InnClass');
$InnClassList = $InnClassDao
->field($InnClassDao->_map_flip)
->where(array( $InnClassDao->_map['menuId'] => 598 ))
->order($InnClassDao->_map['order'])
->select();
$this->assign('InnClassList',makearray($InnClassList, 'id', 'name'));
//客栈设施
$InnFacilityDao = D('InnFacility');
$InnFacilityList = $InnFacilityDao
->field($InnFacilityDao->_map_flip)
->where(array( $InnFacilityDao->_map['menuId'] => 599 ))
->order($InnFacilityDao->_map['order'])
->select();
$this->assign('InnFacilityList',makearray($InnFacilityList, 'id', 'name'));
//客栈主题
$InnSubjectDao = D('InnSubject');
$InnSubjectList = $InnSubjectDao
->field($InnSubjectDao->_map_flip)
->where(array( $InnSubjectDao->_map['menuId'] => 613 ))
->order($InnSubjectDao->_map['order'])
->select();
$this->assign('InnSubjectList',makearray($InnSubjectList, 'id', 'name'));
//合作方式
$InnCooperationDao = D('InnCooperation');
$InnCooperationList = $InnCooperationDao
->field($InnCooperationDao->_map_flip)
->where(array( $InnCooperationDao->_map['menuId'] => 600 ))
->order($InnCooperationDao->_map['order'])
->select();
$this->assign('InnCooperationList',makearray($InnCooperationList, 'id', 'name'));
$this->display();
}
public function contact() {
$innid = cookie('innadd');
if(empty($innid))
parent::_message('error', '非法入口,请按照步骤添加客栈信息!', C('TMPL_PARSE_STRING.__KZURL__') . '/apply/details');
$innDao = D('Inn');
$inn = $innDao->field($innDao->_map_flip)->find($innid);
if(!empty($inn['uid'])) {
cookie('innadd', null);
parent::_message('error', '非法入口,请按照步骤添加客栈信息!', C('TMPL_PARSE_STRING.__KZURL__') . '/apply/details');
}
$this->assign('innid', $innid);
$this->display();
}
public function submit() {
$innDao = D('Inn');
if($innDao->create()) {
if($_POST['detailsSubmit']) {
//数据额外处理
$innDao->facility = ','.implode(',', $_POST['facility']);
if(!empty($_POST['trueType'])) $innDao->type = $_POST['trueType'];
//执行添加
$innid = $innDao->add();
if(false !== $innid) {
cookie('innadd', $innid);
redirect( C('TMPL_PARSE_STRING.__KZURL__') . '/apply/contact' );
} else {
parent::_message('error', '提交失败!请联系管理员!', $_SERVER['HTTP_REFERER'], 3);
}
} elseif($_POST['contactSubmit']) {
$ret = $innDao->save();
if(false !== $ret) {
cookie('innadd', null);
parent::_message('success', '您的资料已提交,请耐心等待审核!', C('TMPL_PARSE_STRING.__KZURL__'));
} else {
parent::_message('error', '提交失败!请联系管理员!', $_SERVER['HTTP_REFERER'], 3);
}
}
} else {
parent::_message('error', implode('<br />', $innDao->getError()), $_SERVER['HTTP_REFERER'], 3);
}
}
} | 10npsite | trunk/Index/Lib/Action/Inn/applyAction.class.php | PHP | asf20 | 4,935 |
<?php
/**
* 点评管理
*/
class MessageAction extends globalAction {
private $messageDao, $myInn;
public function _initialize() {
parent::_initialize();
parent::_loginRequire();
$this->messageDao = D('InnMessage');
$innDao = D('Inn');
$field = array(
$innDao->_map['id'] => 'id',
$innDao->_map['name'] => 'name'
);
$myInnList = $innDao
->field($field)
->where(array(
$innDao->_map['menuId'] => 585,
$innDao->_map['uid'] => __USERID__
))
->select();
if(!empty($myInnList)) {
$this->myInn = makearray($myInnList, 'id', 'name');
$this->assign('myInn', $this->myInn);
}
}
public function index() {
$conditions[$this->messageDao->_map['menu_id']] = 608;
$conditions[$this->messageDao->_map['inn_id']] = array('in',array_keys($this->myInn));
$messageList = $this->messageDao
->field($this->messageDao->_map_flip)
->where($conditions)
->order(array($this->messageDao->_map['add_time']=>'desc'))
->select();
$this->assign('messageList', $messageList);
$this->display();
}
public function batch() {
$BatKey = (array)$_POST['BatKey'];
$BatMethod = $_POST['BatMethod'];
$conditions[$this->messageDao->_map['msg_id']] = array('in',$BatKey);
$conditions[$this->messageDao->_map['menu_id']] = 608;
$conditions[$this->messageDao->_map['inn_id']] = array('in',array_keys($this->myInn));
switch($BatMethod) {
case 'show':
$this->messageDao
->where($conditions)
->setField($this->messageDao->_map['display'],'1212');
break;
case 'hide':
$this->messageDao
->where($conditions)
->setField($this->messageDao->_map['display'],'1213');
break;
case 'delete':
$this->messageDao
->where($conditions)
->delete();
break;
default:
parent::_message('error', '未知操作');
}
redirect(C('TMPL_PARSE_STRING.__KZURL__').'/message/index');
}
} | 10npsite | trunk/Index/Lib/Action/Inn/messageAction.class.php | PHP | asf20 | 2,495 |
<?php
/**
* 预定流程类
* @author Administrator
*
*/
class orderAction extends globalAction {
/**
* 预定第一步界面,
*/
function view1(){
$hid=$_REQUEST["hid"];//客栈id
$rid=$_REQUEST["rid"];//房型id
//die(__USERID__);
//初始化判断
if(!is_numeric($hid)) die("客栈id不能为空");
if(!is_numeric($rid)) die("客型id不能为空");
$mr=M("order");
//获取客栈和房型信息
$sql='select * from '.DQ.'hotel where hotel0='.$hid;
$hotelrs=$mr->query($sql);
//获取房型列表
$sql='select * from '.DQ.'hotelroom where hotelroom2='.$hid.' order by hotelroom18 desc';
$roomrs=$mr->query($sql);
//初始化一些值
$tconfig=array(
"startdate"=>date("Y-m-d"),
"enddate"=>date("Y-m-d",time()+2*3600*24)
);
$this->assign("roomrs",$roomrs);
$this->assign("hotelrs",$hotelrs[0]);
$this->assign("tconfig",$tconfig);
$this->display();
}
/**
* 下订单的第二步
*/
function view2(){
$checkcode=$_REQUEST["checkcode"];//验证码
if($_SESSION['verify'] != md5($_POST['verify'])) {
alert("", 1, "验证码错误,请返回重填");
}
//if(!is_numeric($_REQUEST["orderjingje"])) alert("", 1, "选择参数出错,请重新选择后提交");
//获取初始值
/**
$rid=$_REQUEST["roomtypeid"];//房型id
$hid=$_REQUEST["hid"];//客栈id
$croomnum=$_REQUEST["croomnum"];//房间数量
$chengrens=$_REQUEST["chengrens"];//成人数
$didianshijian=$_REQUEST["didianshijian"];//抵店时间
$startdate=$_REQUEST["startdate"];//入住日期
$enddate=$_REQUEST["enddate"];//离店时间
$useremail=$_REQUEST["useremail"];//用户邮箱
$username=$_REQUEST["username"];//预定用户名
$zhuname=$_REQUEST["zhuname"];//入住用户名
$formarea=$_REQUEST["formarea"];//来自区域
$tel=$_REQUEST["tel"];//电话
$othersuom=$_REQUEST["othersuom"];//其它说明
$duihuanje=$_REQUEST["duihuanje"];//兑换金额
$isduihuan=$_REQUEST["isduihuan"];//是否兑换
$orderjingje=$_REQUEST["orderjingje"];//计算后的价
$_REQUEST["zfbl"];//支付比例,最大为100表示全额
*/
//获取初始值
if($_REQUEST["zfbl"]>100) $_REQUEST["zfbl"]=100;
$str="";
if(!is_numeric($_REQUEST["hid"])) $str="客栈id号不对,请返回";
if(!is_numeric($_REQUEST["roomtypeid"])) $str="房型id不对,请返回";
if(getsubstr($_REQUEST["startdate"], "/^[\d]{4}\-[\d]{1,2}\-[\d]{1,2}$/")=="") $str="你没有填写正确的入住日期,请返回";
if(getsubstr($_REQUEST["enddate"], "/^[\d]{4}\-[\d]{1,2}\-[\d]{1,2}$/")=="") $str="你没有填写正确的离店日期,请返回";
if(getsubstr($_REQUEST["useremail"], "/^[\w\-\_\.]+@[\w\-\_\.]+[\w]+$/")=="") $str="你没有填写正确的电子邮件,请返回";
//if($str!="") alert("", 1, $str);//暂时不启用验证,方便开发
global $SYS_config;
$mr=M("order");
//获取房型名称
$sql="select hotelroom1,hotelroom16 from ".DQ."hotelroom where hotelroom0=".$_REQUEST["roomtypeid"];
$roomrs=$mr->query($sql);
//获取客栈标题
$sql="select hotel1 from ".DQ."hotel where hotel0=".$_REQUEST["hid"];
$hotelrs=$mr->query($sql);
if($hotelrs) $this->assign("hotelrs",$hotelrs[0]);
//订单内容
$content="<b>预定人姓名</b>:".$_REQUEST["username"]."<br>";
$content.="<b>入住人姓名</b>:".$_REQUEST["zhuname"]."<br>";
$content.="<b>来自</b>:".$_REQUEST["formarea"]."<br>";
$content.="<b>联系电话</b>:".$_REQUEST["tel"]."<br>";
$content.="<b>到店时间</b>:".$_REQUEST["didianshijian"]."<br>";
if($roomrs) $content.="<b>预定的房型</b>:".$roomrs[0]["hotelroom1"]."<br>";
if($_REQUEST["isduihuan"]=="1") $content.="<b>您已使用积分(".$_REQUEST["duihuanje"]*$SYS_config["xfsjfnumdy1jenum"].")兑换了人民币</b>:".$_REQUEST["duihuanje"]."元<br>";
$content.="<b>预定房间数量</b>:".$_REQUEST["croomnum"]."<br>";
$content.="<b>其它说明</b>:".$_REQUEST["othersuom"]."<br>";
//生成订单信息
$data=array();
$data["orderform1"]=$_REQUEST["hid"];
$data["orderform31"]=$_REQUEST["roomtypeid"];
$data["orderform7"]=__USERID__;
$data["orderform4"]=$hotelrs[0]["hotel1"];
$data["orderform5"]=$_REQUEST["username"];
$data["orderform6"]=time();//下单时间
$data["orderform8"]=$_REQUEST["chengrens"];
$data["orderform9"]=strtotime($_REQUEST["startdate"]);
$data["orderform30"]=strtotime($_REQUEST["enddate"]);
$data["orderform16"]=$_REQUEST["orderjingje"];//总金额
$data["orderform33"]=$_REQUEST["duihuanje"];//兑换金额
$data["orderform17"]=(int)($data["orderform16"]*$_REQUEST["zfbl"]/100);//订金金额
$data["orderform18"]=time()+3600*$SYS_config["tiqianzftime"];//订金支付期限
$data["orderform19"]=$data["orderform16"]-$data["orderform17"];//余款金额
$data["orderform20"]=time()+3600*$SYS_config["tiqianzftime"];//余款支付期限
$data["orderform26"]=$_REQUEST["useremail"];
$data["orderform31"]=$_REQUEST["roomtypeid"];
$data["orderform34"]=$_REQUEST["croomnum"];
$data["orderform35"]=($roomrs[0]["hotelroom16"]=="5757")?"非":"即";
$data["orderform10"]=$content;//订单内容
//$data["proname"]=$_REQUEST["proname"];
$data["orderform2"]=618;
$ordermr=A("Inn/orderform");
$orderno=$ordermr->addorder($data);//生成订单
//$orderno="H99999999";
//构建支付信息
$paytype=A("Home/paytype");
$paytypehtm=array();
//转帐支付
$paytypehtm["zhuangzhangrmb"]=$paytype->zhuangzhangrmb();
//支付宝
$arr["out_trade_no"]=$orderno;// str商户的订单号
$arr["aliorder"]="预定梦之旅产品--".$hotelrs[0]["hotel1"]; //订单名称,显示在支付宝收银台里的“商品名称”里,显示在支付宝的交易管理的“商品名称”的列表里。
$arr["alibody"]="预定梦之旅产品--".$hotelrs[0]["hotel1"]."的".$roomrs[0]["hotelroom1"].",入住时间:".$_REQUEST["startdate"]; //订单描述、订单详细、订单备注,显示在支付宝收银台里的“商品描述”里
$arr["alimoney"]=$data["orderform17"];// 订单总金额,显示在支付宝收银台里的“应付总额”里
$arr["jetype"]="a";//支付定金
$paytypehtm["alipay"]=$paytype->alipay($arr);
//中国信用卡
unset($arr);
$arr["pMerCode"]=$orderno; //订单号
$arr["pAmount"]=$data["orderform17"];// 金额
$arr["pAttach"]="预定梦之旅产品--".$hotelrs[0]["hotel1"]."的".$roomrs[0]["hotelroom1"].",入住时间:".$_REQUEST["startdate"]; //订单描述、订单详细、订单备注,显示在支付宝收银台里的“商品描述”里
$arr["pGoodsInfo"]= "预定梦之旅产品--".$hotelrs[0]["hotel1"]; //订单名称,显示在支付宝收银台里的“商品名称”里,显示在支付宝的交易管理的“商品名称”的列表里。
$paytypehtm["CardOnlineRmb"]=$paytype->CardOnlineRmb();
$this->assign("data",$data);
$this->assign("orderno",$orderno);
$this->assign("roomrs",$roomrs[0]);
$this->assign("paytypehtm",$paytypehtm);//支付页面
$this->assign("telphone",str_replace("-", "", $_REQUEST["tel"]));
$this->assign("kezhanname",preg_replace("/[\-\"\/]/", "", $hotelrs[0]["hotel1"]));
$this->display();
}
/**
* 当用户下单后,再点击确认要这个订单,这时才发送短息和电子邮件,并更新标识
*/
function yudingqueren(){
$orderno=$_REQUEST["orderno"];//订单号
$uid=$_REQUEST["uid"];//用户id
$n=$_REQUEST["n"];//兑换的金额
$pid=$_REQUEST["pid"];//预定的客栈ID
$pname=$_REQUEST["pname"];//客栈名称
$tomail=$_REQUEST["tomail"];//要发送的邮件
if(getsubstr($orderno, "/^H[\d]+$/")=="") die("pass1");
if(getsubstr($_REQUEST["tel"], "/^1[\d]{10}$/")=="") die("pass2");
if(!is_numeric($uid)) die("pass3");
if(!is_numeric($n)) die("pass4");
$mr=M("order");
$sql="update ".DQ."orderform set orderform36=1 where orderform3='".$orderno."'";
$rs=$mr->execute($sql);
if($rs){
global $SYS_config;
//预定成功,发送短息.
$smsa=A("Home/sms");
$dsmsata["phoneno"]=$_REQUEST["tel"];
$dsmsata["content"]="您的预定已经下单成功,订单号为:".$orderno.",请登陆您的会员中心查询";
//$smsa->senddx($dsmsata);//正式上线后才启用短息发送功能
require_once RootDir."/inc/MailClass.php";
$mailc=file_get_contents($SYS_config["siteurl"]."/sendmail/createinnorderhtml-orderno-".$orderno);
echo(sendmymail($tomail,"梦之旅","你的订单下单成功",$mailc))?" mailsendsuss":" mainsendpass";
$temp=$SYS_config["xfsjfnumdy1jenum"]*$n;
if($temp>0) uc_credit_exchange_request($uid, 1, 1, 1, -$temp);
if(__USERNAME__) uc_feed_add("album",$uid,__USERNAME__,"","{actor} 有新活动了","预定了客栈: $pname ,快来围观!","","","",array());
}else{
echo "失败";
}
}
function test(){
$str="php python pear";
echo getsubstr($str,"/\bp(?!h)\w+\b/");
}
}
?> | 10npsite | trunk/Index/Lib/Action/Inn/orderAction.class.php | PHP | asf20 | 9,287 |
<?php
/**
* 支付网关
* @author Administrator
*
*/
class payAction extends globalAction {
public function _initialize() {
parent::_initialize();
parent::_loginRequire();
$this->orderDao = D('Order');
$this->orderViewDao = $this->orderDao->switchModel("View",array("viewFields"));
}
function Payment() {
/***********************************************************************
* 参数检查
**********************************************************************/
$orderNum = trim($_GET['orderNum']);
$fortype = trim($_GET['fortype']);
if(empty($orderNum))
parent::_message(
'error',
'请提供订单号!',
C('TMPL_PARSE_STRING.__UCHOME__').'/cp.php?ac=mybook'
);
/***********************************************************************
* 获取订单数据
**********************************************************************/
$conditions[$this->orderDao->_map['orderNum']] = array('eq', $orderNum);
$conditions[$this->orderDao->_map['uid']] = array('eq', __USERID__);
$conditions[$this->orderDao->_map['isDel']] = array('exp', 'is null');
$orderInfo = $this->orderViewDao
->where($conditions)
->find();
if(empty($orderInfo))
parent::_message(
'error',
'没有找到您的订单!',
C('TMPL_PARSE_STRING.__UCHOME__').'/cp.php?ac=mybook'
);
/***********************************************************************
* 防止多次支付
**********************************************************************/
switch($fortype) {
case 'a':
if(!empty($depositConfirm))
parent::_message(
'error',
'您已经支付过订金了!',
C('TMPL_PARSE_STRING.__UCHOME__').'/cp.php?ac=mybook'
);
$money = $orderInfo["depositAmount"];
break;
case 'b':
if(empty($depositConfirm))
parent::_message(
'error',
'请先支付订金,然后才能支付余款!',
C('TMPL_PARSE_STRING.__UCHOME__').'/cp.php?ac=mybook'
);
if(!empty($balanceConfirm))
parent::_message(
'error',
'您已经支付过余款了!',
C('TMPL_PARSE_STRING.__UCHOME__').'/cp.php?ac=mybook'
);
$money = $orderInfo["balanceAmount"];
break;
default:
parent::_message(
'error',
'要支付的款项不明确!',
C('TMPL_PARSE_STRING.__UCHOME__').'/cp.php?ac=mybook'
);
}
/***********************************************************************
* 构建支付页面
**********************************************************************/
$product_name = "预定梦之旅产品--".$orderInfo['innName'];
$product_desc = "预定梦之旅产品--".$orderInfo['innName']."的"
.$orderInfo['room_name']
.",入住时间:".date('Y-m-d', $orderInfo["checkinDate"]);
$paytype=A("Home/paytype");
$paytypehtm=array();
//转帐支付
$paytypehtm["zhuangzhangrmb"]=$paytype->zhuangzhangrmb();
//支付宝
$arr["out_trade_no"] = $orderInfo['orderNum'];// str商户的订单号
$arr["aliorder"] = $product_name; //订单名称,显示在支付宝收银台里的“商品名称”里,显示在支付宝的交易管理的“商品名称”的列表里。
$arr["alibody"] = $product_desc; //订单描述、订单详细、订单备注,显示在支付宝收银台里的“商品描述”里
$arr["jetype"] = $fortype;//支付订金a还是余款b
$arr["alimoney"] = $money;//本次应该支付金额
$paytypehtm["alipay"] = $paytype->alipay($arr);
//中国信用卡
unset($arr);
$arr["pMerCode"] = $orderInfo['orderNum']; //订单号
$arr["pAmount"] = $money;
$arr["pAttach"] = $product_desc; //订单描述、订单详细、订单备注,显示在支付宝收银台里的“商品描述”里
$arr["pGoodsInfo"] = $product_name; //订单名称,显示在支付宝收银台里的“商品名称”里,显示在支付宝的交易管理的“商品名称”的列表里。
$paytypehtm["CardOnlineRmb"]= $paytype->CardOnlineRmb();
$this->assign("paytypehtm",$paytypehtm);//支付页面
$this->assign("fortype", $fortype);
$this->assign("orderInfo", $orderInfo);
$this->display();
}
/**
* 当用户下单后,再点击确认要这个订单,这时才发送短息和电子邮件,并更新标识
*/
function yudingqueren(){
$orderno=$_REQUEST["orderno"];//订单号
$uid=$_REQUEST["uid"];//用户id
$n=$_REQUEST["n"];//兑换的金额
$pid=$_REQUEST["pid"];//预定的客栈ID
$pname=$_REQUEST["pname"];//客栈名称
$tomail=$_REQUEST["tomail"];//要发送的邮件
if(getsubstr($orderno, "/^H[\d]+$/")=="") die("pass1");
if(getsubstr($_REQUEST["tel"], "/^1[\d]{10}$/")=="") die("pass2");
if(!is_numeric($uid)) die("pass3");
if(!is_numeric($n)) die("pass4");
$mr=M("order");
$sql="update ".DQ."orderform set orderform36=1 where orderform3='".$orderno."'";
$rs=$mr->execute($sql);
if($rs){
global $SYS_config;
//预定成功,发送短息.
$smsa=A("Home/sms");
$dsmsata["phoneno"]=$_REQUEST["tel"];
$dsmsata["content"]="您的预定已经下单成功,订单号为:".$orderno.",请登陆您的会员中心查询";
//$smsa->senddx($dsmsata);//正式上线后才启用短息发送功能
//@todo:发送邮件
require_once RootDir."/inc/MailClass.php";
$mailc=file_get_contents($SYS_config["siteurl"]."/sendmail/createinnorderhtml-orderno-".$orderno);
echo(sendmymail($tomail,"梦之旅","你的订单下单成功",$mailc))?" mailsendsuss":" mainsendpass";
$temp=$SYS_config["xfsjfnumdy1jenum"]*$n;
if($temp>0) uc_credit_exchange_request($uid, 1, 1, 1, -$temp);
if(__USERNAME__) uc_feed_add("album",$uid,__USERNAME__,"","{actor} 有新活动了","预定了客栈: $pname ,快来围观!","","","",array());
}else{
echo "失败";
}
}
function test(){
echo __USERNAME__;
}
}
?> | 10npsite | trunk/Index/Lib/Action/Inn/payAction.class.php | PHP | asf20 | 6,951 |
<?php
/**
* 客栈老板订单管理
*/
class bookAction extends globalAction {
private $orderDao, $orderViewDao;
public function _initialize() {
parent::_initialize();
parent::_loginRequire();
$this->orderDao = D('Order');
$this->orderViewDao = $this->orderDao->switchModel("View",array("viewFields"));
}
public function index() {
/***********************************************************************
* 构建筛选条件
**********************************************************************/
//属于客栈老板其下的客栈
$innDao = D('Inn');
$myInnSubQuery = $innDao
->field($innDao->_map['id'])
->where(array($innDao->_map['uid']=>__USERID__))
->buildSql();
$conditions[$this->orderDao->_map['innId']] = array('exp', 'in '.$myInnSubQuery);
//没有被删除
$conditions[$this->orderDao->_map['isDel']] = array('exp', 'is null');
//订单号以H1开头的才是客栈订单
$conditions[$this->orderDao->_map['orderNum']] = array('like', 'h1%');
//用户搜索项目
if(!empty($_REQUEST['contact']))
$conditions[$this->orderDao->_map['contact']] = array('like', "%{$_REQUEST['contact']}%");
if(!empty($_REQUEST['mobile']))
$conditions[$this->orderDao->_map['textContent']] = array('like', "%{$_REQUEST['mobile']}%");
if(!empty($_REQUEST['email']))
$conditions[$this->orderDao->_map['email']] = array('like', "%{$_REQUEST['email']}%");
if(!empty($_REQUEST['orderNum']))
$conditions[$this->orderDao->_map['orderNum']] = array('like', "%{$_REQUEST['orderNum']}%");
if($_REQUEST['selectType']=='uncheckin') {
$conditions[$this->orderDao->_map['checkinDate']] = array('EGT', strtotime(date('Y-m-d')));
$conditions[$this->orderDao->_map['status']] = array('neq', 2);//2表示拒绝入住
$order[$this->orderDao->_map['checkinDate']] = 'asc';
} else {
$order[$this->orderDao->_map['orderTime']] = 'desc';
}
import('ORG.Util.Page');
$count = $this->orderDao->where($conditions)->count();
$Page = new Page($count,10);
$pageBar = $Page->show();
$this->assign('pageBar', $pageBar);
$orderList = $this->orderViewDao
->where($conditions)
->order($order)
->limit($Page->firstRow.','.$Page->listRows)
->select();
$this->assign('orderList', $orderList);
C('TOKEN_ON',false);
$this->display();
}
public function details() {
$orderId = intval($_GET['id']);
$orderDetails = $this->getOrder($orderId);
$this->assign('orderDetails', $orderDetails);
$this->display();
}
public function accept() {
$orderId = intval($_GET['id']);
$orderDetails = $this->getOrder($orderId);
if($orderDetails['orderType'] == '即')
parent::_message(
'error',
'即时预定类型的订单无需人工处理!',
C('TMPL_PARSE_STRING.__KZURL__').'/book/details-id-'.$orderDetails['id']
);
if(!empty($orderDetails['status']))
parent::_message(
'error',
'此订单已处理过了!',
C('TMPL_PARSE_STRING.__KZURL__').'/book/details-id-'.$orderDetails['id']
);
$this->orderDao->where(array(
$this->orderDao->_map['id'] => $orderDetails['id']
))->setField(array(
$this->orderDao->_map['status']=>'1',
$this->orderDao->_map['dealTime']=>time()
));
redirect(C('TMPL_PARSE_STRING.__KZURL__').'/book/details-id-'.$orderDetails['id']);
}
public function reject() {
$orderId = intval($_GET['id']);
$orderDetails = $this->getOrder($orderId);
if($orderDetails['orderType'] == '即')
parent::_message(
'error',
'即时预定类型的订单无需人工处理!',
C('TMPL_PARSE_STRING.__KZURL__').'/book/details-id-'.$orderDetails['id']
);
if(!empty($orderDetails['status']))
parent::_message(
'error',
'此订单已处理过了!',
C('TMPL_PARSE_STRING.__KZURL__').'/book/details-id-'.$orderDetails['id']
);
$this->orderDao->where(array(
$this->orderDao->_map['id'] => $orderDetails['id']
))->setField(array(
$this->orderDao->_map['status']=>'2',
$this->orderDao->_map['dealTime']=>time()
));
redirect(C('TMPL_PARSE_STRING.__KZURL__').'/book/details-id-'.$orderDetails['id']);
}
private function getOrder($orderId) {
if(empty($orderId)) {
parent::_message('error','订单ID错误!');
}
//属于客栈老板其下的客栈
$innDao = D('Inn');
$myInnSubQuery = $innDao
->field($innDao->_map['id'])
->where(array($innDao->_map['uid']=>__USERID__))
->buildSql();
//订单ID
$conditions[$this->orderDao->_map['id']] = array('eq', $orderId);
//订单所属客栈归掌柜所有
$conditions[$this->orderDao->_map['innId']] = array('exp', 'in '.$myInnSubQuery);
//没有被删除
$conditions[$this->orderDao->_map['isDel']] = array('exp', 'is null');
//订单号以H1开头的才是客栈订单
$conditions[$this->orderDao->_map['orderNum']] = array('like', 'h1%');
$orderDetails = $this->orderViewDao
->where($conditions)
->find();
if(empty($orderDetails)) {
parent::_message('error','没有找到此订单!');
}
return $orderDetails;
}
} | 10npsite | trunk/Index/Lib/Action/Inn/bookAction.class.php | PHP | asf20 | 6,085 |
<?php
/**
* 系统类别
* @author Administrator
*
*/
class classsysAction extends Action{
/**
* 获取一个酒店的基础设施选项,传入id值,查找出中文名称
* @param $strid 传入的id值,多个id用逗号分隔
* @param $returnfiledid 返回的字段id号
* @return 返回查询后的数组
*/
function getidtoname($strid,$returnfiledid){
if($strid=="") return "";
$sear=array("/^,/","/,$/");
$repla=array("","");
$strid=preg_replace($sear, $repla, $strid);
$sql="select classsys0,classsys".$returnfiledid." from ".DQ."classsys
where classsys0 in($strid) order by classsys4 desc";
$m=M("classsys");
$rs=$m->query($sql);
$temparr=array();
$i=0;
foreach ($rs as $v){
$temparr[$i]=$v["classsys".$returnfiledid];
$i++;
}
return $temparr;
}
}
?> | 10npsite | trunk/Index/Lib/Action/Inn/classsysAction.class.php | PHP | asf20 | 851 |
<?php
class picAction extends Action{
/**
* 获取某一个客栈的图片列表
*/
function getpiclist($pid){
if(!is_numeric($pid)) return "";
$mr=M("pic");
$rs=$mr->field("pic1,pic4")->where("pic2=".$pid)->order("pic6 desc")->select();
return $rs?$rs:"";
}
}
?> | 10npsite | trunk/Index/Lib/Action/Inn/picAction.class.php | PHP | asf20 | 306 |
<?php
/**
* 房型类
* @author jroam
*
*/
class hotelroomAction extends Action{
/**
* 检查一个时间内的日期,每一天这个房间的状态,是否有房,可以住几人,价格是多少 (暂时不启用)
@return 返回格式2012-09-10|可以入住人数|价格值,
*/
function checkdateyoux(){
$startdate=$_REQUEST["startdate"];//入住日期,由于url中的分隔符是-所以这里替换为_
$enddate=$_REQUEST["enddate"];//离店日期 同上
$hid=$_REQUEST["hid"];//客栈id
$rid=$_REQUEST["rid"];//房间id
$croomnum=$_REQUEST["n"];//选择的房间数量
//检查并格式化时间
if(getsubstr($startdate, "/^[\d]{4}_[\d]{1,2}_[\d]{1,2}$/")=="") die("入住时间格式错误");
if(getsubstr($enddate, "/^[\d]{4}_[\d]{1,2}_[\d]{1,2}$/")=="") die("离店时间格式错误");
if(!is_numeric($rid)) die("请从正确的地址进入");
$startdate=str_replace("_", "-", $startdate);
$enddate=str_replace("_", "-", $enddate);
$numstart=strtotime($startdate);
$numend=strtotime($enddate);
$mr=M();
//获取这个房间这段时间的批量值
$sql="select * from ".DQ."price where price4=".$hid." and price3=612 and price13<=".$numstart." and price14>=".$numend."
and price19<>''
";
$rs=$mr->query($sql);
$returnarr=array();//格式化后的数组
if($rs){
foreach ($rs as $v){
$price19=$v["price19"];
$p19arr=explode(",",$price19);
foreach($p19arr as $v2){
if(strstr($v2, "{id:$rid}")!=""){
$returnarr["mzlj"]=getkuohaostr($v2, "/\{mzlj\:([\d\.]+)\}/");//本站价
$returnarr["tiqianyudin"]=getkuohaostr($v2, "/\{tiqianyudin\:([\d\.]+)\}/");//提前预定天数
$returnarr["zfbl"]=getkuohaostr($v2, "/\{zfbl\:([\d\.]+)\}/");//定金支付比例
$returnarr["kucunshu"]=getkuohaostr($v2, "/\{kucunshu\:([\d\.]+)\}/");//库存数
break;
}
}
}
}
$temp=24*3600;
//去获取单独设置的每一天的数据
$sql="select hotelroom0,hotelroom12 from ".DQ."hotelroom where hotelroom0=".$rid;
$rs=$mr->query($sql);
$totelmoney=0;
$flag=1;
for($i=$numend-$temp;$i>=$numstart;$i-=$temp){
$tstr="". date("Y-m-d",$i)." ,";
if($croomnum>$returnarr["kucunshu"]){
$tstr.="满房";
$flag=0;
}
else {
$tstr.="房价:".$returnarr["mzlj"]."元 * ".$croomnum."间";
$totelmoney+=$returnarr["mzlj"]*$croomnum;
}
$tstr.="<br>";
echo $tstr;
}
echo $flag==1? "{".$totelmoney."}":"{0}";
echo "@".$returnarr["zfbl"]."@";
}
}
?> | 10npsite | trunk/Index/Lib/Action/Inn/hotelroomAction.class.php | PHP | asf20 | 2,647 |
<?php
/**
* 客栈列表
*/
class roomAction extends globalAction {
private $dao, $inn;
public function _initialize() {
parent::_initialize();
parent::_loginRequire();
/***********************************************************************
* 客栈管理权限验证
**********************************************************************/
$innId = intval($_REQUEST['innId']);
if(empty($innId)) parent::_message('error','未指定客栈');
$innDao = D('Inn');
$this->inn = $innDao
->field($innDao->_map_flip)
->where(array(
$innDao->_map['id'] => $innId,
$innDao->_map['menuId'] => 585,
$innDao->_map['uid'] => __USERID__
))
->find();
if(empty($this->inn)) parent::_message('error','您无权管理此客栈');
$this->assign('inn', $this->inn);
$this->dao = D('InnRoom');
}
/**
* request $_GET['innId'] OR ($_GET['innId'] AND $_GET['roomid'])
*/
public function index() {
/***********************************************************************
* 查找房型列表
**********************************************************************/
$roomList = $this->dao
->field($this->dao->_map_flip)
->where(array(
$this->dao->_map['menuId'] => 601,
$this->dao->_map['innId'] => $this->inn['id']
))
->order(array(
$this->dao->_map['display_order'] => 'asc'
))
->select();
$this->assign('roomList', $roomList);
/***********************************************************************
* 确定当前查看房型
**********************************************************************/
$roomId = intval($_GET['roomid']);
if(!empty($roomId)) {
foreach($roomList as $roomRow) {
if($roomRow['id']==$roomId) {
$room = $roomRow;
$this->assign('room', $room);
break;
}
}
}
/***********************************************************************
* 房型图片列表
**********************************************************************/
if(!empty($room)) {
$InnRoomImagesDao = D('InnRoomImages');
$InnRoomImagesList = $InnRoomImagesDao
->field($InnRoomImagesDao->_map_flip)
->where(array(
$InnRoomImagesDao->_map['menuId'] => 616,
$InnRoomImagesDao->_map['roomId'] => $room['id']
))
->order($InnRoomImagesDao->_map['display_order'])
->select();
$this->assign('InnRoomImagesList', $InnRoomImagesList);
}
/***********************************************************************
* 房型类别列表
**********************************************************************/
$roomTypeDao = D('InnRoomType');
$roomTypeList = $roomTypeDao
->field($roomTypeDao->_map_flip)
->where(array(
$roomTypeDao->_map['menuId'] => 617
))
->order($roomTypeDao->_map['display_order'])
->select();
$this->assign('roomTypeList', makearray($roomTypeList, 'id', 'name'));
/***********************************************************************
* 预定类别列表
**********************************************************************/
$roomOrderTypeDao = D('InnRoomOrderType');
$roomOrderTypeList = $roomOrderTypeDao
->field($roomOrderTypeDao->_map_flip)
->where(array(
$roomOrderTypeDao->_map['menuId'] => 619
))
->order($roomOrderTypeDao->_map['display_order'])
->select();
$this->assign('roomOrderTypeList', makearray($roomOrderTypeList, 'id', 'name'));
$this->display();
}
/**
* request $_POST['innId'] AND ($_POST['add'] OR ($_POST['modify'] AND $_POST['id']))
*/
public function do_room() {
if($this->dao->create()) {
if(!empty($_POST['add'])) {
$result = $this->dao->add();
if(false !== $result) {
parent::_message('success', '添加成功!', C('TMPL_PARSE_STRING.__KZURL__').'/room/index-innId-'.$this->inn['id'].'-roomid-'.$result);
} else {
parent::_message('error', '添加失败!请联系管理员!', C('TMPL_PARSE_STRING.__KZURL__').'/room/index-innId-'.$this->inn['id']);
}
} elseif(!empty($_POST['modify']) && !empty($_POST['id'])) {
$result = $this->dao->save();
if(false !== $result) {
parent::_message('success', '修改成功!', C('TMPL_PARSE_STRING.__KZURL__').'/room/index-innId-'.$this->inn['id'].'-roomid-'.$_POST['id']);
} else {
parent::_message('error', '修改失败!请联系管理员!', C('TMPL_PARSE_STRING.__KZURL__').'/room/index-innId-'.$this->inn['id'].'-roomid-'.$_POST['id']);
}
}
} else {
parent::_message('error', implode('<br />', $this->dao->getError()), $_SERVER['HTTP_REFERER']);
}
}
/**
* request $_GET['innId'] AND $_GET['roomid']
*/
public function do_delete() {
//查找房型信息
$roomId = intval($_GET['roomid']);
$room = $this->dao
->field($this->dao->_map_flip)
->where(array(
$this->dao->_map['id'] => $roomId,
$this->dao->_map['menuId'] => 601,
$this->dao->_map['innId'] => $this->inn['id']
))
->find();
if(empty($room)) parent::_message('error', '未找到房型信息');
//删除房型图片列表
$InnRoomImagesDao = D('InnRoomImages');
$InnRoomImagesList = $InnRoomImagesDao
->field($InnRoomImagesDao->_map_flip)
->where(array(
$InnRoomImagesDao->_map['menuId'] => 616,
$InnRoomImagesDao->_map['roomId'] => $room['id']
))
->order($InnRoomImagesDao->_map['display_order'])
->select();
$deletedId = array();
foreach($InnRoomImagesList as $pic) {
@unlink('.'.$pic['path']);
$deletedId[] = $pic['id'];
}
$InnRoomImagesDao->where(array(
$InnRoomImagesDao->_map['id'] => array('in',$deletedId)
))->delete();
//TODO 删除房型价格
//删除房型数据
$this->dao
->where(array(
$this->dao->_map['id'] => $room['id'],
$this->dao->_map['menuId'] => 601,
$this->dao->_map['innId'] => $this->inn['id']
))
->delete();
redirect(C('TMPL_PARSE_STRING.__KZURL__').'/room/index-innId-'.$this->inn['id']);
}
/**
* Ajax上传客栈图集
*/
public function upimages() {
//查找房型信息
$roomId = intval($_POST['id']);
if(empty($roomId)) die('未指定房型信息!');
$room = $this->dao
->field($this->dao->_map_flip)
->where(array(
$this->dao->_map['menuId'] => 601,
$this->dao->_map['id'] => $roomId,
$this->dao->_map['innId'] => $this->inn['id']
))
->find();
if(empty($room)) die('未找到房型信息');
//准备接收上传文件
import('ORG.Net.UploadFile');
$this->upload = new UploadFile();
$this->upload->maxSize = 1024*1024; //1M
$this->upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');
$this->upload->savePath = UPLOAD_PATH; //文件保存目录
$this->upload->autoSub = true; //自动创建子目录
$this->upload->subType = 'date'; //按日期创建子目录
$this->upload->dateFormat = 'Ym/d'; //日期子目录规则(前后不加'/')
$this->upload->saveRule = 'uniqid'; //文件名生成规则
//处理文件上传
if(!$this->upload->upload()) {
die('错误提示:文件上传失败!');
} else {
$InnRoomImagesDao = D('InnRoomImages');
$info = $this->upload->getUploadFileInfo();
foreach($info as $upinfo) {
$picpath = strtr(UPLOAD_PATH, array('.'=>'')) . $upinfo['savename'];
//保存新图片
$data = array(
$InnRoomImagesDao->_map['path'] => $picpath,
$InnRoomImagesDao->_map['roomId'] => $roomId,
);
if($InnRoomImagesDao->create($data))
if($picid = $InnRoomImagesDao->add())
die(json_encode(array(
"picid" => $picid,
"picpath" => $picpath
)));
}
}
die('错误提示:文件保存出错!');
}
/**
* Ajax删除客栈图集
*/
public function delimages() {
$imgid = intval($_POST['imgid']);
$roomId = intval($_POST['id']);
if(empty($imgid)) die('没有指定要删除的图片!');
if(empty($roomId)) die('没有指定房型ID!');
//查找房型信息
if(empty($roomId)) die('未指定房型信息!');
$room = $this->dao
->field($this->dao->_map_flip)
->where(array(
$this->dao->_map['menuId'] => 601,
$this->dao->_map['id'] => $roomId,
$this->dao->_map['innId'] => $this->inn['id']
))
->find();
if(empty($room)) die('未找到房型信息');
$InnRoomImagesDao = D('InnRoomImages');
$InnRoomImagesRow = $InnRoomImagesDao
->field($InnRoomImagesDao->_map_flip)
->where(array(
$InnRoomImagesDao->_map['menuId'] => 616,
$InnRoomImagesDao->_map['roomId'] => $room['id'],
$InnRoomImagesDao->_map['id'] => $imgid,
))
->find();
if(empty($InnRoomImagesRow)) die('没有找到要删除的图片!');
@unlink('.'.$InnRoomImagesRow['path']);
$InnRoomImagesDao->where(array($InnRoomImagesDao->_map['id'] => $imgid))->delete();
die('1');
}
} | 10npsite | trunk/Index/Lib/Action/Inn/roomAction.class.php | PHP | asf20 | 11,126 |
<?php
/*
* 评论类
*/
class pinglunAction extends Action {
/**
* 显示html页面
*/
function add(){
$this->display();
}
/**
* 获取客栈评论的列表
*/
function getpinglunlist($hid){
if(!is_numeric($hid)) return "";
$mr=M("pinglun");
$sql="select * from ".DQ."pinglun where pinglun2=".$hid." and pinglun3=604 order by pinglun0 desc limit 0,10";
$rs=$mr->query($sql);
$this->assign("rs",$rs);
return $this->fetch("pinglun:getpinglunlist");
}
/**
* 获取一个客栈总的评分数
* @param $hid
*/
function getonehotelpingf($hid){
if(!is_numeric($hid)) return "";
$mr=M("pinglun");
$sql="select count(*) as tnum, sum(pinglun9+pinglun10+pinglun11+pinglun12+pinglun13+pinglun14)as onenum
from ".DQ."pinglun where pinglun2=".$hid;
$rs=$mr->cache(true)->query($sql);
if($rs[0]){
$t= ($rs[0]["onenum"]*20)/($rs[0]["tnum"]*6);
$t=number_format($t,2);
return(getsubstr($t,"/^0/")=="0")?100:$t;
}else{
return "";
}
}
/**
* 获取一个客栈的每一项的百分比,比如位置的总得分数
* @param $hid 客栈id
* @return 返回一个数组,k为字母s+字段名,v为其值,统计个数为tnum
*/
function getpinglunhotelev($hid){
if(!is_numeric($hid)) return "";
$mr=M("pinglun");
$sql="select count(*) as tnum,sum(pinglun9) as spinglun9,sum(pinglun10) as spinglun10,sum(pinglun11) as spinglun11,
sum(pinglun12) as spinglun12,sum(pinglun13) as spinglun13,sum(pinglun14) as spinglun14 from ".DQ."pinglun
where pinglun2=$hid
";
$rs=$mr->query($sql);
$ra=$rs[0];
if($rs[0]){
$ra["spinglun9"]=number_format($ra["spinglun9"]*20/$ra["tnum"],2);
$ra["spinglun10"]=number_format($ra["spinglun10"]*20/$ra["tnum"],2);
$ra["spinglun11"]=number_format($ra["spinglun11"]*20/$ra["tnum"],2);
$ra["spinglun12"]=number_format($ra["spinglun12"]*20/$ra["tnum"],2);
$ra["spinglun13"]=number_format($ra["spinglun13"]*20/$ra["tnum"],2);
$ra["spinglun14"]=number_format($ra["spinglun14"]*20/$ra["tnum"],2);
}
return $ra;
}
}
?> | 10npsite | trunk/Index/Lib/Action/Inn/pinglunAction.class.php | PHP | asf20 | 2,159 |
<?php
/**
* 客栈申请
*/
class innAdmAction extends globalAction {
private $_inn, $innDao, $upload;
public function _initialize() {
parent::_initialize();
parent::_loginRequire();
//获取客栈ID
$innId = intval($_REQUEST['id']);
if(empty($innId))
parent::_message('error', '客栈ID为空!', __GROUP__);
//查找客栈详情,判断是否有权操作
$this->innDao = D('Inn');
$inn = $this->innDao
->field($this->innDao->_map_flip)
->where(array(
$this->innDao->_map['id'] => $innId,
$this->innDao->_map['uid'] => __USERID__
))
->find();
if(empty($inn))
parent::_message('error', '您无权管理此客栈!');
else {
$this->_inn = $inn;
$this->assign('inn',$this->_inn);
}
//准备接收上传文件
import('ORG.Net.UploadFile');
$this->upload = new UploadFile();
$this->upload->maxSize = 1024*1024; //1M
$this->upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');
$this->upload->savePath = UPLOAD_PATH; //文件保存目录
$this->upload->autoSub = true; //自动创建子目录
$this->upload->subType = 'date'; //按日期创建子目录
$this->upload->dateFormat = 'Ym/d'; //日期子目录规则(前后不加'/')
$this->upload->saveRule = 'uniqid'; //文件名生成规则
}
/**
* 客栈管理首页(会员信息)
*/
public function index() {
$this->display();
}
/**
* 客栈基本信息
*/
public function base() {
//客栈等级
$InnClassDao = D('InnClass');
$InnClassList = $InnClassDao
->field($InnClassDao->_map_flip)
->where(array( $InnClassDao->_map['menuId'] => 598 ))
->order($InnClassDao->_map['order'])
->select();
$this->assign('InnClassList',makearray($InnClassList, 'id', 'name'));//标记客栈等级列表
$this->assign('InnClass',$this->_inn['class']);//标记选中的客栈等级
//客栈设施
$InnFacilityDao = D('InnFacility');
$InnFacilityList = $InnFacilityDao
->field($InnFacilityDao->_map_flip)
->where(array( $InnFacilityDao->_map['menuId'] => 599 ))
->order($InnFacilityDao->_map['order'])
->select();
$this->assign('InnFacilityList',makearray($InnFacilityList, 'id', 'name'));//标记客栈设施列表
$this->assign('InnFacility',preg_split('/,/', $this->_inn['facility']));//标记选中的客栈设施
//渲染输出
$this->display();
}
/**
* 客栈图集
*/
public function images() {
//客栈图集
$InnImagesDao = D('InnImages');
$InnImagesList = $InnImagesDao
->field($InnImagesDao->_map_flip)
->where(array(
$InnImagesDao->_map['menuId'] => 607,
$InnImagesDao->_map['innId'] => $this->inn['id'],
))
->order($InnImagesDao->_map['order'])
->select();
$this->assign('InnImagesList', $InnImagesList);
//渲染输出
$this->display();
}
/**
* Ajax上传客栈图集
*/
public function upimages() {
//处理文件上传
if(!$this->upload->upload()) {
die('错误提示:文件上传失败!');
} else {
$InnImagesDao = D('InnImages');
$info = $this->upload->getUploadFileInfo();
foreach($info as $upinfo) {
$picpath = strtr(UPLOAD_PATH, array('.'=>'')) . $upinfo['savename'];
//保存新图片
$data = array(
$InnImagesDao->_map['path'] => $picpath,
$InnImagesDao->_map['innId'] => $this->inn['id'],
);
if($InnImagesDao->create($data))
if($picid = $InnImagesDao->add())
die(json_encode(array(
"picid" => $picid,
"picpath" => $picpath
)));
}
}
die('错误提示:文件保存出错!');
}
/**
* Ajax删除客栈图集
*/
public function delimages() {
$imgid = intval($_POST['imgid']);
if(empty($imgid)) die('没有指定要删除的图片!');
$InnImagesDao = D('InnImages');
$InnImagesRow = $InnImagesDao
->field($InnImagesDao->_map_flip)
->where(array(
$InnImagesDao->_map['menuId'] => 607,
$InnImagesDao->_map['innId'] => $this->inn['id'],
$InnImagesDao->_map['id'] => $imgid,
))
->find();
if(empty($InnImagesRow)) die('没有找到要删除的图片!');
@unlink('.'.$InnImagesRow['path']);
$InnImagesDao->where(array($InnImagesDao->_map['id'] => $imgid))->delete();
die('1');
}
/**
* 集中处理表单提交
*/
public function submit() {
if(!$this->isPost()) parent::_message('error', '只接受POST数据!', $_SERVER['HTTP_REFERER']);
//保存客栈基本信息
if($_POST['baseSubmit']) {
$_POST['facility'] = ','.implode(',', $_POST['facility']);
}
//保存客栈详情
elseif ($_POST['detailsSubmit']) {
//处理文件上传
if(!$this->upload->upload()) {
//parent::_message('error', $upload->getErrorMsg());
} else {
$info = $this->upload->getUploadFileInfo();
foreach($info as $upinfo) {
//保存新图片
$fieldName = 'pic'.(intval($upinfo['key'])+1);
$_POST[$fieldName] = strtr(UPLOAD_PATH, array('.'=>'')) . $upinfo['savename'];
//删除老图片
if(!empty($this->inn[$fieldName]))
@unlink( $this->inn[$fieldName] );
}
}
}
//保存会员信息
elseif($_POST['indexSubmit']) {
//处理证件上传
if(!$this->upload->upload()) {
//parent::_message('error', $this->upload->getErrorMsg(), $_SERVER['HTTP_REFERER'], 3);
} else {
$info = $this->upload->getUploadFileInfo();
foreach($info as $upinfo) {
$path = strtr(UPLOAD_PATH, array('.'=>'')) . $upinfo['savename'];
if($upinfo['key'] == 0) {
$_POST['idcard_pic'] = $path;
//删除老图片
if(!empty($this->inn['idcard_pic']))
@unlink( '.'.$this->inn['idcard_pic'] );
} elseif($upinfo['key'] == 1) {
$_POST['biz_pic'] = $path;
//删除老图片
if(!empty($this->inn['biz_pic']))
@unlink( '.'.$this->inn['biz_pic'] );
}
}
}
}
if($this->innDao->create()) {
if(false !== $this->innDao->save()) {
parent::_message('success', '保存成功', $_SERVER['HTTP_REFERER'], 3);
} else {
parent::_message('error', '保存失败!请联系管理员!', $_SERVER['HTTP_REFERER']);
}
} else {
parent::_message('error', implode('<br />', $this->innDao->getError()), $_SERVER['HTTP_REFERER']);
}
}
} | 10npsite | trunk/Index/Lib/Action/Inn/innAdmAction.class.php | PHP | asf20 | 8,053 |
<?php
class orderformAction extends Action
{
/**
* 工作人员修改出团通知书后的保存操作
*/
function savechutuanzzs()
{
if($_SESSION["Login"][1]=="" or $_SESSION["Login"][1]==null) die("您不是工作人员或没有登陆");
$orderid=$_REQUEST["orderid"];
$str="{@团号:".$_REQUEST["chutuhao"]."@}";
$str.="{@集合接送:".$_REQUEST["jiejisongji"]."@}";
$str.="{@集合接送:".$_REQUEST["jiejisongji"]."@}";
if($_REQUEST["yukuanzhifu"]!="") $str.="{@余款支付说明:".$_REQUEST["yukuanzhifu"]."@}";
$str.="{@供应商:".$_REQUEST["dangdilvyousang"]."@}";
$str.="{@梦之旅联系信息:".$_REQUEST["contactinfo"]."@}";
$str.="{@余款支付信息:".$_REQUEST["yukuanzhifu"]."@}";
$id=$_REQUEST["id"];
if(!is_numeric($id)) die("传入参数不正确");
$mr=M("orderform");
$data["orderform29"]=$str;
if($mr->where("orderform0=".$id)->save($data))
{
alert("affirm_chutuantongzhi".FGF."orderid".FGF."".$orderid,2,"保存成功");
}
else
{
alert("affirm_chutuantongzhi".FGF."orderid".FGF."".$orderid,2,"保存失败");
}
}
/**
* 保存国内合同内容
*/
function saveguoleihetong()
{
if($_SESSION["Login"][1]=="" or $_SESSION["Login"][1]==null) die("您不是工作人员或没有登陆");
$orderid=$_REQUEST["orderid"];
$str="{@jiafangname:".$_REQUEST["jiafangname"]."@}";//甲方名称
$str.="{@Youraddress:".$_REQUEST["Youraddress"]."@}";//
$str.="{@jiaemail:".$_REQUEST["jiaemail"]."@}";//
$str.="{@Yourtel:".$_REQUEST["Yourtel"]."@}";//
$str.="{@YiafangName:".$_REQUEST["YiafangName"]."@}";//
$str.="{@jinyunXuKeZheng:".$_REQUEST["jinyunXuKeZheng"]."@}";//
$str.="{@jinyunhuanwei:".$_REQUEST["jinyunhuanwei"]."@}";//
$str.="{@Yitel:".$_REQUEST["Yitel"]."@}";//
$str.="{@tuanno:".$_REQUEST["tuanno"]."@}";//
$str.="{@protname:".$_REQUEST["protname"]."@}";//
$str.="{@cfsd:".$_REQUEST["cfsd"]."@}";//
$str.="{@JiaoTongJiBiaoZhun:".$_REQUEST["JiaoTongJiBiaoZhun"]."@}";//
$str.="{@zylsd:".$_REQUEST["zylsd"]."@}";//
$str.="{@ycsbz:".$_REQUEST["ycsbz"]."@}";//
$str.="{@zxbz:".$_REQUEST["zxbz"]."@}";//
$str.="{@gwanpai:".$_REQUEST["gwanpai"]."@}";//
$str.="{@ZhiFeiXiangMu:".$_REQUEST["ZhiFeiXiangMu"]."@}";//
$str.="{@daoyoufeiy:".$_REQUEST["daoyoufeiy"]."@}";//
$str.="{@fyzfbf:".$_REQUEST["fyzfbf"]."@}";//
$str.="{@zhifubanf:".$_REQUEST["zhifubanf"]."@}";//
$str.="{@qtyy:".$_REQUEST["qtyy"]."@}";//
$str.="{@ZhuanBinTuanTravel:".$_REQUEST["ZhuanBinTuanTravel"]."@}";//
$str.="{@DiJieTravel:".$_REQUEST["DiJieTravel"]."@}";//
$str.="{@beizhu:".$_REQUEST["beizhu"]."@}";//
$str.="{@BaoXianGSLianXiRen:".$_REQUEST["BaoXianGSLianXiRen"]."@}";//
$str.="{@LvYouFeiYongShuoMing1:".$_REQUEST["LvYouFeiYongShuoMing1"]."@}";//
$str.="{@LvYouFeiYongShuoMing2:".$_REQUEST["LvYouFeiYongShuoMing2"]."@}";//
$str.="{@QiTaFeiYong:".$_REQUEST["QiTaFeiYong"]."@}";//
$str.="{@xdwp:".$_REQUEST["xdwp"]."@}";//
$str.="{@SuangYueDing:".$_REQUEST["SuangYueDing"]."@}";//
$str.="{@SuangYueDingYiZ:".$_REQUEST["SuangYueDingYiZ"]."@}";//
$str.="{@cfrq:".$_REQUEST["cfrq"]."@}";//
$str.="{@other1:".$_REQUEST["other1"]."@}";//
$str.="{@other2:".$_REQUEST["other2"]."@}";//
$str.="{@other3:".$_REQUEST["other3"]."@}";//
$str.="{@other4:".$_REQUEST["other4"]."@}";//
$str.="{@other5:".$_REQUEST["other5"]."@}";//
$str.="{@jiafangAllPersren:".$_REQUEST["jiafangAllPersren"]."@}";//
$str.="{@jiafangrenydb:".$_REQUEST["jiafangrenydb"]."@}";//
$str.="{@yifangrenydb:".$_REQUEST["yifangrenydb"]."@}";//
$str.="{@qanyuedate:".$_REQUEST["qanyuedate"]."@}";//
$isqiand=$_REQUEST["orderform33"];//是否签定合同
$id=$_REQUEST["id"];
if(!is_numeric($id)) die("传入参数不正确");
$mr=M("orderform");
$data["orderform32"]=$str;
$data["orderform33"]=$isqiand;
if($mr->where("orderform0=".$id)->save($data))
{
$temp="";
//当勾选了签定合同时,生成合同的静态文件
if($isqiand=="1")
{
require_once RootDir.'/inc/ActionFile.class.php';
$myfile=new ActionFile();
$temp=($myfile->CreateAnyPageToPage("http://".$_SERVER['HTTP_HOST']."/affirm".FGF."guoleihetong".FGF."orderid".FGF."".$orderid, RootDir."/html/hetong/".$orderid.".htm"))?"生成静态成功":"生成静态失败";
}
alert("/affirm".FGF."guoleihetong".FGF."orderid".FGF."".$orderid."".FGF."showedit".FGF."yes",2,"保存成功".$temp);
}
else
{
alert("/affirm".FGF."guoleihetong".FGF."orderid".FGF."".$orderid."".FGF."showedit".FGF."yes",2,"保存失败");
}
}
/**
* 保存出境合同
*/
function savechujinghetong()
{
if($_SESSION["Login"][1]=="" or $_SESSION["Login"][1]==null) die("您不是工作人员或没有登陆");
$str.="{@hetongbianhao:".$_REQUEST["hetongbianhao"]."@}";//
$str.="{@jiafangName:".$_REQUEST["jiafangName"]."@}";//
$str.="{@Youraddress:".$_REQUEST["Youraddress"]."@}";//
$str.="{@Email_send:".$_REQUEST["Email_send"]."@}";//
$str.="{@Yourtel:".$_REQUEST["Yourtel"]."@}";//
$str.="{@YifangName:".$_REQUEST["YifangName"]."@}";//
$str.="{@YicompanyAddress:".$_REQUEST["YicompanyAddress"]."@}";//
$str.="{@jinyunhuanwei:".$_REQUEST["jinyunhuanwei"]."@}";//
$str.="{@jinyunXuKeZheng:".$_REQUEST["jinyunXuKeZheng"]."@}";//
$str.="{@Yitel:".$_REQUEST["Yitel"]."@}";//
$str.="{@tuanno:".$_REQUEST["tuanno"]."@}";//
$str.="{@CountryAndArea:".$_REQUEST["CountryAndArea"]."@}";//
$str.="{@chufaTimeSTuan:".$_REQUEST["chufaTimeSTuan"]."@}";//
$str.="{@JiaoTongJiBiaoZhun:".$_REQUEST["JiaoTongJiBiaoZhun"]."@}";//
$str.="{@zylsd:".$_REQUEST["zylsd"]."@}";//
$str.="{@ycsbz:".$_REQUEST["ycsbz"]."@}";//
$str.="{@zxbz:".$_REQUEST["zxbz"]."@}";//
$str.="{@gwanpai:".$_REQUEST["gwanpai"]."@}";//
$str.="{@ZhiFeiXiangMu:".$_REQUEST["ZhiFeiXiangMu"]."@}";//
$str.="{@daoyoufeiy:".$_REQUEST["daoyoufeiy"]."@}";//
$str.="{@fyzfbf:".$_REQUEST["fyzfbf"]."@}";//
$str.="{@LvYouFeiYongBaoHanXuan:".implode("",$_REQUEST["LvYouFeiYongBaoHanXuan"])."@}";//
$str.="{@jiaotongfeiyong:".implode("",$_REQUEST["jiaotongfeiyong"])."@}";//
$str.="{@youleifeiy:".implode("",$_REQUEST["youleifeiy"])."@}";//
$str.="{@jiedaifeiyong:".implode("",$_REQUEST["jiedaifeiyong"])."@}";//
$str.="{@lvyoufuwufei:".implode("",$_REQUEST["lvyoufuwufei"])."@}";//
$str.="{@qitafeiyong:".implode("",$_REQUEST["qitafeiyong"])."@}";//
$str.="{@chanyingzhushu:".implode("",$_REQUEST["chanyingzhushu"])."@}";//
$str.="{@zfbf:".$_REQUEST["zfbf"]."@}";//
$str.="{@JiaoNaFangSi_zt:".implode("",$_REQUEST["JiaoNaFangSi_zt"])."@}";//
$str.="{@JiaoNaFangSi_xyk:".implode("",$_REQUEST["JiaoNaFangSi_zt"])."@}";//
$str.="{@JiaoNaFangSi_qita:".implode("",$_REQUEST["JiaoNaFangSi_qita"])."@}";//
$str.="{@JiaoNaFangSi_xj:".implode("",$_REQUEST["JiaoNaFangSi_xj"])."@}";//
$str.="{@zhuanbit:".$_REQUEST["zhuanbit"]."@}";//
$str.="{@bunenfatian:".$_REQUEST["bunenfatian"]."@}";//
$str.="{@ZhuanBinTuanTravel:".$_REQUEST["ZhuanBinTuanTravel"]."@}";//
$str.="{@DiJieTravel:".$_REQUEST["DiJieTravel"]."@}";//
$str.="{@beizhu:".$_REQUEST["beizhu"]."@}";//
$str.="{@BaoXianGSLianXiRen:".$_REQUEST["BaoXianGSLianXiRen"]."@}";//
$str.="{@BaoXianGSLianXiRen:".$_REQUEST["BaoXianGSLianXiRen"]."@}";//
$str.="{@LvYouFeiYongShuoMing1:".$_REQUEST["LvYouFeiYongShuoMing1"]."@}";//
$str.="{@LvYouFeiYongShuoMing2:".$_REQUEST["LvYouFeiYongShuoMing2"]."@}";//
$str.="{@QiTaFeiYong:".$_REQUEST["QiTaFeiYong"]."@}";//
$str.="{@xdwpchuy:".$_REQUEST["xdwpchuy"]."@}";//
$str.="{@SuangYueDing:".$_REQUEST["SuangYueDing"]."@}";//
$str.="{@SuangYueDingYiZ:".$_REQUEST["SuangYueDingYiZ"]."@}";//
$str.="{@cfrq:".$_REQUEST["cfrq"]."@}";//
$str.="{@other1:".$_REQUEST["other1"]."@}";//
$str.="{@other2:".$_REQUEST["other2"]."@}";//
$str.="{@other3:".$_REQUEST["other3"]."@}";//
$str.="{@other4:".$_REQUEST["other4"]."@}";//
$str.="{@other5:".$_REQUEST["other5"]."@}";//
$str.="{@jiafangAllPersren:".$_REQUEST["jiafangAllPersren"]."@}";//
$str.="{@jiafangdaibiao:".$_REQUEST["jiafangdaibiao"]."@}";//
$str.="{@jiafangshengfengzheng:".$_REQUEST["jiafangshengfengzheng"]."@}";//
$str.="{@jiafangtelfax:".$_REQUEST["jiafangtelfax"]."@}";//
$str.="{@jiafengemail:".$_REQUEST["jiafengemail"]."@}";//
$str.="{@y_name:".$_REQUEST["y_name"]."@}";//
$str.="{@y_tel:".$_REQUEST["y_tel"]."@}";//
$str.="{@y_addr:".$_REQUEST["y_addr"]."@}";//
$str.="{@y_email:".$_REQUEST["y_email"]."@}";//
$str.="{@y_date:".$_REQUEST["y_date"]."@}";//
$isqiand=implode("",$_REQUEST["orderform33"]);//是否签定合同
$orderid=$_REQUEST["orderid"];
$id=$_REQUEST["id"];
if(!is_numeric($id)) die("传入参数不正确");
$mr=M("orderform");
$data["orderform32"]=$str;
$data["orderform33"]=$isqiand;
if($mr->where("orderform0=".$id)->save($data))
{
$temp="";
//当勾选了签定合同时,生成合同的静态文件
if($isqiand=="1")
{
require_once RootDir.'/inc/ActionFile.class.php';
$myfile=new ActionFile();
$temp=($myfile->CreateAnyPageToPage("http://".$_SERVER['HTTP_HOST']."/affirm".FGF."chujinghetong".FGF."orderid".FGF."".$orderid, RootDir."/html/hetong/".$orderid.".htm"))?"生成静态成功":"生成静态失败";
}
alert("/affirm".FGF."chujinghetong".FGF."orderid".FGF.$orderid.FGF."showedit".FGF."yes",2,"保存成功".$temp);
}
else
{
alert("/affirm".FGF."chujinghetong".FGF."orderid".FGF.$orderid.FGF."showedit".FGF."yes",2,"保存失败".$temp);
}
}
/**
* 更新订单数据表里的内容
* @param $wheresql 条件
* @param $data 更新的数组
* @return 成功返回true 失败返回false
*/
function updatersonefiled($wheresql,$data)
{
$mr=M("orderform");
if(!is_array($data)) return false;
$num=$rs=$mr->where($wheresql)->save($data);
return ($num)?true:false;
}
/**
* 客人在下单的时候生成订单
* @param $arr 参数组
* @return 成功true,失败false
*/
function createorder($arr){
$rsc=M("orderform");
if(is_array($arr)){
$temp=$rsc->add($arr);
return (is_numeric($temp))?true:false;
}
return false;
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/orderformAction.class.php | PHP | asf20 | 10,497 |
<?php
/**
* 线路类
* @author jroam
*
*/
class tourAction extends globalAction
{
/**
* 线路列表
*/
function search() {
$field = array(
'*',
"(select count(*) from ".C("DB_PREFIX")."pinglun where pinglun2=tour0)" => "pinglunnum"
);
$order = array(
'tour42'=>'desc',//一级排序
'tour43'=>'desc',//二级排序
'tour48'=>'desc',//修改时间
//'tour53'=>"desc",//DIT指数
//"tour55"=>"desc",//人气值
//"tour51"=>"desc",//想去的人数
//"tour39"=>"desc",//点击查看数
//"tour8" =>"desc",//价格
//"tour7" =>"desc",//持续天数
);
$limit = 10;
$condition["tour44"] = array("eq",1212);//已审核
$condition["tour41"] = array("eq","cn");//中文线路
//出发地
if($from = intval($_GET["from"])) {
$condition["tour10"] = array("like", "%,$from,%");
$dest_condition['tour10'] = array("like", "%,$from,%");
} else {
$condition["tour10"] = array("like", "%," . __FromDestID__ . ",%");//出发地
$dest_condition['tour10'] = array('like', "%," . __FromDestID__ . ",%");
}
//产品类型
if($type = intval($_GET["type"])) {
$condition["tour40"] = array("like", "%,$type,%");
$dest_condition["tour40"] = array("like", "%,$type,%");
}
//特色
if($feature = intval($_GET["feature"]))
$condition["tour50"] = array("like", "%,$feature,%");
//景点
if($scenic = intval($_GET["scenic"]))
$condition["tour49"] = array("like", "%,$scenic,%");
//行程天数
if($days = intval($_GET["days"]))
$condition["tour7"] = array("eq", $days);
//关键字
if($keywords = intval($_GET["keywords"]))
$condition["tour1"] = array("like", "%$keywords%");
//线路类型
$tourtypes = M("classsys")->field(array(
"classsys0"=>"id",
"classsys1"=>"name_cn",
"classsys7"=>"name_cn"
))
->where("classsys3=569")
->order("classsys4 desc")
->select();
$this->assign("tourtypes", $tourtypes);
$destsid = M("tour")->field("tour9")
->where($dest_condition)
->select();
//线路列表
$tours = M("tour")
->field($field)
->where($condition)
->order($order)
->limit($limit)
->select();
$this->assign("tours", $tours);
$this->display();
}
/**
* 获取并返回线路类的多条记录
* @param $wheresql 查询的sql语句
* @return 返回新闻类的多条记录 失败返回null
*/
public function getRsList($wheresql)
{
$rsc=M("tour");
$rs= $rsc->where($wheresql)->select();
return ($rs)?$rs:"";
}
/**
* 获取并返回线路类的一条记录
* @param $wheresql 查询的sql语句
* @return 返回线路类的单条记录 失败返回null
*/
public function getrsone($wheresql)
{
$rsc=M("tour");
$rs= $rsc->where($wheresql)->find();
$this->assign("rs",$rs);
return ($rs)?$rs:"";
}
function showlist()
{
$mr=M("tour");
$rs=fanye($mr,"1=1",2,"1","");
$this->assign("rs",$rs["rs"]);
$this->assign("show",$rs["show"]);
$this->display();
}
/**
* 显示线路详细页面
*/
function view()
{
global $SYS_config;
$id=$_REQUEST["id"];
if(!is_numeric($id)) die("参数不对");
//获取类别导航
//获取左边的栏目导航的类别
//$classsys=A("classsys");
//$cladhtm=$classsys->getteshe();
$mr=M("tour");
$sql="select * from ".DQ."tour as a ,(select * from ".DQ."price order by price8 asc) as b where a.tour0=$id and b.price7=a.tour0 limit 0,1";
$temp=M()->query($sql);
$rs=$temp[0];
if(!$rs) die("没有这条线路或这条线路没有添加价格");
//定义印象背景颜色,前台随机取一个,每一行的第二个样式加margin5
$yingxbgc=array("bq_green","bq_lightgreen","bq_blue","bq_yellow");
//获取这条线路的印象记录
$yxmr=A("pinglun");
$uid=$_COOKIE["uchome_uid"];
$uchome_auth=$_COOKIE["uchome_auth"];
if($uchome_auth){
//$yxrs=$yxmr->getrslist("pinglun4=$uid and pinglun3=580 and pinglun2=$id order by pinglun0 desc limit ".$SYS_config["addYingx"]);
}
//获取这条线路的好评率
//$haoping=$yxmr->gettourhaopinglv($id);
//获取这条线路的评论数
$sql="select count(*) as pnum from ".DQ."pinglun where pinglun2=$id and pinglun3=579";
$pnum=M()->query($sql);
//获取这条线路的想去数
$sql="select count(*) as num from ".DQ."guanzhu where guanzhu2=$id";
$xiangunum=M()->query($sql);
//特别关键字样式
$tebiacss=array("zs bold font16 wy margin5","yellow font12 wy margin5","gray font20 wy");
//折分一个特别关键字字符串为数组
$tebs=preg_split("/[,\s,\.。]/", $rs["tour54"]);
//拆分行程内容为多天.
$xingcecontent=$rs["tour23"];
$xingcecontentar=explode(DanxuangduofenC, $rs["tour23"]);
//获取相关游记内容
$youjikeywordarr=preg_split("/[,\s,\.。]/", $rs["tour56"]);
$subsql="";
foreach ($youjikeywordarr as $v)
{
$subsql.=" and a.subject like '%".$v."%'";
}
//获取游记攻略
$myuser=A("user");
$sql="select a.blogid,a.uid,a.dateline,a.subject,a.pic,a.hot,a.viewnum,a.replynum from ".UHDQ."blog as a left join ".UHDQ."space as b on a.uid=b.uid
where a.pic<>'' $subsql
order by a.dateline desc limit 0,20";
//$youji=$myuser->getRsListBySql($sql);
//获取相关线路tour54
$subsql="";
foreach ($tebs as $v)
{
$subsql.=" and tour1 like '%".$v."%'";
}
$wsql="tour44=1212 and tour41='cn' and tour0<>$id ".$subsql." order by tour42 desc,tour43 desc,tour0 desc limit 0,20";
$pnumsql="(select count(*) from ".DQ."pinglun where pinglun2=a.tour0) as pingluncount";
$sql="select *,$pnumsql from ".DQ."tour as a where ".$wsql;
$xgrs=M()->query($sql);
//获取此行程的相关点评
$sql="select * from ".DQ."pinglun where pinglun3=579 and pinglun2=$id order by pinglun0 desc limit 0,10";
$pinglunrs=M()->query($sql);
//获取此行程所有的价格列表
//获取这条线路的想去数
$sql="select * from ".DQ."price as a left join ".DQ."classsys as b on a.price5=b.classsys0 where a.price7=$id";
$toursprice=M()->query($sql);
$this->assign("rs",$rs);
$this->assign("tophtml",$tophtml);
$this->assign("cladhtm",$cladhtm);
$this->assign("yingxbgc",$yingxbgc);
$this->assign("yxrs",$yxrs);
$this->assign("haopinglv",$haoping);
$this->assign("xiangunum",$xiangunum[0]["num"]);
$this->assign("tebiacss",$tebiacss);
$this->assign("pnum",$pnum[0]["pnum"]);
$this->assign("tebs",$tebs);
$this->assign("xingcecontentar",$xingcecontentar);
$this->assign("youji",$youji);
$this->assign("xgrs",$xgrs);
$this->assign("toursprice",$toursprice);
$this->assign("pinglunrs",$pinglunrs);
$this->display();
}
function addrenqi()
{
$tid=$_REQUEST["tid"];
if(!is_numeric($tid)) die("线路id不正确");
$mr=M("tour");
$mr->where("tour0=$tid")->setInc('tour55'); //tour55加1
$rs=$mr->where("tour0=$tid")->find();
if($rs){
echo $rs["tour55"];
}
else
{
echo "没有此记录";
}
}
/**
* 线路搜索页面
*/
function searchtour()
{
//获取头部
$public=A("public");
$tophtml=$public->top();
$keyword=$_REQUEST["keyword"];//搜索关键字
$sqlsub="";
//初始化查询条件 $keyword
if($keyword) $sqlsub.=" and a.tour1 like '%".$keyword."%'";
//=======================================分析行程天数
$tianshu=$_REQUEST["tianshu"];//行程天数
if(is_numeric($tianshu)) $sqlsub.=" and a.tour7=".$tianshu;
//分析大于某一天的行程数
$temp=getkuohaostr($tianshu,"/^[d]([\d]+)$/");
$sqlsub.=(is_numeric($temp))?" and a.tour7>".$temp:"";
//分析小于某一天的行程数
$temp=getkuohaostr($tianshu,"/^[x]([\d]+)$/");
$sqlsub.=(is_numeric($temp))?" and a.tour7<".$temp:"";
//获取线路列表
$sql="select * ,(select count(*) from ".DQ."pinglun where pinglun2=a.tour0) as pingluncount
from ".DQ."tour as a , (select min(price8) as bprice8,price7,price6 from ".DQ."price group by price7) b where a.tour44=1212 and a.tour0=b.price7 ".$sqlsub." order by a.tour0 desc";
$mr=M("tour");
$rs=fanye($mr,$sql,1,2);
//获取类别导航
//获取左边的栏目导航的类别
$classsys=A("classsys");
$cladhtm=$classsys->getteshe();
$this->assign("rs",$rs["rs"]);
$this->assign("fanyehtml",$rs["show"]);
$this->assign("tophtml",$tophtml);
$this->assign("cladhtm",$cladhtm);
$this->assign("keyword",$keyword);
$this->display();
}
/**
* 线路列表
*/
function tourlist()
{
//获取头部
$public=A("public");
$tophtml=$public->top();
//=======================================分析行程天数
$tianshu=$_REQUEST["tianshu"];//行程天数
if(is_numeric($tianshu)) $subsql=" and a.tour7=".$tianshu;
//分析大于某一天的行程数
$temp=getkuohaostr($tianshu,"/^[d]([\d]+)$/");
$subsql.=(is_numeric($temp))?" and a.tour7>".$temp:"";
//分析小于某一天的行程数
$temp=getkuohaostr($tianshu,"/^[x]([\d]+)$/");
$subsql.=(is_numeric($temp))?" and a.tour7<".$temp:"";
//设置页面的属性
$temp=getsubstr($tianshu,"/[\d]+/");
$pagec=array();
if($temp){
$pagec["pagetitle"]="周边".$temp."日游,".$temp."天行程,".$temp."日游";
$pagec["contenttitle"]="周边所有".$temp."日游";
}
//=======================================================================获取特色类别
$tslb=$_REQUEST["tslb"];//特色类别id
$lbid=$_REQUEST["lbid"];//关联景点id
if(is_numeric($tslb) and is_numeric($lbid)){
$sql="select * from ".DQ."classsys where classsys0=$tslb";
$tslbrs=$public->query($sql);
$sql="select * from ".DQ."classsys where classsys0=$lbid ";
$lbidrs=$public->query($sql);
$pagec["pagetitle"]=$tslbrs[0]["classsys1"]."旅游线路,".$lbidrs[0]["classsys1"]."旅游线路";
$pagec["contenttitle"]=$tslbrs[0]["classsys1"].$lbidrs[0]["classsys1"]."旅游线路";
$subsql.=" and a.tour50 like '%".$tslb."%' and a.tour49=".$lbid;
}
//=============================================================================获取目的地属性
$mdd=$_REQUEST["mdd"];
if(is_numeric($mdd)){
$mddrs=$public->query("select * from ".DQ."classsys where classsys0=".$mdd);
$subsql.=" and a.tour9=".$mdd;
$pagec["pagetitle"]=$mddrs[0]["classsys1"]."旅游线路,".$mddrs[0]["classsys1"]."旅游报价,".$mddrs[0]["classsys1"]."旅游线路怎么样";
$pagec["contenttitle"]=$mddrs[0]["classsys1"]."旅游线路";
}
//获取线路列表
$sql="select * ,(select count(*) from ".DQ."pinglun where pinglun2=a.tour0) as pingluncount
from ".DQ."tour as a , (select min(price8) as bprice8,price7,price6 from ".DQ."price group by price7) b where a.tour44=1212 and a.tour0=b.price7 ".$subsql." order by a.tour0 desc";
$mr=M("tour");
$rs=fanye($mr,$sql,10,2);
//获取类别导航
//获取左边的栏目导航的类别
$classsys=A("classsys");
$cladhtm=$classsys->getteshe();
$this->assign("rs",$rs["rs"]);
$this->assign("fanyehtml",$rs["show"]);
$this->assign("tophtml",$tophtml);
$this->assign("cladhtm",$cladhtm);
$this->assign("pagec",$pagec);
$this->display();
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/tourAction.class.php | PHP | asf20 | 12,033 |
<?php
class paytypeAction extends globalAction
{
/**
* 构建支付宝支付功能页面
* @param $arr 参数值数组
* $arr["out_trade_no"] str商户的订单号
* $arr["aliorder"] 订单名称,显示在支付宝收银台里的“商品名称”里,显示在支付宝的交易管理的“商品名称”的列表里。
* $arr["alibody"] 订单描述、订单详细、订单备注,显示在支付宝收银台里的“商品描述”里
* $arr["alimoney"] 订单总金额,显示在支付宝收银台里的“应付总额”里
* $arr["jetype"] 是支付定金还是支付余额 定金时其值为a,余额时为b
* @return 返回生成的html代码
*/
function alipay($arr)
{
$this->assign("arr",$arr);
//return "alipay333";
//$this->display();
return $this->fetch("./Index/Tpl/Home/default/paytype/alipay.htm");
}
/**
* 上海环讯,普通借记卡
* $arr["Amount"] 定单金额
* $arr["Billno"] 定单号
* $arr["Currency_Type"] 支付币种
* $arr["Attach"] 商户数据包
* @return 返回生成的支付页面
*/
function ipsrmb($arr)
{
$this->assign("arr",$arr);
return $this->fetch("paytype:ipsrmb");
//$this->display();
}
/**
* 转帐支付美元
* 转帐支付是一个静态页面,发布银行帐号等
*/
function zhuangzhang()
{
//$this->display();
return $this->fetch("paytype:zhuangzhang");
}
/**
* 转帐支付人民币
* 转帐支付是一个静态页面,发布银行帐号等
*/
function zhuangzhangrmb()
{
//$this->display();
//return "fdfdfdf";
return $this->fetch("./Index/Tpl/Home/default/paytype/zhuangzhangrmb.htm");
}
/**
* 信用卡人民币支付 环讯
* $arr["pMerCode"] 订单号
* $arr["pAmount"] 金额
* $arr["pAttach"] 附加信息
* $arr["pGoodsInfo"] 商品名称
* $arr["jetype"] 是支付定金还是支付余额 定金时其值为a,余额时为b
*/
function CardOnlineRmb($arr)
{
$arr["pDate"]=date('Ymd');
$this->assign("arr",$arr);
return $this->fetch("./Index/Tpl/Home/default/paytype/CardOnlineRmb.htm");
}
/**
* 信用卡人民币支付 环讯(默认显示选择国际卡选项)
* $arr["pMerCode"] 订单号
* $arr["pAmount"] 金额
* $arr["pAttach"] 附加信息
* $arr["pGoodsInfo"] 商品名称
*/
function CardOnlineusd($arr)
{
$arr["pDate"]=date('Ymd');
$this->assign("arr",$arr);
return $this->fetch("paytype:CardOnlineusd");
}
/**
* 国际信用卡人民币支付 环讯(客人提交一个申请,财务人员再去手工支付)
* $arr["pMerCode"] 订单号
* $arr["pAmount"] 金额
* $arr["pAttach"] 附加信息
* $arr["pGoodsInfo"] 商品名称
*/
function Cardguojiyuangong($arr)
{
$arr["pDate"]=date('Ymd');
for($i=1;$i<=12;$i++)
{
$monthday=$monthday."<option value='".$i."'>".$i."月</option>";
}
$y=date("Y")+0;
for($i=$y;$i<=$y+6;$i++)
{
$year=$year."<option value='".$i."'>".$i."年</option>";
}
$this->assign("arr",$arr);
$this->assign("y",$year);
$this->assign("monthday",$monthday);
return $this->fetch("paytype:Cardguojiyuangong");
}
/**
* 贝宝美元支付功能
* @param $arr 参数数组
* $arr["item_name"] 产品名称
* $arr["item_number"] 产品数量
* $arr["amount"] 支付金额
* $arr["invoice"] 用于传订单号
* $arr["custom"] 标识变量 表示是dj 订金还是余款
$ $arr["productid"] 线路id;
*
*/
function paypalusd($arr)
{
$this->assign("hostname","http://".$_SERVER['SERVER_NAME']);
$this->assign("arr",$arr);
return $this->fetch("paytype:paypalusd");
}
/**
* 显示贝宝的支付返回页面,用于显示付款后的信息,不处理数据库,处理数据库不在这里
*/
/*
function paypalReturnUrl()
{
$this->display();
}
*/
/**
* 信用卡美元支付 环讯
* $arr["pMerCode"] 订单号
* $arr["pAmount"] 金额
* $arr["pAttach"] 附加信息
* $arr["pGoodsInfo"] 商品名称
*/
function cardonlinepay($arr)
{
$arr["pDate"]=date('Ymd');
$this->assign("arr",$arr);
return $this->fetch("paytype:cardonlinepay");
}
/**
* 构建无定单支付页面
*/
function npay()
{
$this->display();
}
/**
* 构建不支付定金页面
* @param $arr
* $arr["orderno"] 订单号
*/
function npaydj($arr)
{
$this->assign("arr",$arr);
return $this->fetch("paytype:npaydj");
}
/**
* 构建chinabank支付界面
* @param $arr 参数数组
* $arr["item_name"] 产品名称
* $arr["item_number"] 产品数量
* $arr["amount"] 支付金额
* $arr["invoice"] 用于传订单号
* $arr["custom"] 标识变量 表示是dj 订金还是余款
* $arr["productid"] 线路id;
$arr["orderno"] 订单号
*/
function chinabank($arr)
{
$this->assign("hostname","http://".$_SERVER['SERVER_NAME']);
$this->assign("arr",$arr);
return $this->fetch("paytype:chinabank");
}
/**
* 付款成功后,显示给顾客看到的信息页面
*/
function showpaysucctocustomer()
{
require RootDir."/inc/Function.Libary.php";
$arr["orderno"]=$_REQUEST["orderno"];//获取订单号
$arr["moneynum"]=$_REQUEST["moneynum"];//支付的金额
$arr["bizhong"]=$_REQUEST["bizhong"];//支付的币种
$arr["paytype"]=iconv("gb2312", "UTF-8", $_REQUEST["paytype"]);//支付方式 如支付宝支付等
$arr["djorwk"]=$_REQUEST["djorwk"];//支付的是定金还是余款
if($arr["djorwk"]=="") $arr["djorwk"]="dj";
if($arr["paytype"]=="chinabank") $arr["paytype"]="国际信用卡在线支付";
//获取订单信息
if($arr["orderno"]!="")
{
$orderinfo=A("tourorder");
$orderinfors=$orderinfo->getOneOrder($arr["orderno"]);
//获取线路信息
if($orderinfors)
{
$tourinfo=A("tours");
$toursinfors=$tourinfo->getrsone($orderinfors["tourid"]);
//获取支付信息
$payinfo=A("orderpaylist");
$payinfors=$payinfo->getOneRs($arr["orderno"]);
}
$djzfbizhong=$payinfors["earnbizhong"];
$bance=$orderinfors["amountmoney"]-$payinfors["earnestmoney"];
if($djzfbizhong=="RMB")
{
$bance=$orderinfors["amountmoney"]-RmbToDols($payinfors["earnestmoney"]);
}
$this->assign("hostname","http://".$_SERVER['SERVER_NAME']."");
$this->assign("toursinfors",$toursinfors);
$this->assign("orderinfors",$orderinfors);
$this->assign("payinfors",$payinfors);
$this->assign("isprint",$_GET["isprint"]);
$this->assign("bance",$bance);
}
$this->assign("arr",$arr);
$this->display();
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/paytypeAction.class.php | PHP | asf20 | 6,776 |
<?php
/**
* 邮件模板类
* @author jroam
*
*/
class mailAction extends Action{
/**
*
*/
function createorder($info,$orderlist){
global $SYS_config;
$this->assign("SYS_config",$SYS_config);
$this->assign("info",$info);
$this->assign("orderlist",$orderlist);
return $this->fetch("mail:createorder");
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/mailAction.class.php | PHP | asf20 | 372 |
<?php
// 本类由系统自动生成,仅供测试用途
class IndexAction extends globalAction {
function test(){
$TMPL_PARSE_STRING = C('TMPL_PARSE_STRING');
echo $TMPL_PARSE_STRING['__UCHOME__'];
}
public function index() {
/**
//周边游索引
$this->assign('ZhouBianYouIndex', ZhouBianYouIndex(__FromDestID__));
//国内游索引
$this->assign('GuoNeiYouIndex', GuoNeiYouIndex(__FromDestID__));
//出境游索引
$this->assign('ChuJingYouIndex', ChuJingYouIndex(__FromDestID__));
//自助游索引(含国内和出境)
$this->assign('ZiZhuYouIndex', ZiZhuYouIndex(__FromDestID__));
//包团游索引(含国内周边包团游,国内包团游,出境包团游)
$this->assign('BaoTuanYouIndex', BaoTuanYouIndex(__FromDestID__));
//获取线路列表**********************************************************
$field = array(
'*',
"(select count(*) from ".C("DB_PREFIX")."pinglun where pinglun2=tour0)" => "pinglunnum"
);
$order = array(
'tour42'=>'desc',
'tour43'=>'desc',
'tour48'=>'desc'
);
$limit = 10;
//必须符合:[当前出发地][已审核]的[热门][中文]线路
$condition["tour10"] = array("like", "%," . __FromDestID__ . ",%");//出发地
$condition["tour44"] = array("eq",1212);//已审核
$condition["tour41"] = array("eq","cn");//中文
//热门线路************************************************
$_condition = array();
$_condition["tour4"] = array("in",array(544,563));//国内和出境线路
$_condition["tour13"] = array("like","%,1285,%");//热门
$hottour_common = M("tour")
->field($field)
->where(array_merge($condition,$_condition))
->order($order)
->limit($limit)
->select();
trace('热门线路查询语句',M("tour")->getLastSQL());//debug
$this->assign("hottour_common", $hottour_common);
//周边游************************************************
$_condition = array();
$_condition["tour4"] = array("eq",544);//国内线路
$_condition["tour40"] = array("like",'%,1273,%');//周边游
$hottour_zhoubian = M("tour")
->field($field)
->where(array_merge($condition,$_condition))
->order($order)
->limit($limit)
->select();
trace('周边游查询语句',M("tour")->getLastSQL());//debug
$this->assign("hottour_zhoubian", $hottour_zhoubian);
//国内游
$_condition = array();
$_condition["tour4"] = array("eq",544);
$hottour_guonei = M("tour")
->field($field)
->where(array_merge($condition,$_condition))
->order($order)
->limit($limit)
->select();
trace('国内游查询语句',M("tour")->getLastSQL());//debug
$this->assign("hottour_guonei", $hottour_guonei);
//出境游
$_condition = array();
$_condition["tour4"] = array("eq",563);
$hottour_chujing = M("tour")
->field($field)
->where(array_merge($condition,$_condition))
->order($order)
->limit($limit)
->select();
trace('出境游查询语句',M("tour")->getLastSQL());//debug
$this->assign("hottour_chujing", $hottour_chujing);
*/
/***********************************************************************
* 线路列表
**********************************************************************/
global $SYS_config;
$indextour = S('indextour' . __FromDestID__);
if(empty($indextour)) {
//$lead = urlencode( iconv("UTF-8", "gb2312", __FromDestName__) );
$lead = __FromDestName__;
$tourtypeArray = array('hot','zhoubian','guonei','chujing');
foreach($tourtypeArray as $tourtype) {
$url = $SYS_config['Gettourxoldurl']."/xdreams.asp"
. "?lead={$lead}&tourtype={$tourtype}&limit=23";
$tour[$tourtype] = file_get_contents($url);
$tour[$tourtype] = iconv('GB2312', 'UTF-8', $tour[$tourtype]);
}
$indextour = $tour;
S('indextour' . __FromDestID__ , $indextour, 3600);
}
$this->assign('indextour', $indextour);
/***********************************************************************
* 客栈列表
**********************************************************************/
$innDao = D('Inn');
//查询条件
$condition = array();
$condition[$innDao->_map['menuId']] = 585;//客栈数据标志
$condition[$innDao->_map['status']] = 1212;//审核标志
//$condition[$innDao->_map['area']] = ;//所属地区
//排序
$order = array();
$order[$innDao->_map['status']] = 'asc';
//查询数据
$innList = $innDao->unionField()
->where($condition)
->limit(5)
->order($order)
->select();
$this->assign('innList', $innList);
/***********************************************************************
* 热门攻略目的地
**********************************************************************/
$blog_dest_dao = M('destination',UHDQ);
$blog_dest_list = $blog_dest_dao
->field('id,name')
->order('hot desc')
->limit(30)
->select();
$this->assign('blog_dest_list', $blog_dest_list);
$this->display();
}
} | 10npsite | trunk/Index/Lib/Action/Home/IndexAction.class.php | PHP | asf20 | 5,870 |
<?php
/**
* 发送邮件的类
* @author jroam
*
*/
class sendmailAction extends globalAction
{
/**
* 发送出团通知书页面给客户,需要以url的方式分层协议 递订单号,发送到的邮箱,订单的id
*/
function chutuantzs()
{
$orderid=$_REQUEST["orderid"];//订单号
$tomail=ui_huanyuanxiahuax($_REQUEST["tomail"]);//发送到的邮箱
$oid=$_REQUEST["id"];
if(!isstri($orderid)) die("订单号不正确");
if(!ismail($tomail)) die("邮箱地址不正确");
if(!is_numeric($oid)) die("订单id不正确");
require_once RootDir."/inc/MailClass.php";
$contenthtml=file_get_contents("http://".$_SERVER['SERVER_NAME']."/affirm".FGF."chutuantongzhi".FGF."orderid".FGF.$orderid);
if(sendmymail($tomail,"mzl","梦之旅提醒您,请查收您的出团通知书",$contenthtml))
{
//发送成功更改发送标识
$ar=A("orderform");
$data["orderform30"]=1;
$ar->updatersonefiled("orderform0=".$oid,$data);
alert("/".Syshoutai."/u.php/orderform".FGF."editorder".FGF."id".FGF."".$oid,2,"出团通知书发送成功");
}
else
{
alert("/".Syshoutai."/u.php/orderform".FGF."editorder".FGF."id".FGF."".$oid,2,"出团通知书发送失败");
}
}
/**
*
* 发送国内合同
*/
function guoleihetong()
{
$orderid=$_REQUEST["orderid"];//订单号
$tomail=ui_huanyuanxiahuax($_REQUEST["tomail"]);//发送到的邮箱
$oid=$_REQUEST["id"];
if(!isstri($orderid)) die("订单号不正确");
if(!ismail($tomail)) die("邮箱地址不正确");
if(!is_numeric($oid)) die("订单id不正确");
require_once RootDir."/inc/MailClass.php";
$contenthtml=file_get_contents("http://".$_SERVER['SERVER_NAME']."/affirm".FGF."guoleihetong".FGF."orderid".FGF."".$orderid);
if(sendmymail($tomail,"mzl","梦之旅提醒您,请查收您的旅游合同(订单号:$orderid)",$contenthtml))
{
//发送成功更改发送标识
$ar=A("orderform");
$data["orderform31"]=1;
$ar->updatersonefiled("orderform0=".$oid,$data);
alert("/".Syshoutai."/u.php/orderform".FGF."editorder".FGF."id".FGF."".$oid,2,"旅游合同发送成功");
}
else{
alert("/".Syshoutai."/u.php/orderform".FGF."editorder".FGF."id".FGF.$oid,2,"旅游合同发送失败");
}
}
/**
*
* 发送出境合同
*/
function chujinghetong()
{
$orderid=$_REQUEST["orderid"];//订单号
$tomail=ui_huanyuanxiahuax($_REQUEST["tomail"]);//发送到的邮箱
$oid=$_REQUEST["id"];
if(!isstri($orderid)) die("订单号不正确");
if(!ismail($tomail)) die("邮箱地址不正确");
if(!is_numeric($oid)) die("订单id不正确");
require_once RootDir."/inc/MailClass.php";
$contenthtml=file_get_contents("http://".$_SERVER['SERVER_NAME']."/affirm".FGF."chujinghetong".FGF."orderid".FGF."".$orderid);
if(sendmymail($tomail,"mzl","梦之旅提醒您,请查收您的旅游合同(订单号:$orderid)",$contenthtml))
{
//发送成功更改发送标识
$ar=A("orderform");
$data["orderform31"]=1;
$ar->updatersonefiled("orderform0=".$oid,$data);
alert("/".Syshoutai."/u.php/orderform".FGF."editorder".FGF."id".FGF."".$oid,2,"旅游合同发送成功");
}
else
{
alert("/".Syshoutai."/u.php/orderform".FGF."editorder".FGF."id".FGF.$oid,2,"旅游合同发送失败");
}
}
/**
* 支付成功时发送给客人的邮件内容
*/
function paysuss(){
$orderlist=$_GET["orderlist"];//订单列表,字符串的格式 :订单号1|支付金额|支付类型,订单号2|支付金额2|支付类型
//下面的以后再来弄
//初始化信息
preg_match("/^[a-zA-Z][0-9]+/",$orderlist,$ordernoarr);
$jelistarr=explode(",",$jelist);
//获取这个订单信息,
$public=A("public");
$sql="select * from ".DQ."orderform where orderform3='".$ordernoarr[0]."'";
$rs=$public->query($sql);
if($rs){
$this->assign("rs",$rs[0]);
$this->assign("paytype",$paytype);
$this->assign("ordernoarr",$ordernoarr);
$this->assign("jelistarr",$jelistarr);
$html=$this->fetch("sendmail:paysuss");//获取邮件内容
require_once RootDir."/inc/MailClass.php";
sendmymail($tomail,"梦之旅","梦之旅提醒您,您的订单已经支付成功",$html);
}
$this->display();
}
/**
* 支付成功时发送给客人的邮件内容
*/
function paysusshotel(){
$orderlist=$_GET["orderno"];//格式H1000000001(a12) a表示是定金,小括号前面的是订单号
//初始化参数
$dingdanno= getsubstr($orderlist, "/^H[\d]+/");
$jetype=getkuohaostr($orderlist, "/\(([a-z])/");//如果是a表示支付的是定金,如果是b支付的是余额
//获取这个订单信息,
$public=M("sendmail");
$sql="select a.*,c.*,b.hotelroom1 from ".DQ."orderform as a left join ".DQ."hotelroom as b on a.orderform31 =b.hotelroom0
left join ".DQ."pay as c on a.orderform3=c.pay1
where orderform3='".$dingdanno."'";
$rs=$public->query($sql);
if($rs){
$this->assign("rs",$rs[0]);
$this->assign("paytype",$jetype);
//获取相关推荐的产品 目前主要推荐相同地区域酒店信息
$sql="select * from ".DQ."hotel where
hotel5=(select hotel5 from ".DQ."hotel where hotel0=".$rs[0]["orderform1"].")
and hotel0<>".$rs[0]["orderform1"]." order by hotel0 desc limit 0,10";
$sql="select hotel0,hotel1,hotel15 from ".DQ."hotel where hotel15<>'' order by hotel0 desc limit 0,10";
$otherrs=$public->query($sql);
$this->assign("otherrs",$otherrs);
$html=$this->fetch("sendmail:paysusshotel");//获取邮件内容
require_once RootDir."/inc/MailClass.php";
//如果邮箱正确就发送邮箱
//if(getsubstr($rs[0]["orderform26"], "/^[\w\-\_\.]+@[\w\-\_\.]+[\w]+$/")) sendmymail($rs[0]["orderform26"],"梦之旅","梦之旅提醒您,您的订单已经支付成功",$html);
}
$this->display();
}
/**
* 当后台工作人员确认此订单时发送
*/
function ReceiveOrder()
{
$ordrid=$_REQUEST["orderid"];
if(!is_numeric($ordrid)) return "";
$this->display();
}
/**
* 当下客栈订单成功时的发送邮件的html代码
*/
function createinnorderhtml(){
$orderno=$_REQUEST["orderno"];//订单号
$mr=M("sendmail");
$sql="select *,c.hotelroom1 from ".DQ."orderform as a left join ".DQ."pay as b on a.orderform3=b.pay1
left join ".DQ."hotelroom as c on a.orderform31=c.hotelroom0
where a.orderform3='".$orderno."'";
$rs=$mr->query($sql);
$this->assign("rs",$rs[0]);
$this->display();
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/sendmailAction.class.php | PHP | asf20 | 6,769 |
<?php
class domesticAction extends Action
{
//国内游首页
public function index(){
$public=A("public");
$tophtml=$public->top();
//获取左边的栏目导航的类别
$classsys=A("classsys");
$cladhtm=$classsys->getteshe();
$countpunlun="(select count(*) from ".DQ."pinglun where pinglun2=tour0) as pinglunnum";
//---------------获取线路列表
$sqlpaixu=" order by tour42 desc,tour43 desc,tour48 desc limit 0,10";
$sqlcns=" and tour44=1212 and tour41='cn' ";
//获取热门线路--城市周边
$sql="select *,".$countpunlun." from ".DQ."tour where tour13 like '%1285%' and tour50 <>''".$sqlcns.$sqlpaixu;
$hottour_zhoubian=$public->getRsListBySql($sql);
//获取热门线路--国内游
$sql="select *,".$countpunlun." from ".DQ."tour where tour4=544 and tour13 like '%1285%' ".$sqlcns.$sqlpaixu;
$hottour_guolei=$public->getRsListBySql($sql);
//获取热门线路--出境游
$sql="select *,".$countpunlun." from ".DQ."tour where tour4=563 and tour13 like '%1285%' ".$sqlcns.$sqlpaixu;
$hottour_chuji=$public->getRsListBySql($sql);
//获取游记攻略
$myuser=A("user");
$sql="select * from ".UHDQ."blog as a left join ".UHDQ."space as b on a.uid=b.uid
left join ".UHDQ."blogfield as c on a.blogid=c.blogid
where c.message like '%<img %'
order by a.dateline desc limit 0,5";
$youji=$myuser->getRsListBySql($sql);
$this->assign("tophtml",$tophtml);
$this->assign("hottour_zhoubian",$hottour_zhoubian);
$this->assign("hottour_guolei",$hottour_guolei);
$this->assign("cladhtm",$cladhtm);
$this->assign("hottour_chuji",$hottour_chuji);
$this->assign("youji",$youji);
$this->display();
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/domesticAction.class.php | PHP | asf20 | 1,793 |
<?php
class payAction extends Action
{
/**
* 显示购物车主列表,
* 购物车每个选项的值在用户没有登陆之前用cookie
* cookie格式:cart["tour_idnum1"]["price"] 价格
* cookie格式cart["tour_idnum1"]["erprice"] 儿童价
* cookie格式cart["tour_idnum2"]["price"] 价格
* cookie格式cart["tour_idnum2"]["erprice"] 儿童价
*/
public function cart(){
//获取头部
$public=A("public");
$tophtml=$public->top();
//获取cookie里的购物车值
$cart=array();
$i=0;
//反序列化购物车cookie
//$syscookie=unserialize($_COOKIE["syscookie"]);
foreach ($_SESSION["cart"] as $k=> $v){
$cart[$i]=$v;
$cart[$i]["key"]=$k;
$i++;
}
//获取每个商品的项目属性,在模板里来展示
foreach ($_SESSION["cart"] as $k=>$v){
//判断是否有必选项目
if(preg_match("/^tour$/", $k)){
$sql="select count(*) from ".DQ."info where info2=".$vo["proid"]." and info3=560";
}
}
$this->assign("syscookie",$_SESSION["cart"]);
$this->assign("cart",$cart);
$this->assign("tophtml",$tophtml);
$this->display();
}
function addcart()
{
$prostype=$_REQUEST["prostype"];
$proid=$_REQUEST["proid"];
$proname=$_REQUEST["proname"];
$chengren=$_REQUEST["chengren"];
$et=$_REQUEST["et"];
$cooisepriceid=$_REQUEST["cooisepriceid"];
$maxyouhuinum=$_REQUEST["maxyouhuinum"];//最高优惠金额
$maxjifenduihuan=$_REQUEST["maxjifenduihuan"];//最高积分兑换金额
$public=A("public");
//$syscookie=unserialize($_COOKIE["syscookie"]);
//初始化获取的值
$maxyouhuinum=($maxyouhuinum=="")?0:$maxyouhuinum;
//获取当是线路的时候的id
if($prostype=="tour"){
if(!isset($_SESSION["cart"][$prostype.$proid])){
$_SESSION["cart"][$prostype.$proid]=array(
"proid"=>$proid,
"chengren"=>$chengren,
"et"=>$et,
"cooisepriceid"=>$cooisepriceid,
"proname"=>$proname,
"propic"=>$_REQUEST["propic"],
"chufashijiand"=>$_REQUEST["chufashijiand"],
"maxchengrennum"=>$_REQUEST["maxchengrennum"],//最大成人数
"prourl"=>"/tour/view-id-".$proid,//这个商品的连接
"maxyouhuinum"=>$maxyouhuinum,
"maxjifenduihuan"=>$maxjifenduihuan
);
//序列化保存
//setmycookies("syscookie",serialize($syscookie));
}
}
alert("/pay/cart",4,"");
}
/**
* 下订单流程的第一步
*/
function order()
{
$proid=$_REQUEST["proid"];//产品id
$priceid=$_REQUEST["cooisepriceid"];//选择的价格类型的id
$chengren=$_REQUEST["chengren"];//成人数
$et=$_REQUEST["et"];//儿童数
//获取头部
$public=A("public");
$tophtml=$public->top();
$this->assign("tophtml",$tophtml);
$this->display();
}
/**
* 修改购物车中的一单项商品
*
*/
function editcart()
{
$protypeflag=$_REQUEST["protypeflag"];//所修改的商品类别,如tour9 表示是线路id为9的商品
if(!$protypeflag){
alert("", 1, "参数值不正确");
die;
}
$chengren=$_REQUEST["chengren_".$protypeflag];//成人数
$et=$_REQUEST["et_".$protypeflag];//儿童数
$chufatime=$_REQUEST["chufatime_".$protypeflag];//具体出发日期
$cooisepriceid=$_REQUEST["cooisepriceid_".$protypeflag];//选择价格类别的id
$chufashijiand=$_REQUEST["chufashijiand_".$protypeflag];//时间段信息
$roomnum=$_REQUEST["roomnum_".$protypeflag];//选择的房间数
$agreedanfangcha=$_REQUEST["agreedanfangcha_".$protypeflag];//是否同意单房差
$jiejifuwux=$_REQUEST["jiejifuwux_".$protypeflag];//接机服务
$jihedidianl=$_REQUEST["jihedidianl_".$protypeflag];//集合地点
$bixuanxiang=$_REQUEST["bixuanxiang_".$protypeflag];//必选项目
$zixuanxiangmu=$_REQUEST["zixuanxiangmu_".$protypeflag];//自选项目
$biaoxian=$_REQUEST["biaoxian_".$protypeflag];//保险项目
$priceshuoming=$_REQUEST["priceshuoming_".$protypeflag];//价格的详细说明
$chengrenprice=$_REQUEST["chengrenprice_".$protypeflag];//成人价
$etprice=$_REQUEST["etprice_".$protypeflag];//儿童价
$danfangcha=$_REQUEST["danfangcha_".$protypeflag];//单房价
$proprice=$_REQUEST["proprice_".$protypeflag];//每个商品计算后的总价
//更新其中一个的cookie值
//$syscookie=unserialize($_COOKIE["syscookie"]);
$_SESSION["cart"][$protypeflag]["et"]=$et;
$_SESSION["cart"][$protypeflag]["chengren"]=$chengren;
$_SESSION["cart"][$protypeflag]["chufatime"]=$chufatime;
$_SESSION["cart"][$protypeflag]["cooisepriceid"]=$cooisepriceid;
$_SESSION["cart"][$protypeflag]["chufashijiand"]=$chufashijiand;
$_SESSION["cart"][$protypeflag]["roomnum"]=$roomnum;
$_SESSION["cart"][$protypeflag]["agreedanfangcha"]=$agreedanfangcha;
$_SESSION["cart"][$protypeflag]["jiejifuwux"]=$jiejifuwux;
$_SESSION["cart"][$protypeflag]["jihedidianl"]=$jihedidianl;
$_SESSION["cart"][$protypeflag]["bixuanxiang"]=$bixuanxiang;
$_SESSION["cart"][$protypeflag]["zixuanxiangmu"]=$zixuanxiangmu;
$_SESSION["cart"][$protypeflag]["biaoxian"]=$biaoxian;
$_SESSION["cart"][$protypeflag]["priceshuoming"]=$priceshuoming;
$_SESSION["cart"][$protypeflag]["chengrenprice"]=$chengrenprice;
$_SESSION["cart"][$protypeflag]["etprice"]=$etprice;
$_SESSION["cart"][$protypeflag]["danfangcha"]=$danfangcha;
$_SESSION["cart"][$protypeflag]["proprice"]=$proprice;
//setmycookies("syscookie",serialize($syscookie));
alert("/pay/cart",4,"");
}
/**
* 删除购物车里的其中一个商品
*/
function delcart(){
$protypeflag=$_REQUEST["protypeflag"];
if($protypeflag){
unset($_SESSION["cart"][$protypeflag]);
alert("/pay/cart",2,"删除成功");
}
else {
alert("/pay/cart",2,"失败");
}
}
/**
* 进入支付流程,填写写顾客的信息
*
*/
function paytwo()
{
//获取头部
$public=A("public");
$tophtml=$public->top();
//$syscookie=unserialize($_COOKIE["syscookie"]);
$this->assign("syscookie",$_SESSION);
$this->assign("tophtml",$tophtml);
$this->display();
}
/**
* 进入获取客人信息,生成订单
*
*/
function paythree()
{
include RootDir.'/inc/MailClass.php';
//获取头部
$public=A("public");
$tophtml=$public->top();
//$syscookie=unserialize($_COOKIE["syscookie"]);
//==========================生成订单号
if(count($_SESSION["cart"])<1){
alert("/",2,"购物车里没有线路或酒店,请先去选购");
die();
}
$showinfo=array();
$orderform=A("orderform");//初始化订单表的模型
$ordernolist="";//订单号列表,多个订单号时用逗号分隔
$dingjiallnumlist="";//各个订单的订金数,多个时用逗号分隔
$dingjinallnum=0;//各个订单的订金之和
foreach ($_SESSION["cart"] as $k=>$v){
$userid=($_COOKIE["uchome_uid"]!="")?$_COOKIE["uchome_uid"]:0;
$totalmoney=0;
//获取这条价格的信息
if(!is_numeric($v["cooisepriceid"])) die("你没有选择价格");
$pricers=$public->query("select * from ".DQ."price where price0=".$v["cooisepriceid"]);
$dingjingzifubl=($pricers[0]["price4"]=="" or (int)$pricers[0]["price4"] >100)?100:$pricers[0]["price4"];//定金支付比例
//定金金额
$dingjingnum=$v["proprice"]*$dingjingzifubl/100;
//定金支付期限
if(!is_numeric($pricers[0]["price18"])){
$djzfqx=time()+3*3600*24;//默认三天内支付
}else{
$djzfqx=time()+$pricers[0]["price18"]*3600*24;
}
//余款支付期限
if(!is_numeric($pricers[0]["price14"])){
$yukuzfqx=time()+7*3600*24;//默认七天内支付
}else{
$yukuzfqx=time()+$pricers[0]["price14"]*3600*24;
}
//组合订单内容
$ordercontent="<b>类型(出发时间段):</b>".$v["chufashijiand"]."<br>";
$ordercontent.="<b>人数</b>:成人:".$v["chengren"]."位,儿童:".$v["et"]."个<br>";
$ordercontent.="<b>选择的项目</b>:<br>";
if($v["jiejifuwux"]!="") $ordercontent.=" 接机服务:".preg_replace("/\^[\d\.]+$/", "", $v["jiejifuwux"])."<br>";
if($v["bixuanxiang"]!="") $ordercontent.=" 必选项目:".preg_replace("/\^[\d\.]+$/", "", $v["bixuanxiang"])."<br>";
if($v["roomnum"]!="") $ordercontent.="选择的房间数:".$v["roomnum"]."间<br>";
$ordercontent.="是否同意拼房:".($v["agreedanfangcha"]=="1")?"是":"否";
if($v["zixuanxiangmu"]){
$ordercontent.="自选项目:";
foreach ($v["zixuanxiangmu"] as $vz){
$ordercontent.=preg_replace("/\^[\d\.]+$/", "", $vz)." ";
}
$ordercontent.="<br>";
}
if($v["biaoxian"]){
$ordercontent.="购买的保险项目:";
foreach ($v["biaoxian"] as $vz){
$ordercontent.=preg_replace("/\^[\d\.]+$/", "", $vz)." ";
}
$ordercontent.="<br>";
}
//游客信息
$totalren=(int)$v["chengren"]+(int)$v["et"];
for($i=1;$i<=$totalren;$i++){
$ordercontent.="第$i位客人:".$_REQUEST["gukename_$k_$i"].",".$_REQUEST["tel_$k_$i"].",".$_REQUEST["sex_$k_$i"]."<br>";
}
if($v["priceshuoming"]!="") $ordercontent.="价格计算公式:".$v["priceshuoming"]."<br>";
$orderno=$this->creatorderno($k);
$data=array();
$data["orderform1"]=$v["proid"];
$data["orderform2"]=554;
$data["orderform3"]=$orderno;
$data["orderform4"]=$v["proname"];
$data["orderform6"]=time();
$data["orderform7"]=$userid;
$data["orderform5"]=$_REQUEST["usernamelx"];
$data["orderform26"]=$_REQUEST["useremail"];
$data["orderform9"]=strtotime($v["chufatime"]);
$data["orderform16"]=$v["proprice"];
$data["orderform17"]=$dingjingnum;
$data["orderform10"]=$ordercontent;
$data["orderform34"]=$v["cooisepriceid"];
$data["orderform18"]=$djzfqx;
$data["orderform19"]=$v["proprice"]-$dingjingnum;//余款金额
$data["orderform20"]=$yukuzfqx;//余款支付期限
if($orderform->createorder($data))
{
//当插入数据库成功后,整理数据,显示页面
$showinfo[$k]["order"]=$orderno;//订单号
$showinfo[$k]["usernamelx"]=$_REQUEST["usernamelx"];//联系人
$showinfo[$k]["useremail"]=$_REQUEST["useremail"];//联系人邮件
$showinfo[$k]["totalmoney"]=$v["proprice"];//每个商品的总价
$showinfo[$k]["dingjingmoney"]=$v["proprice"]*$dingjingzifubl/100;//定金金额
$showinfo[$k]["djzfqx"]=$djzfqx;//定金支付期限
$showinfo[$k]["proname"]=$v["proname"];//产品名称
$showinfo[$k]["chufatime"]=$v["chufatime"];//出发时间
$showinfo[$k]["dingjingnum"]=$dingjingnum;//订金金额
$showinfo[$k]["proid"]=$v["proid"];//产品id号
$showinfo[$k]["createtime"]=$data["orderform6"];//订单生成的时间
$dingjiallnumlist.=$showinfo[$k]["dingjingmoney"].",";
$dingjinallnum+=$showinfo[$k]["dingjingmoney"];
$ordernolist.=$orderno.",";
}
}
//发送邮件
$mailrsc=A("mail");
$info=array();
$info["username"]=$_REQUEST["usernamelx"];
$bodyhtml=$mailrsc->createorder($info,$showinfo);
if($bodyhtml!="") sendmygmail("梦之旅",$_REQUEST["useremail"],"您的订单已经生成成功",$bodyhtml."");
//生成支付选项
$ordernolist=substr($ordernolist, 0,-1);
$dingjiallnumlist=substr($dingjiallnumlist, 0,-1);
$paytype=A("paytype");
//支付宝
$arr["out_trade_no"]=$ordernolist;//订单号
$arr["aliorder"]="梦之旅旅游产品订单";
$arr["alibody"]="旅游产品定金";
$arr["alimoney"]=$dingjinallnum;//支付金额
$arr["productid"]=$tid;//产品的id号
$arr["paymoneytype"]="j1";//支付的是定金还是余款 dj表示支付的是定金
$arr["alimoneylist"]=$dingjiallnumlist;//各个订单的定金列表
$alipay_pay=$paytype->alipay($arr);
//环讯信用卡在线支付人民币
$arrco["pBillNo"]=$ordernolist;
$arrco["pAmount"]=$dingjinallnum;
$arrco["pAttachpaty"]="j1";
$arrco["productid"]=$tid;//产品的id号
$arrco["pGoodsInfo"]="梦之旅旅游产品服务";
$arrco["pAttach"]=$dingjiallnumlist;//各个订单的定金列表
$cardonlinepayrmb=$paytype->CardOnlineRmb($arrco);
$this->assign("showinfo",$showinfo);
$this->assign("syscookie",$_SESSION);
$this->assign("alipay_pay",$alipay_pay);
$this->assign("alipay_pay",$alipay_pay);
$this->assign("cardonlinepayrmb",$cardonlinepayrmb);
$this->display();
}
/**
* 生成订单号,生成的格式如:t0000001 或h0000001
* 条件是在最大的订单号值是加1
*
*/
function creatorderno($type)
{
$public=A("public");
$rs=$public->query("select orderform3 from ".DQ."orderform order by orderform0 desc limit 0,1");
if(preg_match("/^tour[0-9]+$/", $type)) $ttype="t";
if(preg_match("/^hotel[0-9]+$/", $type)) $ttype="h";
if($rs){
$temp=$rs[0]["orderform3"];
$temp=preg_replace("/^[a-zA-Z]+/", "", $temp);
$temp+=1;
$n=strlen($temp);
return $ttype."".preg_replace("/0{".$n."}$/", $temp, "0000000");
}
else
{
return $ttype."".preg_replace("/0{".$n."}$/", $temp, "0000001");
}
}
/**
* 当客人支付成功时显示的页面
*/
function showpaysuss(){
$orderlist=$_REQUEST["orderlist"];//订单号列表 格式应为:
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/payAction.class.php | PHP | asf20 | 13,809 |
<?php
/**
* 新闻表类
* @author jroam
*@time 2012-4-5
*/
class newsAction extends Action
{
/**
* 获取并返回新闻类的多条记录
* @param $wheresql 查询的sql语句
* @return 返回新闻类的多条记录 失败返回null
*/
function getRsList($wheresql)
{
$rsc=M("news");
$rs= $rsc->where($wheresql)->select();
return ($rs)?$rs:"";
}
/**
* 获取并返回新闻类的一条记录
* @param $wheresql 查询的sql语句
* @return 返回新闻类的单条记录 失败返回null
*/
function getRsOne($wheresql)
{
$rsc=M("news");
$rs= $rsc->where($wheresql)->find();
$this->assign("rs",$rs);
$this->display();
//return ($rs)?$rs:"";
}
function getlist()
{
$mr=M("news");
$rs=fanye($mr,"news0>0",2);
$this->assign("rs",$rs["rs"]);
$this->assign("show",$rs["show"]);
$this->display();
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/newsAction.class.php | PHP | asf20 | 946 |
<?php
class classsysAction extends Action
{
/**
* 获取目的地,输出为json,供社区调用
*/
function getmididi()
{
$pid=$_REQUEST["pid"];
if($pid=="") $pid="0";
if(!is_numeric($pid))
{
$temp="{'success':false}";
die($temp);
}
$mr=M("classsys");
$rs=$mr->where("classsys2=".$pid." and (classsys3=551 or classsys3=562)")->select();
$temp="{'success':true";
if($rs)$temp.=",'data':[";
foreach ($rs as $v)
{
$temp=$temp."{'id':".$v["classsys0"].",'text':'".$v["classsys1"]."'},";
}
if($rs)
{
$temp=substr($temp, 0,-1);
$temp.="]";
}
$temp.="}";
echo($temp);
$temp=null;
}
/**
* 获取已经有线路数据的特色类别
*/
function getteshe()
{
$mr=M("classsys");
$result=array();
$rs=$mr->where("classsys3=565 order by classsys4 desc")->limit("0,3")->select();
$i=0;
foreach($rs as $k=>$v)
{
$result[$i]=$v;
//查询这个目录下有无线路,并确定其关联景点
$sql="select * from ".DQ."classsys as a where classsys3=566 and
exists( select * from ".DQ."tour as b where a.classsys0=b.tour49 and b.tour50 like '%".$v["classsys0"]."%')
order by classsys4 desc limit 0,6
";
$rs2=$mr->query($sql);
$result[$i]["lei"]=$rs2;
$i++;
}
$this->assign("rs",$result);
//获取国内游类别
$rsguolei=$mr->where("classsys3=551 and classsys2>0 ")->select();
//获取出境旅游线路类别
$rsabroad=$mr->where("classsys3=562 and classsys2>0 ")->select();
$this->assign("rsguolei",$rsguolei);
$this->assign("rsabroad",$rsabroad);
return $this->fetch("classsys:getteshe");
}
/**
*
* 获取所有出发地列表,
* @return 出发地的数组列表,失败返回false
*/
function getchufadi()
{
$mr=M("classsys");
$rs=$mr->where("classsys3=542 order by classsys4 desc")->select();
return ($rs)?$rs:null;
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/classsysAction.class.php | PHP | asf20 | 1,993 |
<?php
class guanzhuAction extends Action
{
/**
* 会员想去时添加值
*/
function add()
{
$uid=$_COOKIE["uchome_uid"];
$tid=$_REQUEST["tid"];
$uchome_auth=$_COOKIE["uchome_auth"];
if(!$uchome_auth) die("会员没有登陆");
$mr=M("guanzhu");
$rs=$mr->where("guanzhu1=$uid and guanzhu2=$tid")->find();
if($rs)
{
die("这条线路已经是您想去的了");
}
$data["guanzhu1"]=$uid;
$data["guanzhu2"]=$tid;
$num=$mr->data($data)->add();
if($num)
{
$rs=$mr->query("select count(*) as num from ".DQ."guanzhu where guanzhu2=$tid");
echo $rs[0]["num"];
}
else
{
echo "添加失败";
}
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/guanzhuAction.class.php | PHP | asf20 | 697 |
<?php
/**
*
* @author jroam
*
*/
class onepageAction extends Action
{
/**
* 获取并返回单页类的多条记录
* @param $wheresql 查询的sql语句
* @return 返回产品类的多条记录 失败返回null
*/
function getRsList($wheresql)
{
$rsc=M("onepage");
$rs= $rsc->where($wheresql)->select();
return ($rs)?$rs:null;
}
/**
* 获取并返回单页类的一条记录
* @param $wheresql 查询的sql语句
* @return 返回单页类的单条记录 失败返回null
*/
function getRsOne()
{
$rsc=M("onepage");
$wheresql="";
$rs= $rsc->where($wheresql)->find();
//$this->assign("rs",$rs);
//$this->display();
//return ($rs)?$rs:null;
}
function showdti()
{
$mr=M("onepage");
$rs=$mr->where("onepage5=581")->find();
$this->assign("rs",$rs);
$this->display();
}
function show()
{
$mid=$_REQUEST["mid"];//获取menuid的值
$did=$_REQUEST["did"];//获取显示字段号的值
$mr=M("onepage");
if(!is_numeric($mid) or !is_numeric($did)) die("传入的参数不对,请重新传入");
$rs=$mr->field("onepage5,onepage".$did)->where("onepage5=$mid")->find();
echo $rs["onepage$did"];
$this->assign("content",$rs["onepage$d"]);
$this->display();
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/onepageAction.class.php | PHP | asf20 | 1,313 |
<?php
/**
* 短息发送模块
* @author jroam
*
*/
class smsAction extends Action{
/**
* 发送单条短息
* @param $data $data["phoneno"]手机号 $data["content"]发送内容
* @return 成功返回 true 失败返回false
*/
function sendsms($data){
//验证数据
/**
if(!$data) return false;
if(!preg_match("/^1[\d]{10}$/", $data["phoneno"])) return false;
if($data["content"]=="" or !$data["content"]) return false;
*/
//短信接口用户名 $uid
global $SYS_config;
$uid = $SYS_config["smsuser"];
//短信接口密码 $passwd
$passwd = $SYS_config["smspass"];;
//发送到的目标手机号码 $telphone
$telphone = $data["phoneno"];
//短信内容 $message
$message = mb_convert_encoding($data["content"], "GB2312", "utf-8");
//iconv("UTF-8","GB2312//TRANSLIT",$message);
//$message=urlencode($message);
$url="CorpID={$uid}&Pwd={$passwd}&Mobile={$telphone}&Content={$message}&Cell=&SendTime=";
$gateway = "http://mb345.com:999/ws/batchSend.aspx?".$url;
$result = file_get_contents($gateway);
return ($result>=0)?true:false;
}
/**
*
* @param $data $data["phoneno"]手机号 $data["content"]内容
*
*/
function senddx($data){
if(!preg_match("/^1[\d]{10}$/", $data["phoneno"])) return("手机号格式不对");
if($data["content"]=="") return("内容不能不空");
$data["content"]=$data["content"];
return $this->sendsms($data)?"suss":"pass";
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/smsAction.class.php | PHP | asf20 | 1,524 |
<?php
/**
* 用于获取用户社区信息的类
* @author jroam
*
*/
class userAction extends Action
{
/**
* 根据sql查询并返回查询的结果记录集
* @param $sql
* @return 如果数据非法或者查询错误则返回false 否则返回查询结果数据集(同select方法)
*/
function getRsListBySql($sql)
{
require_once RootDir."/inc/mysql_userdb.php";//加载社区配置文件
$mr=new USERDB();
return $mr->select($sql);
}
/**
* 根据sql更新或删除记录集
* @param $sql
* @return 如果数据非法或者查询错误则返回false 否则返回影响的记录数
*/
function executeBySql($sql)
{
require_once RootDir."/inc/mysql_userdb.php";//加载社区配置文件
$mr=new USERDB();
return $mr->execute($sql);
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/userAction.class.php | PHP | asf20 | 833 |
<?php
class pinglunAction extends Action
{
function add()
{
$uid=$_COOKIE["uchome_uid"];
$uchome_auth=$_COOKIE["uchome_auth"];
if(!$uchome_auth) die("会员没有登陆");
$content=$_REQUEST["yingxiangcontent"];//应像内容
$tid=$_REQUEST["tid"];//线路的id
$mr=M("pinglun");
//获取这个用户的最大数,如果没有达到最大数就添加
global $SYS_config;
$rs=$mr->query("select count(*) as ynum from ".DQ."pinglun where pinglun3=580 and pinglun2=$tid and pinglun4=$uid");
if($rs["ynum"]>$SYS_config["addYingx"]) die("您已经添加到最大条数了");
$data["pinglun3"]=580;
$data["pinglun1"]=$content;
$data["pinglun2"]=$tid;
$data["pinglun8"]=time();
$data["pinglun4"]=$uid;
$rs=$mr->data($data)->add();
echo ($rs)?"添加成功":"添加失败";
}
function getrslist($sql)
{
$mr=M("pinglun");
$rs=$mr->where($sql)->select();
return $rs?$rs:null;
}
/**
* 获取某一条线路的好评率,返回样式:98%
* @param $tid 线路id
*/
function gettourhaopinglv($tid)
{
if(!is_numeric($tid)) die("线路id必须为数字");
$mr=M("pinlun");
$rs=$mr->query("select avg(pinglun9+pinglun10+pinglun11+pinglun12+pinglun13+pinglun14) as onetotal from ".DQ."pinglun where pinglun2=$tid and pinglun3=579");
$n=0;
$i=0;
foreach($rs as $v)
{
$n+=$v["onetotal"];
$i+=1;
}
return number_format(($n*100)/($i*30),0,".","") ."%";
}
/**
* 显示添加评论的主界面
*/
function addhtm()
{
$orderno=$_REQUEST["orderno"];
if(!preg_match("/^[a-zA-Z][\d]+$/", $orderno)) die("订单号不正确,请从正确的地址进入");
$public=A("public");
//查询订单和线路信息
$sql="select * from ".DQ."orderform a left join ".DQ."tour b on a.orderform1=b.tour0 where a.orderform3='".$orderno."'";
$rs=$public->query($sql);
$this->assign("rs",$rs[0]);
$this->display();
}
/**
* 保存添加评论数据
*/
function addsave()
{
$yzm=$_REQUEST["yzm"];//获取验证码
if($yzm!=$_SESSION['SafeCode']){
alert("",1,"验证码不正确,请认真填写");
die();
}
$myp=D("pinglun");
$myp->create() ;
$res=$myp->add();
$t= ($res>0)?"评论提交成功":"评论提交失败";
alert("/",2,"$t");
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/pinglunAction.class.php | PHP | asf20 | 2,392 |
<?php
class baseAction extends Action{
/**
* 显示验证码
*/
Public function verify(){
import("@.ORG.Util.Image");
//Image::buildImageVerify();
Image::buildImageVerify ( 5, 5, "gif" );
}
/**
* 获取当前购物车商品的数量
*/
function getcartnum()
{
$syscookie=unserialize($_COOKIE["syscookie"]);
echo count($syscookie["cart"]);
}
/**
* 页面上部搜索框
*/
function search()
{
$this->display();
}
/*
* 供ajax方式调用,并获取cookie值
*/
function ajaxgetcookie()
{
$c1=$_REQUEST["c1"];//第一级名称
$c2=$_REQUEST["c2"];//第二级名称
$c3=$_REQUEST["c3"];//第三级名称
$c4=$_REQUEST["c4"];
$syscookie=unserialize($_COOKIE["syscookie"]);
if($c1!="" and $c2=="" and $c3=="" and $c4=="" ) echo $syscookie[$c1];
if($c1!="" and $c2!="" and $c3=="" and $c4=="" ) echo $syscookie[$c1][$c2];
if($c1!="" and $c2!="" and $c3!="" and $c4=="" ) echo $syscookie[$c1][$c2][$c3];
if($c1!="" and $c2!="" and $c3!="" and $c4!="" ) echo $syscookie[$c1][$c2][$c3][$c4];
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/baseAction.class.php | PHP | asf20 | 1,140 |
<?php
class infoAction extends Action{
/**
* 获取页面底部的帮助信息
*/
function getpagefootlist(){
//获取帮助底部信息
$sql="select classsys0,classsys1 from ".DQ."classsys where classsys3=611 order by classsys4 desc";
$crs=M()->query($sql);
$rarr=array();
$i=0;
foreach ($crs as $v){
$sql="select info0,info1 from ".DQ."info where info2=".$v["classsys0"]." and info8=1212 order by info11 desc limit 0,4";
$rarr[$i]["title"]=$v["classsys1"];
$rarr[$i]["id"]=$v["classsys0"];
$rarr[$i]["c"]=M()->query($sql);
$i++;
}
$this->assign("rs",$rarr);
return $this->fetch("info:getpagefootlist");
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/infoAction.class.php | PHP | asf20 | 694 |
<?php
/**
*
公共类处理函数
* @author jqrr
*
*/
class publicAction extends Action
{
function top()
{
global $_SC;
$myuser=new USERDB();
$cmr=new Model();
$classsys=A("classsys");
/***********************************************************************
*自动获取当前出发地
***********************************************************************/
//获取所有出发地城市
$chufalist=$classsys->getchufadi();
//尝试解析COOKIE中设置的当前出发地
$now_from_dest = '';
if(!empty($_COOKIE['from_dest'])) {
foreach ($chufalist as $v) {
if($v["classsys0"]==$_COOKIE['from_dest']) {
$now_from_dest = $v;
break;
}
}
}
//TODO 尝试获取用户常用出发地列表设置
else {
$uid = $_COOKIE["uchome_uid"];
$uchome_auth = $_COOKIE["uchome_auth"];
$choosechufa = $cmr->table(UHDQ."userchuafadi U")
->join(DQ."classsys F on U.chuafaid = F.classsys0")
->where("U.uid=".$uid)
->select();
if( strlen($uchome_auth)>5 && !empty($choosechufa))
$now_from_dest = $choosechufa[0];
}
//以上都没有获取到出发地信息,则通过IP识别
if(empty($now_from_dest)) {
import("ORG.Net.IpLocation");
$loc = new IpLocation();
$userloc = $loc->getlocation('202.98.192.168');
$user_country = iconv( "gbk" , "UTF-8//IGNORE", $userloc['country'] );
$user_area = iconv( "gbk" , "UTF-8//IGNORE", $userloc['area'] );
//TODO debug
//echo $user_country.$user_area;
$now_from_dest = array(
'classsys0' => '1815',
'classsys1' => '南昌',
'classsys2' => '0',
'classsys3' => '542',
'classsys4' => '7',
'classsys5' => '0',
'classsys6' => '0',
'classsys7' => 'nanchang',
'classsys8' => '0',
'classsys9' => null,
'classsys10' => '0',
'classsys11' => null,
'classsys12' => null,
'classsys13' => null,
'classsys14' => null
);
}
//标记出发地
$this->assign('now_from_dest', $now_from_dest);
//定义全站常量:当前出发地
define('__FromDestID__', $now_from_dest['classsys0']);
//主推线路
$topproduct = M('topproduct')->where(array('topproduct2'=>__FromDestID__))->order('topproduct4 desc')->select();
$this->assign('topproduct', $topproduct);
//热门搜索词
$hotkeyword = M('info')->where(array('info2'=>__FromDestID__))->order('info6 desc')->select();
$this->assign('hotkeyword', $hotkeyword);
//获取最后注册的会员
$sql="select uid,username from ".$_SC["tablepre"]."space order by uid desc limit 0,5";
$rs=$myuser->select($sql);
//获取最近发表了文章的记录
$sql="select * from ".$_SC["tablepre"]."blog as a left join ".$_SC["tablepre"]."space as b
on a.uid=b.uid where a.friend=0 order by a.dateline desc limit 0,3";
$blog=$myuser->select($sql);
//获取登陆会员的信息
/****************************************************************************************/
//统计有多少人选择了第一个出发地
$sql="select count(*) as cnum from ".UHDQ."userchuafadi where chuafaid=".$choosechufa[0]["classsys0"];
$choosechufafnum=$cmr->query($sql);
if($rs) $this->assign("userlist",$rs);
if($blog) $this->assign("bloglist",$blog);
$this->assign("choosechufa",$choosechufa);
$this->assign("choosechufafnum",$choosechufafnum[0]);
$this->assign("chufalist",$chufalist);
return $this->fetch("public:top");
}
/**
* 共js用ajax方式调用,作用:远程提交社区的用户名和密码,。获取登陆状态
*
*/
function ajaxuserlogin()
{
$username=$_REQUEST["username"];
$password=$_REQUEST["password"];
if(preg_replace("/[\s]*/", "", $username)=="") die("用户名不正确");
if(preg_replace("/[\s]*/", "", $password)=="") die("密码不正确");
$content=file_get_contents(SYS_UCHOMEURL."/api/login.php?username=".$username."&password=".$password);
//echo preg_replace("/^[\s\S]+returnrecord\=/", "", $content);
echo $content;
}
/**
* 给用户添加选定的出发地
*/
function addcoochechufa()
{
$uid=$_GET["uid"];
$chufaid=$_GET["chufaid"];
if(!is_numeric($uid) or !is_numeric($chufaid)) die("请输入正确的id");
if($this->countuserchufa()>4) die("已经超出了最大数");
$mr=new Model();
$sql="select * from ".UHDQ."userchuafadi where uid=".$uid." chuafaid=".$chufaid;
$rs=$this->getRsListBySql($sql);;
if(!$rs)
{
$sql="insert into ".UHDQ."userchuafadi(uid,chuafaid)values($uid,$chufaid)";
$this->executeBySql($sql);
}
}
/**
* 更新用户所选的出发地
*/
function updatecoochechufa()
{
$uid=$_GET["uid"];//
$chufaid=$_GET["chufaid"];//目标出发地id
$oldchufaid=$_GET["oldchufaid"];//旧的出发地id
if(!is_numeric($uid) or !is_numeric($chufaid) or !is_numeric($oldchufaid)) die("请输入正确的id");
$sql="update ".UHDQ."userchuafadi set chuafaid=$chufaid where uid=$uid and chuafaid=$oldchufaid";
$this->executeBySql($sql);
}
/**
* 删除用户所选的出发地
*/
function delcoochechufa()
{
$uid=$_GET["uid"];//
$chufaid=$_GET["chufaid"];//目标出发地id
if(!is_numeric($uid) or !is_numeric($chufaid) ) die("请输入正确的id");
$sql="delete from ".UHDQ."userchuafadi where chuafaid=$chufaid and uid=$uid ";
$this->executeBySql($sql);
echo "dook";
}
/**
* 获取已经选择了的个数
*/
function countuserchufa()
{
$sql="select count(*) as totnum from ".UHDQ."userchuafadi where uid=7";
$rs=$this->getRsListBySql($sql);
return $rs[0]["totnum"];
}
/**
* 统计有多少人选择了第一个出发地
*/
function countuserchooes()
{
$chufaid=$_GET["chufaid"];
$sql="select count(*) as cnum from ".UHDQ."userchuafadi where chuafaid=".$chufaid;
$choosechufafnum=$this->getRsListBySql($sql);
echo $choosechufafnum[0]["cnum"];
}
/**
* 显示某个用户所选的出发地
*/
function showuserchufadi()
{
$uid=$_REQUEST["uid"];
if(!is_numeric($uid)) die("你的用户名不正确");
$sql="select * from ".UHDQ."userchuafadi as a
left join ".DQ."classsys as b on a.chuafaid=b.classsys0 where uid=".$uid;
$rs=$this->getRsListBySql($sql);
//生成返回的html代码
$i=0;
foreach ($rs as $k=>$v)
{
if($i==0)
{
?><item key=<?php echo $i; ?>><a href='/classsys/chufadi-cid-<?php echo $v["chuafaid"] ?>' id="chooseedlist_0_mchufa_url"><span class="bold">出发城市:</span><span id="chooseedlist_0_mchufa"><?php echo $v["classsys1"]; ?></span></a>
</item>
<?}
else
{ ?>
<li id="chooseedlist_<?php echo $i; ?>" class="nav_bg"><a href='/classsys/chufadi-cid-<?php echo $v["classsys0"]; ?>' id="chooseedlist_<?php echo $i; ?>_mchufa_url">从<span id="chooseedlist_<?php echo $i; ?>_mchufa"><?php echo $v["classsys1"]; ?></span>出发</a> <a id="delchufa_<?php echo $i; ?>" turl="/public/delcoochechufa-uid-<?php echo $uid; ?>-chufaid-<?php echo $v["classsys0"]; ?>">-</a></li>
<?
}
$i++;
}
}
/**
* 根据sql查询并返回查询的结果记录集
* @param $sql
* @return 如果数据非法或者查询错误则返回false 否则返回查询结果数据集(同select方法)
*/
function getRsListBySql($sql)
{
$mr=new Model();
return $mr->query($sql);
}
/**
* 根据sql更新或删除记录集
* @param $sql
* @return 如果数据非法或者查询错误则返回false 否则返回影响的记录数
*/
function executeBySql($sql)
{
$mr=new Model();
return $mr->execute($sql);
}
/**
* 根据sql查询并返回查询的结果记录集
* @param $sql
* @return 如果数据非法或者查询错误则返回false 否则返回查询结果数据集(同select方法)
*/
function query($sql)
{
$mr=new Model();
return $mr->query($sql);
}
/**
* 根据sql更新或删除记录集
* @param $sql
* @return 如果数据非法或者查询错误则返回false 否则返回影响的记录数
*/
function execute($sql)
{
$mr=new Model();
return $mr->execute($sql);
}
/**
* 页面底部
*/
function pagehelpfoot(){
$infomr=A("Home/info");
$helplist=$infomr->getpagefootlist();
$this->assign("helplist",$helplist);
//静态化页面底部
$this->buildHtml("pagehelpfoot",RootDir."/Index/html/","public:pagehelpfoot");
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/publicAction.class.php | PHP | asf20 | 9,304 |
<?php
/**
* 各种确认书界面
* @author Administrator
*
*/
class affirmAction extends Action
{
/**
* 支付确认书
* 显示支付的确认书,
* 每个员工只能查看自己的确认书,工作人员可以查看所有的
*
*/
function zhifu()
{
$orderid=$_REQUEST["orderid"];//订单号
$mr=D("orderform");
global $SystemConest;
//@todo: 以后再添加会员只能查看自己的订单,管理人员可以查看所有的.
$sql="select * from ".$SystemConest[7]."orderform as a left join ".$SystemConest[7]."pay as b on a.orderform3=b.pay1 where a.orderform3='".$orderid."' order by a.orderform0 desc";
$rs=$mr->query($sql);
//获取是哪一条线路
if($rs[0]["orderform1"]!="")
{
$tourmr=A("tour");
$trs=$tourmr->getrsone("tour0=".$rs[0]["orderform1"]);
}
$this->assign("tourrs",$trs);//所订的线路信息
$this->assign("rs",$rs[0]);
$this->display();
}
/**
* 支付确认书
* 显示支付的确认书,
* 每个员工只能查看自己的确认书,工作人员可以查看所有的
*
*/
function hotelzhifu()
{
$orderid=$_REQUEST["orderid"];//订单号
$mr=D("Home/orderform");
global $SystemConest;
//@todo: 以后再添加会员只能查看自己的订单,管理人员可以查看所有的.
$sql="select * from ".$SystemConest[7]."orderform as a left join ".$SystemConest[7]."pay as b on a.orderform3=b.pay1 where a.orderform3='".$orderid."' order by a.orderform0 desc";
$rs=$mr->query($sql);
//获取是哪一条线路
if($rs[0]["orderform1"]!="")
{
$tourmr=A("tour");
$trs=$tourmr->getrsone("tour0=".$rs[0]["orderform1"]);
}
$this->assign("tourrs",$trs);//所订的线路信息
$this->assign("rs",$rs[0]);
$this->display();
}
/**
* 出团通知书界面
*/
function chutuantongzhi()
{
$orderid=$_REQUEST["orderid"];//订单号
$showedit=$_REQUEST["showedit"];//是否显示html样式 值为ye时显示html样式
$sendflag=$_REQUEST["sendflag"];//是否显示发送标识
$mr=D("orderform");
global $SystemConest;
//@todo: 以后再添加会员只能查看自己的订单,管理人员可以查看所有的.
$sql="select * from ".$SystemConest[7]."orderform as a left join ".$SystemConest[7]."pay as b on a.orderform3=b.pay1 where a.orderform3='".$orderid."' order by a.orderform0 desc";
$rs=$mr->query($sql);
//获取是哪一条线路
if($rs[0]["orderform1"]!="")
{
$tourmr=A("tour");
$trs=$tourmr->getrsone("tour0=".$rs[0]["orderform1"]);
}
//用数组格化化需要的信息
$ac=array(
"jiejisongji"=>getformcontent($rs[0]["orderform29"],"集合接送"),
"chutuhao"=>getformcontent($rs[0]["orderform29"],"团号"),
"yukuanzhifu"=>getformcontent($rs[0]["orderform29"],"余款支付信息"),
"dangdilvyousang"=>getformcontent($rs[0]["orderform29"],"供应商"),
"contactinfo"=>getformcontent($rs[0]["orderform29"],"梦之旅联系信息"),
);
$this->assign("tourrs",$trs);//所订的线路信息
$this->assign("sendflag",$sendflag);
$this->assign("ac",$ac);
$this->assign("showedit",$showedit);
$this->assign("rs",$rs[0]);
$this->display();
}
/**
* 国内合同模板
*/
function guoleihetong()
{
$orderid=$_REQUEST["orderid"];
$mr=D("orderform");
global $SystemConest;
$sql="select * from ".$SystemConest[7]."orderform as a left join ".$SystemConest[7]."pay as b on a.orderform3=b.pay1 where a.orderform3='".$orderid."' order by a.orderform0 desc";
$rs=$mr->query($sql);
if($rs[0]["orderform1"]!="")
{
$tourmr=A("tour");
$trs=$tourmr->getrsone("tour0=".$rs[0]["orderform1"]);
}
//获取合同里的各项值
$hetong=$rs[0]["orderform32"];
$ac=array(
"jiafangname"=>getformcontent($hetong,"jiafangname"),//甲方名称
"Youraddress"=>getformcontent($hetong,"Youraddress"),//甲方地址
"jiaemail"=>getformcontent($hetong,"jiaemail"),////甲方电子邮件
"Yourtel"=>getformcontent($hetong,"Yourtel"),//甲方电话
"YiafangName"=>getformcontent($hetong,"YiafangName"),//乙方名称
"jinyunXuKeZheng"=>getformcontent($hetong,"jinyunXuKeZheng"),//许可证编号
"jinyunhuanwei"=>getformcontent($hetong,"jinyunhuanwei"),//经营范围
"Yitel"=>getformcontent($hetong,"Yitel"),//乙方电话
"tuanno"=>getformcontent($hetong,"tuanno"),//团号
"protname"=>getformcontent($hetong,"protname"),//旅游线路
"cfsd"=>getformcontent($hetong,"cfsd"),//出发时间地址
"JiaoTongJiBiaoZhun"=>getformcontent($hetong,"JiaoTongJiBiaoZhun"),//交通及标准
"zylsd"=>getformcontent($hetong,"zylsd"),//行程
"ycsbz"=>getformcontent($hetong,"ycsbz"),//用餐次数及标准
"zxbz"=>getformcontent($hetong,"zxbz"),//住宿标准
"gwanpai"=>getformcontent($hetong,"gwanpai"),//购物安排
"ZhiFeiXiangMu"=>getformcontent($hetong,"ZhiFeiXiangMu"),//自费项目
"daoyoufeiy"=>getformcontent($hetong,"daoyoufeiy"),//导游及费用
"fyzfbf"=>getformcontent($hetong,"fyzfbf"),//旅游费用
"zhifubanf"=>getformcontent($hetong,"zhifubanf"),//支付办法
"qtyy"=>getformcontent($hetong,"qtyy"),//不成团时转旅行社
"ZhuanBinTuanTravel"=>getformcontent($hetong,"ZhuanBinTuanTravel"),//转并团信息
"DiJieTravel"=>getformcontent($hetong,"DiJieTravel"),//地接社信息
"beizhu"=>getformcontent($hetong,"beizhu"),//备注
"BaoXianGSLianXiRen"=>getformcontent($hetong,"BaoXianGSLianXiRen"),//保险公司联系人
"LvYouFeiYongShuoMing1"=>getformcontent($hetong,"LvYouFeiYongShuoMing1"),//旅游交通费1
"LvYouFeiYongShuoMing2"=>getformcontent($hetong,"LvYouFeiYongShuoMing2"),//旅游交通费2
"QiTaFeiYong"=>getformcontent($hetong,"QiTaFeiYong"),//其它费用
"xdwp"=>getformcontent($hetong,"xdwp"),//携带证件
"SuangYueDing"=>getformcontent($hetong,"SuangYueDing"),//约定1
"SuangYueDingYiZ"=>getformcontent($hetong,"SuangYueDingYiZ"),//约定2
"cfrq"=>getformcontent($hetong,"cfrq"),//提前通知天数
"other1"=>getformcontent($hetong,"other1"),//其它条款1
"other2"=>getformcontent($hetong,"other2"),//
"other3"=>getformcontent($hetong,"other3"),//
"other4"=>getformcontent($hetong,"other4"),//
"other5"=>getformcontent($hetong,"other5"),//
"jiafangAllPersren"=>getformcontent($hetong,"jiafangAllPersren"),//甲方所有人员名单及证件
"jiafangrenydb"=>getformcontent($hetong,"jiafangrenydb"),//甲方人员代表
"yifangrenydb"=>getformcontent($hetong,"yifangrenydb"),//乙方人员代表
"qanyuedate"=>getformcontent($hetong,"qanyuedate"),//签定日期
);
$this->assign("Login",$_SESSION["Login"]);
$this->assign("rs",$rs[0]);
$this->assign("ddr","hello");
$this->assign("showedit",$_REQUEST["showedit"]);
$this->assign("sendflag",$_REQUEST["sendflag"]);
$this->assign("trs",$trs);
$this->assign("ac",$ac);
$this->display();
}
/**
* 出境合同模板
*/
function chujinghetong()
{
$orderid=$_REQUEST["orderid"];
$mr=D("orderform");
global $SystemConest;
$sql="select * from ".$SystemConest[7]."orderform as a left join ".$SystemConest[7]."pay as b on a.orderform3=b.pay1 where a.orderform3='".$orderid."' order by a.orderform0 desc";
$rs=$mr->query($sql);
if($rs[0]["orderform1"]!="")
{
$tourmr=A("tour");
$trs=$tourmr->getrsone("tour0=".$rs[0]["orderform1"]);
}
//获取合同里的各项值
$hetong=$rs[0]["orderform32"];
$ac=array(
"hetongbianhao"=>getformcontent($hetong,"hetongbianhao"),//合同编号
"jiafangName"=>getformcontent($hetong,"jiafangName"),//甲方名称
"Youraddress"=>getformcontent($hetong,"Youraddress"),//住所或单位地址
"Email_send"=>getformcontent($hetong,"Email_send"),//
"Yourtel"=>getformcontent($hetong,"Yourtel"),//
"YifangName"=>getformcontent($hetong,"YifangName"),//
"YicompanyAddress"=>getformcontent($hetong,"YicompanyAddress"),//
"jinyunhuanwei"=>getformcontent($hetong,"jinyunhuanwei"),//
"jinyunXuKeZheng"=>getformcontent($hetong,"jinyunXuKeZheng"),//
"Yitel"=>getformcontent($hetong,"Yitel"),//
"tuanno"=>getformcontent($hetong,"tuanno"),//
"CountryAndArea"=>getformcontent($hetong,"CountryAndArea"),//
"chufaTimeSTuan"=>getformcontent($hetong,"chufaTimeSTuan"),//
"JiaoTongJiBiaoZhun"=>getformcontent($hetong,"JiaoTongJiBiaoZhun"),//
"zylsd"=>getformcontent($hetong,"zylsd"),//
"ycsbz"=>getformcontent($hetong,"ycsbz"),//
"zxbz"=>getformcontent($hetong,"zxbz"),//
"gwanpai"=>getformcontent($hetong,"gwanpai"),//
"ZhiFeiXiangMu"=>getformcontent($hetong,"ZhiFeiXiangMu"),//
"daoyoufeiy"=>getformcontent($hetong,"daoyoufeiy"),//
"fyzfbf"=>getformcontent($hetong,"fyzfbf"),//
"LvYouFeiYongBaoHanXuan"=>getformcontent($hetong,"LvYouFeiYongBaoHanXuan"),//
"jiaotongfeiyong"=>getformcontent($hetong,"jiaotongfeiyong"),//
"youleifeiy"=>getformcontent($hetong,"youleifeiy"),//
"jiedaifeiyong"=>getformcontent($hetong,"jiedaifeiyong"),//
"chanyingzhushu"=>getformcontent($hetong,"chanyingzhushu"),//
"lvyoufuwufei"=>getformcontent($hetong,"lvyoufuwufei"),//
"qitafeiyong"=>getformcontent($hetong,"qitafeiyong"),//
"zfbf"=>getformcontent($hetong,"zfbf"),//
"JiaoNaFangSi_zt"=>getformcontent($hetong,"JiaoNaFangSi_zt"),//
"JiaoNaFangSi_xyk"=>getformcontent($hetong,"JiaoNaFangSi_xyk"),//
"JiaoNaFangSi_qita"=>getformcontent($hetong,"JiaoNaFangSi_qita"),//
"JiaoNaFangSi_xj"=>getformcontent($hetong,"JiaoNaFangSi_xj"),//
"zhuanbit"=>getformcontent($hetong,"zhuanbit"),//
"bunenfatian"=>getformcontent($hetong,"bunenfatian"),//
"ZhuanBinTuanTravel"=>getformcontent($hetong,"ZhuanBinTuanTravel"),//
"DiJieTravel"=>getformcontent($hetong,"DiJieTravel"),//
"beizhu"=>getformcontent($hetong,"beizhu"),//
"BaoXianGSLianXiRen"=>getformcontent($hetong,"BaoXianGSLianXiRen"),//
"LvYouFeiYongShuoMing1"=>getformcontent($hetong,"LvYouFeiYongShuoMing1"),//
"LvYouFeiYongShuoMing2"=>getformcontent($hetong,"LvYouFeiYongShuoMing2"),//
"QiTaFeiYong"=>getformcontent($hetong,"QiTaFeiYong"),//
"xdwpchuy"=>getformcontent($hetong,"xdwpchuy"),//
"SuangYueDing"=>getformcontent($hetong,"SuangYueDing"),//
"SuangYueDingYiZ"=>getformcontent($hetong,"SuangYueDingYiZ"),//
"cfrq"=>getformcontent($hetong,"cfrq"),//
"other1"=>getformcontent($hetong,"other1"),//
"other2"=>getformcontent($hetong,"other2"),//
"other3"=>getformcontent($hetong,"other3"),//
"other4"=>getformcontent($hetong,"other4"),//
"other5"=>getformcontent($hetong,"other5"),//
"jiafangAllPersren"=>getformcontent($hetong,"jiafangAllPersren"),//
"jiafangdaibiao"=>getformcontent($hetong,"jiafangdaibiao"),//
"jiafangshengfengzheng"=>getformcontent($hetong,"jiafangshengfengzheng"),//
"jiafangtelfax"=>getformcontent($hetong,"jiafangtelfax"),//
"jiafengemail"=>getformcontent($hetong,"jiafengemail"),//
"y_name"=>getformcontent($hetong,"y_name"),//
"y_tel"=>getformcontent($hetong,"y_tel"),//
"y_addr"=>getformcontent($hetong,"y_addr"),//
"y_email"=>getformcontent($hetong,"y_email"),//
"y_date"=>getformcontent($hetong,"y_date"),//
);
$ac['jiaotongfeiyong']="1";
$showedit=$_REQUEST["showedit"];
$sendflag=$_REQUEST["sendflag"];
$this->assign("Login",$_SESSION["Login"]);
$this->assign("rs",$rs[0]);
$this->assign("showedit",$_REQUEST["showedit"]);
$this->assign("sendflag",$sendflag);
$this->assign("trs",$trs);
$this->assign("ac",$ac);
$this->display();
}
}
?> | 10npsite | trunk/Index/Lib/Action/Home/affirmAction.class.php | PHP | asf20 | 11,809 |
<?php
/**
* 获取游记列表
*/
class LastScrollDataWidget extends Widget {
public function render($data) {
//获取最后注册的会员
$sql="select uid,username from ".UHDQ."space order by uid desc limit 5";
$data["newuser"] = M()->query($sql);
//获取最后发表的游记
$sql="select blogid,uid,username,subject from ".UHDQ."blog order by dateline desc limit 5";
$data["newblog"] = M()->query($sql);
$content = $this->renderFile("LastScrollData", $data);
return $content;
}
} | 10npsite | trunk/Index/Lib/Widget/LastScrollDataWidget.class.php | PHP | asf20 | 581 |
<?php
/**
* 获取游记列表
*/
class BlogSideListWidget extends Widget {
public function render($data) {
$sql = "select * from ".UHDQ."blog as a left join ".UHDQ."space as b on a.uid=b.uid
left join ".UHDQ."blogfield as c on a.blogid=c.blogid
where c.message like '%<img %'
order by a.dateline desc limit 0,5";
$data["list"] = M()->query($sql);
$content = $this->renderFile("BlogSideList", $data);
return $content;
}
} | 10npsite | trunk/Index/Lib/Widget/BlogSideListWidget.class.php | PHP | asf20 | 532 |
<!--bottom start-->
<div class="bottom">
<div class="footer">
<div class="hzhb">
<ul>
<li class="hz_title">合作伙伴:</li>
<li class="hz_nr"> <a href="" target="_blank">新浪旅游</a> <a href="" target="_blank">搜狐旅游</a> <a href="" target="_blank">网易旅游</a> <a href="" target="_blank">央视旅游</a> <a href="" target="_blank">雅虎旅游</a> <a href="" target="_blank">凤凰卫视</a> <a href="" target="_blank">旅游光明</a> <a href="" target="_blank">日报旅游中</a> <a href="" target="_blank">国日报旅游</a> <a href="" target="_blank">中华网旅游环球</a> <a href="" target="_blank">网旅游中</a> <a href="" target="_blank">央广播电台</a> <a href="" target="_blank">国日报旅游</a> </li>
</ul>
<ul>
<li class="hz_title">友情链接:</li>
<li class="hz_nr">
<volist name="rslink" id="vol">
<a target="_blank" href="<{$vol.connectsys2}>"><{$vol.connectsys1}></a>
</volist>
</li>
</ul>
</div>
<div class="about"> <a href="" target="_blank">关于梦之旅</a> <span>|</span> <a href="" target="_blank">联系梦之旅</a> <span>|</span> <a href="" target="_blank">诚邀合作</a> <span>|</span> <a href="" target="_blank">广告招标</a> <span>|</span> <a href="" target="_blank">网站地图</a> <span>|</span> <a href="" target="_blank">快速支付</a> <span>|</span> <a href="" target="_blank">支付安全</a> <span>|</span> <a href="" target="_blank">法律声明</a> <span>|</span> <a href="" target="_blank">新手指南</a> </div>
<div class="bqxx">
<li> Copyright © 1997-2012 梦之旅(mzl5.com) 版权所有 </li>
<li style="float:right;"> 国际旅行社经营许可证注册号: L-SC-CJ00014 蜀ICP备08007806号 京公网安备1101055404号 </li>
</div>
</div>
</div>
<!--bottom end-->
</body></html> | 10npsite | trunk/Index/Lib/Widget/foot/foot.htm | HTML | asf20 | 1,962 |
<volist name="newuser" id="vo">
<div>欢迎<a href="/user/space.php?uid=<{$vo.uid}>"><strong><{$vo.username}></strong></a>入驻本网</div>
</volist>
<volist name="newblog" id="vo">
<div><a href="/user/space.php?uid=<{$vo.uid}>&do=blog&id=<{$vo.blogid}>"><{$vo.username}>刚刚发表了:<{$vo.subject}></a></div>
</volist> | 10npsite | trunk/Index/Lib/Widget/LastScrollData/LastScrollData.htm | HTML | asf20 | 330 |
<?php
/**
* 页面底部
* @author jqrr
*
*/
class footWidget extends Widget {
public function render($data) {
//获取友情链接
$sql="select * from ".DQ."connectsys where connectsys7=".$data["linkid"];
$data["rslink"]=M()->query($sql);
//获取帮助信息
$sql="select classsys0,classsys1 from ".DQ."classsys where classsys3=611 order by classsys4 desc";
$crs=M()->query($sql);
$rarr=array();
$i=0;
foreach ($crs as $v){
$sql="select info0,info1 from ".DQ."info where info2=".$v["classsys0"]." and info8=1212 order by info11 desc limit 0,4";
$rarr[$i]["title"]=$v["classsys1"];
$rarr[$i]["id"]=$v["classsys0"];
$rarr[$i]["c"]=M()->query($sql);
$i++;
}
$data["rshelp"]=$rarr;
$c= $this->renderFile("foot", $data);
return $c;
}
}
?> | 10npsite | trunk/Index/Lib/Widget/footWidget.class.php | PHP | asf20 | 850 |
<?php
class LinkWidget extends Widget{
/**
*/
public function render($data) {
$sql="select * from ".DQ."connectsys where connectsys7=".$data["cid"];
$data["rs"]=M()->query($sql);
$c= $this->renderFile("Linkoffoot", $data);
return $c;
}
}
?> | 10npsite | trunk/Index/Lib/Widget/LinkWidget.class.php | PHP | asf20 | 291 |
<div class="yjgl">
<!-- <ul class="right_title">
<li class="left_title">游记攻略</li>
<li class="jf"><a href="__UCHOME__/cp.php?ac=blog" target="_blank">写游记</a></li>
</ul>
-->
<ul class="fl_nr">
<volist name="list" id="vo">
<if condition="$i eq 1">
<li class="yjgl_nr">
<p>
<span><a href="__UCHOME__/space.php?uid=<{$vo.uid}>&do=blog&id=<{$vo.blogid}>" target="_blank"> <img height="70" width="110" src="<{$vo.message|getstrtopic}>" alt="<{$vo.subject}>"></a></span>
</p>
<p class="yjgl_nr_right">
<span><a href="__UCHOME__/space.php?uid=<{$vo.uid}>&do=blog&id=<{$vo.blogid}>" target="_blank" class="red bold"><{$vo.subject}></a></span>
<span class="yj_ly">
<{$vo.uid|getUsertouxiang=###,"small",16,16,'$vo.username'}>
<a href="" target="_blank" class="gray font12"><{$vo.username}> 撰写</a>
</span>
<span>
<a href="__UCHOME__/space.php?uid=<{$vo.uid}>&do=blog&id=<{$vo.blogid}>" target="_blank" class="black"><{$vo.message|getDelHtml|my_substr=###,0,10}> </a>
</span>
</p>
</li>
<else />
<li class="yj_lb">
<span> <{$vo.uid|getUsertouxiang=###,"small",16,16,'$vo.username'}></span>
<span><a href="__UCHOME__/space.php?uid=<{$vo.uid}>&do=blog&id=<{$vo.blogid}>" target="_blank"><{$vo.subject}></a></span>
</li>
</if>
</volist>
</ul>
</div> | 10npsite | trunk/Index/Lib/Widget/BlogSideList/BlogSideList.htm | HTML | asf20 | 1,725 |
<volist name="rs" id="vo">
<a href="<{$vo.connectsys2}>"><{$vo.connectsys1}></a>
</volist> | 10npsite | trunk/Index/Lib/Widget/Link/Linkoffoot.htm | HTML | asf20 | 94 |
<?php
/*~ class.smtp.php
.---------------------------------------------------------------------------.
| Software: PHPMailer - PHP email class |
| Version: 5.1 |
| Contact: via sourceforge.net support pages (also www.codeworxtech.com) |
| Info: http://phpmailer.sourceforge.net |
| Support: http://sourceforge.net/projects/phpmailer/ |
| ------------------------------------------------------------------------- |
| Admin: Andy Prevost (project admininistrator) |
| Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
| : Marcus Bointon (coolbru) coolbru@users.sourceforge.net |
| Founder: Brent R. Matzelle (original founder) |
| Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. |
| Copyright (c) 2001-2003, Brent R. Matzelle |
| ------------------------------------------------------------------------- |
| License: Distributed under the Lesser General Public License (LGPL) |
| http://www.gnu.org/copyleft/lesser.html |
| This program is distributed in the hope that it will be useful - WITHOUT |
| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| FITNESS FOR A PARTICULAR PURPOSE. |
| ------------------------------------------------------------------------- |
| We offer a number of paid services (www.codeworxtech.com): |
| - Web Hosting on highly optimized fast and secure servers |
| - Technology Consulting |
| - Oursourcing (highly qualified programmers and graphic designers) |
'---------------------------------------------------------------------------'
*/
/**
* PHPMailer - PHP SMTP email transport class
* NOTE: Designed for use with PHP version 5 and up
* @package PHPMailer
* @author Andy Prevost
* @author Marcus Bointon
* @copyright 2004 - 2008 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
* @version $Id: class.smtp.php 444 2009-05-05 11:22:26Z coolbru $
*/
/**
* SMTP is rfc 821 compliant and implements all the rfc 821 SMTP
* commands except TURN which will always return a not implemented
* error. SMTP also provides some utility methods for sending mail
* to an SMTP server.
* original author: Chris Ryan
*/
class SMTP {
/**
* SMTP server port
* @var int
*/
public $SMTP_PORT = 25;
/**
* SMTP reply line ending
* @var string
*/
public $CRLF = "\r\n";
/**
* Sets whether debugging is turned on
* @var bool
*/
public $do_debug; // the level of debug to perform
/**
* Sets VERP use on/off (default is off)
* @var bool
*/
public $do_verp = false;
/////////////////////////////////////////////////
// PROPERTIES, PRIVATE AND PROTECTED
/////////////////////////////////////////////////
private $smtp_conn; // the socket to the server
private $error; // error if any on the last call
private $helo_rply; // the reply the server sent to us for HELO
/**
* Initialize the class so that the data is in a known state.
* @access public
* @return void
*/
public function __construct() {
$this->smtp_conn = 0;
$this->error = null;
$this->helo_rply = null;
$this->do_debug = 0;
}
/////////////////////////////////////////////////
// CONNECTION FUNCTIONS
/////////////////////////////////////////////////
/**
* Connect to the server specified on the port specified.
* If the port is not specified use the default SMTP_PORT.
* If tval is specified then a connection will try and be
* established with the server for that number of seconds.
* If tval is not specified the default is 30 seconds to
* try on the connection.
*
* SMTP CODE SUCCESS: 220
* SMTP CODE FAILURE: 421
* @access public
* @return bool
*/
public function Connect($host, $port = 0, $tval = 30) {
// set the error val to null so there is no confusion
$this->error = null;
// make sure we are __not__ connected
if($this->connected()) {
// already connected, generate error
$this->error = array("error" => "Already connected to a server");
return false;
}
if(empty($port)) {
$port = $this->SMTP_PORT;
}
// connect to the smtp server
$this->smtp_conn = @fsockopen($host, // the host of the server
$port, // the port to use
$errno, // error number if any
$errstr, // error message if any
$tval); // give up after ? secs
// verify we connected properly
if(empty($this->smtp_conn)) {
$this->error = array("error" => "Failed to connect to server",
"errno" => $errno,
"errstr" => $errstr);
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '<br />';
}
return false;
}
// SMTP server can take longer to respond, give longer timeout for first read
// Windows does not have support for this timeout function
if(substr(PHP_OS, 0, 3) != "WIN")
socket_set_timeout($this->smtp_conn, $tval, 0);
// get any announcement
$announce = $this->get_lines();
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $announce . $this->CRLF . '<br />';
}
return true;
}
/**
* Initiate a TLS communication with the server.
*
* SMTP CODE 220 Ready to start TLS
* SMTP CODE 501 Syntax error (no parameters allowed)
* SMTP CODE 454 TLS not available due to temporary reason
* @access public
* @return bool success
*/
public function StartTLS() {
$this->error = null; # to avoid confusion
if(!$this->connected()) {
$this->error = array("error" => "Called StartTLS() without being connected");
return false;
}
fputs($this->smtp_conn,"STARTTLS" . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
}
if($code != 220) {
$this->error =
array("error" => "STARTTLS not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
// Begin encrypted connection
if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
return false;
}
return true;
}
/**
* Performs SMTP authentication. Must be run after running the
* Hello() method. Returns true if successfully authenticated.
* @access public
* @return bool
*/
public function Authenticate($username, $password) {
// Start authentication
fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($code != 334) {
$this->error =
array("error" => "AUTH not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
// Send encoded username
fputs($this->smtp_conn, base64_encode($username) . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($code != 334) {
$this->error =
array("error" => "Username not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
// Send encoded password
fputs($this->smtp_conn, base64_encode($password) . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($code != 235) {
$this->error =
array("error" => "Password not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
return true;
}
/**
* Returns true if connected to a server otherwise false
* @access public
* @return bool
*/
public function Connected() {
if(!empty($this->smtp_conn)) {
$sock_status = socket_get_status($this->smtp_conn);
if($sock_status["eof"]) {
// the socket is valid but we are not connected
if($this->do_debug >= 1) {
echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected";
}
$this->Close();
return false;
}
return true; // everything looks good
}
return false;
}
/**
* Closes the socket and cleans up the state of the class.
* It is not considered good to use this function without
* first trying to use QUIT.
* @access public
* @return void
*/
public function Close() {
$this->error = null; // so there is no confusion
$this->helo_rply = null;
if(!empty($this->smtp_conn)) {
// close the connection and cleanup
fclose($this->smtp_conn);
$this->smtp_conn = 0;
}
}
/////////////////////////////////////////////////
// SMTP COMMANDS
/////////////////////////////////////////////////
/**
* Issues a data command and sends the msg_data to the server
* finializing the mail transaction. $msg_data is the message
* that is to be send with the headers. Each header needs to be
* on a single line followed by a <CRLF> with the message headers
* and the message body being seperated by and additional <CRLF>.
*
* Implements rfc 821: DATA <CRLF>
*
* SMTP CODE INTERMEDIATE: 354
* [data]
* <CRLF>.<CRLF>
* SMTP CODE SUCCESS: 250
* SMTP CODE FAILURE: 552,554,451,452
* SMTP CODE FAILURE: 451,554
* SMTP CODE ERROR : 500,501,503,421
* @access public
* @return bool
*/
public function Data($msg_data) {
$this->error = null; // so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called Data() without being connected");
return false;
}
fputs($this->smtp_conn,"DATA" . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
}
if($code != 354) {
$this->error =
array("error" => "DATA command not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
/* the server is ready to accept data!
* according to rfc 821 we should not send more than 1000
* including the CRLF
* characters on a single line so we will break the data up
* into lines by \r and/or \n then if needed we will break
* each of those into smaller lines to fit within the limit.
* in addition we will be looking for lines that start with
* a period '.' and append and additional period '.' to that
* line. NOTE: this does not count towards limit.
*/
// normalize the line breaks so we know the explode works
$msg_data = str_replace("\r\n","\n",$msg_data);
$msg_data = str_replace("\r","\n",$msg_data);
$lines = explode("\n",$msg_data);
/* we need to find a good way to determine is headers are
* in the msg_data or if it is a straight msg body
* currently I am assuming rfc 822 definitions of msg headers
* and if the first field of the first line (':' sperated)
* does not contain a space then it _should_ be a header
* and we can process all lines before a blank "" line as
* headers.
*/
$field = substr($lines[0],0,strpos($lines[0],":"));
$in_headers = false;
if(!empty($field) && !strstr($field," ")) {
$in_headers = true;
}
$max_line_length = 998; // used below; set here for ease in change
while(list(,$line) = @each($lines)) {
$lines_out = null;
if($line == "" && $in_headers) {
$in_headers = false;
}
// ok we need to break this line up into several smaller lines
while(strlen($line) > $max_line_length) {
$pos = strrpos(substr($line,0,$max_line_length)," ");
// Patch to fix DOS attack
if(!$pos) {
$pos = $max_line_length - 1;
$lines_out[] = substr($line,0,$pos);
$line = substr($line,$pos);
} else {
$lines_out[] = substr($line,0,$pos);
$line = substr($line,$pos + 1);
}
/* if processing headers add a LWSP-char to the front of new line
* rfc 822 on long msg headers
*/
if($in_headers) {
$line = "\t" . $line;
}
}
$lines_out[] = $line;
// send the lines to the server
while(list(,$line_out) = @each($lines_out)) {
if(strlen($line_out) > 0)
{
if(substr($line_out, 0, 1) == ".") {
$line_out = "." . $line_out;
}
}
fputs($this->smtp_conn,$line_out . $this->CRLF);
}
}
// message data has been sent
fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
}
if($code != 250) {
$this->error =
array("error" => "DATA not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
return true;
}
/**
* Sends the HELO command to the smtp server.
* This makes sure that we and the server are in
* the same known state.
*
* Implements from rfc 821: HELO <SP> <domain> <CRLF>
*
* SMTP CODE SUCCESS: 250
* SMTP CODE ERROR : 500, 501, 504, 421
* @access public
* @return bool
*/
public function Hello($host = '') {
$this->error = null; // so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called Hello() without being connected");
return false;
}
// if hostname for HELO was not specified send default
if(empty($host)) {
// determine appropriate default to send to server
$host = "localhost";
}
// Send extended hello first (RFC 2821)
if(!$this->SendHello("EHLO", $host)) {
if(!$this->SendHello("HELO", $host)) {
return false;
}
}
return true;
}
/**
* Sends a HELO/EHLO command.
* @access private
* @return bool
*/
private function SendHello($hello, $host) {
fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER: " . $rply . $this->CRLF . '<br />';
}
if($code != 250) {
$this->error =
array("error" => $hello . " not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
$this->helo_rply = $rply;
return true;
}
/**
* Starts a mail transaction from the email address specified in
* $from. Returns true if successful or false otherwise. If True
* the mail transaction is started and then one or more Recipient
* commands may be called followed by a Data command.
*
* Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
*
* SMTP CODE SUCCESS: 250
* SMTP CODE SUCCESS: 552,451,452
* SMTP CODE SUCCESS: 500,501,421
* @access public
* @return bool
*/
public function Mail($from) {
$this->error = null; // so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called Mail() without being connected");
return false;
}
$useVerp = ($this->do_verp ? "XVERP" : "");
fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $useVerp . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
}
if($code != 250) {
$this->error =
array("error" => "MAIL not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
return true;
}
/**
* Sends the quit command to the server and then closes the socket
* if there is no error or the $close_on_error argument is true.
*
* Implements from rfc 821: QUIT <CRLF>
*
* SMTP CODE SUCCESS: 221
* SMTP CODE ERROR : 500
* @access public
* @return bool
*/
public function Quit($close_on_error = true) {
$this->error = null; // so there is no confusion
if(!$this->connected()) {
$this->error = array(
"error" => "Called Quit() without being connected");
return false;
}
// send the quit command to the server
fputs($this->smtp_conn,"quit" . $this->CRLF);
// get any good-bye messages
$byemsg = $this->get_lines();
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '<br />';
}
$rval = true;
$e = null;
$code = substr($byemsg,0,3);
if($code != 221) {
// use e as a tmp var cause Close will overwrite $this->error
$e = array("error" => "SMTP server rejected quit command",
"smtp_code" => $code,
"smtp_rply" => substr($byemsg,4));
$rval = false;
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '<br />';
}
}
if(empty($e) || $close_on_error) {
$this->Close();
}
return $rval;
}
/**
* Sends the command RCPT to the SMTP server with the TO: argument of $to.
* Returns true if the recipient was accepted false if it was rejected.
*
* Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
*
* SMTP CODE SUCCESS: 250,251
* SMTP CODE FAILURE: 550,551,552,553,450,451,452
* SMTP CODE ERROR : 500,501,503,421
* @access public
* @return bool
*/
public function Recipient($to) {
$this->error = null; // so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called Recipient() without being connected");
return false;
}
fputs($this->smtp_conn,"RCPT TO:<" . $to . ">" . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
}
if($code != 250 && $code != 251) {
$this->error =
array("error" => "RCPT not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
return true;
}
/**
* Sends the RSET command to abort and transaction that is
* currently in progress. Returns true if successful false
* otherwise.
*
* Implements rfc 821: RSET <CRLF>
*
* SMTP CODE SUCCESS: 250
* SMTP CODE ERROR : 500,501,504,421
* @access public
* @return bool
*/
public function Reset() {
$this->error = null; // so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called Reset() without being connected");
return false;
}
fputs($this->smtp_conn,"RSET" . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
}
if($code != 250) {
$this->error =
array("error" => "RSET failed",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
return true;
}
/**
* Starts a mail transaction from the email address specified in
* $from. Returns true if successful or false otherwise. If True
* the mail transaction is started and then one or more Recipient
* commands may be called followed by a Data command. This command
* will send the message to the users terminal if they are logged
* in and send them an email.
*
* Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
*
* SMTP CODE SUCCESS: 250
* SMTP CODE SUCCESS: 552,451,452
* SMTP CODE SUCCESS: 500,501,502,421
* @access public
* @return bool
*/
public function SendAndMail($from) {
$this->error = null; // so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called SendAndMail() without being connected");
return false;
}
fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
}
if($code != 250) {
$this->error =
array("error" => "SAML not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
return true;
}
/**
* This is an optional command for SMTP that this class does not
* support. This method is here to make the RFC821 Definition
* complete for this class and __may__ be implimented in the future
*
* Implements from rfc 821: TURN <CRLF>
*
* SMTP CODE SUCCESS: 250
* SMTP CODE FAILURE: 502
* SMTP CODE ERROR : 500, 503
* @access public
* @return bool
*/
public function Turn() {
$this->error = array("error" => "This method, TURN, of the SMTP ".
"is not implemented");
if($this->do_debug >= 1) {
echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '<br />';
}
return false;
}
/**
* Get the current error
* @access public
* @return array
*/
public function getError() {
return $this->error;
}
/////////////////////////////////////////////////
// INTERNAL FUNCTIONS
/////////////////////////////////////////////////
/**
* Read in as many lines as possible
* either before eof or socket timeout occurs on the operation.
* With SMTP we can tell if we have more lines to read if the
* 4th character is '-' symbol. If it is a space then we don't
* need to read anything else.
* @access private
* @return string
*/
private function get_lines() {
$data = "";
while($str = @fgets($this->smtp_conn,515)) {
if($this->do_debug >= 4) {
echo "SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '<br />';
echo "SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '<br />';
}
$data .= $str;
if($this->do_debug >= 4) {
echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '<br />';
}
// if 4th character is a space, we are done reading, break the loop
if(substr($str,3,1) == " ") { break; }
}
return $data;
}
}
?> | 10npsite | trunk/Index/Lib/Public/class.smtp.php | PHP | asf20 | 25,613 |
<?php
/*~ class.phpmailer.php
.---------------------------------------------------------------------------.
| Software: PHPMailer - PHP email class |
| Version: 5.1 |
| Contact: via sourceforge.net support pages (also www.worxware.com) |
| Info: http://phpmailer.sourceforge.net |
| Support: http://sourceforge.net/projects/phpmailer/ |
| ------------------------------------------------------------------------- |
| Admin: Andy Prevost (project admininistrator) |
| Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
| : Marcus Bointon (coolbru) coolbru@users.sourceforge.net |
| Founder: Brent R. Matzelle (original founder) |
| Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. |
| Copyright (c) 2001-2003, Brent R. Matzelle |
| ------------------------------------------------------------------------- |
| License: Distributed under the Lesser General Public License (LGPL) |
| http://www.gnu.org/copyleft/lesser.html |
| This program is distributed in the hope that it will be useful - WITHOUT |
| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| FITNESS FOR A PARTICULAR PURPOSE. |
| ------------------------------------------------------------------------- |
| We offer a number of paid services (www.worxware.com): |
| - Web Hosting on highly optimized fast and secure servers |
| - Technology Consulting |
| - Oursourcing (highly qualified programmers and graphic designers) |
'---------------------------------------------------------------------------'
*/
/**
* PHPMailer - PHP email transport class
* NOTE: Requires PHP version 5 or later
* @package PHPMailer
* @author Andy Prevost
* @author Marcus Bointon
* @copyright 2004 - 2009 Andy Prevost
* @version $Id: class.phpmailer.php 447 2009-05-25 01:36:38Z codeworxtech $
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
*/
if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
class PHPMailer {
/////////////////////////////////////////////////
// PROPERTIES, PUBLIC
/////////////////////////////////////////////////
/**
* Email priority (1 = High, 3 = Normal, 5 = low).
* @var int
*/
public $Priority = 3;
/**
* Sets the CharSet of the message.
* @var string
*/
public $CharSet = 'utf-8';
/**
* Sets the Content-type of the message.
* @var string
*/
public $ContentType = 'text/plain';
/**
* Sets the Encoding of the message. Options for this are
* "8bit", "7bit", "binary", "base64", and "quoted-printable".
* @var string
*/
public $Encoding = '8bit';
/**
* Holds the most recent mailer error message.
* @var string
*/
public $ErrorInfo = '';
/**
* Sets the From email address for the message.
* @var string
*/
public $From = 'root@localhost';
/**
* Sets the From name of the message.
* @var string
*/
public $FromName = 'Root User';
/**
* Sets the Sender email (Return-Path) of the message. If not empty,
* will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
* @var string
*/
public $Sender = '';
/**
* Sets the Subject of the message.
* @var string
*/
public $Subject = '';
/**
* Sets the Body of the message. This can be either an HTML or text body.
* If HTML then run IsHTML(true).
* @var string
*/
public $Body = '';
/**
* Sets the text-only body of the message. This automatically sets the
* email to multipart/alternative. This body can be read by mail
* clients that do not have HTML email capability such as mutt. Clients
* that can read HTML will view the normal Body.
* @var string
*/
public $AltBody = '';
/**
* Sets word wrapping on the body of the message to a given number of
* characters.
* @var int
*/
public $WordWrap = 0;
/**
* Method to send mail: ("mail", "sendmail", or "smtp").
* @var string
*/
public $Mailer = 'mail';
/**
* Sets the path of the sendmail program.
* @var string
*/
public $Sendmail = '/usr/sbin/sendmail';
/**
* Path to PHPMailer plugins. Useful if the SMTP class
* is in a different directory than the PHP include path.
* @var string
*/
public $PluginDir = '';
/**
* Sets the email address that a reading confirmation will be sent.
* @var string
*/
public $ConfirmReadingTo = '';
/**
* Sets the hostname to use in Message-Id and Received headers
* and as default HELO string. If empty, the value returned
* by SERVER_NAME is used or 'localhost.localdomain'.
* @var string
*/
public $Hostname = '';
/**
* Sets the message ID to be used in the Message-Id header.
* If empty, a unique id will be generated.
* @var string
*/
public $MessageID = '';
/////////////////////////////////////////////////
// PROPERTIES FOR SMTP
/////////////////////////////////////////////////
/**
* Sets the SMTP hosts. All hosts must be separated by a
* semicolon. You can also specify a different port
* for each host by using this format: [hostname:port]
* (e.g. "smtp1.example.com:25;smtp2.example.com").
* Hosts will be tried in order.
* @var string
*/
public $Host = 'localhost';
/**
* Sets the default SMTP server port.
* @var int
*/
public $Port = 25;
/**
* Sets the SMTP HELO of the message (Default is $Hostname).
* @var string
*/
public $Helo = '';
/**
* Sets connection prefix.
* Options are "", "ssl" or "tls"
* @var string
*/
public $SMTPSecure = '';
/**
* Sets SMTP authentication. Utilizes the Username and Password variables.
* @var bool
*/
public $SMTPAuth = false;
/**
* Sets SMTP username.
* @var string
*/
public $Username = '';
/**
* Sets SMTP password.
* @var string
*/
public $Password = '';
/**
* Sets the SMTP server timeout in seconds.
* This function will not work with the win32 version.
* @var int
*/
public $Timeout = 10;
/**
* Sets SMTP class debugging on or off.
* @var bool
*/
public $SMTPDebug = false;
/**
* Prevents the SMTP connection from being closed after each mail
* sending. If this is set to true then to close the connection
* requires an explicit call to SmtpClose().
* @var bool
*/
public $SMTPKeepAlive = false;
/**
* Provides the ability to have the TO field process individual
* emails, instead of sending to entire TO addresses
* @var bool
*/
public $SingleTo = false;
/**
* If SingleTo is true, this provides the array to hold the email addresses
* @var bool
*/
public $SingleToArray = array();
/**
* Provides the ability to change the line ending
* @var string
*/
public $LE = "\n";
/**
* Used with DKIM DNS Resource Record
* @var string
*/
public $DKIM_selector = 'phpmailer';
/**
* Used with DKIM DNS Resource Record
* optional, in format of email address 'you@yourdomain.com'
* @var string
*/
public $DKIM_identity = '';
/**
* Used with DKIM DNS Resource Record
* optional, in format of email address 'you@yourdomain.com'
* @var string
*/
public $DKIM_domain = '';
/**
* Used with DKIM DNS Resource Record
* optional, in format of email address 'you@yourdomain.com'
* @var string
*/
public $DKIM_private = '';
/**
* Callback Action function name
* the function that handles the result of the send email action. Parameters:
* bool $result result of the send action
* string $to email address of the recipient
* string $cc cc email addresses
* string $bcc bcc email addresses
* string $subject the subject
* string $body the email body
* @var string
*/
public $action_function = ''; //'callbackAction';
/**
* Sets the PHPMailer Version number
* @var string
*/
public $Version = '5.1';
/////////////////////////////////////////////////
// PROPERTIES, PRIVATE AND PROTECTED
/////////////////////////////////////////////////
private $smtp = NULL;
private $to = array();
private $cc = array();
private $bcc = array();
private $ReplyTo = array();
private $all_recipients = array();
private $attachment = array();
private $CustomHeader = array();
private $message_type = '';
private $boundary = array();
protected $language = array();
private $error_count = 0;
private $sign_cert_file = "";
private $sign_key_file = "";
private $sign_key_pass = "";
private $exceptions = false;
/////////////////////////////////////////////////
// CONSTANTS
/////////////////////////////////////////////////
const STOP_MESSAGE = 0; // message only, continue processing
const STOP_CONTINUE = 1; // message?, likely ok to continue processing
const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
/////////////////////////////////////////////////
// METHODS, VARIABLES
/////////////////////////////////////////////////
/**
* Constructor
* @param boolean $exceptions Should we throw external exceptions?
*/
public function __construct($exceptions = false) {
$this->exceptions = ($exceptions == true);
}
/**
* Sets message type to HTML.
* @param bool $ishtml
* @return void
*/
public function IsHTML($ishtml = true) {
if ($ishtml) {
$this->ContentType = 'text/html';
} else {
$this->ContentType = 'text/plain';
}
}
/**
* Sets Mailer to send message using SMTP.
* @return void
*/
public function IsSMTP() {
$this->Mailer = 'smtp';
}
/**
* Sets Mailer to send message using PHP mail() function.
* @return void
*/
public function IsMail() {
$this->Mailer = 'mail';
}
/**
* Sets Mailer to send message using the $Sendmail program.
* @return void
*/
public function IsSendmail() {
if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
$this->Sendmail = '/var/qmail/bin/sendmail';
}
$this->Mailer = 'sendmail';
}
/**
* Sets Mailer to send message using the qmail MTA.
* @return void
*/
public function IsQmail() {
if (stristr(ini_get('sendmail_path'), 'qmail')) {
$this->Sendmail = '/var/qmail/bin/sendmail';
}
$this->Mailer = 'sendmail';
}
/////////////////////////////////////////////////
// METHODS, RECIPIENTS
/////////////////////////////////////////////////
/**
* Adds a "To" address.
* @param string $address
* @param string $name
* @return boolean true on success, false if address already used
*/
public function AddAddress($address, $name = '') {
return $this->AddAnAddress('to', $address, $name);
}
/**
* Adds a "Cc" address.
* Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
* @param string $address
* @param string $name
* @return boolean true on success, false if address already used
*/
public function AddCC($address, $name = '') {
return $this->AddAnAddress('cc', $address, $name);
}
/**
* Adds a "Bcc" address.
* Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
* @param string $address
* @param string $name
* @return boolean true on success, false if address already used
*/
public function AddBCC($address, $name = '') {
return $this->AddAnAddress('bcc', $address, $name);
}
/**
* Adds a "Reply-to" address.
* @param string $address
* @param string $name
* @return boolean
*/
public function AddReplyTo($address, $name = '') {
return $this->AddAnAddress('ReplyTo', $address, $name);
}
/**
* Adds an address to one of the recipient arrays
* Addresses that have been added already return false, but do not throw exceptions
* @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
* @param string $address The email address to send to
* @param string $name
* @return boolean true on success, false if address already used or invalid in some way
* @access private
*/
private function AddAnAddress($kind, $address, $name = '') {
if (!preg_match('/^(to|cc|bcc|ReplyTo)$/', $kind)) {
echo 'Invalid recipient array: ' . kind;
return false;
}
$address = trim($address);
$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
if (!self::ValidateAddress($address)) {
$this->SetError($this->Lang('invalid_address').': '. $address);
if ($this->exceptions) {
throw new phpmailerException($this->Lang('invalid_address').': '.$address);
}
echo $this->Lang('invalid_address').': '.$address;
return false;
}
if ($kind != 'ReplyTo') {
if (!isset($this->all_recipients[strtolower($address)])) {
array_push($this->$kind, array($address, $name));
$this->all_recipients[strtolower($address)] = true;
return true;
}
} else {
if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
$this->ReplyTo[strtolower($address)] = array($address, $name);
return true;
}
}
return false;
}
/**
* Set the From and FromName properties
* @param string $address
* @param string $name
* @return boolean
*/
public function SetFrom($address, $name = '',$auto=1) {
$address = trim($address);
$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
if (!self::ValidateAddress($address)) {
$this->SetError($this->Lang('invalid_address').': '. $address);
if ($this->exceptions) {
throw new phpmailerException($this->Lang('invalid_address').': '.$address);
}
echo $this->Lang('invalid_address').': '.$address;
return false;
}
$this->From = $address;
$this->FromName = $name;
if ($auto) {
if (empty($this->ReplyTo)) {
$this->AddAnAddress('ReplyTo', $address, $name);
}
if (empty($this->Sender)) {
$this->Sender = $address;
}
}
return true;
}
/**
* Check that a string looks roughly like an email address should
* Static so it can be used without instantiation
* Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator
* Conforms approximately to RFC2822
* @link http://www.hexillion.com/samples/#Regex Original pattern found here
* @param string $address The email address to check
* @return boolean
* @static
* @access public
*/
public static function ValidateAddress($address) {
if (function_exists('filter_var')) { //Introduced in PHP 5.2
if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) {
return false;
} else {
return true;
}
} else {
return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);
}
}
/////////////////////////////////////////////////
// METHODS, MAIL SENDING
/////////////////////////////////////////////////
/**
* Creates message and assigns Mailer. If the message is
* not sent successfully then it returns false. Use the ErrorInfo
* variable to view description of the error.
* @return bool
*/
public function Send() {
try {
if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
}
// Set whether the message is multipart/alternative
if(!empty($this->AltBody)) {
$this->ContentType = 'multipart/alternative';
}
$this->error_count = 0; // reset errors
$this->SetMessageType();
$header = $this->CreateHeader();
$body = $this->CreateBody();
if (empty($this->Body)) {
throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
}
// digitally sign with DKIM if enabled
if ($this->DKIM_domain && $this->DKIM_private) {
$header_dkim = $this->DKIM_Add($header,$this->Subject,$body);
$header = str_replace("\r\n","\n",$header_dkim) . $header;
}
// Choose the mailer and send through it
switch($this->Mailer) {
case 'sendmail':
return $this->SendmailSend($header, $body);
case 'smtp':
return $this->SmtpSend($header, $body);
default:
return $this->MailSend($header, $body);
}
} catch (phpmailerException $e) {
$this->SetError($e->getMessage());
if ($this->exceptions) {
throw $e;
}
echo $e->getMessage()."\n";
return false;
}
}
/**
* Sends mail using the $Sendmail program.
* @param string $header The message headers
* @param string $body The message body
* @access protected
* @return bool
*/
protected function SendmailSend($header, $body) {
if ($this->Sender != '') {
$sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
} else {
$sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
}
if ($this->SingleTo === true) {
foreach ($this->SingleToArray as $key => $val) {
if(!@$mail = popen($sendmail, 'w')) {
throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
fputs($mail, "To: " . $val . "\n");
fputs($mail, $header);
fputs($mail, $body);
$result = pclose($mail);
// implement call back function if it exists
$isSent = ($result == 0) ? 1 : 0;
$this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
if($result != 0) {
throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
}
} else {
if(!@$mail = popen($sendmail, 'w')) {
throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
fputs($mail, $header);
fputs($mail, $body);
$result = pclose($mail);
// implement call back function if it exists
$isSent = ($result == 0) ? 1 : 0;
$this->doCallback($isSent,$this->to,$this->cc,$this->bcc,$this->Subject,$body);
if($result != 0) {
throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
}
return true;
}
/**
* Sends mail using the PHP mail() function.
* @param string $header The message headers
* @param string $body The message body
* @access protected
* @return bool
*/
protected function MailSend($header, $body) {
$toArr = array();
foreach($this->to as $t) {
$toArr[] = $this->AddrFormat($t);
}
$to = implode(', ', $toArr);
$params = sprintf("-oi -f %s", $this->Sender);
if ($this->Sender != '' && strlen(ini_get('safe_mode'))< 1) {
$old_from = ini_get('sendmail_from');
ini_set('sendmail_from', $this->Sender);
if ($this->SingleTo === true && count($toArr) > 1) {
foreach ($toArr as $key => $val) {
$rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
// implement call back function if it exists
$isSent = ($rt == 1) ? 1 : 0;
$this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
}
} else {
$rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
// implement call back function if it exists
$isSent = ($rt == 1) ? 1 : 0;
$this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$body);
}
} else {
if ($this->SingleTo === true && count($toArr) > 1) {
foreach ($toArr as $key => $val) {
$rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
// implement call back function if it exists
$isSent = ($rt == 1) ? 1 : 0;
$this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
}
} else {
$rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
// implement call back function if it exists
$isSent = ($rt == 1) ? 1 : 0;
$this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$body);
}
}
if (isset($old_from)) {
ini_set('sendmail_from', $old_from);
}
if(!$rt) {
throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
}
return true;
}
/**
* Sends mail via SMTP using PhpSMTP
* Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
* @param string $header The message headers
* @param string $body The message body
* @uses SMTP
* @access protected
* @return bool
*/
protected function SmtpSend($header, $body) {
$bad_rcpt = array();
if(!$this->SmtpConnect()) {
throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
}
$smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
if(!$this->smtp->Mail($smtp_from)) {
throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL);
}
// Attempt to send attach all recipients
foreach($this->to as $to) {
if (!$this->smtp->Recipient($to[0])) {
$bad_rcpt[] = $to[0];
// implement call back function if it exists
$isSent = 0;
$this->doCallback($isSent,$to[0],'','',$this->Subject,$body);
} else {
// implement call back function if it exists
$isSent = 1;
$this->doCallback($isSent,$to[0],'','',$this->Subject,$body);
}
}
foreach($this->cc as $cc) {
if (!$this->smtp->Recipient($cc[0])) {
$bad_rcpt[] = $cc[0];
// implement call back function if it exists
$isSent = 0;
$this->doCallback($isSent,'',$cc[0],'',$this->Subject,$body);
} else {
// implement call back function if it exists
$isSent = 1;
$this->doCallback($isSent,'',$cc[0],'',$this->Subject,$body);
}
}
foreach($this->bcc as $bcc) {
if (!$this->smtp->Recipient($bcc[0])) {
$bad_rcpt[] = $bcc[0];
// implement call back function if it exists
$isSent = 0;
$this->doCallback($isSent,'','',$bcc[0],$this->Subject,$body);
} else {
// implement call back function if it exists
$isSent = 1;
$this->doCallback($isSent,'','',$bcc[0],$this->Subject,$body);
}
}
if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
$badaddresses = implode(', ', $bad_rcpt);
throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
}
if(!$this->smtp->Data($header . $body)) {
throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
}
if($this->SMTPKeepAlive == true) {
$this->smtp->Reset();
}
return true;
}
/**
* Initiates a connection to an SMTP server.
* Returns false if the operation failed.
* @uses SMTP
* @access public
* @return bool
*/
public function SmtpConnect() {
if(is_null($this->smtp)) {
$this->smtp = new SMTP();
}
$this->smtp->do_debug = $this->SMTPDebug;
$hosts = explode(';', $this->Host);
$index = 0;
$connection = $this->smtp->Connected();
// Retry while there is no connection
try {
while($index < count($hosts) && !$connection) {
$hostinfo = array();
if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
$host = $hostinfo[1];
$port = $hostinfo[2];
} else {
$host = $hosts[$index];
$port = $this->Port;
}
$tls = ($this->SMTPSecure == 'tls');
$ssl = ($this->SMTPSecure == 'ssl');
if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {
$hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
$this->smtp->Hello($hello);
if ($tls) {
if (!$this->smtp->StartTLS()) {
throw new phpmailerException($this->Lang('tls'));
}
//We must resend HELO after tls negotiation
$this->smtp->Hello($hello);
}
$connection = true;
if ($this->SMTPAuth) {
if (!$this->smtp->Authenticate($this->Username, $this->Password)) {
throw new phpmailerException($this->Lang('authenticate'));
}
}
}
$index++;
if (!$connection) {
throw new phpmailerException($this->Lang('connect_host'));
}
}
} catch (phpmailerException $e) {
$this->smtp->Reset();
throw $e;
}
return true;
}
/**
* Closes the active SMTP session if one exists.
* @return void
*/
public function SmtpClose() {
if(!is_null($this->smtp)) {
if($this->smtp->Connected()) {
$this->smtp->Quit();
$this->smtp->Close();
}
}
}
/**
* Sets the language for all class error messages.
* Returns false if it cannot load the language file. The default language is English.
* @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
* @param string $lang_path Path to the language file directory
* @access public
*/
function SetLanguage($langcode = 'en', $lang_path = 'language/') {
//Define full set of translatable strings
$PHPMAILER_LANG = array(
'provide_address' => 'You must provide at least one recipient email address.',
'mailer_not_supported' => ' mailer is not supported.',
'execute' => 'Could not execute: ',
'instantiate' => 'Could not instantiate mail function.',
'authenticate' => 'SMTP Error: Could not authenticate.',
'from_failed' => 'The following From address failed: ',
'recipients_failed' => 'SMTP Error: The following recipients failed: ',
'data_not_accepted' => 'SMTP Error: Data not accepted.',
'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
'file_access' => 'Could not access file: ',
'file_open' => 'File Error: Could not open file: ',
'encoding' => 'Unknown encoding: ',
'signing' => 'Signing Error: ',
'smtp_error' => 'SMTP server error: ',
'empty_message' => 'Message body empty',
'invalid_address' => 'Invalid address',
'variable_set' => 'Cannot set or reset variable: '
);
//Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
$l = true;
if ($langcode != 'en') { //There is no English translation file
$l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
}
$this->language = $PHPMAILER_LANG;
return ($l == true); //Returns false if language not found
}
/**
* Return the current array of language strings
* @return array
*/
public function GetTranslations() {
return $this->language;
}
/////////////////////////////////////////////////
// METHODS, MESSAGE CREATION
/////////////////////////////////////////////////
/**
* Creates recipient headers.
* @access public
* @return string
*/
public function AddrAppend($type, $addr) {
$addr_str = $type . ': ';
$addresses = array();
foreach ($addr as $a) {
$addresses[] = $this->AddrFormat($a);
}
$addr_str .= implode(', ', $addresses);
$addr_str .= $this->LE;
return $addr_str;
}
/**
* Formats an address correctly.
* @access public
* @return string
*/
public function AddrFormat($addr) {
if (empty($addr[1])) {
return $this->SecureHeader($addr[0]);
} else {
return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
}
}
/**
* Wraps message for use with mailers that do not
* automatically perform wrapping and for quoted-printable.
* Original written by philippe.
* @param string $message The message to wrap
* @param integer $length The line length to wrap to
* @param boolean $qp_mode Whether to run in Quoted-Printable mode
* @access public
* @return string
*/
public function WrapText($message, $length, $qp_mode = false) {
$soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
// If utf-8 encoding is used, we will need to make sure we don't
// split multibyte characters when we wrap
$is_utf8 = (strtolower($this->CharSet) == "utf-8");
$message = $this->FixEOL($message);
if (substr($message, -1) == $this->LE) {
$message = substr($message, 0, -1);
}
$line = explode($this->LE, $message);
$message = '';
for ($i=0 ;$i < count($line); $i++) {
$line_part = explode(' ', $line[$i]);
$buf = '';
for ($e = 0; $e<count($line_part); $e++) {
$word = $line_part[$e];
if ($qp_mode and (strlen($word) > $length)) {
$space_left = $length - strlen($buf) - 1;
if ($e != 0) {
if ($space_left > 20) {
$len = $space_left;
if ($is_utf8) {
$len = $this->UTF8CharBoundary($word, $len);
} elseif (substr($word, $len - 1, 1) == "=") {
$len--;
} elseif (substr($word, $len - 2, 1) == "=") {
$len -= 2;
}
$part = substr($word, 0, $len);
$word = substr($word, $len);
$buf .= ' ' . $part;
$message .= $buf . sprintf("=%s", $this->LE);
} else {
$message .= $buf . $soft_break;
}
$buf = '';
}
while (strlen($word) > 0) {
$len = $length;
if ($is_utf8) {
$len = $this->UTF8CharBoundary($word, $len);
} elseif (substr($word, $len - 1, 1) == "=") {
$len--;
} elseif (substr($word, $len - 2, 1) == "=") {
$len -= 2;
}
$part = substr($word, 0, $len);
$word = substr($word, $len);
if (strlen($word) > 0) {
$message .= $part . sprintf("=%s", $this->LE);
} else {
$buf = $part;
}
}
} else {
$buf_o = $buf;
$buf .= ($e == 0) ? $word : (' ' . $word);
if (strlen($buf) > $length and $buf_o != '') {
$message .= $buf_o . $soft_break;
$buf = $word;
}
}
}
$message .= $buf . $this->LE;
}
return $message;
}
/**
* Finds last character boundary prior to maxLength in a utf-8
* quoted (printable) encoded string.
* Original written by Colin Brown.
* @access public
* @param string $encodedText utf-8 QP text
* @param int $maxLength find last character boundary prior to this length
* @return int
*/
public function UTF8CharBoundary($encodedText, $maxLength) {
$foundSplitPos = false;
$lookBack = 3;
while (!$foundSplitPos) {
$lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
$encodedCharPos = strpos($lastChunk, "=");
if ($encodedCharPos !== false) {
// Found start of encoded character byte within $lookBack block.
// Check the encoded byte value (the 2 chars after the '=')
$hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
$dec = hexdec($hex);
if ($dec < 128) { // Single byte character.
// If the encoded char was found at pos 0, it will fit
// otherwise reduce maxLength to start of the encoded char
$maxLength = ($encodedCharPos == 0) ? $maxLength :
$maxLength - ($lookBack - $encodedCharPos);
$foundSplitPos = true;
} elseif ($dec >= 192) { // First byte of a multi byte character
// Reduce maxLength to split at start of character
$maxLength = $maxLength - ($lookBack - $encodedCharPos);
$foundSplitPos = true;
} elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
$lookBack += 3;
}
} else {
// No encoded character found
$foundSplitPos = true;
}
}
return $maxLength;
}
/**
* Set the body wrapping.
* @access public
* @return void
*/
public function SetWordWrap() {
if($this->WordWrap < 1) {
return;
}
switch($this->message_type) {
case 'alt':
case 'alt_attachments':
$this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
break;
default:
$this->Body = $this->WrapText($this->Body, $this->WordWrap);
break;
}
}
/**
* Assembles message header.
* @access public
* @return string The assembled header
*/
public function CreateHeader() {
$result = '';
// Set the boundaries
$uniq_id = md5(uniqid(time()));
$this->boundary[1] = 'b1_' . $uniq_id;
$this->boundary[2] = 'b2_' . $uniq_id;
$result .= $this->HeaderLine('Date', self::RFCDate());
if($this->Sender == '') {
$result .= $this->HeaderLine('Return-Path', trim($this->From));
} else {
$result .= $this->HeaderLine('Return-Path', trim($this->Sender));
}
// To be created automatically by mail()
if($this->Mailer != 'mail') {
if ($this->SingleTo === true) {
foreach($this->to as $t) {
$this->SingleToArray[] = $this->AddrFormat($t);
}
} else {
if(count($this->to) > 0) {
$result .= $this->AddrAppend('To', $this->to);
} elseif (count($this->cc) == 0) {
$result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
}
}
}
$from = array();
$from[0][0] = trim($this->From);
$from[0][1] = $this->FromName;
$result .= $this->AddrAppend('From', $from);
// sendmail and mail() extract Cc from the header before sending
if(count($this->cc) > 0) {
$result .= $this->AddrAppend('Cc', $this->cc);
}
// sendmail and mail() extract Bcc from the header before sending
if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
$result .= $this->AddrAppend('Bcc', $this->bcc);
}
if(count($this->ReplyTo) > 0) {
$result .= $this->AddrAppend('Reply-to', $this->ReplyTo);
}
// mail() sets the subject itself
if($this->Mailer != 'mail') {
$result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
}
if($this->MessageID != '') {
$result .= $this->HeaderLine('Message-ID',$this->MessageID);
} else {
$result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
}
$result .= $this->HeaderLine('X-Priority', $this->Priority);
$result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (phpmailer.sourceforge.net)');
if($this->ConfirmReadingTo != '') {
$result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
}
// Add custom headers
for($index = 0; $index < count($this->CustomHeader); $index++) {
$result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
}
if (!$this->sign_key_file) {
$result .= $this->HeaderLine('MIME-Version', '1.0');
$result .= $this->GetMailMIME();
}
return $result;
}
/**
* Returns the message MIME.
* @access public
* @return string
*/
public function GetMailMIME() {
$result = '';
switch($this->message_type) {
case 'plain':
$result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
$result .= sprintf("Content-Type: %s; charset=\"%s\"", $this->ContentType, $this->CharSet);
break;
case 'attachments':
case 'alt_attachments':
if($this->InlineImageExists()){
$result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 'multipart/related', $this->LE, $this->LE, $this->boundary[1], $this->LE);
} else {
$result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
$result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
}
break;
case 'alt':
$result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
$result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
break;
}
if($this->Mailer != 'mail') {
$result .= $this->LE.$this->LE;
}
return $result;
}
/**
* Assembles the message body. Returns an empty string on failure.
* @access public
* @return string The assembled message body
*/
public function CreateBody() {
$body = '';
if ($this->sign_key_file) {
$body .= $this->GetMailMIME();
}
$this->SetWordWrap();
switch($this->message_type) {
case 'alt':
$body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
$body .= $this->EncodeString($this->AltBody, $this->Encoding);
$body .= $this->LE.$this->LE;
$body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
$body .= $this->EncodeString($this->Body, $this->Encoding);
$body .= $this->LE.$this->LE;
$body .= $this->EndBoundary($this->boundary[1]);
break;
case 'plain':
$body .= $this->EncodeString($this->Body, $this->Encoding);
break;
case 'attachments':
$body .= $this->GetBoundary($this->boundary[1], '', '', '');
$body .= $this->EncodeString($this->Body, $this->Encoding);
$body .= $this->LE;
$body .= $this->AttachAll();
break;
case 'alt_attachments':
$body .= sprintf("--%s%s", $this->boundary[1], $this->LE);
$body .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE.$this->LE);
$body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE; // Create text body
$body .= $this->EncodeString($this->AltBody, $this->Encoding);
$body .= $this->LE.$this->LE;
$body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE; // Create the HTML body
$body .= $this->EncodeString($this->Body, $this->Encoding);
$body .= $this->LE.$this->LE;
$body .= $this->EndBoundary($this->boundary[2]);
$body .= $this->AttachAll();
break;
}
if ($this->IsError()) {
$body = '';
} elseif ($this->sign_key_file) {
try {
$file = tempnam('', 'mail');
file_put_contents($file, $body); //TODO check this worked
$signed = tempnam("", "signed");
if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
@unlink($file);
@unlink($signed);
$body = file_get_contents($signed);
} else {
@unlink($file);
@unlink($signed);
throw new phpmailerException($this->Lang("signing").openssl_error_string());
}
} catch (phpmailerException $e) {
$body = '';
if ($this->exceptions) {
throw $e;
}
}
}
return $body;
}
/**
* Returns the start of a message boundary.
* @access private
*/
private function GetBoundary($boundary, $charSet, $contentType, $encoding) {
$result = '';
if($charSet == '') {
$charSet = $this->CharSet;
}
if($contentType == '') {
$contentType = $this->ContentType;
}
if($encoding == '') {
$encoding = $this->Encoding;
}
$result .= $this->TextLine('--' . $boundary);
$result .= sprintf("Content-Type: %s; charset = \"%s\"", $contentType, $charSet);
$result .= $this->LE;
$result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
$result .= $this->LE;
return $result;
}
/**
* Returns the end of a message boundary.
* @access private
*/
private function EndBoundary($boundary) {
return $this->LE . '--' . $boundary . '--' . $this->LE;
}
/**
* Sets the message type.
* @access private
* @return void
*/
private function SetMessageType() {
if(count($this->attachment) < 1 && strlen($this->AltBody) < 1) {
$this->message_type = 'plain';
} else {
if(count($this->attachment) > 0) {
$this->message_type = 'attachments';
}
if(strlen($this->AltBody) > 0 && count($this->attachment) < 1) {
$this->message_type = 'alt';
}
if(strlen($this->AltBody) > 0 && count($this->attachment) > 0) {
$this->message_type = 'alt_attachments';
}
}
}
/**
* Returns a formatted header line.
* @access public
* @return string
*/
public function HeaderLine($name, $value) {
return $name . ': ' . $value . $this->LE;
}
/**
* Returns a formatted mail line.
* @access public
* @return string
*/
public function TextLine($value) {
return $value . $this->LE;
}
/////////////////////////////////////////////////
// CLASS METHODS, ATTACHMENTS
/////////////////////////////////////////////////
/**
* Adds an attachment from a path on the filesystem.
* Returns false if the file could not be found
* or accessed.
* @param string $path Path to the attachment.
* @param string $name Overrides the attachment name.
* @param string $encoding File encoding (see $Encoding).
* @param string $type File extension (MIME) type.
* @return bool
*/
public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
try {
if ( !@is_file($path) ) {
throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
}
$filename = basename($path);
if ( $name == '' ) {
$name = $filename;
}
$this->attachment[] = array(
0 => $path,
1 => $filename,
2 => $name,
3 => $encoding,
4 => $type,
5 => false, // isStringAttachment
6 => 'attachment',
7 => 0
);
} catch (phpmailerException $e) {
$this->SetError($e->getMessage());
if ($this->exceptions) {
throw $e;
}
echo $e->getMessage()."\n";
if ( $e->getCode() == self::STOP_CRITICAL ) {
return false;
}
}
return true;
}
/**
* Return the current array of attachments
* @return array
*/
public function GetAttachments() {
return $this->attachment;
}
/**
* Attaches all fs, string, and binary attachments to the message.
* Returns an empty string on failure.
* @access private
* @return string
*/
private function AttachAll() {
// Return text of body
$mime = array();
$cidUniq = array();
$incl = array();
// Add all attachments
foreach ($this->attachment as $attachment) {
// Check for string attachment
$bString = $attachment[5];
if ($bString) {
$string = $attachment[0];
} else {
$path = $attachment[0];
}
if (in_array($attachment[0], $incl)) { continue; }
$filename = $attachment[1];
$name = $attachment[2];
$encoding = $attachment[3];
$type = $attachment[4];
$disposition = $attachment[6];
$cid = $attachment[7];
$incl[] = $attachment[0];
if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
$cidUniq[$cid] = true;
$mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
$mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
$mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
if($disposition == 'inline') {
$mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
}
$mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
// Encode as string attachment
if($bString) {
$mime[] = $this->EncodeString($string, $encoding);
if($this->IsError()) {
return '';
}
$mime[] = $this->LE.$this->LE;
} else {
$mime[] = $this->EncodeFile($path, $encoding);
if($this->IsError()) {
return '';
}
$mime[] = $this->LE.$this->LE;
}
}
$mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
return join('', $mime);
}
/**
* Encodes attachment in requested format.
* Returns an empty string on failure.
* @param string $path The full path to the file
* @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
* @see EncodeFile()
* @access private
* @return string
*/
private function EncodeFile($path, $encoding = 'base64') {
try {
if (!is_readable($path)) {
throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
}
if (function_exists('get_magic_quotes')) {
function get_magic_quotes() {
return false;
}
}
if (PHP_VERSION < 6) {
$magic_quotes = get_magic_quotes_runtime();
set_magic_quotes_runtime(0);
}
$file_buffer = file_get_contents($path);
$file_buffer = $this->EncodeString($file_buffer, $encoding);
if (PHP_VERSION < 6) { set_magic_quotes_runtime($magic_quotes); }
return $file_buffer;
} catch (Exception $e) {
$this->SetError($e->getMessage());
return '';
}
}
/**
* Encodes string to requested format.
* Returns an empty string on failure.
* @param string $str The text to encode
* @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
* @access public
* @return string
*/
public function EncodeString ($str, $encoding = 'base64') {
$encoded = '';
switch(strtolower($encoding)) {
case 'base64':
$encoded = chunk_split(base64_encode($str), 76, $this->LE);
break;
case '7bit':
case '8bit':
$encoded = $this->FixEOL($str);
//Make sure it ends with a line break
if (substr($encoded, -(strlen($this->LE))) != $this->LE)
$encoded .= $this->LE;
break;
case 'binary':
$encoded = $str;
break;
case 'quoted-printable':
$encoded = $this->EncodeQP($str);
break;
default:
$this->SetError($this->Lang('encoding') . $encoding);
break;
}
return $encoded;
}
/**
* Encode a header string to best (shortest) of Q, B, quoted or none.
* @access public
* @return string
*/
public function EncodeHeader($str, $position = 'text') {
$x = 0;
switch (strtolower($position)) {
case 'phrase':
if (!preg_match('/[\200-\377]/', $str)) {
// Can't use addslashes as we don't know what value has magic_quotes_sybase
$encoded = addcslashes($str, "\0..\37\177\\\"");
if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
return ($encoded);
} else {
return ("\"$encoded\"");
}
}
$x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
break;
case 'comment':
$x = preg_match_all('/[()"]/', $str, $matches);
// Fall-through
case 'text':
default:
$x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
break;
}
if ($x == 0) {
return ($str);
}
$maxlen = 75 - 7 - strlen($this->CharSet);
// Try to select the encoding which should produce the shortest output
if (strlen($str)/3 < $x) {
$encoding = 'B';
if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
// Use a custom function which correctly encodes and wraps long
// multibyte strings without breaking lines within a character
$encoded = $this->Base64EncodeWrapMB($str);
} else {
$encoded = base64_encode($str);
$maxlen -= $maxlen % 4;
$encoded = trim(chunk_split($encoded, $maxlen, "\n"));
}
} else {
$encoding = 'Q';
$encoded = $this->EncodeQ($str, $position);
$encoded = $this->WrapText($encoded, $maxlen, true);
$encoded = str_replace('='.$this->LE, "\n", trim($encoded));
}
$encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
$encoded = trim(str_replace("\n", $this->LE, $encoded));
return $encoded;
}
/**
* Checks if a string contains multibyte characters.
* @access public
* @param string $str multi-byte text to wrap encode
* @return bool
*/
public function HasMultiBytes($str) {
if (function_exists('mb_strlen')) {
return (strlen($str) > mb_strlen($str, $this->CharSet));
} else { // Assume no multibytes (we can't handle without mbstring functions anyway)
return false;
}
}
/**
* Correctly encodes and wraps long multibyte strings for mail headers
* without breaking lines within a character.
* Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
* @access public
* @param string $str multi-byte text to wrap encode
* @return string
*/
public function Base64EncodeWrapMB($str) {
$start = "=?".$this->CharSet."?B?";
$end = "?=";
$encoded = "";
$mb_length = mb_strlen($str, $this->CharSet);
// Each line must have length <= 75, including $start and $end
$length = 75 - strlen($start) - strlen($end);
// Average multi-byte ratio
$ratio = $mb_length / strlen($str);
// Base64 has a 4:3 ratio
$offset = $avgLength = floor($length * $ratio * .75);
for ($i = 0; $i < $mb_length; $i += $offset) {
$lookBack = 0;
do {
$offset = $avgLength - $lookBack;
$chunk = mb_substr($str, $i, $offset, $this->CharSet);
$chunk = base64_encode($chunk);
$lookBack++;
}
while (strlen($chunk) > $length);
$encoded .= $chunk . $this->LE;
}
// Chomp the last linefeed
$encoded = substr($encoded, 0, -strlen($this->LE));
return $encoded;
}
/**
* Encode string to quoted-printable.
* Only uses standard PHP, slow, but will always work
* @access public
* @param string $string the text to encode
* @param integer $line_max Number of chars allowed on a line before wrapping
* @return string
*/
public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
$hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
$lines = preg_split('/(?:\r\n|\r|\n)/', $input);
$eol = "\r\n";
$escape = '=';
$output = '';
while( list(, $line) = each($lines) ) {
$linlen = strlen($line);
$newline = '';
for($i = 0; $i < $linlen; $i++) {
$c = substr( $line, $i, 1 );
$dec = ord( $c );
if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E
$c = '=2E';
}
if ( $dec == 32 ) {
if ( $i == ( $linlen - 1 ) ) { // convert space at eol only
$c = '=20';
} else if ( $space_conv ) {
$c = '=20';
}
} elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
$h2 = floor($dec/16);
$h1 = floor($dec%16);
$c = $escape.$hex[$h2].$hex[$h1];
}
if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
$output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
$newline = '';
// check if newline first character will be point or not
if ( $dec == 46 ) {
$c = '=2E';
}
}
$newline .= $c;
} // end of for
$output .= $newline.$eol;
} // end of while
return $output;
}
/**
* Encode string to RFC2045 (6.7) quoted-printable format
* Uses a PHP5 stream filter to do the encoding about 64x faster than the old version
* Also results in same content as you started with after decoding
* @see EncodeQPphp()
* @access public
* @param string $string the text to encode
* @param integer $line_max Number of chars allowed on a line before wrapping
* @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function
* @return string
* @author Marcus Bointon
*/
public function EncodeQP($string, $line_max = 76, $space_conv = false) {
if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
return quoted_printable_encode($string);
}
$filters = stream_get_filters();
if (!in_array('convert.*', $filters)) { //Got convert stream filter?
return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation
}
$fp = fopen('php://temp/', 'r+');
$string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks
$params = array('line-length' => $line_max, 'line-break-chars' => $this->LE);
$s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
fputs($fp, $string);
rewind($fp);
$out = stream_get_contents($fp);
stream_filter_remove($s);
$out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange
fclose($fp);
return $out;
}
/**
* Encode string to q encoding.
* @link http://tools.ietf.org/html/rfc2047
* @param string $str the text to encode
* @param string $position Where the text is going to be used, see the RFC for what that means
* @access public
* @return string
*/
public function EncodeQ ($str, $position = 'text') {
// There should not be any EOL in the string
$encoded = preg_replace('/[\r\n]*/', '', $str);
switch (strtolower($position)) {
case 'phrase':
$encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
break;
case 'comment':
$encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
case 'text':
default:
// Replace every high ascii, control =, ? and _ characters
//TODO using /e (equivalent to eval()) is probably not a good idea
$encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
"'='.sprintf('%02X', ord('\\1'))", $encoded);
break;
}
// Replace every spaces to _ (more readable than =20)
$encoded = str_replace(' ', '_', $encoded);
return $encoded;
}
/**
* Adds a string or binary attachment (non-filesystem) to the list.
* This method can be used to attach ascii or binary data,
* such as a BLOB record from a database.
* @param string $string String attachment data.
* @param string $filename Name of the attachment.
* @param string $encoding File encoding (see $Encoding).
* @param string $type File extension (MIME) type.
* @return void
*/
public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
// Append to $attachment array
$this->attachment[] = array(
0 => $string,
1 => $filename,
2 => basename($filename),
3 => $encoding,
4 => $type,
5 => true, // isStringAttachment
6 => 'attachment',
7 => 0
);
}
/**
* Adds an embedded attachment. This can include images, sounds, and
* just about any other document. Make sure to set the $type to an
* image type. For JPEG images use "image/jpeg" and for GIF images
* use "image/gif".
* @param string $path Path to the attachment.
* @param string $cid Content ID of the attachment. Use this to identify
* the Id for accessing the image in an HTML form.
* @param string $name Overrides the attachment name.
* @param string $encoding File encoding (see $Encoding).
* @param string $type File extension (MIME) type.
* @return bool
*/
public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
if ( !@is_file($path) ) {
$this->SetError($this->Lang('file_access') . $path);
return false;
}
$filename = basename($path);
if ( $name == '' ) {
$name = $filename;
}
// Append to $attachment array
$this->attachment[] = array(
0 => $path,
1 => $filename,
2 => $name,
3 => $encoding,
4 => $type,
5 => false, // isStringAttachment
6 => 'inline',
7 => $cid
);
return true;
}
/**
* Returns true if an inline attachment is present.
* @access public
* @return bool
*/
public function InlineImageExists() {
foreach($this->attachment as $attachment) {
if ($attachment[6] == 'inline') {
return true;
}
}
return false;
}
/////////////////////////////////////////////////
// CLASS METHODS, MESSAGE RESET
/////////////////////////////////////////////////
/**
* Clears all recipients assigned in the TO array. Returns void.
* @return void
*/
public function ClearAddresses() {
foreach($this->to as $to) {
unset($this->all_recipients[strtolower($to[0])]);
}
$this->to = array();
}
/**
* Clears all recipients assigned in the CC array. Returns void.
* @return void
*/
public function ClearCCs() {
foreach($this->cc as $cc) {
unset($this->all_recipients[strtolower($cc[0])]);
}
$this->cc = array();
}
/**
* Clears all recipients assigned in the BCC array. Returns void.
* @return void
*/
public function ClearBCCs() {
foreach($this->bcc as $bcc) {
unset($this->all_recipients[strtolower($bcc[0])]);
}
$this->bcc = array();
}
/**
* Clears all recipients assigned in the ReplyTo array. Returns void.
* @return void
*/
public function ClearReplyTos() {
$this->ReplyTo = array();
}
/**
* Clears all recipients assigned in the TO, CC and BCC
* array. Returns void.
* @return void
*/
public function ClearAllRecipients() {
$this->to = array();
$this->cc = array();
$this->bcc = array();
$this->all_recipients = array();
}
/**
* Clears all previously set filesystem, string, and binary
* attachments. Returns void.
* @return void
*/
public function ClearAttachments() {
$this->attachment = array();
}
/**
* Clears all custom headers. Returns void.
* @return void
*/
public function ClearCustomHeaders() {
$this->CustomHeader = array();
}
/////////////////////////////////////////////////
// CLASS METHODS, MISCELLANEOUS
/////////////////////////////////////////////////
/**
* Adds the error message to the error container.
* @access protected
* @return void
*/
protected function SetError($msg) {
$this->error_count++;
if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
$lasterror = $this->smtp->getError();
if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
$msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
}
}
$this->ErrorInfo = $msg;
}
/**
* Returns the proper RFC 822 formatted date.
* @access public
* @return string
* @static
*/
public static function RFCDate() {
$tz = date('Z');
$tzs = ($tz < 0) ? '-' : '+';
$tz = abs($tz);
$tz = (int)($tz/3600)*100 + ($tz%3600)/60;
$result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
return $result;
}
/**
* Returns the server hostname or 'localhost.localdomain' if unknown.
* @access private
* @return string
*/
private function ServerHostname() {
if (!empty($this->Hostname)) {
$result = $this->Hostname;
} elseif (isset($_SERVER['SERVER_NAME'])) {
$result = $_SERVER['SERVER_NAME'];
} else {
$result = 'localhost.localdomain';
}
return $result;
}
/**
* Returns a message in the appropriate language.
* @access private
* @return string
*/
private function Lang($key) {
if(count($this->language) < 1) {
$this->SetLanguage('en'); // set the default language
}
if(isset($this->language[$key])) {
return $this->language[$key];
} else {
return 'Language string failed to load: ' . $key;
}
}
/**
* Returns true if an error occurred.
* @access public
* @return bool
*/
public function IsError() {
return ($this->error_count > 0);
}
/**
* Changes every end of line from CR or LF to CRLF.
* @access private
* @return string
*/
private function FixEOL($str) {
$str = str_replace("\r\n", "\n", $str);
$str = str_replace("\r", "\n", $str);
$str = str_replace("\n", $this->LE, $str);
return $str;
}
/**
* Adds a custom header.
* @access public
* @return void
*/
public function AddCustomHeader($custom_header) {
$this->CustomHeader[] = explode(':', $custom_header, 2);
}
/**
* Evaluates the message and returns modifications for inline images and backgrounds
* @access public
* @return $message
*/
public function MsgHTML($message, $basedir = '') {
preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images);
if(isset($images[2])) {
foreach($images[2] as $i => $url) {
// do not change urls for absolute images (thanks to corvuscorax)
if (!preg_match('#^[A-z]+://#',$url)) {
$filename = basename($url);
$directory = dirname($url);
($directory == '.')?$directory='':'';
$cid = 'cid:' . md5($filename);
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$mimeType = self::_mime_types($ext);
if ( strlen($basedir) > 1 && substr($basedir,-1) != '/') { $basedir .= '/'; }
if ( strlen($directory) > 1 && substr($directory,-1) != '/') { $directory .= '/'; }
if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64',$mimeType) ) {
$message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message);
}
}
}
}
$this->IsHTML(true);
$this->Body = $message;
$textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message)));
if (!empty($textMsg) && empty($this->AltBody)) {
$this->AltBody = html_entity_decode($textMsg);
}
if (empty($this->AltBody)) {
$this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
}
}
/**
* Gets the MIME type of the embedded or inline image
* @param string File extension
* @access public
* @return string MIME type of ext
* @static
*/
public static function _mime_types($ext = '') {
$mimes = array(
'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'doc' => 'application/msword',
'bin' => 'application/macbinary',
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => 'application/octet-stream',
'class' => 'application/octet-stream',
'psd' => 'application/octet-stream',
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => 'application/pdf',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'wbxml' => 'application/vnd.wap.wbxml',
'wmlc' => 'application/vnd.wap.wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'php' => 'application/x-httpd-php',
'php4' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'js' => 'application/x-javascript',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => 'application/x-tar',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => 'application/zip',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'aif' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'rv' => 'video/vnd.rn-realvideo',
'wav' => 'audio/x-wav',
'bmp' => 'image/bmp',
'gif' => 'image/gif',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'jpe' => 'image/jpeg',
'png' => 'image/png',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'css' => 'text/css',
'html' => 'text/html',
'htm' => 'text/html',
'shtml' => 'text/html',
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => 'text/plain',
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => 'text/xml',
'xsl' => 'text/xml',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'doc' => 'application/msword',
'word' => 'application/msword',
'xl' => 'application/excel',
'eml' => 'message/rfc822'
);
return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
}
/**
* Set (or reset) Class Objects (variables)
*
* Usage Example:
* $page->set('X-Priority', '3');
*
* @access public
* @param string $name Parameter Name
* @param mixed $value Parameter Value
* NOTE: will not work with arrays, there are no arrays to set/reset
* @todo Should this not be using __set() magic function?
*/
public function set($name, $value = '') {
try {
if (isset($this->$name) ) {
$this->$name = $value;
} else {
throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL);
}
} catch (Exception $e) {
$this->SetError($e->getMessage());
if ($e->getCode() == self::STOP_CRITICAL) {
return false;
}
}
return true;
}
/**
* Strips newlines to prevent header injection.
* @access public
* @param string $str String
* @return string
*/
public function SecureHeader($str) {
$str = str_replace("\r", '', $str);
$str = str_replace("\n", '', $str);
return trim($str);
}
/**
* Set the private key file and password to sign the message.
*
* @access public
* @param string $key_filename Parameter File Name
* @param string $key_pass Password for private key
*/
public function Sign($cert_filename, $key_filename, $key_pass) {
$this->sign_cert_file = $cert_filename;
$this->sign_key_file = $key_filename;
$this->sign_key_pass = $key_pass;
}
/**
* Set the private key file and password to sign the message.
*
* @access public
* @param string $key_filename Parameter File Name
* @param string $key_pass Password for private key
*/
public function DKIM_QP($txt) {
$tmp="";
$line="";
for ($i=0;$i<strlen($txt);$i++) {
$ord=ord($txt[$i]);
if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
$line.=$txt[$i];
} else {
$line.="=".sprintf("%02X",$ord);
}
}
return $line;
}
/**
* Generate DKIM signature
*
* @access public
* @param string $s Header
*/
public function DKIM_Sign($s) {
$privKeyStr = file_get_contents($this->DKIM_private);
if ($this->DKIM_passphrase!='') {
$privKey = openssl_pkey_get_private($privKeyStr,$this->DKIM_passphrase);
} else {
$privKey = $privKeyStr;
}
if (openssl_sign($s, $signature, $privKey)) {
return base64_encode($signature);
}
}
/**
* Generate DKIM Canonicalization Header
*
* @access public
* @param string $s Header
*/
public function DKIM_HeaderC($s) {
$s=preg_replace("/\r\n\s+/"," ",$s);
$lines=explode("\r\n",$s);
foreach ($lines as $key=>$line) {
list($heading,$value)=explode(":",$line,2);
$heading=strtolower($heading);
$value=preg_replace("/\s+/"," ",$value) ; // Compress useless spaces
$lines[$key]=$heading.":".trim($value) ; // Don't forget to remove WSP around the value
}
$s=implode("\r\n",$lines);
return $s;
}
/**
* Generate DKIM Canonicalization Body
*
* @access public
* @param string $body Message Body
*/
public function DKIM_BodyC($body) {
if ($body == '') return "\r\n";
// stabilize line endings
$body=str_replace("\r\n","\n",$body);
$body=str_replace("\n","\r\n",$body);
// END stabilize line endings
while (substr($body,strlen($body)-4,4) == "\r\n\r\n") {
$body=substr($body,0,strlen($body)-2);
}
return $body;
}
/**
* Create the DKIM header, body, as new header
*
* @access public
* @param string $headers_line Header lines
* @param string $subject Subject
* @param string $body Body
*/
public function DKIM_Add($headers_line,$subject,$body) {
$DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
$DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
$DKIMquery = 'dns/txt'; // Query method
$DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
$subject_header = "Subject: $subject";
$headers = explode("\r\n",$headers_line);
foreach($headers as $header) {
if (strpos($header,'From:') === 0) {
$from_header=$header;
} elseif (strpos($header,'To:') === 0) {
$to_header=$header;
}
}
$from = str_replace('|','=7C',$this->DKIM_QP($from_header));
$to = str_replace('|','=7C',$this->DKIM_QP($to_header));
$subject = str_replace('|','=7C',$this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
$body = $this->DKIM_BodyC($body);
$DKIMlen = strlen($body) ; // Length of body
$DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
$ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
$dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
"\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
"\th=From:To:Subject;\r\n".
"\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
"\tz=$from\r\n".
"\t|$to\r\n".
"\t|$subject;\r\n".
"\tbh=" . $DKIMb64 . ";\r\n".
"\tb=";
$toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
$signed = $this->DKIM_Sign($toSign);
return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n";
}
protected function doCallback($isSent,$to,$cc,$bcc,$subject,$body) {
if (!empty($this->action_function) && function_exists($this->action_function)) {
$params = array($isSent,$to,$cc,$bcc,$subject,$body);
call_user_func_array($this->action_function,$params);
}
}
}
class phpmailerException extends Exception {
public function errorMessage() {
$errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
return $errorMsg;
}
}
?> | 10npsite | trunk/Index/Lib/Public/class.phpmailer.php | PHP | asf20 | 76,791 |
<?php
/**
* 时间段模型
*/
class InnBatPriceModel extends AutoMapModel {
protected $tableName = 'price';
protected $patchValidate = true;
public $_map = array(
'id' => 'price0', //类型ID
'name' => 'price1', //时间段名称
'menuId' => 'price3', //分类标志612
'innId' => 'price4', //客栈ID
'begin' => 'price13', //开始时间
'end' => 'price14', //结束时间
'display_order' => 'price18',//排序
'price_data' => 'price19',//价格数据
);
protected $_validate = array(
array('name', 'require', '时间段名称必须填写!'),
array('innId', 'require', '客栈ID未找到!'),
array('begin', 'require', '开始时间必须填写!'),
array('end', 'require', '结束时间必须填写!'),
);
protected $_auto = array(
array('menuId','612',Model::MODEL_INSERT,'string'),
array('begin','strtotime',Model::MODEL_BOTH,'function'),
array('end','strtotime',Model::MODEL_BOTH,'function')
);
}
?> | 10npsite | trunk/Index/Lib/Model/InnBatPriceModel.class.php | PHP | asf20 | 1,169 |