PageRenderTime 53ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 2ms

/administrator/components/com_virtuemart/classes/nusoap/nusoap.php

https://bitbucket.org/dgough/annamaria-daneswood-25102012
PHP | 7993 lines | 6477 code | 205 blank | 1311 comment | 768 complexity | 42eea740f488ce7181aa724e56831550 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. /*
  3. $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $
  4. NuSOAP - Web Services Toolkit for PHP
  5. Copyright (c) 2002 NuSphere Corporation
  6. This library is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU Lesser General Public
  8. License as published by the Free Software Foundation; either
  9. version 2.1 of the License, or (at your option) any later version.
  10. This library is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. Lesser General Public License for more details.
  14. You should have received a copy of the GNU Lesser General Public
  15. License along with this library; if not, write to the Free Software
  16. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. The NuSOAP project home is:
  18. http://sourceforge.net/projects/nusoap/
  19. The primary support for NuSOAP is the mailing list:
  20. nusoap-general@lists.sourceforge.net
  21. If you have any questions or comments, please email:
  22. Dietrich Ayala
  23. dietrich@ganx4.com
  24. http://dietrich.ganx4.com/nusoap
  25. NuSphere Corporation
  26. http://www.nusphere.com
  27. */
  28. /*
  29. * Some of the standards implmented in whole or part by NuSOAP:
  30. *
  31. * SOAP 1.1 (http://www.w3.org/TR/2000/NOTE-SOAP-20000508/)
  32. * WSDL 1.1 (http://www.w3.org/TR/2001/NOTE-wsdl-20010315)
  33. * SOAP Messages With Attachments (http://www.w3.org/TR/SOAP-attachments)
  34. * XML 1.0 (http://www.w3.org/TR/2006/REC-xml-20060816/)
  35. * Namespaces in XML 1.0 (http://www.w3.org/TR/2006/REC-xml-names-20060816/)
  36. * XML Schema 1.0 (http://www.w3.org/TR/xmlschema-0/)
  37. * RFC 2045 Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies
  38. * RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1
  39. * RFC 2617 HTTP Authentication: Basic and Digest Access Authentication
  40. */
  41. /* load classes
  42. // necessary classes
  43. require_once('class.soapclient.php');
  44. require_once('class.soap_val.php');
  45. require_once('class.soap_parser.php');
  46. require_once('class.soap_fault.php');
  47. // transport classes
  48. require_once('class.soap_transport_http.php');
  49. // optional add-on classes
  50. require_once('class.xmlschema.php');
  51. require_once('class.wsdl.php');
  52. // server class
  53. require_once('class.soap_server.php');*/
  54. // class variable emulation
  55. // cf. http://www.webkreator.com/php/techniques/php-static-class-variables.html
  56. $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel = 9;
  57. /**
  58. *
  59. * nusoap_base
  60. *
  61. * @author Dietrich Ayala <dietrich@ganx4.com>
  62. * @author Scott Nichol <snichol@users.sourceforge.net>
  63. * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $
  64. * @access public
  65. */
  66. class nusoap_base {
  67. /**
  68. * Identification for HTTP headers.
  69. *
  70. * @var string
  71. * @access private
  72. */
  73. var $title = 'NuSOAP';
  74. /**
  75. * Version for HTTP headers.
  76. *
  77. * @var string
  78. * @access private
  79. */
  80. var $version = '0.7.3';
  81. /**
  82. * CVS revision for HTTP headers.
  83. *
  84. * @var string
  85. * @access private
  86. */
  87. var $revision = '$Revision: 1.114 $';
  88. /**
  89. * Current error string (manipulated by getError/setError)
  90. *
  91. * @var string
  92. * @access private
  93. */
  94. var $error_str = '';
  95. /**
  96. * Current debug string (manipulated by debug/appendDebug/clearDebug/getDebug/getDebugAsXMLComment)
  97. *
  98. * @var string
  99. * @access private
  100. */
  101. var $debug_str = '';
  102. /**
  103. * toggles automatic encoding of special characters as entities
  104. * (should always be true, I think)
  105. *
  106. * @var boolean
  107. * @access private
  108. */
  109. var $charencoding = true;
  110. /**
  111. * the debug level for this instance
  112. *
  113. * @var integer
  114. * @access private
  115. */
  116. var $debugLevel;
  117. /**
  118. * set schema version
  119. *
  120. * @var string
  121. * @access public
  122. */
  123. var $XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema';
  124. /**
  125. * charset encoding for outgoing messages
  126. *
  127. * @var string
  128. * @access public
  129. */
  130. var $soap_defencoding = 'ISO-8859-1';
  131. //var $soap_defencoding = 'UTF-8';
  132. /**
  133. * namespaces in an array of prefix => uri
  134. *
  135. * this is "seeded" by a set of constants, but it may be altered by code
  136. *
  137. * @var array
  138. * @access public
  139. */
  140. var $namespaces = array(
  141. 'SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/',
  142. 'xsd' => 'http://www.w3.org/2001/XMLSchema',
  143. 'xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
  144. 'SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/'
  145. );
  146. /**
  147. * namespaces used in the current context, e.g. during serialization
  148. *
  149. * @var array
  150. * @access private
  151. */
  152. var $usedNamespaces = array();
  153. /**
  154. * XML Schema types in an array of uri => (array of xml type => php type)
  155. * is this legacy yet?
  156. * no, this is used by the nusoap_xmlschema class to verify type => namespace mappings.
  157. * @var array
  158. * @access public
  159. */
  160. var $typemap = array(
  161. 'http://www.w3.org/2001/XMLSchema' => array(
  162. 'string'=>'string','boolean'=>'boolean','float'=>'double','double'=>'double','decimal'=>'double',
  163. 'duration'=>'','dateTime'=>'string','time'=>'string','date'=>'string','gYearMonth'=>'',
  164. 'gYear'=>'','gMonthDay'=>'','gDay'=>'','gMonth'=>'','hexBinary'=>'string','base64Binary'=>'string',
  165. // abstract "any" types
  166. 'anyType'=>'string','anySimpleType'=>'string',
  167. // derived datatypes
  168. 'normalizedString'=>'string','token'=>'string','language'=>'','NMTOKEN'=>'','NMTOKENS'=>'','Name'=>'','NCName'=>'','ID'=>'',
  169. 'IDREF'=>'','IDREFS'=>'','ENTITY'=>'','ENTITIES'=>'','integer'=>'integer','nonPositiveInteger'=>'integer',
  170. 'negativeInteger'=>'integer','long'=>'integer','int'=>'integer','short'=>'integer','byte'=>'integer','nonNegativeInteger'=>'integer',
  171. 'unsignedLong'=>'','unsignedInt'=>'','unsignedShort'=>'','unsignedByte'=>'','positiveInteger'=>''),
  172. 'http://www.w3.org/2000/10/XMLSchema' => array(
  173. 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double',
  174. 'float'=>'double','dateTime'=>'string',
  175. 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'),
  176. 'http://www.w3.org/1999/XMLSchema' => array(
  177. 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double',
  178. 'float'=>'double','dateTime'=>'string',
  179. 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'),
  180. 'http://soapinterop.org/xsd' => array('SOAPStruct'=>'struct'),
  181. 'http://schemas.xmlsoap.org/soap/encoding/' => array('base64'=>'string','array'=>'array','Array'=>'array'),
  182. 'http://xml.apache.org/xml-soap' => array('Map')
  183. );
  184. /**
  185. * XML entities to convert
  186. *
  187. * @var array
  188. * @access public
  189. * @deprecated
  190. * @see expandEntities
  191. */
  192. var $xmlEntities = array('quot' => '"','amp' => '&',
  193. 'lt' => '<','gt' => '>','apos' => "'");
  194. /**
  195. * constructor
  196. *
  197. * @access public
  198. */
  199. function nusoap_base() {
  200. $this->debugLevel = $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel;
  201. }
  202. /**
  203. * gets the global debug level, which applies to future instances
  204. *
  205. * @return integer Debug level 0-9, where 0 turns off
  206. * @access public
  207. */
  208. function getGlobalDebugLevel() {
  209. return $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel;
  210. }
  211. /**
  212. * sets the global debug level, which applies to future instances
  213. *
  214. * @param int $level Debug level 0-9, where 0 turns off
  215. * @access public
  216. */
  217. function setGlobalDebugLevel($level) {
  218. $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel = $level;
  219. }
  220. /**
  221. * gets the debug level for this instance
  222. *
  223. * @return int Debug level 0-9, where 0 turns off
  224. * @access public
  225. */
  226. function getDebugLevel() {
  227. return $this->debugLevel;
  228. }
  229. /**
  230. * sets the debug level for this instance
  231. *
  232. * @param int $level Debug level 0-9, where 0 turns off
  233. * @access public
  234. */
  235. function setDebugLevel($level) {
  236. $this->debugLevel = $level;
  237. }
  238. /**
  239. * adds debug data to the instance debug string with formatting
  240. *
  241. * @param string $string debug data
  242. * @access private
  243. */
  244. function debug($string){
  245. if ($this->debugLevel > 0) {
  246. $this->appendDebug($this->getmicrotime().' '.get_class($this).": $string\n");
  247. }
  248. }
  249. /**
  250. * adds debug data to the instance debug string without formatting
  251. *
  252. * @param string $string debug data
  253. * @access public
  254. */
  255. function appendDebug($string){
  256. if ($this->debugLevel > 0) {
  257. // it would be nice to use a memory stream here to use
  258. // memory more efficiently
  259. $this->debug_str .= $string;
  260. }
  261. }
  262. /**
  263. * clears the current debug data for this instance
  264. *
  265. * @access public
  266. */
  267. function clearDebug() {
  268. // it would be nice to use a memory stream here to use
  269. // memory more efficiently
  270. $this->debug_str = '';
  271. }
  272. /**
  273. * gets the current debug data for this instance
  274. *
  275. * @return debug data
  276. * @access public
  277. */
  278. function &getDebug() {
  279. // it would be nice to use a memory stream here to use
  280. // memory more efficiently
  281. return $this->debug_str;
  282. }
  283. /**
  284. * gets the current debug data for this instance as an XML comment
  285. * this may change the contents of the debug data
  286. *
  287. * @return debug data as an XML comment
  288. * @access public
  289. */
  290. function &getDebugAsXMLComment() {
  291. // it would be nice to use a memory stream here to use
  292. // memory more efficiently
  293. while (strpos($this->debug_str, '--')) {
  294. $this->debug_str = str_replace('--', '- -', $this->debug_str);
  295. }
  296. $ret = "<!--\n" . $this->debug_str . "\n-->";
  297. return $ret;
  298. }
  299. /**
  300. * expands entities, e.g. changes '<' to '&lt;'.
  301. *
  302. * @param string $val The string in which to expand entities.
  303. * @access private
  304. */
  305. function expandEntities($val) {
  306. if ($this->charencoding) {
  307. $val = str_replace('&', '&amp;', $val);
  308. $val = str_replace("'", '&apos;', $val);
  309. $val = str_replace('"', '&quot;', $val);
  310. $val = str_replace('<', '&lt;', $val);
  311. $val = str_replace('>', '&gt;', $val);
  312. }
  313. return $val;
  314. }
  315. /**
  316. * returns error string if present
  317. *
  318. * @return mixed error string or false
  319. * @access public
  320. */
  321. function getError(){
  322. if($this->error_str != ''){
  323. return $this->error_str;
  324. }
  325. return false;
  326. }
  327. /**
  328. * sets error string
  329. *
  330. * @return boolean $string error string
  331. * @access private
  332. */
  333. function setError($str){
  334. $this->error_str = $str;
  335. }
  336. /**
  337. * detect if array is a simple array or a struct (associative array)
  338. *
  339. * @param mixed $val The PHP array
  340. * @return string (arraySimple|arrayStruct)
  341. * @access private
  342. */
  343. function isArraySimpleOrStruct($val) {
  344. $keyList = array_keys($val);
  345. foreach ($keyList as $keyListValue) {
  346. if (!is_int($keyListValue)) {
  347. return 'arrayStruct';
  348. }
  349. }
  350. return 'arraySimple';
  351. }
  352. /**
  353. * serializes PHP values in accordance w/ section 5. Type information is
  354. * not serialized if $use == 'literal'.
  355. *
  356. * @param mixed $val The value to serialize
  357. * @param string $name The name (local part) of the XML element
  358. * @param string $type The XML schema type (local part) for the element
  359. * @param string $name_ns The namespace for the name of the XML element
  360. * @param string $type_ns The namespace for the type of the element
  361. * @param array $attributes The attributes to serialize as name=>value pairs
  362. * @param string $use The WSDL "use" (encoded|literal)
  363. * @param boolean $soapval Whether this is called from soapval.
  364. * @return string The serialized element, possibly with child elements
  365. * @access public
  366. */
  367. function serialize_val($val,$name=false,$type=false,$name_ns=false,$type_ns=false,$attributes=false,$use='encoded',$soapval=false) {
  368. $this->debug("in serialize_val: name=$name, type=$type, name_ns=$name_ns, type_ns=$type_ns, use=$use, soapval=$soapval");
  369. $this->appendDebug('value=' . $this->varDump($val));
  370. $this->appendDebug('attributes=' . $this->varDump($attributes));
  371. if (is_object($val) && get_class($val) == 'soapval' && (! $soapval)) {
  372. $this->debug("serialize_val: serialize soapval");
  373. $xml = $val->serialize($use);
  374. $this->appendDebug($val->getDebug());
  375. $val->clearDebug();
  376. $this->debug("serialize_val of soapval returning $xml");
  377. return $xml;
  378. }
  379. // force valid name if necessary
  380. if (is_numeric($name)) {
  381. $name = '__numeric_' . $name;
  382. } elseif (! $name) {
  383. $name = 'noname';
  384. }
  385. // if name has ns, add ns prefix to name
  386. $xmlns = '';
  387. if($name_ns){
  388. $prefix = 'nu'.rand(1000,9999);
  389. $name = $prefix.':'.$name;
  390. $xmlns .= " xmlns:$prefix=\"$name_ns\"";
  391. }
  392. // if type is prefixed, create type prefix
  393. if($type_ns != '' && $type_ns == $this->namespaces['xsd']){
  394. // need to fix this. shouldn't default to xsd if no ns specified
  395. // w/o checking against typemap
  396. $type_prefix = 'xsd';
  397. } elseif($type_ns){
  398. $type_prefix = 'ns'.rand(1000,9999);
  399. $xmlns .= " xmlns:$type_prefix=\"$type_ns\"";
  400. }
  401. // serialize attributes if present
  402. $atts = '';
  403. if($attributes){
  404. foreach($attributes as $k => $v){
  405. $atts .= " $k=\"".$this->expandEntities($v).'"';
  406. }
  407. }
  408. // serialize null value
  409. if (is_null($val)) {
  410. $this->debug("serialize_val: serialize null");
  411. if ($use == 'literal') {
  412. // TODO: depends on minOccurs
  413. $xml = "<$name$xmlns$atts/>";
  414. $this->debug("serialize_val returning $xml");
  415. return $xml;
  416. } else {
  417. if (isset($type) && isset($type_prefix)) {
  418. $type_str = " xsi:type=\"$type_prefix:$type\"";
  419. } else {
  420. $type_str = '';
  421. }
  422. $xml = "<$name$xmlns$type_str$atts xsi:nil=\"true\"/>";
  423. $this->debug("serialize_val returning $xml");
  424. return $xml;
  425. }
  426. }
  427. // serialize if an xsd built-in primitive type
  428. if($type != '' && isset($this->typemap[$this->XMLSchemaVersion][$type])){
  429. $this->debug("serialize_val: serialize xsd built-in primitive type");
  430. if (is_bool($val)) {
  431. if ($type == 'boolean') {
  432. $val = $val ? 'true' : 'false';
  433. } elseif (! $val) {
  434. $val = 0;
  435. }
  436. } else if (is_string($val)) {
  437. $val = $this->expandEntities($val);
  438. }
  439. if ($use == 'literal') {
  440. $xml = "<$name$xmlns$atts>$val</$name>";
  441. $this->debug("serialize_val returning $xml");
  442. return $xml;
  443. } else {
  444. $xml = "<$name$xmlns xsi:type=\"xsd:$type\"$atts>$val</$name>";
  445. $this->debug("serialize_val returning $xml");
  446. return $xml;
  447. }
  448. }
  449. // detect type and serialize
  450. $xml = '';
  451. switch(true) {
  452. case (is_bool($val) || $type == 'boolean'):
  453. $this->debug("serialize_val: serialize boolean");
  454. if ($type == 'boolean') {
  455. $val = $val ? 'true' : 'false';
  456. } elseif (! $val) {
  457. $val = 0;
  458. }
  459. if ($use == 'literal') {
  460. $xml .= "<$name$xmlns$atts>$val</$name>";
  461. } else {
  462. $xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val</$name>";
  463. }
  464. break;
  465. case (is_int($val) || is_long($val) || $type == 'int'):
  466. $this->debug("serialize_val: serialize int");
  467. if ($use == 'literal') {
  468. $xml .= "<$name$xmlns$atts>$val</$name>";
  469. } else {
  470. $xml .= "<$name$xmlns xsi:type=\"xsd:int\"$atts>$val</$name>";
  471. }
  472. break;
  473. case (is_float($val)|| is_double($val) || $type == 'float'):
  474. $this->debug("serialize_val: serialize float");
  475. if ($use == 'literal') {
  476. $xml .= "<$name$xmlns$atts>$val</$name>";
  477. } else {
  478. $xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val</$name>";
  479. }
  480. break;
  481. case (is_string($val) || $type == 'string'):
  482. $this->debug("serialize_val: serialize string");
  483. $val = $this->expandEntities($val);
  484. if ($use == 'literal') {
  485. $xml .= "<$name$xmlns$atts>$val</$name>";
  486. } else {
  487. $xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val</$name>";
  488. }
  489. break;
  490. case is_object($val):
  491. $this->debug("serialize_val: serialize object");
  492. if (get_class($val) == 'soapval') {
  493. $this->debug("serialize_val: serialize soapval object");
  494. $pXml = $val->serialize($use);
  495. $this->appendDebug($val->getDebug());
  496. $val->clearDebug();
  497. } else {
  498. if (! $name) {
  499. $name = get_class($val);
  500. $this->debug("In serialize_val, used class name $name as element name");
  501. } else {
  502. $this->debug("In serialize_val, do not override name $name for element name for class " . get_class($val));
  503. }
  504. foreach(get_object_vars($val) as $k => $v){
  505. $pXml = isset($pXml) ? $pXml.$this->serialize_val($v,$k,false,false,false,false,$use) : $this->serialize_val($v,$k,false,false,false,false,$use);
  506. }
  507. }
  508. if(isset($type) && isset($type_prefix)){
  509. $type_str = " xsi:type=\"$type_prefix:$type\"";
  510. } else {
  511. $type_str = '';
  512. }
  513. if ($use == 'literal') {
  514. $xml .= "<$name$xmlns$atts>$pXml</$name>";
  515. } else {
  516. $xml .= "<$name$xmlns$type_str$atts>$pXml</$name>";
  517. }
  518. break;
  519. break;
  520. case (is_array($val) || $type):
  521. // detect if struct or array
  522. $valueType = $this->isArraySimpleOrStruct($val);
  523. if($valueType=='arraySimple' || ereg('^ArrayOf',$type)){
  524. $this->debug("serialize_val: serialize array");
  525. $i = 0;
  526. if(is_array($val) && count($val)> 0){
  527. foreach($val as $v){
  528. if(is_object($v) && get_class($v) == 'soapval'){
  529. $tt_ns = $v->type_ns;
  530. $tt = $v->type;
  531. } elseif (is_array($v)) {
  532. $tt = $this->isArraySimpleOrStruct($v);
  533. } else {
  534. $tt = gettype($v);
  535. }
  536. $array_types[$tt] = 1;
  537. // TODO: for literal, the name should be $name
  538. $xml .= $this->serialize_val($v,'item',false,false,false,false,$use);
  539. ++$i;
  540. }
  541. if(count($array_types) > 1){
  542. $array_typename = 'xsd:anyType';
  543. } elseif(isset($tt) && isset($this->typemap[$this->XMLSchemaVersion][$tt])) {
  544. if ($tt == 'integer') {
  545. $tt = 'int';
  546. }
  547. $array_typename = 'xsd:'.$tt;
  548. } elseif(isset($tt) && $tt == 'arraySimple'){
  549. $array_typename = 'SOAP-ENC:Array';
  550. } elseif(isset($tt) && $tt == 'arrayStruct'){
  551. $array_typename = 'unnamed_struct_use_soapval';
  552. } else {
  553. // if type is prefixed, create type prefix
  554. if ($tt_ns != '' && $tt_ns == $this->namespaces['xsd']){
  555. $array_typename = 'xsd:' . $tt;
  556. } elseif ($tt_ns) {
  557. $tt_prefix = 'ns' . rand(1000, 9999);
  558. $array_typename = "$tt_prefix:$tt";
  559. $xmlns .= " xmlns:$tt_prefix=\"$tt_ns\"";
  560. } else {
  561. $array_typename = $tt;
  562. }
  563. }
  564. $array_type = $i;
  565. if ($use == 'literal') {
  566. $type_str = '';
  567. } else if (isset($type) && isset($type_prefix)) {
  568. $type_str = " xsi:type=\"$type_prefix:$type\"";
  569. } else {
  570. $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"".$array_typename."[$array_type]\"";
  571. }
  572. // empty array
  573. } else {
  574. if ($use == 'literal') {
  575. $type_str = '';
  576. } else if (isset($type) && isset($type_prefix)) {
  577. $type_str = " xsi:type=\"$type_prefix:$type\"";
  578. } else {
  579. $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"xsd:anyType[0]\"";
  580. }
  581. }
  582. // TODO: for array in literal, there is no wrapper here
  583. $xml = "<$name$xmlns$type_str$atts>".$xml."</$name>";
  584. } else {
  585. // got a struct
  586. $this->debug("serialize_val: serialize struct");
  587. if(isset($type) && isset($type_prefix)){
  588. $type_str = " xsi:type=\"$type_prefix:$type\"";
  589. } else {
  590. $type_str = '';
  591. }
  592. if ($use == 'literal') {
  593. $xml .= "<$name$xmlns$atts>";
  594. } else {
  595. $xml .= "<$name$xmlns$type_str$atts>";
  596. }
  597. foreach($val as $k => $v){
  598. // Apache Map
  599. if ($type == 'Map' && $type_ns == 'http://xml.apache.org/xml-soap') {
  600. $xml .= '<item>';
  601. $xml .= $this->serialize_val($k,'key',false,false,false,false,$use);
  602. $xml .= $this->serialize_val($v,'value',false,false,false,false,$use);
  603. $xml .= '</item>';
  604. } else {
  605. $xml .= $this->serialize_val($v,$k,false,false,false,false,$use);
  606. }
  607. }
  608. $xml .= "</$name>";
  609. }
  610. break;
  611. default:
  612. $this->debug("serialize_val: serialize unknown");
  613. $xml .= 'not detected, got '.gettype($val).' for '.$val;
  614. break;
  615. }
  616. $this->debug("serialize_val returning $xml");
  617. return $xml;
  618. }
  619. /**
  620. * serializes a message
  621. *
  622. * @param string $body the XML of the SOAP body
  623. * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers, or associative array
  624. * @param array $namespaces optional the namespaces used in generating the body and headers
  625. * @param string $style optional (rpc|document)
  626. * @param string $use optional (encoded|literal)
  627. * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
  628. * @return string the message
  629. * @access public
  630. */
  631. function serializeEnvelope($body,$headers=false,$namespaces=array(),$style='rpc',$use='encoded',$encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'){
  632. // TODO: add an option to automatically run utf8_encode on $body and $headers
  633. // if $this->soap_defencoding is UTF-8. Not doing this automatically allows
  634. // one to send arbitrary UTF-8 characters, not just characters that map to ISO-8859-1
  635. $this->debug("In serializeEnvelope length=" . strlen($body) . " body (max 1000 characters)=" . substr($body, 0, 1000) . " style=$style use=$use encodingStyle=$encodingStyle");
  636. $this->debug("headers:");
  637. $this->appendDebug($this->varDump($headers));
  638. $this->debug("namespaces:");
  639. $this->appendDebug($this->varDump($namespaces));
  640. // serialize namespaces
  641. $ns_string = '';
  642. foreach(array_merge($this->namespaces,$namespaces) as $k => $v){
  643. $ns_string .= " xmlns:$k=\"$v\"";
  644. }
  645. if($encodingStyle) {
  646. $ns_string = " SOAP-ENV:encodingStyle=\"$encodingStyle\"$ns_string";
  647. }
  648. // serialize headers
  649. if($headers){
  650. if (is_array($headers)) {
  651. $xml = '';
  652. foreach ($headers as $k => $v) {
  653. if (is_object($v) && get_class($v) == 'soapval') {
  654. $xml .= $this->serialize_val($v, false, false, false, false, false, $use);
  655. } else {
  656. $xml .= $this->serialize_val($v, $k, false, false, false, false, $use);
  657. }
  658. }
  659. $headers = $xml;
  660. $this->debug("In serializeEnvelope, serialized array of headers to $headers");
  661. }
  662. $headers = "<SOAP-ENV:Header>".$headers."</SOAP-ENV:Header>";
  663. }
  664. // serialize envelope
  665. return
  666. '<?xml version="1.0" encoding="'.$this->soap_defencoding .'"?'.">".
  667. '<SOAP-ENV:Envelope'.$ns_string.">".
  668. $headers.
  669. "<SOAP-ENV:Body>".
  670. $body.
  671. "</SOAP-ENV:Body>".
  672. "</SOAP-ENV:Envelope>";
  673. }
  674. /**
  675. * formats a string to be inserted into an HTML stream
  676. *
  677. * @param string $str The string to format
  678. * @return string The formatted string
  679. * @access public
  680. * @deprecated
  681. */
  682. function formatDump($str){
  683. $str = htmlspecialchars($str);
  684. return nl2br($str);
  685. }
  686. /**
  687. * contracts (changes namespace to prefix) a qualified name
  688. *
  689. * @param string $qname qname
  690. * @return string contracted qname
  691. * @access private
  692. */
  693. function contractQname($qname){
  694. // get element namespace
  695. //$this->xdebug("Contract $qname");
  696. if (strrpos($qname, ':')) {
  697. // get unqualified name
  698. $name = substr($qname, strrpos($qname, ':') + 1);
  699. // get ns
  700. $ns = substr($qname, 0, strrpos($qname, ':'));
  701. $p = $this->getPrefixFromNamespace($ns);
  702. if ($p) {
  703. return $p . ':' . $name;
  704. }
  705. return $qname;
  706. } else {
  707. return $qname;
  708. }
  709. }
  710. /**
  711. * expands (changes prefix to namespace) a qualified name
  712. *
  713. * @param string $qname qname
  714. * @return string expanded qname
  715. * @access private
  716. */
  717. function expandQname($qname){
  718. // get element prefix
  719. if(strpos($qname,':') && !ereg('^http://',$qname)){
  720. // get unqualified name
  721. $name = substr(strstr($qname,':'),1);
  722. // get ns prefix
  723. $prefix = substr($qname,0,strpos($qname,':'));
  724. if(isset($this->namespaces[$prefix])){
  725. return $this->namespaces[$prefix].':'.$name;
  726. } else {
  727. return $qname;
  728. }
  729. } else {
  730. return $qname;
  731. }
  732. }
  733. /**
  734. * returns the local part of a prefixed string
  735. * returns the original string, if not prefixed
  736. *
  737. * @param string $str The prefixed string
  738. * @return string The local part
  739. * @access public
  740. */
  741. function getLocalPart($str){
  742. if($sstr = strrchr($str,':')){
  743. // get unqualified name
  744. return substr( $sstr, 1 );
  745. } else {
  746. return $str;
  747. }
  748. }
  749. /**
  750. * returns the prefix part of a prefixed string
  751. * returns false, if not prefixed
  752. *
  753. * @param string $str The prefixed string
  754. * @return mixed The prefix or false if there is no prefix
  755. * @access public
  756. */
  757. function getPrefix($str){
  758. if($pos = strrpos($str,':')){
  759. // get prefix
  760. return substr($str,0,$pos);
  761. }
  762. return false;
  763. }
  764. /**
  765. * pass it a prefix, it returns a namespace
  766. *
  767. * @param string $prefix The prefix
  768. * @return mixed The namespace, false if no namespace has the specified prefix
  769. * @access public
  770. */
  771. function getNamespaceFromPrefix($prefix){
  772. if (isset($this->namespaces[$prefix])) {
  773. return $this->namespaces[$prefix];
  774. }
  775. //$this->setError("No namespace registered for prefix '$prefix'");
  776. return false;
  777. }
  778. /**
  779. * returns the prefix for a given namespace (or prefix)
  780. * or false if no prefixes registered for the given namespace
  781. *
  782. * @param string $ns The namespace
  783. * @return mixed The prefix, false if the namespace has no prefixes
  784. * @access public
  785. */
  786. function getPrefixFromNamespace($ns) {
  787. foreach ($this->namespaces as $p => $n) {
  788. if ($ns == $n || $ns == $p) {
  789. $this->usedNamespaces[$p] = $n;
  790. return $p;
  791. }
  792. }
  793. return false;
  794. }
  795. /**
  796. * returns the time in ODBC canonical form with microseconds
  797. *
  798. * @return string The time in ODBC canonical form with microseconds
  799. * @access public
  800. */
  801. function getmicrotime() {
  802. if (function_exists('gettimeofday')) {
  803. $tod = gettimeofday();
  804. $sec = $tod['sec'];
  805. $usec = $tod['usec'];
  806. } else {
  807. $sec = time();
  808. $usec = 0;
  809. }
  810. return strftime('%Y-%m-%d %H:%M:%S', $sec) . '.' . sprintf('%06d', $usec);
  811. }
  812. /**
  813. * Returns a string with the output of var_dump
  814. *
  815. * @param mixed $data The variable to var_dump
  816. * @return string The output of var_dump
  817. * @access public
  818. */
  819. function varDump($data) {
  820. ob_start();
  821. var_dump($data);
  822. $ret_val = ob_get_contents();
  823. ob_end_clean();
  824. return $ret_val;
  825. }
  826. /**
  827. * represents the object as a string
  828. *
  829. * @return string
  830. * @access public
  831. */
  832. function __toString() {
  833. return $this->varDump($this);
  834. }
  835. }
  836. // XML Schema Datatype Helper Functions
  837. //xsd:dateTime helpers
  838. /**
  839. * convert unix timestamp to ISO 8601 compliant date string
  840. *
  841. * @param string $timestamp Unix time stamp
  842. * @param boolean $utc Whether the time stamp is UTC or local
  843. * @access public
  844. */
  845. function timestamp_to_iso8601($timestamp,$utc=true){
  846. $datestr = date('Y-m-d\TH:i:sO',$timestamp);
  847. if($utc){
  848. $eregStr =
  849. '([0-9]{4})-'. // centuries & years CCYY-
  850. '([0-9]{2})-'. // months MM-
  851. '([0-9]{2})'. // days DD
  852. 'T'. // separator T
  853. '([0-9]{2}):'. // hours hh:
  854. '([0-9]{2}):'. // minutes mm:
  855. '([0-9]{2})(\.[0-9]*)?'. // seconds ss.ss...
  856. '(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
  857. if(ereg($eregStr,$datestr,$regs)){
  858. return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',$regs[1],$regs[2],$regs[3],$regs[4],$regs[5],$regs[6]);
  859. }
  860. return false;
  861. } else {
  862. return $datestr;
  863. }
  864. }
  865. /**
  866. * convert ISO 8601 compliant date string to unix timestamp
  867. *
  868. * @param string $datestr ISO 8601 compliant date string
  869. * @access public
  870. */
  871. function iso8601_to_timestamp($datestr){
  872. $eregStr =
  873. '([0-9]{4})-'. // centuries & years CCYY-
  874. '([0-9]{2})-'. // months MM-
  875. '([0-9]{2})'. // days DD
  876. 'T'. // separator T
  877. '([0-9]{2}):'. // hours hh:
  878. '([0-9]{2}):'. // minutes mm:
  879. '([0-9]{2})(\.[0-9]+)?'. // seconds ss.ss...
  880. '(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
  881. if(ereg($eregStr,$datestr,$regs)){
  882. // not utc
  883. if($regs[8] != 'Z'){
  884. $op = substr($regs[8],0,1);
  885. $h = substr($regs[8],1,2);
  886. $m = substr($regs[8],strlen($regs[8])-2,2);
  887. if($op == '-'){
  888. $regs[4] = $regs[4] + $h;
  889. $regs[5] = $regs[5] + $m;
  890. } elseif($op == '+'){
  891. $regs[4] = $regs[4] - $h;
  892. $regs[5] = $regs[5] - $m;
  893. }
  894. }
  895. return gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
  896. // return strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z");
  897. } else {
  898. return false;
  899. }
  900. }
  901. /**
  902. * sleeps some number of microseconds
  903. *
  904. * @param string $usec the number of microseconds to sleep
  905. * @access public
  906. * @deprecated
  907. */
  908. function usleepWindows($usec)
  909. {
  910. $start = gettimeofday();
  911. do
  912. {
  913. $stop = gettimeofday();
  914. $timePassed = 1000000 * ($stop['sec'] - $start['sec'])
  915. + $stop['usec'] - $start['usec'];
  916. }
  917. while ($timePassed < $usec);
  918. }
  919. ?><?php
  920. /**
  921. * Contains information for a SOAP fault.
  922. * Mainly used for returning faults from deployed functions
  923. * in a server instance.
  924. * @author Dietrich Ayala <dietrich@ganx4.com>
  925. * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $
  926. * @access public
  927. */
  928. class nusoap_fault extends nusoap_base {
  929. /**
  930. * The fault code (client|server)
  931. * @var string
  932. * @access private
  933. */
  934. var $faultcode;
  935. /**
  936. * The fault actor
  937. * @var string
  938. * @access private
  939. */
  940. var $faultactor;
  941. /**
  942. * The fault string, a description of the fault
  943. * @var string
  944. * @access private
  945. */
  946. var $faultstring;
  947. /**
  948. * The fault detail, typically a string or array of string
  949. * @var mixed
  950. * @access private
  951. */
  952. var $faultdetail;
  953. /**
  954. * constructor
  955. *
  956. * @param string $faultcode (SOAP-ENV:Client | SOAP-ENV:Server)
  957. * @param string $faultactor only used when msg routed between multiple actors
  958. * @param string $faultstring human readable error message
  959. * @param mixed $faultdetail detail, typically a string or array of string
  960. */
  961. function nusoap_fault($faultcode,$faultactor='',$faultstring='',$faultdetail=''){
  962. parent::nusoap_base();
  963. $this->faultcode = $faultcode;
  964. $this->faultactor = $faultactor;
  965. $this->faultstring = $faultstring;
  966. $this->faultdetail = $faultdetail;
  967. }
  968. /**
  969. * serialize a fault
  970. *
  971. * @return string The serialization of the fault instance.
  972. * @access public
  973. */
  974. function serialize(){
  975. $ns_string = '';
  976. foreach($this->namespaces as $k => $v){
  977. $ns_string .= "\n xmlns:$k=\"$v\"";
  978. }
  979. $return_msg =
  980. '<?xml version="1.0" encoding="'.$this->soap_defencoding.'"?>'.
  981. '<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"'.$ns_string.">\n".
  982. '<SOAP-ENV:Body>'.
  983. '<SOAP-ENV:Fault>'.
  984. $this->serialize_val($this->faultcode, 'faultcode').
  985. $this->serialize_val($this->faultactor, 'faultactor').
  986. $this->serialize_val($this->faultstring, 'faultstring').
  987. $this->serialize_val($this->faultdetail, 'detail').
  988. '</SOAP-ENV:Fault>'.
  989. '</SOAP-ENV:Body>'.
  990. '</SOAP-ENV:Envelope>';
  991. return $return_msg;
  992. }
  993. }
  994. /**
  995. * Backward compatibility
  996. */
  997. class soap_fault extends nusoap_fault {
  998. }
  999. ?><?php
  1000. /**
  1001. * parses an XML Schema, allows access to it's data, other utility methods.
  1002. * imperfect, no validation... yet, but quite functional.
  1003. *
  1004. * @author Dietrich Ayala <dietrich@ganx4.com>
  1005. * @author Scott Nichol <snichol@users.sourceforge.net>
  1006. * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $
  1007. * @access public
  1008. */
  1009. class nusoap_xmlschema extends nusoap_base {
  1010. // files
  1011. var $schema = '';
  1012. var $xml = '';
  1013. // namespaces
  1014. var $enclosingNamespaces;
  1015. // schema info
  1016. var $schemaInfo = array();
  1017. var $schemaTargetNamespace = '';
  1018. // types, elements, attributes defined by the schema
  1019. var $attributes = array();
  1020. var $complexTypes = array();
  1021. var $complexTypeStack = array();
  1022. var $currentComplexType = null;
  1023. var $elements = array();
  1024. var $elementStack = array();
  1025. var $currentElement = null;
  1026. var $simpleTypes = array();
  1027. var $simpleTypeStack = array();
  1028. var $currentSimpleType = null;
  1029. // imports
  1030. var $imports = array();
  1031. // parser vars
  1032. var $parser;
  1033. var $position = 0;
  1034. var $depth = 0;
  1035. var $depth_array = array();
  1036. var $message = array();
  1037. var $defaultNamespace = array();
  1038. /**
  1039. * constructor
  1040. *
  1041. * @param string $schema schema document URI
  1042. * @param string $xml xml document URI
  1043. * @param string $namespaces namespaces defined in enclosing XML
  1044. * @access public
  1045. */
  1046. function nusoap_xmlschema($schema='',$xml='',$namespaces=array()){
  1047. parent::nusoap_base();
  1048. $this->debug('nusoap_xmlschema class instantiated, inside constructor');
  1049. // files
  1050. $this->schema = $schema;
  1051. $this->xml = $xml;
  1052. // namespaces
  1053. $this->enclosingNamespaces = $namespaces;
  1054. $this->namespaces = array_merge($this->namespaces, $namespaces);
  1055. // parse schema file
  1056. if($schema != ''){
  1057. $this->debug('initial schema file: '.$schema);
  1058. $this->parseFile($schema, 'schema');
  1059. }
  1060. // parse xml file
  1061. if($xml != ''){
  1062. $this->debug('initial xml file: '.$xml);
  1063. $this->parseFile($xml, 'xml');
  1064. }
  1065. }
  1066. /**
  1067. * parse an XML file
  1068. *
  1069. * @param string $xml path/URL to XML file
  1070. * @param string $type (schema | xml)
  1071. * @return boolean
  1072. * @access public
  1073. */
  1074. function parseFile($xml,$type){
  1075. // parse xml file
  1076. if($xml != ""){
  1077. $xmlStr = @join("",@file($xml));
  1078. if($xmlStr == ""){
  1079. $msg = 'Error reading XML from '.$xml;
  1080. $this->setError($msg);
  1081. $this->debug($msg);
  1082. return false;
  1083. } else {
  1084. $this->debug("parsing $xml");
  1085. $this->parseString($xmlStr,$type);
  1086. $this->debug("done parsing $xml");
  1087. return true;
  1088. }
  1089. }
  1090. return false;
  1091. }
  1092. /**
  1093. * parse an XML string
  1094. *
  1095. * @param string $xml path or URL
  1096. * @param string $type (schema|xml)
  1097. * @access private
  1098. */
  1099. function parseString($xml,$type){
  1100. // parse xml string
  1101. if($xml != ""){
  1102. // Create an XML parser.
  1103. $this->parser = xml_parser_create();
  1104. // Set the options for parsing the XML data.
  1105. xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
  1106. // Set the object for the parser.
  1107. xml_set_object($this->parser, $this);
  1108. // Set the element handlers for the parser.
  1109. if($type == "schema"){
  1110. xml_set_element_handler($this->parser, 'schemaStartElement','schemaEndElement');
  1111. xml_set_character_data_handler($this->parser,'schemaCharacterData');
  1112. } elseif($type == "xml"){
  1113. xml_set_element_handler($this->parser, 'xmlStartElement','xmlEndElement');
  1114. xml_set_character_data_handler($this->parser,'xmlCharacterData');
  1115. }
  1116. // Parse the XML file.
  1117. if(!xml_parse($this->parser,$xml,true)){
  1118. // Display an error message.
  1119. $errstr = sprintf('XML error parsing XML schema on line %d: %s',
  1120. xml_get_current_line_number($this->parser),
  1121. xml_error_string(xml_get_error_code($this->parser))
  1122. );
  1123. $this->debug($errstr);
  1124. $this->debug("XML payload:\n" . $xml);
  1125. $this->setError($errstr);
  1126. }
  1127. xml_parser_free($this->parser);
  1128. } else{
  1129. $this->debug('no xml passed to parseString()!!');
  1130. $this->setError('no xml passed to parseString()!!');
  1131. }
  1132. }
  1133. /**
  1134. * gets a type name for an unnamed type
  1135. *
  1136. * @param string Element name
  1137. * @return string A type name for an unnamed type
  1138. * @access private
  1139. */
  1140. function CreateTypeName($ename) {
  1141. $scope = '';
  1142. for ($i = 0; $i < count($this->complexTypeStack); $i++) {
  1143. $scope .= $this->complexTypeStack[$i] . '_';
  1144. }
  1145. return $scope . $ename . '_ContainedType';
  1146. }
  1147. /**
  1148. * start-element handler
  1149. *
  1150. * @param string $parser XML parser object
  1151. * @param string $name element name
  1152. * @param string $attrs associative array of attributes
  1153. * @access private
  1154. */
  1155. function schemaStartElement($parser, $name, $attrs) {
  1156. // position in the total number of elements, starting from 0
  1157. $pos = $this->position++;
  1158. $depth = $this->depth++;
  1159. // set self as current value for this depth
  1160. $this->depth_array[$depth] = $pos;
  1161. $this->message[$pos] = array('cdata' => '');
  1162. if ($depth > 0) {
  1163. $this->defaultNamespace[$pos] = $this->defaultNamespace[$this->depth_array[$depth - 1]];
  1164. } else {
  1165. $this->defaultNamespace[$pos] = false;
  1166. }
  1167. // get element prefix
  1168. if($prefix = $this->getPrefix($name)){
  1169. // get unqualified name
  1170. $name = $this->getLocalPart($name);
  1171. } else {
  1172. $prefix = '';
  1173. }
  1174. // loop thru attributes, expanding, and registering namespace declarations
  1175. if(count($attrs) > 0){
  1176. foreach($attrs as $k => $v){
  1177. // if ns declarations, add to class level array of valid namespaces
  1178. if(ereg("^xmlns",$k)){
  1179. //$this->xdebug("$k: $v");
  1180. //$this->xdebug('ns_prefix: '.$this->getPrefix($k));
  1181. if($ns_prefix = substr(strrchr($k,':'),1)){
  1182. //$this->xdebug("Add namespace[$ns_prefix] = $v");
  1183. $this->namespaces[$ns_prefix] = $v;
  1184. } else {
  1185. $this->defaultNamespace[$pos] = $v;
  1186. if (! $this->getPrefixFromNamespace($v)) {
  1187. $this->namespaces['ns'.(count($this->namespaces)+1)] = $v;
  1188. }
  1189. }
  1190. if($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema'){
  1191. $this->XMLSchemaVersion = $v;
  1192. $this->namespaces['xsi'] = $v.'-instance';
  1193. }
  1194. }
  1195. }
  1196. foreach($attrs as $k => $v){
  1197. // expand each attribute
  1198. $k = strpos($k,':') ? $this->expandQname($k) : $k;
  1199. $v = strpos($v,':') ? $this->expandQname($v) : $v;
  1200. $eAttrs[$k] = $v;
  1201. }
  1202. $attrs = $eAttrs;
  1203. } else {
  1204. $attrs = array();
  1205. }
  1206. // find status, register data
  1207. switch($name){
  1208. case 'all': // (optional) compositor content for a complexType
  1209. case 'choice':
  1210. case 'group':
  1211. case 'sequence':
  1212. //$this->xdebug("compositor $name for currentComplexType: $this->currentComplexType and currentElement: $this->currentElement");
  1213. $this->complexTypes[$this->currentComplexType]['compositor'] = $name;
  1214. //if($name == 'all' || $name == 'sequence'){
  1215. // $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
  1216. //}
  1217. break;
  1218. case 'attribute': // complexType attribute
  1219. //$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']);
  1220. $this->xdebug("parsing attribute:");
  1221. $this->appendDebug($this->varDump($attrs));
  1222. if (!isset($attrs['form'])) {
  1223. $attrs['form'] = $this->schemaInfo['attributeFormDefault'];
  1224. }
  1225. if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) {
  1226. $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
  1227. if (!strpos($v, ':')) {
  1228. // no namespace in arrayType attribute value...
  1229. if ($this->defaultNamespace[$pos]) {
  1230. // ...so use the default
  1231. $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'] = $this->defaultNamespace[$pos] . ':' . $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
  1232. }
  1233. }
  1234. }
  1235. if(isset($attrs['name'])){
  1236. $this->attributes[$attrs['name']] = $attrs;
  1237. $aname = $attrs['name'];
  1238. } elseif(isset($attrs['ref']) && $attrs['ref'] == 'http://schemas.xmlsoap.org/soap/encoding/:arrayType'){
  1239. if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) {
  1240. $aname = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
  1241. } else {
  1242. $aname = '';
  1243. }
  1244. } elseif(isset($attrs['ref'])){
  1245. $aname = $attrs['ref'];
  1246. $this->attributes[$attrs['ref']] = $attrs;
  1247. }
  1248. if($this->currentComplexType){ // This should *always* be
  1249. $this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs;
  1250. }
  1251. // arrayType attribute
  1252. if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']) || $this->getLocalPart($aname) == 'arrayType'){
  1253. $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
  1254. $prefix = $this->getPrefix($aname);
  1255. if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])){
  1256. $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
  1257. } else {
  1258. $v = '';
  1259. }
  1260. if(strpos($v,'[,]')){
  1261. $this->complexTypes[$this->currentComplexType]['multidimensional'] = true;
  1262. }
  1263. $v = substr($v,0,strpos($v,'[')); // clip the []
  1264. if(!strpos($v,':') && isset($this->typemap[$this->XMLSchemaVersion][$v])){
  1265. $v = $this->XMLSchemaVersion.':'.$v;
  1266. }
  1267. $this->complexTypes[$this->currentComplexType]['arrayType'] = $v;
  1268. }
  1269. break;
  1270. case 'complexContent': // (optional) content for a complexType
  1271. break;
  1272. case 'complexType':
  1273. array_push($this->complexTypeStack, $this->currentComplexType);
  1274. if(isset($attrs['name'])){
  1275. // TODO: what is the scope of named complexTypes that appear
  1276. // nested within other c complexTypes?
  1277. $this->xdebug('processing named complexType '.$attrs['name']);
  1278. //$this->currentElement = false;
  1279. $this->currentComplexType = $attrs['name'];
  1280. $this->complexTypes[$this->currentComplexType] = $attrs;
  1281. $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';
  1282. // This is for constructs like
  1283. // <complexType name="ListOfString" base="soap:Array">
  1284. // <sequence>
  1285. // <element name="string" type="xsd:string"
  1286. // minOccurs="0" maxOccurs="unbounded" />
  1287. // </sequence>
  1288. // </complexType>
  1289. if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){
  1290. $this->xdebug('complexType is unusual array');
  1291. $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
  1292. } else {
  1293. $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
  1294. }
  1295. } else {
  1296. $name = $this->CreateTypeName($this->currentElement);
  1297. $this->xdebug('processing unnamed complexType for element ' . $this->currentElement . ' named ' . $name);
  1298. $this->currentComplexType = $name;
  1299. //$this->currentElement = false;
  1300. $this->complexTypes[$this->currentComplexType] = $attrs;
  1301. $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';
  1302. // This is for constructs like
  1303. // <complexType name="ListOfString" base="soap:Array">
  1304. // <sequence>
  1305. // <element name="string" type="xsd:string"
  1306. // minOccurs="0" maxOccurs="unbounded" />
  1307. // </sequence>
  1308. // </complexType>
  1309. if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){
  1310. $this->xdebug('complexType is unusual array');
  1311. $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
  1312. } else {
  1313. $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
  1314. }
  1315. }
  1316. break;
  1317. case 'element':
  1318. array_push($this->elementStack, $this->currentElement);
  1319. if (!isset($attrs['form'])) {
  1320. $attrs['form'] = $this->schemaInfo['elementFormDefault'];
  1321. }
  1322. if(isset($attrs['type'])){
  1323. $this->xdebug("processing typed element ".$attrs['name']." of type ".$attrs['type']);
  1324. if (! $this->getPrefix($attrs['type'])) {
  1325. if ($this->defaultNamespace[$pos]) {
  1326. $attrs['type'] = $this->defaultNamespace[$pos] . ':' . $attrs['type'];
  1327. $this->xdebug('used default namespace to make type ' . $attrs['type']);
  1328. }
  1329. }
  1330. // This is for constructs like
  1331. // <complexType name="ListOfString" base="soap:Array">
  1332. // <sequence>
  1333. // <element name="string" type="xsd:string"
  1334. // minOccurs="0" maxOccurs="unbounded" />
  1335. // </sequence>
  1336. // </complexType>
  1337. if ($this->currentComplexType && $this->complexTypes[$this->currentComplexType]['phpType'] == 'array') {
  1338. $this->xdebug('arrayType for unusual array is ' . $attrs['type']);
  1339. $this->complexTypes[$this->currentComplexType]['arrayType'] = $attrs['type'];
  1340. }
  1341. $this->currentElement = $attrs['name'];
  1342. $ename = $attrs['name'];
  1343. } elseif(isset($attrs['ref'])){
  1344. $this->xdebug("processing element as ref to ".$attrs['ref']);
  1345. $this->currentElement = "ref to ".$attrs['ref'];
  1346. $ename = $this->getLocalPart($attrs['ref']);
  1347. } else {
  1348. $type = $this->CreateTypeName($this->currentComplexType . '_' . $attrs['name']);
  1349. $this->xdebug("processing untyped element " . $attrs['name'] . ' type ' . $type);
  1350. $this->currentElement = $attrs['name'];
  1351. $attrs['type'] = $this->schemaTargetNamespace . ':' . $type;
  1352. $ename = $attrs['name'];
  1353. }
  1354. if (isset($ename) && $this->currentComplexType) {
  1355. $this->xdebug("add element $ename to complexType $this->currentComplexType");
  1356. $this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs;
  1357. } elseif (!isset($attrs['ref'])) {
  1358. $this->xdebug("add element $ename to elements array");
  1359. $this->elements[ $attrs['name'] ] = $attrs;
  1360. $this->elements[ $attrs['name'] ]['typeClass'] = 'element';
  1361. }
  1362. break;
  1363. case 'enumeration': // restriction value list member
  1364. $this->xdebug('enumeration ' . $attrs['value']);
  1365. if ($this->currentSimpleType) {
  1366. $this->simpleTypes[$this->currentSimpleType]['enumeration'][] = $attrs['value'];
  1367. } elseif ($this->currentComplexType) {
  1368. $this->complexTypes[$this->currentComplexType]['enumeration'][] = $attrs['value'];
  1369. }
  1370. break;
  1371. case 'extension': // simpleContent or complexContent type extension
  1372. $this->xdebug('extension ' . $attrs['base']);
  1373. if ($this->currentComplexType) {
  1374. $this->complexTypes[$this->currentComplexType]['extensionBase'] = $attrs['base'];
  1375. }
  1376. break;
  1377. case 'import':
  1378. if (isset($attrs['schemaLocation'])) {
  1379. //$this->xdebug('import namespace ' . $attrs['namespace'] . ' from ' . $attrs['schemaLocation']);
  1380. $this->imports[$attrs['namespace']][] = array('location' => $attrs['schemaLocation'], 'loaded' => false);
  1381. } else {
  1382. //$this->xdebug('import namespace ' . $attrs['namespace']);
  1383. $this->imports[$attrs['namespace']][] = array('location' => '', 'loaded' => true);
  1384. if (! $this->getPrefixFromNamespace($attrs['namespace'])) {
  1385. $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace'];
  1386. }
  1387. }
  1388. break;
  1389. case 'list': // simpleType value list
  1390. break;
  1391. case 'restriction': // simpleType, simpleContent or complexContent value restriction
  1392. $this->xdebug('restriction ' . $attrs['base']);
  1393. if($this->currentSimpleType){
  1394. $this->simpleTypes[$this->currentSimpleType]['type'] = $attrs['base'];
  1395. } elseif($this->currentComplexType){
  1396. $this->complexTypes[$this->currentComplexType]['restrictionBase'] = $attrs['base'];
  1397. if(strstr($attrs['base'],':') == ':Array'){
  1398. $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
  1399. }
  1400. }
  1401. break;
  1402. case 'schema':
  1403. $this->schemaInfo = $attrs;
  1404. $this->schemaInfo['schemaVersion'] = $this->getNamespaceFromPrefix($prefix);
  1405. if (isset($attrs['targetNamespace'])) {
  1406. $this->schemaTargetNamespace = $attrs['targetNamespace'];
  1407. }
  1408. if (!isset($attrs['elementFormDefault'])) {
  1409. $this->schemaInfo['elementFormDefault'] = 'unqualified';
  1410. }
  1411. if (!isset($attrs['attributeFormDefault'])) {
  1412. $this->schemaInfo['attributeFormDefault'] = 'unqualified';
  1413. }
  1414. break;
  1415. case 'simpleContent': // (optional) content for a complexType
  1416. break;
  1417. case 'simpleType':
  1418. array_push($this->simpleTypeStack, $this->currentSimpleType);
  1419. if(isset($attrs['name'])){
  1420. $this->xdebug("processing simpleType for name " . $attrs['name']);
  1421. $this->currentSimpleType = $attrs['name'];
  1422. $this->simpleTypes[ $attrs['name'] ] = $attrs;
  1423. $this->simpleTypes[ $attrs['name'] ]['typeClass'] = 'simpleType';
  1424. $this->simpleTypes[ $attrs['name'] ]['phpType'] = 'scalar';
  1425. } else {
  1426. $name = $this->CreateTypeName($this->currentComplexType . '_' . $this->currentElement);
  1427. $this->xdebug('processing unnamed simpleType for element ' . $this->currentElement . ' named ' . $name);
  1428. $this->currentSimpleType = $name;
  1429. //$this->currentElement = false;
  1430. $this->simpleTypes[$this->currentSimpleType] = $attrs;
  1431. $this->simpleTypes[$this->currentSimpleType]['phpType'] = 'scalar';
  1432. }
  1433. break;
  1434. case 'union': // simpleType type list
  1435. break;
  1436. default:
  1437. //$this->xdebug("do not have anything to do for element $name");
  1438. }
  1439. }
  1440. /**
  1441. * end-element handler
  1442. *
  1443. * @param string $parser XML parser object
  1444. * @param string $name element name
  1445. * @access private
  1446. */
  1447. function schemaEndElement($parser, $name) {
  1448. // bring depth down a notch
  1449. $this->depth--;
  1450. // position of current element is equal to the last value left in depth_array for my depth
  1451. if(isset($this->depth_array[$this->depth])){
  1452. $pos = $this->depth_array[$this->depth];
  1453. }
  1454. // get element prefix
  1455. if ($prefix = $this->getPrefix($name)){
  1456. // get unqualified name
  1457. $name = $this->getLocalPart($name);
  1458. } else {
  1459. $prefix = '';
  1460. }
  1461. // move on...
  1462. if($name == 'complexType'){
  1463. $this->xdebug('done processing complexType ' . ($this->currentComplexType ? $this->currentComplexType : '(unknown)'));
  1464. $this->currentComplexType = array_pop($this->complexTypeStack);
  1465. //$this->currentElement = false;
  1466. }
  1467. if($name == 'element'){
  1468. $this->xdebug('done processing element ' . ($this->currentElement ? $this->currentElement : '(unknown)'));
  1469. $this->currentElement = array_pop($this->elementStack);
  1470. }
  1471. if($name == 'simpleType'){
  1472. $this->xdebug('done processing simpleType ' . ($this->currentSimpleType ? $this->currentSimpleType : '(unknown)'));
  1473. $this->currentSimpleType = array_pop($this->simpleTypeStack);
  1474. }
  1475. }
  1476. /**
  1477. * element content handler
  1478. *
  1479. * @param string $parser XML parser object
  1480. * @param string $data element content
  1481. * @access private
  1482. */
  1483. function schemaCharacterData($parser, $data){
  1484. $pos = $this->depth_array[$this->depth - 1];
  1485. $this->message[$pos]['cdata'] .= $data;
  1486. }
  1487. /**
  1488. * serialize the schema
  1489. *
  1490. * @access public
  1491. */
  1492. function serializeSchema(){
  1493. $schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion);
  1494. $xml = '';
  1495. // imports
  1496. if (sizeof($this->imports) > 0) {
  1497. foreach($this->imports as $ns => $list) {
  1498. foreach ($list as $ii) {
  1499. if ($ii['location'] != '') {
  1500. $xml .= " <$schemaPrefix:import location=\"" . $ii['location'] . '" namespace="' . $ns . "\" />\n";
  1501. } else {
  1502. $xml .= " <$schemaPrefix:import namespace=\"" . $ns . "\" />\n";
  1503. }
  1504. }
  1505. }
  1506. }
  1507. // complex types
  1508. foreach($this->complexTypes as $typeName => $attrs){
  1509. $contentStr = '';
  1510. // serialize child elements
  1511. if(isset($attrs['elements']) && (count($attrs['elements']) > 0)){
  1512. foreach($attrs['elements'] as $element => $eParts){
  1513. if(isset($eParts['ref'])){
  1514. $contentStr .= " <$schemaPrefix:element ref=\"$element\"/>\n";
  1515. } else {
  1516. $contentStr .= " <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\"";
  1517. foreach ($eParts as $aName => $aValue) {
  1518. // handle, e.g., abstract, default, form, minOccurs, maxOccurs, nillable
  1519. if ($aName != 'name' && $aName != 'type') {
  1520. $contentStr .= " $aName=\"$aValue\"";
  1521. }
  1522. }
  1523. $contentStr .= "/>\n";
  1524. }
  1525. }
  1526. // compositor wraps elements
  1527. if (isset($attrs['compositor']) && ($attrs['compositor'] != '')) {
  1528. $contentStr = " <$schemaPrefix:$attrs[compositor]>\n".$contentStr." </$schemaPrefix:$attrs[compositor]>\n";
  1529. }
  1530. }
  1531. // attributes
  1532. if(isset($attrs['attrs']) && (count($attrs['attrs']) >= 1)){
  1533. foreach($attrs['attrs'] as $attr => $aParts){
  1534. $contentStr .= " <$schemaPrefix:attribute";
  1535. foreach ($aParts as $a => $v) {
  1536. if ($a == 'ref' || $a == 'type') {
  1537. $contentStr .= " $a=\"".$this->contractQName($v).'"';
  1538. } elseif ($a == 'http://schemas.xmlsoap.org/wsdl/:arrayType') {
  1539. $this->usedNamespaces['wsdl'] = $this->namespaces['wsdl'];
  1540. $contentStr .= ' wsdl:arrayType="'.$this->contractQName($v).'"';
  1541. } else {
  1542. $contentStr .= " $a=\"$v\"";
  1543. }
  1544. }
  1545. $contentStr .= "/>\n";
  1546. }
  1547. }
  1548. // if restriction
  1549. if (isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != ''){
  1550. $contentStr = " <$schemaPrefix:restriction base=\"".$this->contractQName($attrs['restrictionBase'])."\">\n".$contentStr." </$schemaPrefix:restriction>\n";
  1551. // complex or simple content
  1552. if ((isset($attrs['elements']) && count($attrs['elements']) > 0) || (isset($attrs['attrs']) && count($attrs['attrs']) > 0)){
  1553. $contentStr = " <$schemaPrefix:complexContent>\n".$contentStr." </$schemaPrefix:complexContent>\n";
  1554. }
  1555. }
  1556. // finalize complex type
  1557. if($contentStr != ''){
  1558. $contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." </$schemaPrefix:complexType>\n";
  1559. } else {
  1560. $contentStr = " <$schemaPrefix:complexType name=\"$typeName\"/>\n";
  1561. }
  1562. $xml .= $contentStr;
  1563. }
  1564. // simple types
  1565. if(isset($this->simpleTypes) && count($this->simpleTypes) > 0){
  1566. foreach($this->simpleTypes as $typeName => $eParts){
  1567. $xml .= " <$schemaPrefix:simpleType name=\"$typeName\">\n <$schemaPrefix:restriction base=\"".$this->contractQName($eParts['type'])."\">\n";
  1568. if (isset($eParts['enumeration'])) {
  1569. foreach ($eParts['enumeration'] as $e) {
  1570. $xml .= " <$schemaPrefix:enumeration value=\"$e\"/>\n";
  1571. }
  1572. }
  1573. $xml .= " </$schemaPrefix:restriction>\n </$schemaPrefix:simpleType>";
  1574. }
  1575. }
  1576. // elements
  1577. if(isset($this->elements) && count($this->elements) > 0){
  1578. foreach($this->elements as $element => $eParts){
  1579. $xml .= " <$schemaPrefix:element name=\"$element\" type=\"".$this->contractQName($eParts['type'])."\"/>\n";
  1580. }
  1581. }
  1582. // attributes
  1583. if(isset($this->attributes) && count($this->attributes) > 0){
  1584. foreach($this->attributes as $attr => $aParts){
  1585. $xml .= " <$schemaPrefix:attribute name=\"$attr\" type=\"".$this->contractQName($aParts['type'])."\"\n/>";
  1586. }
  1587. }
  1588. // finish 'er up
  1589. $attr = '';
  1590. foreach ($this->schemaInfo as $k => $v) {
  1591. if ($k == 'elementFormDefault' || $k == 'attributeFormDefault') {
  1592. $attr .= " $k=\"$v\"";
  1593. }
  1594. }
  1595. $el = "<$schemaPrefix:schema$attr targetNamespace=\"$this->schemaTargetNamespace\"\n";
  1596. foreach (array_diff($this->usedNamespaces, $this->enclosingNamespaces) as $nsp => $ns) {
  1597. $el .= " xmlns:$nsp=\"$ns\"";
  1598. }
  1599. $xml = $el . ">\n".$xml."</$schemaPrefix:schema>\n";
  1600. return $xml;
  1601. }
  1602. /**
  1603. * adds debug data to the clas level debug string
  1604. *
  1605. * @param string $string debug data
  1606. * @access private
  1607. */
  1608. function xdebug($string){
  1609. $this->debug('<' . $this->schemaTargetNamespace . '> '.$string);
  1610. }
  1611. /**
  1612. * get the PHP type of a user defined type in the schema
  1613. * PHP type is kind of a misnomer since it actually returns 'struct' for assoc. arrays
  1614. * returns false if no type exists, or not w/ the given namespace
  1615. * else returns a string that is either a native php type, or 'struct'
  1616. *
  1617. * @param string $type name of defined type
  1618. * @param string $ns namespace of type
  1619. * @return mixed
  1620. * @access public
  1621. * @deprecated
  1622. */
  1623. function getPHPType($type,$ns){
  1624. if(isset($this->typemap[$ns][$type])){
  1625. //print "found type '$type' and ns $ns in typemap<br>";
  1626. return $this->typemap[$ns][$type];
  1627. } elseif(isset($this->complexTypes[$type])){
  1628. //print "getting type '$type' and ns $ns from complexTypes array<br>";
  1629. return $this->complexTypes[$type]['phpType'];
  1630. }
  1631. return false;
  1632. }
  1633. /**
  1634. * returns an associative array of information about a given type
  1635. * returns false if no type exists by the given name
  1636. *
  1637. * For a complexType typeDef = array(
  1638. * 'restrictionBase' => '',
  1639. * 'phpType' => '',
  1640. * 'compositor' => '(sequence|all)',
  1641. * 'elements' => array(), // refs to elements array
  1642. * 'attrs' => array() // refs to attributes array
  1643. * ... and so on (see addComplexType)
  1644. * )
  1645. *
  1646. * For simpleType or element, the array has different keys.
  1647. *
  1648. * @param string $type
  1649. * @return mixed
  1650. * @access public
  1651. * @see addComplexType
  1652. * @see addSimpleType
  1653. * @see addElement
  1654. */
  1655. function getTypeDef($type){
  1656. //$this->debug("in getTypeDef for type $type");
  1657. if (substr($type, -1) == '^') {
  1658. $is_element = 1;
  1659. $type = substr($type, 0, -1);
  1660. } else {
  1661. $is_element = 0;
  1662. }
  1663. if((! $is_element) && isset($this->complexTypes[$type])){
  1664. $this->xdebug("in getTypeDef, found complexType $type");
  1665. return $this->complexTypes[$type];
  1666. } elseif((! $is_element) && isset($this->simpleTypes[$type])){
  1667. $this->xdebug("in getTypeDef, found simpleType $type");
  1668. if (!isset($this->simpleTypes[$type]['phpType'])) {
  1669. // get info for type to tack onto the simple type
  1670. // TODO: can this ever really apply (i.e. what is a simpleType really?)
  1671. $uqType = substr($this->simpleTypes[$type]['type'], strrpos($this->simpleTypes[$type]['type'], ':') + 1);
  1672. $ns = substr($this->simpleTypes[$type]['type'], 0, strrpos($this->simpleTypes[$type]['type'], ':'));
  1673. $etype = $this->getTypeDef($uqType);
  1674. if ($etype) {
  1675. $this->xdebug("in getTypeDef, found type for simpleType $type:");
  1676. $this->xdebug($this->varDump($etype));
  1677. if (isset($etype['phpType'])) {
  1678. $this->simpleTypes[$type]['phpType'] = $etype['phpType'];
  1679. }
  1680. if (isset($etype['elements'])) {
  1681. $this->simpleTypes[$type]['elements'] = $etype['elements'];
  1682. }
  1683. }
  1684. }
  1685. return $this->simpleTypes[$type];
  1686. } elseif(isset($this->elements[$type])){
  1687. $this->xdebug("in getTypeDef, found element $type");
  1688. if (!isset($this->elements[$type]['phpType'])) {
  1689. // get info for type to tack onto the element
  1690. $uqType = substr($this->elements[$type]['type'], strrpos($this->elements[$type]['type'], ':') + 1);
  1691. $ns = substr($this->elements[$type]['type'], 0, strrpos($this->elements[$type]['type'], ':'));
  1692. $etype = $this->getTypeDef($uqType);
  1693. if ($etype) {
  1694. $this->xdebug("in getTypeDef, found type for element $type:");
  1695. $this->xdebug($this->varDump($etype));
  1696. if (isset($etype['phpType'])) {
  1697. $this->elements[$type]['phpType'] = $etype['phpType'];
  1698. }
  1699. if (isset($etype['elements'])) {
  1700. $this->elements[$type]['elements'] = $etype['elements'];
  1701. }
  1702. } elseif ($ns == 'http://www.w3.org/2001/XMLSchema') {
  1703. $this->xdebug("in getTypeDef, element $type is an XSD type");
  1704. $this->elements[$type]['phpType'] = 'scalar';
  1705. }
  1706. }
  1707. return $this->elements[$type];
  1708. } elseif(isset($this->attributes[$type])){
  1709. $this->xdebug("in getTypeDef, found attribute $type");
  1710. return $this->attributes[$type];
  1711. } elseif (ereg('_ContainedType$', $type)) {
  1712. $this->xdebug("in getTypeDef, have an untyped element $type");
  1713. $typeDef['typeClass'] = 'simpleType';
  1714. $typeDef['phpType'] = 'scalar';
  1715. $typeDef['type'] = 'http://www.w3.org/2001/XMLSchema:string';
  1716. return $typeDef;
  1717. }
  1718. $this->xdebug("in getTypeDef, did not find $type");
  1719. return false;
  1720. }
  1721. /**
  1722. * returns a sample serialization of a given type, or false if no type by the given name
  1723. *
  1724. * @param string $type name of type
  1725. * @return mixed
  1726. * @access public
  1727. * @deprecated
  1728. */
  1729. function serializeTypeDef($type){
  1730. //print "in sTD() for type $type<br>";
  1731. if($typeDef = $this->getTypeDef($type)){
  1732. $str .= '<'.$type;
  1733. if(is_array($typeDef['attrs'])){
  1734. foreach($typeDef['attrs'] as $attName => $data){
  1735. $str .= " $attName=\"{type = ".$data['type']."}\"";
  1736. }
  1737. }
  1738. $str .= " xmlns=\"".$this->schema['targetNamespace']."\"";
  1739. if(count($typeDef['elements']) > 0){
  1740. $str .= ">";
  1741. foreach($typeDef['elements'] as $element => $eData){
  1742. $str .= $this->serializeTypeDef($element);
  1743. }
  1744. $str .= "</$type>";
  1745. } elseif($typeDef['typeClass'] == 'element') {
  1746. $str .= "></$type>";
  1747. } else {
  1748. $str .= "/>";
  1749. }
  1750. return $str;
  1751. }
  1752. return false;
  1753. }
  1754. /**
  1755. * returns HTML form elements that allow a user
  1756. * to enter values for creating an instance of the given type.
  1757. *
  1758. * @param string $name name for type instance
  1759. * @param string $type name of type
  1760. * @return string
  1761. * @access public
  1762. * @deprecated
  1763. */
  1764. function typeToForm($name,$type){
  1765. // get typedef
  1766. if($typeDef = $this->getTypeDef($type)){
  1767. // if struct
  1768. if($typeDef['phpType'] == 'struct'){
  1769. $buffer .= '<table>';
  1770. foreach($typeDef['elements'] as $child => $childDef){
  1771. $buffer .= "
  1772. <tr><td align='right'>$childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):</td>
  1773. <td><input type='text' name='parameters[".$name."][$childDef[name]]'></td></tr>";
  1774. }
  1775. $buffer .= '</table>';
  1776. // if array
  1777. } elseif($typeDef['phpType'] == 'array'){
  1778. $buffer .= '<table>';
  1779. for($i=0;$i < 3; $i++){
  1780. $buffer .= "
  1781. <tr><td align='right'>array item (type: $typeDef[arrayType]):</td>
  1782. <td><input type='text' name='parameters[".$name."][]'></td></tr>";
  1783. }
  1784. $buffer .= '</table>';
  1785. // if scalar
  1786. } else {
  1787. $buffer .= "<input type='text' name='parameters[$name]'>";
  1788. }
  1789. } else {
  1790. $buffer .= "<input type='text' name='parameters[$name]'>";
  1791. }
  1792. return $buffer;
  1793. }
  1794. /**
  1795. * adds a complex type to the schema
  1796. *
  1797. * example: array
  1798. *
  1799. * addType(
  1800. * 'ArrayOfstring',
  1801. * 'complexType',
  1802. * 'array',
  1803. * '',
  1804. * 'SOAP-ENC:Array',
  1805. * array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'string[]'),
  1806. * 'xsd:string'
  1807. * );
  1808. *
  1809. * example: PHP associative array ( SOAP Struct )
  1810. *
  1811. * addType(
  1812. * 'SOAPStruct',
  1813. * 'complexType',
  1814. * 'struct',
  1815. * 'all',
  1816. * array('myVar'=> array('name'=>'myVar','type'=>'string')
  1817. * );
  1818. *
  1819. * @param name
  1820. * @param typeClass (complexType|simpleType|attribute)
  1821. * @param phpType: currently supported are array and struct (php assoc array)
  1822. * @param compositor (all|sequence|choice)
  1823. * @param restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
  1824. * @param elements = array ( name = array(name=>'',type=>'') )
  1825. * @param attrs = array(
  1826. * array(
  1827. * 'ref' => "http://schemas.xmlsoap.org/soap/encoding/:arrayType",
  1828. * "http://schemas.xmlsoap.org/wsdl/:arrayType" => "string[]"
  1829. * )
  1830. * )
  1831. * @param arrayType: namespace:name (http://www.w3.org/2001/XMLSchema:string)
  1832. * @access public
  1833. * @see getTypeDef
  1834. */
  1835. function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType=''){
  1836. $this->complexTypes[$name] = array(
  1837. 'name' => $name,
  1838. 'typeClass' => $typeClass,
  1839. 'phpType' => $phpType,
  1840. 'compositor'=> $compositor,
  1841. 'restrictionBase' => $restrictionBase,
  1842. 'elements' => $elements,
  1843. 'attrs' => $attrs,
  1844. 'arrayType' => $arrayType
  1845. );
  1846. $this->xdebug("addComplexType $name:");
  1847. $this->appendDebug($this->varDump($this->complexTypes[$name]));
  1848. }
  1849. /**
  1850. * adds a simple type to the schema
  1851. *
  1852. * @param string $name
  1853. * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
  1854. * @param string $typeClass (should always be simpleType)
  1855. * @param string $phpType (should always be scalar)
  1856. * @param array $enumeration array of values
  1857. * @access public
  1858. * @see nusoap_xmlschema
  1859. * @see getTypeDef
  1860. */
  1861. function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
  1862. $this->simpleTypes[$name] = array(
  1863. 'name' => $name,
  1864. 'typeClass' => $typeClass,
  1865. 'phpType' => $phpType,
  1866. 'type' => $restrictionBase,
  1867. 'enumeration' => $enumeration
  1868. );
  1869. $this->xdebug("addSimpleType $name:");
  1870. $this->appendDebug($this->varDump($this->simpleTypes[$name]));
  1871. }
  1872. /**
  1873. * adds an element to the schema
  1874. *
  1875. * @param array $attrs attributes that must include name and type
  1876. * @see nusoap_xmlschema
  1877. * @access public
  1878. */
  1879. function addElement($attrs) {
  1880. if (! $this->getPrefix($attrs['type'])) {
  1881. $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type'];
  1882. }
  1883. $this->elements[ $attrs['name'] ] = $attrs;
  1884. $this->elements[ $attrs['name'] ]['typeClass'] = 'element';
  1885. $this->xdebug("addElement " . $attrs['name']);
  1886. $this->appendDebug($this->varDump($this->elements[ $attrs['name'] ]));
  1887. }
  1888. }
  1889. /**
  1890. * Backward compatibility
  1891. */
  1892. class XMLSchema extends nusoap_xmlschema {
  1893. }
  1894. ?><?php
  1895. /**
  1896. * For creating serializable abstractions of native PHP types. This class
  1897. * allows element name/namespace, XSD type, and XML attributes to be
  1898. * associated with a value. This is extremely useful when WSDL is not
  1899. * used, but is also useful when WSDL is used with polymorphic types, including
  1900. * xsd:anyType and user-defined types.
  1901. *
  1902. * @author Dietrich Ayala <dietrich@ganx4.com>
  1903. * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $
  1904. * @access public
  1905. */
  1906. class soapval extends nusoap_base {
  1907. /**
  1908. * The XML element name
  1909. *
  1910. * @var string
  1911. * @access private
  1912. */
  1913. var $name;
  1914. /**
  1915. * The XML type name (string or false)
  1916. *
  1917. * @var mixed
  1918. * @access private
  1919. */
  1920. var $type;
  1921. /**
  1922. * The PHP value
  1923. *
  1924. * @var mixed
  1925. * @access private
  1926. */
  1927. var $value;
  1928. /**
  1929. * The XML element namespace (string or false)
  1930. *
  1931. * @var mixed
  1932. * @access private
  1933. */
  1934. var $element_ns;
  1935. /**
  1936. * The XML type namespace (string or false)
  1937. *
  1938. * @var mixed
  1939. * @access private
  1940. */
  1941. var $type_ns;
  1942. /**
  1943. * The XML element attributes (array or false)
  1944. *
  1945. * @var mixed
  1946. * @access private
  1947. */
  1948. var $attributes;
  1949. /**
  1950. * constructor
  1951. *
  1952. * @param string $name optional name
  1953. * @param mixed $type optional type name
  1954. * @param mixed $value optional value
  1955. * @param mixed $element_ns optional namespace of value
  1956. * @param mixed $type_ns optional namespace of type
  1957. * @param mixed $attributes associative array of attributes to add to element serialization
  1958. * @access public
  1959. */
  1960. function soapval($name='soapval',$type=false,$value=-1,$element_ns=false,$type_ns=false,$attributes=false) {
  1961. parent::nusoap_base();
  1962. $this->name = $name;
  1963. $this->type = $type;
  1964. $this->value = $value;
  1965. $this->element_ns = $element_ns;
  1966. $this->type_ns = $type_ns;
  1967. $this->attributes = $attributes;
  1968. }
  1969. /**
  1970. * return serialized value
  1971. *
  1972. * @param string $use The WSDL use value (encoded|literal)
  1973. * @return string XML data
  1974. * @access public
  1975. */
  1976. function serialize($use='encoded') {
  1977. return $this->serialize_val($this->value, $this->name, $this->type, $this->element_ns, $this->type_ns, $this->attributes, $use, true);
  1978. }
  1979. /**
  1980. * decodes a soapval object into a PHP native type
  1981. *
  1982. * @return mixed
  1983. * @access public
  1984. */
  1985. function decode(){
  1986. return $this->value;
  1987. }
  1988. }
  1989. ?><?php
  1990. /**
  1991. * transport class for sending/receiving data via HTTP and HTTPS
  1992. * NOTE: PHP must be compiled with the CURL extension for HTTPS support
  1993. *
  1994. * @author Dietrich Ayala <dietrich@ganx4.com>
  1995. * @author Scott Nichol <snichol@users.sourceforge.net>
  1996. * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $
  1997. * @access public
  1998. */
  1999. class soap_transport_http extends nusoap_base {
  2000. var $url = '';
  2001. var $uri = '';
  2002. var $digest_uri = '';
  2003. var $scheme = '';
  2004. var $host = '';
  2005. var $port = '';
  2006. var $path = '';
  2007. var $request_method = 'POST';
  2008. var $protocol_version = '1.0';
  2009. var $encoding = '';
  2010. var $outgoing_headers = array();
  2011. var $incoming_headers = array();
  2012. var $incoming_cookies = array();
  2013. var $outgoing_payload = '';
  2014. var $incoming_payload = '';
  2015. var $response_status_line; // HTTP response status line
  2016. var $useSOAPAction = true;
  2017. var $persistentConnection = false;
  2018. var $ch = false; // cURL handle
  2019. var $ch_options = array(); // cURL custom options
  2020. var $use_curl = false; // force cURL use
  2021. var $proxy = null; // proxy information (associative array)
  2022. var $username = '';
  2023. var $password = '';
  2024. var $authtype = '';
  2025. var $digestRequest = array();
  2026. var $certRequest = array(); // keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional)
  2027. // cainfofile: certificate authority file, e.g. '$pathToPemFiles/rootca.pem'
  2028. // sslcertfile: SSL certificate file, e.g. '$pathToPemFiles/mycert.pem'
  2029. // sslkeyfile: SSL key file, e.g. '$pathToPemFiles/mykey.pem'
  2030. // passphrase: SSL key password/passphrase
  2031. // certpassword: SSL certificate password
  2032. // verifypeer: default is 1
  2033. // verifyhost: default is 1
  2034. /**
  2035. * constructor
  2036. *
  2037. * @param string $url The URL to which to connect
  2038. * @param array $curl_options User-specified cURL options
  2039. * @param boolean $use_curl Whether to try to force cURL use
  2040. * @access public
  2041. */
  2042. function soap_transport_http($url, $curl_options = NULL, $use_curl = false){
  2043. parent::nusoap_base();
  2044. $this->debug("ctor url=$url use_curl=$use_curl curl_options:");
  2045. $this->appendDebug($this->varDump($curl_options));
  2046. $this->setURL($url);
  2047. if (is_array($curl_options)) {
  2048. $this->ch_options = $curl_options;
  2049. }
  2050. $this->use_curl = $use_curl;
  2051. ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev);
  2052. $this->setHeader('User-Agent', $this->title.'/'.$this->version.' ('.$rev[1].')');
  2053. }
  2054. /**
  2055. * sets a cURL option
  2056. *
  2057. * @param mixed $option The cURL option (always integer?)
  2058. * @param mixed $value The cURL option value
  2059. * @access private
  2060. */
  2061. function setCurlOption($option, $value) {
  2062. $this->debug("setCurlOption option=$option, value=");
  2063. $this->appendDebug($this->varDump($value));
  2064. curl_setopt($this->ch, $option, $value);
  2065. }
  2066. /**
  2067. * sets an HTTP header
  2068. *
  2069. * @param string $name The name of the header
  2070. * @param string $value The value of the header
  2071. * @access private
  2072. */
  2073. function setHeader($name, $value) {
  2074. $this->outgoing_headers[$name] = $value;
  2075. $this->debug("set header $name: $value");
  2076. }
  2077. /**
  2078. * unsets an HTTP header
  2079. *
  2080. * @param string $name The name of the header
  2081. * @access private
  2082. */
  2083. function unsetHeader($name) {
  2084. if (isset($this->outgoing_headers[$name])) {
  2085. $this->debug("unset header $name");
  2086. unset($this->outgoing_headers[$name]);
  2087. }
  2088. }
  2089. /**
  2090. * sets the URL to which to connect
  2091. *
  2092. * @param string $url The URL to which to connect
  2093. * @access private
  2094. */
  2095. function setURL($url) {
  2096. $this->url = $url;
  2097. $u = parse_url($url);
  2098. foreach($u as $k => $v){
  2099. $this->debug("parsed URL $k = $v");
  2100. $this->$k = $v;
  2101. }
  2102. // add any GET params to path
  2103. if(isset($u['query']) && $u['query'] != ''){
  2104. $this->path .= '?' . $u['query'];
  2105. }
  2106. // set default port
  2107. if(!isset($u['port'])){
  2108. if($u['scheme'] == 'https'){
  2109. $this->port = 443;
  2110. } else {
  2111. $this->port = 80;
  2112. }
  2113. }
  2114. $this->uri = $this->path;
  2115. $this->digest_uri = $this->uri;
  2116. // build headers
  2117. if (!isset($u['port'])) {
  2118. $this->setHeader('Host', $this->host);
  2119. } else {
  2120. $this->setHeader('Host', $this->host.':'.$this->port);
  2121. }
  2122. if (isset($u['user']) && $u['user'] != '') {
  2123. $this->setCredentials(urldecode($u['user']), isset($u['pass']) ? urldecode($u['pass']) : '');
  2124. }
  2125. }
  2126. /**
  2127. * gets the I/O method to use
  2128. *
  2129. * @return string I/O method to use (socket|curl|unknown)
  2130. * @access private
  2131. */
  2132. function io_method() {
  2133. if ($this->use_curl || ($this->scheme == 'https') || ($this->scheme == 'http' && $this->authtype == 'ntlm') || ($this->scheme == 'http' && is_array($this->proxy) && $this->proxy['authtype'] == 'ntlm'))
  2134. return 'curl';
  2135. if (($this->scheme == 'http' || $this->scheme == 'ssl') && $this->authtype != 'ntlm' && (!is_array($this->proxy) || $this->proxy['authtype'] != 'ntlm'))
  2136. return 'socket';
  2137. return 'unknown';
  2138. }
  2139. /**
  2140. * establish an HTTP connection
  2141. *
  2142. * @param integer $timeout set connection timeout in seconds
  2143. * @param integer $response_timeout set response timeout in seconds
  2144. * @return boolean true if connected, false if not
  2145. * @access private
  2146. */
  2147. function connect($connection_timeout=0,$response_timeout=30){
  2148. // For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like
  2149. // "regular" socket.
  2150. // TODO: disabled for now because OpenSSL must be *compiled* in (not just
  2151. // loaded), and until PHP5 stream_get_wrappers is not available.
  2152. // if ($this->scheme == 'https') {
  2153. // if (version_compare(phpversion(), '4.3.0') >= 0) {
  2154. // if (extension_loaded('openssl')) {
  2155. // $this->scheme = 'ssl';
  2156. // $this->debug('Using SSL over OpenSSL');
  2157. // }
  2158. // }
  2159. // }
  2160. $this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port");
  2161. if ($this->io_method() == 'socket') {
  2162. if (!is_array($this->proxy)) {
  2163. $host = $this->host;
  2164. $port = $this->port;
  2165. } else {
  2166. $host = $this->proxy['host'];
  2167. $port = $this->proxy['port'];
  2168. }
  2169. // use persistent connection
  2170. if($this->persistentConnection && isset($this->fp) && is_resource($this->fp)){
  2171. if (!feof($this->fp)) {
  2172. $this->debug('Re-use persistent connection');
  2173. return true;
  2174. }
  2175. fclose($this->fp);
  2176. $this->debug('Closed persistent connection at EOF');
  2177. }
  2178. // munge host if using OpenSSL
  2179. if ($this->scheme == 'ssl') {
  2180. $host = 'ssl://' . $host;
  2181. }
  2182. $this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout);
  2183. // open socket
  2184. if($connection_timeout > 0){
  2185. $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str, $connection_timeout);
  2186. } else {
  2187. $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str);
  2188. }
  2189. // test pointer
  2190. if(!$this->fp) {
  2191. $msg = 'Couldn\'t open socket connection to server ' . $this->url;
  2192. if ($this->errno) {
  2193. $msg .= ', Error ('.$this->errno.'): '.$this->error_str;
  2194. } else {
  2195. $msg .= ' prior to connect(). This is often a problem looking up the host name.';
  2196. }
  2197. $this->debug($msg);
  2198. $this->setError($msg);
  2199. return false;
  2200. }
  2201. // set response timeout
  2202. $this->debug('set response timeout to ' . $response_timeout);
  2203. socket_set_timeout( $this->fp, $response_timeout);
  2204. $this->debug('socket connected');
  2205. return true;
  2206. } else if ($this->io_method() == 'curl') {
  2207. if (!extension_loaded('curl')) {
  2208. // $this->setError('cURL Extension, or OpenSSL extension w/ PHP version >= 4.3 is required for HTTPS');
  2209. $this->setError('The PHP cURL Extension is required for HTTPS or NLTM. You will need to re-build or update your PHP to included cURL.');
  2210. return false;
  2211. }
  2212. // Avoid warnings when PHP does not have these options
  2213. if (defined('CURLOPT_CONNECTIONTIMEOUT'))
  2214. $CURLOPT_CONNECTIONTIMEOUT = CURLOPT_CONNECTIONTIMEOUT;
  2215. else
  2216. $CURLOPT_CONNECTIONTIMEOUT = 78;
  2217. if (defined('CURLOPT_HTTPAUTH'))
  2218. $CURLOPT_HTTPAUTH = CURLOPT_HTTPAUTH;
  2219. else
  2220. $CURLOPT_HTTPAUTH = 107;
  2221. if (defined('CURLOPT_PROXYAUTH'))
  2222. $CURLOPT_PROXYAUTH = CURLOPT_PROXYAUTH;
  2223. else
  2224. $CURLOPT_PROXYAUTH = 111;
  2225. if (defined('CURLAUTH_BASIC'))
  2226. $CURLAUTH_BASIC = CURLAUTH_BASIC;
  2227. else
  2228. $CURLAUTH_BASIC = 1;
  2229. if (defined('CURLAUTH_DIGEST'))
  2230. $CURLAUTH_DIGEST = CURLAUTH_DIGEST;
  2231. else
  2232. $CURLAUTH_DIGEST = 2;
  2233. if (defined('CURLAUTH_NTLM'))
  2234. $CURLAUTH_NTLM = CURLAUTH_NTLM;
  2235. else
  2236. $CURLAUTH_NTLM = 8;
  2237. $this->debug('connect using cURL');
  2238. // init CURL
  2239. $this->ch = curl_init();
  2240. // set url
  2241. $hostURL = ($this->port != '') ? "$this->scheme://$this->host:$this->port" : "$this->scheme://$this->host";
  2242. // add path
  2243. $hostURL .= $this->path;
  2244. $this->setCurlOption(CURLOPT_URL, $hostURL);
  2245. // follow location headers (re-directs)
  2246. if (ini_get('safe_mode') || ini_get('open_basedir')) {
  2247. $this->debug('safe_mode or open_basedir set, so do not set CURLOPT_FOLLOWLOCATION');
  2248. $this->debug('safe_mode = ');
  2249. $this->appendDebug($this->varDump(ini_get('safe_mode')));
  2250. $this->debug('open_basedir = ');
  2251. $this->appendDebug($this->varDump(ini_get('open_basedir')));
  2252. } else {
  2253. $this->setCurlOption(CURLOPT_FOLLOWLOCATION, 1);
  2254. }
  2255. // ask for headers in the response output
  2256. $this->setCurlOption(CURLOPT_HEADER, 1);
  2257. // ask for the response output as the return value
  2258. $this->setCurlOption(CURLOPT_RETURNTRANSFER, 1);
  2259. // encode
  2260. // We manage this ourselves through headers and encoding
  2261. // if(function_exists('gzuncompress')){
  2262. // $this->setCurlOption(CURLOPT_ENCODING, 'deflate');
  2263. // }
  2264. // persistent connection
  2265. if ($this->persistentConnection) {
  2266. // I believe the following comment is now bogus, having applied to
  2267. // the code when it used CURLOPT_CUSTOMREQUEST to send the request.
  2268. // The way we send data, we cannot use persistent connections, since
  2269. // there will be some "junk" at the end of our request.
  2270. //$this->setCurlOption(CURL_HTTP_VERSION_1_1, true);
  2271. $this->persistentConnection = false;
  2272. $this->setHeader('Connection', 'close');
  2273. }
  2274. // set timeouts
  2275. if ($connection_timeout != 0) {
  2276. $this->setCurlOption($CURLOPT_CONNECTIONTIMEOUT, $connection_timeout);
  2277. }
  2278. if ($response_timeout != 0) {
  2279. $this->setCurlOption(CURLOPT_TIMEOUT, $response_timeout);
  2280. }
  2281. if ($this->scheme == 'https') {
  2282. $this->debug('set cURL SSL verify options');
  2283. // recent versions of cURL turn on peer/host checking by default,
  2284. // while PHP binaries are not compiled with a default location for the
  2285. // CA cert bundle, so disable peer/host checking.
  2286. //$this->setCurlOption(CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt');
  2287. $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 0);
  2288. $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 0);
  2289. // support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo)
  2290. if ($this->authtype == 'certificate') {
  2291. $this->debug('set cURL certificate options');
  2292. if (isset($this->certRequest['cainfofile'])) {
  2293. $this->setCurlOption(CURLOPT_CAINFO, $this->certRequest['cainfofile']);
  2294. }
  2295. if (isset($this->certRequest['verifypeer'])) {
  2296. $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, $this->certRequest['verifypeer']);
  2297. } else {
  2298. $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 1);
  2299. }
  2300. if (isset($this->certRequest['verifyhost'])) {
  2301. $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, $this->certRequest['verifyhost']);
  2302. } else {
  2303. $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 1);
  2304. }
  2305. if (isset($this->certRequest['sslcertfile'])) {
  2306. $this->setCurlOption(CURLOPT_SSLCERT, $this->certRequest['sslcertfile']);
  2307. }
  2308. if (isset($this->certRequest['sslkeyfile'])) {
  2309. $this->setCurlOption(CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']);
  2310. }
  2311. if (isset($this->certRequest['passphrase'])) {
  2312. $this->setCurlOption(CURLOPT_SSLKEYPASSWD, $this->certRequest['passphrase']);
  2313. }
  2314. if (isset($this->certRequest['certpassword'])) {
  2315. $this->setCurlOption(CURLOPT_SSLCERTPASSWD, $this->certRequest['certpassword']);
  2316. }
  2317. }
  2318. }
  2319. if ($this->authtype && ($this->authtype != 'certificate')) {
  2320. if ($this->username) {
  2321. $this->debug('set cURL username/password');
  2322. $this->setCurlOption(CURLOPT_USERPWD, "$this->username:$this->password");
  2323. }
  2324. if ($this->authtype == 'basic') {
  2325. $this->debug('set cURL for Basic authentication');
  2326. $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_BASIC);
  2327. }
  2328. if ($this->authtype == 'digest') {
  2329. $this->debug('set cURL for digest authentication');
  2330. $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_DIGEST);
  2331. }
  2332. if ($this->authtype == 'ntlm') {
  2333. $this->debug('set cURL for NTLM authentication');
  2334. $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_NTLM);
  2335. }
  2336. }
  2337. if (is_array($this->proxy)) {
  2338. $this->debug('set cURL proxy options');
  2339. if ($this->proxy['port'] != '') {
  2340. $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host'].':'.$this->proxy['port']);
  2341. } else {
  2342. $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host']);
  2343. }
  2344. if ($this->proxy['username'] || $this->proxy['password']) {
  2345. $this->debug('set cURL proxy authentication options');
  2346. $this->setCurlOption(CURLOPT_PROXYUSERPWD, $this->proxy['username'].':'.$this->proxy['password']);
  2347. if ($this->proxy['authtype'] == 'basic') {
  2348. $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_BASIC);
  2349. }
  2350. if ($this->proxy['authtype'] == 'ntlm') {
  2351. $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_NTLM);
  2352. }
  2353. }
  2354. }
  2355. $this->debug('cURL connection set up');
  2356. return true;
  2357. } else {
  2358. $this->setError('Unknown scheme ' . $this->scheme);
  2359. $this->debug('Unknown scheme ' . $this->scheme);
  2360. return false;
  2361. }
  2362. }
  2363. /**
  2364. * sends the SOAP request and gets the SOAP response via HTTP[S]
  2365. *
  2366. * @param string $data message data
  2367. * @param integer $timeout set connection timeout in seconds
  2368. * @param integer $response_timeout set response timeout in seconds
  2369. * @param array $cookies cookies to send
  2370. * @return string data
  2371. * @access public
  2372. */
  2373. function send($data, $timeout=0, $response_timeout=30, $cookies=NULL) {
  2374. $this->debug('entered send() with data of length: '.strlen($data));
  2375. $this->tryagain = true;
  2376. $tries = 0;
  2377. while ($this->tryagain) {
  2378. $this->tryagain = false;
  2379. if ($tries++ < 2) {
  2380. // make connnection
  2381. if (!$this->connect($timeout, $response_timeout)){
  2382. return false;
  2383. }
  2384. // send request
  2385. if (!$this->sendRequest($data, $cookies)){
  2386. return false;
  2387. }
  2388. // get response
  2389. $respdata = $this->getResponse();
  2390. } else {
  2391. $this->setError("Too many tries to get an OK response ($this->response_status_line)");
  2392. }
  2393. }
  2394. $this->debug('end of send()');
  2395. return $respdata;
  2396. }
  2397. /**
  2398. * sends the SOAP request and gets the SOAP response via HTTPS using CURL
  2399. *
  2400. * @param string $data message data
  2401. * @param integer $timeout set connection timeout in seconds
  2402. * @param integer $response_timeout set response timeout in seconds
  2403. * @param array $cookies cookies to send
  2404. * @return string data
  2405. * @access public
  2406. * @deprecated
  2407. */
  2408. function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) {
  2409. return $this->send($data, $timeout, $response_timeout, $cookies);
  2410. }
  2411. /**
  2412. * if authenticating, set user credentials here
  2413. *
  2414. * @param string $username
  2415. * @param string $password
  2416. * @param string $authtype (basic|digest|certificate|ntlm)
  2417. * @param array $digestRequest (keys must be nonce, nc, realm, qop)
  2418. * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
  2419. * @access public
  2420. */
  2421. function setCredentials($username, $password, $authtype = 'basic', $digestRequest = array(), $certRequest = array()) {
  2422. $this->debug("setCredentials username=$username authtype=$authtype digestRequest=");
  2423. $this->appendDebug($this->varDump($digestRequest));
  2424. $this->debug("certRequest=");
  2425. $this->appendDebug($this->varDump($certRequest));
  2426. // cf. RFC 2617
  2427. if ($authtype == 'basic') {
  2428. $this->setHeader('Authorization', 'Basic '.base64_encode(str_replace(':','',$username).':'.$password));
  2429. } elseif ($authtype == 'digest') {
  2430. if (isset($digestRequest['nonce'])) {
  2431. $digestRequest['nc'] = isset($digestRequest['nc']) ? $digestRequest['nc']++ : 1;
  2432. // calculate the Digest hashes (calculate code based on digest implementation found at: http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html)
  2433. // A1 = unq(username-value) ":" unq(realm-value) ":" passwd
  2434. $A1 = $username. ':' . (isset($digestRequest['realm']) ? $digestRequest['realm'] : '') . ':' . $password;
  2435. // H(A1) = MD5(A1)
  2436. $HA1 = md5($A1);
  2437. // A2 = Method ":" digest-uri-value
  2438. $A2 = $this->request_method . ':' . $this->digest_uri;
  2439. // H(A2)
  2440. $HA2 = md5($A2);
  2441. // KD(secret, data) = H(concat(secret, ":", data))
  2442. // if qop == auth:
  2443. // request-digest = <"> < KD ( H(A1), unq(nonce-value)
  2444. // ":" nc-value
  2445. // ":" unq(cnonce-value)
  2446. // ":" unq(qop-value)
  2447. // ":" H(A2)
  2448. // ) <">
  2449. // if qop is missing,
  2450. // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <">
  2451. $unhashedDigest = '';
  2452. $nonce = isset($digestRequest['nonce']) ? $digestRequest['nonce'] : '';
  2453. $cnonce = $nonce;
  2454. if ($digestRequest['qop'] != '') {
  2455. $unhashedDigest = $HA1 . ':' . $nonce . ':' . sprintf("%08d", $digestRequest['nc']) . ':' . $cnonce . ':' . $digestRequest['qop'] . ':' . $HA2;
  2456. } else {
  2457. $unhashedDigest = $HA1 . ':' . $nonce . ':' . $HA2;
  2458. }
  2459. $hashedDigest = md5($unhashedDigest);
  2460. $opaque = '';
  2461. if (isset($digestRequest['opaque'])) {
  2462. $opaque = ', opaque="' . $digestRequest['opaque'] . '"';
  2463. }
  2464. $this->setHeader('Authorization', 'Digest username="' . $username . '", realm="' . $digestRequest['realm'] . '", nonce="' . $nonce . '", uri="' . $this->digest_uri . $opaque . '", cnonce="' . $cnonce . '", nc=' . sprintf("%08x", $digestRequest['nc']) . ', qop="' . $digestRequest['qop'] . '", response="' . $hashedDigest . '"');
  2465. }
  2466. } elseif ($authtype == 'certificate') {
  2467. $this->certRequest = $certRequest;
  2468. $this->debug('Authorization header not set for certificate');
  2469. } elseif ($authtype == 'ntlm') {
  2470. // do nothing
  2471. $this->debug('Authorization header not set for ntlm');
  2472. }
  2473. $this->username = $username;
  2474. $this->password = $password;
  2475. $this->authtype = $authtype;
  2476. $this->digestRequest = $digestRequest;
  2477. }
  2478. /**
  2479. * set the soapaction value
  2480. *
  2481. * @param string $soapaction
  2482. * @access public
  2483. */
  2484. function setSOAPAction($soapaction) {
  2485. $this->setHeader('SOAPAction', '"' . $soapaction . '"');
  2486. }
  2487. /**
  2488. * use http encoding
  2489. *
  2490. * @param string $enc encoding style. supported values: gzip, deflate, or both
  2491. * @access public
  2492. */
  2493. function setEncoding($enc='gzip, deflate') {
  2494. if (function_exists('gzdeflate')) {
  2495. $this->protocol_version = '1.1';
  2496. $this->setHeader('Accept-Encoding', $enc);
  2497. if (!isset($this->outgoing_headers['Connection'])) {
  2498. $this->setHeader('Connection', 'close');
  2499. $this->persistentConnection = false;
  2500. }
  2501. set_magic_quotes_runtime(0);
  2502. // deprecated
  2503. $this->encoding = $enc;
  2504. }
  2505. }
  2506. /**
  2507. * set proxy info here
  2508. *
  2509. * @param string $proxyhost use an empty string to remove proxy
  2510. * @param string $proxyport
  2511. * @param string $proxyusername
  2512. * @param string $proxypassword
  2513. * @param string $proxyauthtype (basic|ntlm)
  2514. * @access public
  2515. */
  2516. function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 'basic') {
  2517. if ($proxyhost) {
  2518. $this->proxy = array(
  2519. 'host' => $proxyhost,
  2520. 'port' => $proxyport,
  2521. 'username' => $proxyusername,
  2522. 'password' => $proxypassword,
  2523. 'authtype' => $proxyauthtype
  2524. );
  2525. if ($proxyusername != '' && $proxypassword != '' && $proxyauthtype = 'basic') {
  2526. $this->setHeader('Proxy-Authorization', ' Basic '.base64_encode($proxyusername.':'.$proxypassword));
  2527. }
  2528. } else {
  2529. $this->debug('remove proxy');
  2530. $proxy = null;
  2531. unsetHeader('Proxy-Authorization');
  2532. }
  2533. }
  2534. /**
  2535. * Test if the given string starts with a header that is to be skipped.
  2536. * Skippable headers result from chunked transfer and proxy requests.
  2537. *
  2538. * @param string $data The string to check.
  2539. * @returns boolean Whether a skippable header was found.
  2540. * @access private
  2541. */
  2542. function isSkippableCurlHeader(&$data) {
  2543. $skipHeaders = array( 'HTTP/1.1 100',
  2544. 'HTTP/1.0 301',
  2545. 'HTTP/1.1 301',
  2546. 'HTTP/1.0 302',
  2547. 'HTTP/1.1 302',
  2548. 'HTTP/1.0 401',
  2549. 'HTTP/1.1 401',
  2550. 'HTTP/1.0 200 Connection established');
  2551. foreach ($skipHeaders as $hd) {
  2552. $prefix = substr($data, 0, strlen($hd));
  2553. if ($prefix == $hd) return true;
  2554. }
  2555. return false;
  2556. }
  2557. /**
  2558. * decode a string that is encoded w/ "chunked' transfer encoding
  2559. * as defined in RFC2068 19.4.6
  2560. *
  2561. * @param string $buffer
  2562. * @param string $lb
  2563. * @returns string
  2564. * @access public
  2565. * @deprecated
  2566. */
  2567. function decodeChunked($buffer, $lb){
  2568. // length := 0
  2569. $length = 0;
  2570. $new = '';
  2571. // read chunk-size, chunk-extension (if any) and CRLF
  2572. // get the position of the linebreak
  2573. $chunkend = strpos($buffer, $lb);
  2574. if ($chunkend == FALSE) {
  2575. $this->debug('no linebreak found in decodeChunked');
  2576. return $new;
  2577. }
  2578. $temp = substr($buffer,0,$chunkend);
  2579. $chunk_size = hexdec( trim($temp) );
  2580. $chunkstart = $chunkend + strlen($lb);
  2581. // while (chunk-size > 0) {
  2582. while ($chunk_size > 0) {
  2583. $this->debug("chunkstart: $chunkstart chunk_size: $chunk_size");
  2584. $chunkend = strpos( $buffer, $lb, $chunkstart + $chunk_size);
  2585. // Just in case we got a broken connection
  2586. if ($chunkend == FALSE) {
  2587. $chunk = substr($buffer,$chunkstart);
  2588. // append chunk-data to entity-body
  2589. $new .= $chunk;
  2590. $length += strlen($chunk);
  2591. break;
  2592. }
  2593. // read chunk-data and CRLF
  2594. $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart);
  2595. // append chunk-data to entity-body
  2596. $new .= $chunk;
  2597. // length := length + chunk-size
  2598. $length += strlen($chunk);
  2599. // read chunk-size and CRLF
  2600. $chunkstart = $chunkend + strlen($lb);
  2601. $chunkend = strpos($buffer, $lb, $chunkstart) + strlen($lb);
  2602. if ($chunkend == FALSE) {
  2603. break; //Just in case we got a broken connection
  2604. }
  2605. $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);
  2606. $chunk_size = hexdec( trim($temp) );
  2607. $chunkstart = $chunkend;
  2608. }
  2609. return $new;
  2610. }
  2611. /**
  2612. * Writes the payload, including HTTP headers, to $this->outgoing_payload.
  2613. *
  2614. * @param string $data HTTP body
  2615. * @param string $cookie_str data for HTTP Cookie header
  2616. * @return void
  2617. * @access private
  2618. */
  2619. function buildPayload($data, $cookie_str = '') {
  2620. // Note: for cURL connections, $this->outgoing_payload is ignored,
  2621. // as is the Content-Length header, but these are still created as
  2622. // debugging guides.
  2623. // add content-length header
  2624. $this->setHeader('Content-Length', strlen($data));
  2625. // start building outgoing payload:
  2626. if ($this->proxy) {
  2627. $uri = $this->url;
  2628. } else {
  2629. $uri = $this->uri;
  2630. }
  2631. $req = "$this->request_method $uri HTTP/$this->protocol_version";
  2632. $this->debug("HTTP request: $req");
  2633. $this->outgoing_payload = "$req\r\n";
  2634. // loop thru headers, serializing
  2635. foreach($this->outgoing_headers as $k => $v){
  2636. $hdr = $k.': '.$v;
  2637. $this->debug("HTTP header: $hdr");
  2638. $this->outgoing_payload .= "$hdr\r\n";
  2639. }
  2640. // add any cookies
  2641. if ($cookie_str != '') {
  2642. $hdr = 'Cookie: '.$cookie_str;
  2643. $this->debug("HTTP header: $hdr");
  2644. $this->outgoing_payload .= "$hdr\r\n";
  2645. }
  2646. // header/body separator
  2647. $this->outgoing_payload .= "\r\n";
  2648. // add data
  2649. $this->outgoing_payload .= $data;
  2650. }
  2651. /**
  2652. * sends the SOAP request via HTTP[S]
  2653. *
  2654. * @param string $data message data
  2655. * @param array $cookies cookies to send
  2656. * @return boolean true if OK, false if problem
  2657. * @access private
  2658. */
  2659. function sendRequest($data, $cookies = NULL) {
  2660. // build cookie string
  2661. $cookie_str = $this->getCookiesForRequest($cookies, (($this->scheme == 'ssl') || ($this->scheme == 'https')));
  2662. // build payload
  2663. $this->buildPayload($data, $cookie_str);
  2664. if ($this->io_method() == 'socket') {
  2665. // send payload
  2666. if(!fputs($this->fp, $this->outgoing_payload, strlen($this->outgoing_payload))) {
  2667. $this->setError('couldn\'t write message data to socket');
  2668. $this->debug('couldn\'t write message data to socket');
  2669. return false;
  2670. }
  2671. $this->debug('wrote data to socket, length = ' . strlen($this->outgoing_payload));
  2672. return true;
  2673. } else if ($this->io_method() == 'curl') {
  2674. // set payload
  2675. // cURL does say this should only be the verb, and in fact it
  2676. // turns out that the URI and HTTP version are appended to this, which
  2677. // some servers refuse to work with (so we no longer use this method!)
  2678. //$this->setCurlOption(CURLOPT_CUSTOMREQUEST, $this->outgoing_payload);
  2679. $curl_headers = array();
  2680. foreach($this->outgoing_headers as $k => $v){
  2681. if ($k == 'Connection' || $k == 'Content-Length' || $k == 'Host' || $k == 'Authorization' || $k == 'Proxy-Authorization') {
  2682. $this->debug("Skip cURL header $k: $v");
  2683. } else {
  2684. $curl_headers[] = "$k: $v";
  2685. }
  2686. }
  2687. if ($cookie_str != '') {
  2688. $curl_headers[] = 'Cookie: ' . $cookie_str;
  2689. }
  2690. $this->setCurlOption(CURLOPT_HTTPHEADER, $curl_headers);
  2691. $this->debug('set cURL HTTP headers');
  2692. if ($this->request_method == "POST") {
  2693. $this->setCurlOption(CURLOPT_POST, 1);
  2694. $this->setCurlOption(CURLOPT_POSTFIELDS, $data);
  2695. $this->debug('set cURL POST data');
  2696. } else {
  2697. }
  2698. // insert custom user-set cURL options
  2699. foreach ($this->ch_options as $key => $val) {
  2700. $this->setCurlOption($key, $val);
  2701. }
  2702. $this->debug('set cURL payload');
  2703. return true;
  2704. }
  2705. }
  2706. /**
  2707. * gets the SOAP response via HTTP[S]
  2708. *
  2709. * @return string the response (also sets member variables like incoming_payload)
  2710. * @access private
  2711. */
  2712. function getResponse(){
  2713. $this->incoming_payload = '';
  2714. if ($this->io_method() == 'socket') {
  2715. // loop until headers have been retrieved
  2716. $data = '';
  2717. while (!isset($lb)){
  2718. // We might EOF during header read.
  2719. if(feof($this->fp)) {
  2720. $this->incoming_payload = $data;
  2721. $this->debug('found no headers before EOF after length ' . strlen($data));
  2722. $this->debug("received before EOF:\n" . $data);
  2723. $this->setError('server failed to send headers');
  2724. return false;
  2725. }
  2726. $tmp = fgets($this->fp, 256);
  2727. $tmplen = strlen($tmp);
  2728. $this->debug("read line of $tmplen bytes: " . trim($tmp));
  2729. if ($tmplen == 0) {
  2730. $this->incoming_payload = $data;
  2731. $this->debug('socket read of headers timed out after length ' . strlen($data));
  2732. $this->debug("read before timeout: " . $data);
  2733. $this->setError('socket read of headers timed out');
  2734. return false;
  2735. }
  2736. $data .= $tmp;
  2737. $pos = strpos($data,"\r\n\r\n");
  2738. if($pos > 1){
  2739. $lb = "\r\n";
  2740. } else {
  2741. $pos = strpos($data,"\n\n");
  2742. if($pos > 1){
  2743. $lb = "\n";
  2744. }
  2745. }
  2746. // remove 100 headers
  2747. if (isset($lb) && ereg('^HTTP/1.1 100',$data)) {
  2748. unset($lb);
  2749. $data = '';
  2750. }//
  2751. }
  2752. // store header data
  2753. $this->incoming_payload .= $data;
  2754. $this->debug('found end of headers after length ' . strlen($data));
  2755. // process headers
  2756. $header_data = trim(substr($data,0,$pos));
  2757. $header_array = explode($lb,$header_data);
  2758. $this->incoming_headers = array();
  2759. $this->incoming_cookies = array();
  2760. foreach($header_array as $header_line){
  2761. $arr = explode(':',$header_line, 2);
  2762. if(count($arr) > 1){
  2763. $header_name = strtolower(trim($arr[0]));
  2764. $this->incoming_headers[$header_name] = trim($arr[1]);
  2765. if ($header_name == 'set-cookie') {
  2766. // TODO: allow multiple cookies from parseCookie
  2767. $cookie = $this->parseCookie(trim($arr[1]));
  2768. if ($cookie) {
  2769. $this->incoming_cookies[] = $cookie;
  2770. $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']);
  2771. } else {
  2772. $this->debug('did not find cookie in ' . trim($arr[1]));
  2773. }
  2774. }
  2775. } else if (isset($header_name)) {
  2776. // append continuation line to previous header
  2777. $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line;
  2778. }
  2779. }
  2780. // loop until msg has been received
  2781. if (isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked') {
  2782. $content_length = 2147483647; // ignore any content-length header
  2783. $chunked = true;
  2784. $this->debug("want to read chunked content");
  2785. } elseif (isset($this->incoming_headers['content-length'])) {
  2786. $content_length = $this->incoming_headers['content-length'];
  2787. $chunked = false;
  2788. $this->debug("want to read content of length $content_length");
  2789. } else {
  2790. $content_length = 2147483647;
  2791. $chunked = false;
  2792. $this->debug("want to read content to EOF");
  2793. }
  2794. $data = '';
  2795. do {
  2796. if ($chunked) {
  2797. $tmp = fgets($this->fp, 256);
  2798. $tmplen = strlen($tmp);
  2799. $this->debug("read chunk line of $tmplen bytes");
  2800. if ($tmplen == 0) {
  2801. $this->incoming_payload = $data;
  2802. $this->debug('socket read of chunk length timed out after length ' . strlen($data));
  2803. $this->debug("read before timeout:\n" . $data);
  2804. $this->setError('socket read of chunk length timed out');
  2805. return false;
  2806. }
  2807. $content_length = hexdec(trim($tmp));
  2808. $this->debug("chunk length $content_length");
  2809. }
  2810. $strlen = 0;
  2811. while (($strlen < $content_length) && (!feof($this->fp))) {
  2812. $readlen = min(8192, $content_length - $strlen);
  2813. $tmp = fread($this->fp, $readlen);
  2814. $tmplen = strlen($tmp);
  2815. $this->debug("read buffer of $tmplen bytes");
  2816. if (($tmplen == 0) && (!feof($this->fp))) {
  2817. $this->incoming_payload = $data;
  2818. $this->debug('socket read of body timed out after length ' . strlen($data));
  2819. $this->debug("read before timeout:\n" . $data);
  2820. $this->setError('socket read of body timed out');
  2821. return false;
  2822. }
  2823. $strlen += $tmplen;
  2824. $data .= $tmp;
  2825. }
  2826. if ($chunked && ($content_length > 0)) {
  2827. $tmp = fgets($this->fp, 256);
  2828. $tmplen = strlen($tmp);
  2829. $this->debug("read chunk terminator of $tmplen bytes");
  2830. if ($tmplen == 0) {
  2831. $this->incoming_payload = $data;
  2832. $this->debug('socket read of chunk terminator timed out after length ' . strlen($data));
  2833. $this->debug("read before timeout:\n" . $data);
  2834. $this->setError('socket read of chunk terminator timed out');
  2835. return false;
  2836. }
  2837. }
  2838. } while ($chunked && ($content_length > 0) && (!feof($this->fp)));
  2839. if (feof($this->fp)) {
  2840. $this->debug('read to EOF');
  2841. }
  2842. $this->debug('read body of length ' . strlen($data));
  2843. $this->incoming_payload .= $data;
  2844. $this->debug('received a total of '.strlen($this->incoming_payload).' bytes of data from server');
  2845. // close filepointer
  2846. if(
  2847. (isset($this->incoming_headers['connection']) && strtolower($this->incoming_headers['connection']) == 'close') ||
  2848. (! $this->persistentConnection) || feof($this->fp)){
  2849. fclose($this->fp);
  2850. $this->fp = false;
  2851. $this->debug('closed socket');
  2852. }
  2853. // connection was closed unexpectedly
  2854. if($this->incoming_payload == ''){
  2855. $this->setError('no response from server');
  2856. return false;
  2857. }
  2858. // decode transfer-encoding
  2859. // if(isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked'){
  2860. // if(!$data = $this->decodeChunked($data, $lb)){
  2861. // $this->setError('Decoding of chunked data failed');
  2862. // return false;
  2863. // }
  2864. //print "<pre>\nde-chunked:\n---------------\n$data\n\n---------------\n</pre>";
  2865. // set decoded payload
  2866. // $this->incoming_payload = $header_data.$lb.$lb.$data;
  2867. // }
  2868. } else if ($this->io_method() == 'curl') {
  2869. // send and receive
  2870. $this->debug('send and receive with cURL');
  2871. $this->incoming_payload = curl_exec($this->ch);
  2872. $data = $this->incoming_payload;
  2873. $cErr = curl_error($this->ch);
  2874. if ($cErr != '') {
  2875. $err = 'cURL ERROR: '.curl_errno($this->ch).': '.$cErr.'<br>';
  2876. // TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE
  2877. foreach(curl_getinfo($this->ch) as $k => $v){
  2878. $err .= "$k: $v<br>";
  2879. }
  2880. $this->debug($err);
  2881. $this->setError($err);
  2882. curl_close($this->ch);
  2883. return false;
  2884. } else {
  2885. //echo '<pre>';
  2886. //var_dump(curl_getinfo($this->ch));
  2887. //echo '</pre>';
  2888. }
  2889. // close curl
  2890. $this->debug('No cURL error, closing cURL');
  2891. curl_close($this->ch);
  2892. // try removing skippable headers
  2893. $savedata = $data;
  2894. while ($this->isSkippableCurlHeader($data)) {
  2895. $this->debug("Found HTTP header to skip");
  2896. if ($pos = strpos($data,"\r\n\r\n")) {
  2897. $data = ltrim(substr($data,$pos));
  2898. } elseif($pos = strpos($data,"\n\n") ) {
  2899. $data = ltrim(substr($data,$pos));
  2900. }
  2901. }
  2902. if ($data == '') {
  2903. // have nothing left; just remove 100 header(s)
  2904. $data = $savedata;
  2905. while (ereg('^HTTP/1.1 100',$data)) {
  2906. if ($pos = strpos($data,"\r\n\r\n")) {
  2907. $data = ltrim(substr($data,$pos));
  2908. } elseif($pos = strpos($data,"\n\n") ) {
  2909. $data = ltrim(substr($data,$pos));
  2910. }
  2911. }
  2912. }
  2913. // separate content from HTTP headers
  2914. if ($pos = strpos($data,"\r\n\r\n")) {
  2915. $lb = "\r\n";
  2916. } elseif( $pos = strpos($data,"\n\n")) {
  2917. $lb = "\n";
  2918. } else {
  2919. $this->debug('no proper separation of headers and document');
  2920. $this->setError('no proper separation of headers and document');
  2921. return false;
  2922. }
  2923. $header_data = trim(substr($data,0,$pos));
  2924. $header_array = explode($lb,$header_data);
  2925. $data = ltrim(substr($data,$pos));
  2926. $this->debug('found proper separation of headers and document');
  2927. $this->debug('cleaned data, stringlen: '.strlen($data));
  2928. // clean headers
  2929. foreach ($header_array as $header_line) {
  2930. $arr = explode(':',$header_line,2);
  2931. if(count($arr) > 1){
  2932. $header_name = strtolower(trim($arr[0]));
  2933. $this->incoming_headers[$header_name] = trim($arr[1]);
  2934. if ($header_name == 'set-cookie') {
  2935. // TODO: allow multiple cookies from parseCookie
  2936. $cookie = $this->parseCookie(trim($arr[1]));
  2937. if ($cookie) {
  2938. $this->incoming_cookies[] = $cookie;
  2939. $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']);
  2940. } else {
  2941. $this->debug('did not find cookie in ' . trim($arr[1]));
  2942. }
  2943. }
  2944. } else if (isset($header_name)) {
  2945. // append continuation line to previous header
  2946. $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line;
  2947. }
  2948. }
  2949. }
  2950. $this->response_status_line = $header_array[0];
  2951. $arr = explode(' ', $this->response_status_line, 3);
  2952. $http_version = $arr[0];
  2953. $http_status = intval($arr[1]);
  2954. $http_reason = count($arr) > 2 ? $arr[2] : '';
  2955. // see if we need to resend the request with http digest authentication
  2956. if (isset($this->incoming_headers['location']) && ($http_status == 301 || $http_status == 302)) {
  2957. $this->debug("Got $http_status $http_reason with Location: " . $this->incoming_headers['location']);
  2958. $this->setURL($this->incoming_headers['location']);
  2959. $this->tryagain = true;
  2960. return false;
  2961. }
  2962. // see if we need to resend the request with http digest authentication
  2963. if (isset($this->incoming_headers['www-authenticate']) && $http_status == 401) {
  2964. $this->debug("Got 401 $http_reason with WWW-Authenticate: " . $this->incoming_headers['www-authenticate']);
  2965. if (strstr($this->incoming_headers['www-authenticate'], "Digest ")) {
  2966. $this->debug('Server wants digest authentication');
  2967. // remove "Digest " from our elements
  2968. $digestString = str_replace('Digest ', '', $this->incoming_headers['www-authenticate']);
  2969. // parse elements into array
  2970. $digestElements = explode(',', $digestString);
  2971. foreach ($digestElements as $val) {
  2972. $tempElement = explode('=', trim($val), 2);
  2973. $digestRequest[$tempElement[0]] = str_replace("\"", '', $tempElement[1]);
  2974. }
  2975. // should have (at least) qop, realm, nonce
  2976. if (isset($digestRequest['nonce'])) {
  2977. $this->setCredentials($this->username, $this->password, 'digest', $digestRequest);
  2978. $this->tryagain = true;
  2979. return false;
  2980. }
  2981. }
  2982. $this->debug('HTTP authentication failed');
  2983. $this->setError('HTTP authentication failed');
  2984. return false;
  2985. }
  2986. if (
  2987. ($http_status >= 300 && $http_status <= 307) ||
  2988. ($http_status >= 400 && $http_status <= 417) ||
  2989. ($http_status >= 501 && $http_status <= 505)
  2990. ) {
  2991. $this->setError("Unsupported HTTP response status $http_status $http_reason (soapclient->response has contents of the response)");
  2992. return false;
  2993. }
  2994. // decode content-encoding
  2995. if(isset($this->incoming_headers['content-encoding']) && $this->incoming_headers['content-encoding'] != ''){
  2996. if(strtolower($this->incoming_headers['content-encoding']) == 'deflate' || strtolower($this->incoming_headers['content-encoding']) == 'gzip'){
  2997. // if decoding works, use it. else assume data wasn't gzencoded
  2998. if(function_exists('gzinflate')){
  2999. //$timer->setMarker('starting decoding of gzip/deflated content');
  3000. // IIS 5 requires gzinflate instead of gzuncompress (similar to IE 5 and gzdeflate v. gzcompress)
  3001. // this means there are no Zlib headers, although there should be
  3002. $this->debug('The gzinflate function exists');
  3003. $datalen = strlen($data);
  3004. if ($this->incoming_headers['content-encoding'] == 'deflate') {
  3005. if ($degzdata = @gzinflate($data)) {
  3006. $data = $degzdata;
  3007. $this->debug('The payload has been inflated to ' . strlen($data) . ' bytes');
  3008. if (strlen($data) < $datalen) {
  3009. // test for the case that the payload has been compressed twice
  3010. $this->debug('The inflated payload is smaller than the gzipped one; try again');
  3011. if ($degzdata = @gzinflate($data)) {
  3012. $data = $degzdata;
  3013. $this->debug('The payload has been inflated again to ' . strlen($data) . ' bytes');
  3014. }
  3015. }
  3016. } else {
  3017. $this->debug('Error using gzinflate to inflate the payload');
  3018. $this->setError('Error using gzinflate to inflate the payload');
  3019. }
  3020. } elseif ($this->incoming_headers['content-encoding'] == 'gzip') {
  3021. if ($degzdata = @gzinflate(substr($data, 10))) { // do our best
  3022. $data = $degzdata;
  3023. $this->debug('The payload has been un-gzipped to ' . strlen($data) . ' bytes');
  3024. if (strlen($data) < $datalen) {
  3025. // test for the case that the payload has been compressed twice
  3026. $this->debug('The un-gzipped payload is smaller than the gzipped one; try again');
  3027. if ($degzdata = @gzinflate(substr($data, 10))) {
  3028. $data = $degzdata;
  3029. $this->debug('The payload has been un-gzipped again to ' . strlen($data) . ' bytes');
  3030. }
  3031. }
  3032. } else {
  3033. $this->debug('Error using gzinflate to un-gzip the payload');
  3034. $this->setError('Error using gzinflate to un-gzip the payload');
  3035. }
  3036. }
  3037. //$timer->setMarker('finished decoding of gzip/deflated content');
  3038. //print "<xmp>\nde-inflated:\n---------------\n$data\n-------------\n</xmp>";
  3039. // set decoded payload
  3040. $this->incoming_payload = $header_data.$lb.$lb.$data;
  3041. } else {
  3042. $this->debug('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.');
  3043. $this->setError('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.');
  3044. }
  3045. } else {
  3046. $this->debug('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']);
  3047. $this->setError('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']);
  3048. }
  3049. } else {
  3050. $this->debug('No Content-Encoding header');
  3051. }
  3052. if(strlen($data) == 0){
  3053. $this->debug('no data after headers!');
  3054. $this->setError('no data present after HTTP headers');
  3055. return false;
  3056. }
  3057. return $data;
  3058. }
  3059. /**
  3060. * sets the content-type for the SOAP message to be sent
  3061. *
  3062. * @param string $type the content type, MIME style
  3063. * @param mixed $charset character set used for encoding (or false)
  3064. * @access public
  3065. */
  3066. function setContentType($type, $charset = false) {
  3067. $this->setHeader('Content-Type', $type . ($charset ? '; charset=' . $charset : ''));
  3068. }
  3069. /**
  3070. * specifies that an HTTP persistent connection should be used
  3071. *
  3072. * @return boolean whether the request was honored by this method.
  3073. * @access public
  3074. */
  3075. function usePersistentConnection(){
  3076. if (isset($this->outgoing_headers['Accept-Encoding'])) {
  3077. return false;
  3078. }
  3079. $this->protocol_version = '1.1';
  3080. $this->persistentConnection = true;
  3081. $this->setHeader('Connection', 'Keep-Alive');
  3082. return true;
  3083. }
  3084. /**
  3085. * parse an incoming Cookie into it's parts
  3086. *
  3087. * @param string $cookie_str content of cookie
  3088. * @return array with data of that cookie
  3089. * @access private
  3090. */
  3091. /*
  3092. * TODO: allow a Set-Cookie string to be parsed into multiple cookies
  3093. */
  3094. function parseCookie($cookie_str) {
  3095. $cookie_str = str_replace('; ', ';', $cookie_str) . ';';
  3096. $data = split(';', $cookie_str);
  3097. $value_str = $data[0];
  3098. $cookie_param = 'domain=';
  3099. $start = strpos($cookie_str, $cookie_param);
  3100. if ($start > 0) {
  3101. $domain = substr($cookie_str, $start + strlen($cookie_param));
  3102. $domain = substr($domain, 0, strpos($domain, ';'));
  3103. } else {
  3104. $domain = '';
  3105. }
  3106. $cookie_param = 'expires=';
  3107. $start = strpos($cookie_str, $cookie_param);
  3108. if ($start > 0) {
  3109. $expires = substr($cookie_str, $start + strlen($cookie_param));
  3110. $expires = substr($expires, 0, strpos($expires, ';'));
  3111. } else {
  3112. $expires = '';
  3113. }
  3114. $cookie_param = 'path=';
  3115. $start = strpos($cookie_str, $cookie_param);
  3116. if ( $start > 0 ) {
  3117. $path = substr($cookie_str, $start + strlen($cookie_param));
  3118. $path = substr($path, 0, strpos($path, ';'));
  3119. } else {
  3120. $path = '/';
  3121. }
  3122. $cookie_param = ';secure;';
  3123. if (strpos($cookie_str, $cookie_param) !== FALSE) {
  3124. $secure = true;
  3125. } else {
  3126. $secure = false;
  3127. }
  3128. $sep_pos = strpos($value_str, '=');
  3129. if ($sep_pos) {
  3130. $name = substr($value_str, 0, $sep_pos);
  3131. $value = substr($value_str, $sep_pos + 1);
  3132. $cookie= array( 'name' => $name,
  3133. 'value' => $value,
  3134. 'domain' => $domain,
  3135. 'path' => $path,
  3136. 'expires' => $expires,
  3137. 'secure' => $secure
  3138. );
  3139. return $cookie;
  3140. }
  3141. return false;
  3142. }
  3143. /**
  3144. * sort out cookies for the current request
  3145. *
  3146. * @param array $cookies array with all cookies
  3147. * @param boolean $secure is the send-content secure or not?
  3148. * @return string for Cookie-HTTP-Header
  3149. * @access private
  3150. */
  3151. function getCookiesForRequest($cookies, $secure=false) {
  3152. $cookie_str = '';
  3153. if ((! is_null($cookies)) && (is_array($cookies))) {
  3154. foreach ($cookies as $cookie) {
  3155. if (! is_array($cookie)) {
  3156. continue;
  3157. }
  3158. $this->debug("check cookie for validity: ".$cookie['name'].'='.$cookie['value']);
  3159. if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) {
  3160. if (strtotime($cookie['expires']) <= time()) {
  3161. $this->debug('cookie has expired');
  3162. continue;
  3163. }
  3164. }
  3165. if ((isset($cookie['domain'])) && (! empty($cookie['domain']))) {
  3166. $domain = preg_quote($cookie['domain']);
  3167. if (! preg_match("'.*$domain$'i", $this->host)) {
  3168. $this->debug('cookie has different domain');
  3169. continue;
  3170. }
  3171. }
  3172. if ((isset($cookie['path'])) && (! empty($cookie['path']))) {
  3173. $path = preg_quote($cookie['path']);
  3174. if (! preg_match("'^$path.*'i", $this->path)) {
  3175. $this->debug('cookie is for a different path');
  3176. continue;
  3177. }
  3178. }
  3179. if ((! $secure) && (isset($cookie['secure'])) && ($cookie['secure'])) {
  3180. $this->debug('cookie is secure, transport is not');
  3181. continue;
  3182. }
  3183. $cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; ';
  3184. $this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']);
  3185. }
  3186. }
  3187. return $cookie_str;
  3188. }
  3189. }
  3190. ?><?php
  3191. /**
  3192. *
  3193. * nusoap_server allows the user to create a SOAP server
  3194. * that is capable of receiving messages and returning responses
  3195. *
  3196. * @author Dietrich Ayala <dietrich@ganx4.com>
  3197. * @author Scott Nichol <snichol@users.sourceforge.net>
  3198. * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $
  3199. * @access public
  3200. */
  3201. class nusoap_server extends nusoap_base {
  3202. /**
  3203. * HTTP headers of request
  3204. * @var array
  3205. * @access private
  3206. */
  3207. var $headers = array();
  3208. /**
  3209. * HTTP request
  3210. * @var string
  3211. * @access private
  3212. */
  3213. var $request = '';
  3214. /**
  3215. * SOAP headers from request (incomplete namespace resolution; special characters not escaped) (text)
  3216. * @var string
  3217. * @access public
  3218. */
  3219. var $requestHeaders = '';
  3220. /**
  3221. * SOAP Headers from request (parsed)
  3222. * @var mixed
  3223. * @access public
  3224. */
  3225. var $requestHeader = NULL;
  3226. /**
  3227. * SOAP body request portion (incomplete namespace resolution; special characters not escaped) (text)
  3228. * @var string
  3229. * @access public
  3230. */
  3231. var $document = '';
  3232. /**
  3233. * SOAP payload for request (text)
  3234. * @var string
  3235. * @access public
  3236. */
  3237. var $requestSOAP = '';
  3238. /**
  3239. * requested method namespace URI
  3240. * @var string
  3241. * @access private
  3242. */
  3243. var $methodURI = '';
  3244. /**
  3245. * name of method requested
  3246. * @var string
  3247. * @access private
  3248. */
  3249. var $methodname = '';
  3250. /**
  3251. * method parameters from request
  3252. * @var array
  3253. * @access private
  3254. */
  3255. var $methodparams = array();
  3256. /**
  3257. * SOAP Action from request
  3258. * @var string
  3259. * @access private
  3260. */
  3261. var $SOAPAction = '';
  3262. /**
  3263. * character set encoding of incoming (request) messages
  3264. * @var string
  3265. * @access public
  3266. */
  3267. var $xml_encoding = '';
  3268. /**
  3269. * toggles whether the parser decodes element content w/ utf8_decode()
  3270. * @var boolean
  3271. * @access public
  3272. */
  3273. var $decode_utf8 = true;
  3274. /**
  3275. * HTTP headers of response
  3276. * @var array
  3277. * @access public
  3278. */
  3279. var $outgoing_headers = array();
  3280. /**
  3281. * HTTP response
  3282. * @var string
  3283. * @access private
  3284. */
  3285. var $response = '';
  3286. /**
  3287. * SOAP headers for response (text or array of soapval or associative array)
  3288. * @var mixed
  3289. * @access public
  3290. */
  3291. var $responseHeaders = '';
  3292. /**
  3293. * SOAP payload for response (text)
  3294. * @var string
  3295. * @access private
  3296. */
  3297. var $responseSOAP = '';
  3298. /**
  3299. * method return value to place in response
  3300. * @var mixed
  3301. * @access private
  3302. */
  3303. var $methodreturn = false;
  3304. /**
  3305. * whether $methodreturn is a string of literal XML
  3306. * @var boolean
  3307. * @access public
  3308. */
  3309. var $methodreturnisliteralxml = false;
  3310. /**
  3311. * SOAP fault for response (or false)
  3312. * @var mixed
  3313. * @access private
  3314. */
  3315. var $fault = false;
  3316. /**
  3317. * text indication of result (for debugging)
  3318. * @var string
  3319. * @access private
  3320. */
  3321. var $result = 'successful';
  3322. /**
  3323. * assoc array of operations => opData; operations are added by the register()
  3324. * method or by parsing an external WSDL definition
  3325. * @var array
  3326. * @access private
  3327. */
  3328. var $operations = array();
  3329. /**
  3330. * wsdl instance (if one)
  3331. * @var mixed
  3332. * @access private
  3333. */
  3334. var $wsdl = false;
  3335. /**
  3336. * URL for WSDL (if one)
  3337. * @var mixed
  3338. * @access private
  3339. */
  3340. var $externalWSDLURL = false;
  3341. /**
  3342. * whether to append debug to response as XML comment
  3343. * @var boolean
  3344. * @access public
  3345. */
  3346. var $debug_flag = false;
  3347. /**
  3348. * constructor
  3349. * the optional parameter is a path to a WSDL file that you'd like to bind the server instance to.
  3350. *
  3351. * @param mixed $wsdl file path or URL (string), or wsdl instance (object)
  3352. * @access public
  3353. */
  3354. function nusoap_server($wsdl=false){
  3355. parent::nusoap_base();
  3356. // turn on debugging?
  3357. global $debug;
  3358. global $HTTP_SERVER_VARS;
  3359. if (isset($_SERVER)) {
  3360. $this->debug("_SERVER is defined:");
  3361. $this->appendDebug($this->varDump($_SERVER));
  3362. } elseif (isset($HTTP_SERVER_VARS)) {
  3363. $this->debug("HTTP_SERVER_VARS is defined:");
  3364. $this->appendDebug($this->varDump($HTTP_SERVER_VARS));
  3365. } else {
  3366. $this->debug("Neither _SERVER nor HTTP_SERVER_VARS is defined.");
  3367. }
  3368. if (isset($debug)) {
  3369. $this->debug("In nusoap_server, set debug_flag=$debug based on global flag");
  3370. $this->debug_flag = $debug;
  3371. } elseif (isset($_SERVER['QUERY_STRING'])) {
  3372. $qs = explode('&', $_SERVER['QUERY_STRING']);
  3373. foreach ($qs as $v) {
  3374. if (substr($v, 0, 6) == 'debug=') {
  3375. $this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #1");
  3376. $this->debug_flag = substr($v, 6);
  3377. }
  3378. }
  3379. } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
  3380. $qs = explode('&', $HTTP_SERVER_VARS['QUERY_STRING']);
  3381. foreach ($qs as $v) {
  3382. if (substr($v, 0, 6) == 'debug=') {
  3383. $this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #2");
  3384. $this->debug_flag = substr($v, 6);
  3385. }
  3386. }
  3387. }
  3388. // wsdl
  3389. if($wsdl){
  3390. $this->debug("In nusoap_server, WSDL is specified");
  3391. if (is_object($wsdl) && (get_class($wsdl) == 'wsdl')) {
  3392. $this->wsdl = $wsdl;
  3393. $this->externalWSDLURL = $this->wsdl->wsdl;
  3394. $this->debug('Use existing wsdl instance from ' . $this->externalWSDLURL);
  3395. } else {
  3396. $this->debug('Create wsdl from ' . $wsdl);
  3397. $this->wsdl = new wsdl($wsdl);
  3398. $this->externalWSDLURL = $wsdl;
  3399. }
  3400. $this->appendDebug($this->wsdl->getDebug());
  3401. $this->wsdl->clearDebug();
  3402. if($err = $this->wsdl->getError()){
  3403. die('WSDL ERROR: '.$err);
  3404. }
  3405. }
  3406. }
  3407. /**
  3408. * processes request and returns response
  3409. *
  3410. * @param string $data usually is the value of $HTTP_RAW_POST_DATA
  3411. * @access public
  3412. */
  3413. function service($data){
  3414. global $HTTP_SERVER_VARS;
  3415. if (isset($_SERVER['QUERY_STRING'])) {
  3416. $qs = $_SERVER['QUERY_STRING'];
  3417. } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
  3418. $qs = $HTTP_SERVER_VARS['QUERY_STRING'];
  3419. } else {
  3420. $qs = '';
  3421. }
  3422. $this->debug("In service, query string=$qs");
  3423. if (ereg('wsdl', $qs) ){
  3424. $this->debug("In service, this is a request for WSDL");
  3425. if($this->externalWSDLURL){
  3426. if (strpos($this->externalWSDLURL,"://")!==false) { // assume URL
  3427. header('Location: '.$this->externalWSDLURL);
  3428. } else { // assume file
  3429. header("Content-Type: text/xml\r\n");
  3430. $fp = fopen($this->externalWSDLURL, 'r');
  3431. fpassthru($fp);
  3432. }
  3433. } elseif ($this->wsdl) {
  3434. header("Content-Type: text/xml; charset=ISO-8859-1\r\n");
  3435. print $this->wsdl->serialize($this->debug_flag);
  3436. if ($this->debug_flag) {
  3437. $this->debug('wsdl:');
  3438. $this->appendDebug($this->varDump($this->wsdl));
  3439. print $this->getDebugAsXMLComment();
  3440. }
  3441. } else {
  3442. header("Content-Type: text/html; charset=ISO-8859-1\r\n");
  3443. print "This service does not provide WSDL";
  3444. }
  3445. } elseif ($data == '' && $this->wsdl) {
  3446. $this->debug("In service, there is no data, so return Web description");
  3447. print $this->wsdl->webDescription();
  3448. } else {
  3449. $this->debug("In service, invoke the request");
  3450. $this->parse_request($data);
  3451. if (! $this->fault) {
  3452. $this->invoke_method();
  3453. }
  3454. if (! $this->fault) {
  3455. $this->serialize_return();
  3456. }
  3457. $this->send_response();
  3458. }
  3459. }
  3460. /**
  3461. * parses HTTP request headers.
  3462. *
  3463. * The following fields are set by this function (when successful)
  3464. *
  3465. * headers
  3466. * request
  3467. * xml_encoding
  3468. * SOAPAction
  3469. *
  3470. * @access private
  3471. */
  3472. function parse_http_headers() {
  3473. global $HTTP_SERVER_VARS;
  3474. $this->request = '';
  3475. $this->SOAPAction = '';
  3476. if(function_exists('getallheaders')){
  3477. $this->debug("In parse_http_headers, use getallheaders");
  3478. $headers = getallheaders();
  3479. foreach($headers as $k=>$v){
  3480. $k = strtolower($k);
  3481. $this->headers[$k] = $v;
  3482. $this->request .= "$k: $v\r\n";
  3483. $this->debug("$k: $v");
  3484. }
  3485. // get SOAPAction header
  3486. if(isset($this->headers['soapaction'])){
  3487. $this->SOAPAction = str_replace('"','',$this->headers['soapaction']);
  3488. }
  3489. // get the character encoding of the incoming request
  3490. if(isset($this->headers['content-type']) && strpos($this->headers['content-type'],'=')){
  3491. $enc = str_replace('"','',substr(strstr($this->headers["content-type"],'='),1));
  3492. if(eregi('^(ISO-8859-1|US-ASCII|UTF-8)$',$enc)){
  3493. $this->xml_encoding = strtoupper($enc);
  3494. } else {
  3495. $this->xml_encoding = 'US-ASCII';
  3496. }
  3497. } else {
  3498. // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
  3499. $this->xml_encoding = 'ISO-8859-1';
  3500. }
  3501. } elseif(isset($_SERVER) && is_array($_SERVER)){
  3502. $this->debug("In parse_http_headers, use _SERVER");
  3503. foreach ($_SERVER as $k => $v) {
  3504. if (substr($k, 0, 5) == 'HTTP_') {
  3505. $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5))));
  3506. } else {
  3507. $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k)));
  3508. }
  3509. if ($k == 'soapaction') {
  3510. // get SOAPAction header
  3511. $k = 'SOAPAction';
  3512. $v = str_replace('"', '', $v);
  3513. $v = str_replace('\\', '', $v);
  3514. $this->SOAPAction = $v;
  3515. } else if ($k == 'content-type') {
  3516. // get the character encoding of the incoming request
  3517. if (strpos($v, '=')) {
  3518. $enc = substr(strstr($v, '='), 1);
  3519. $enc = str_replace('"', '', $enc);
  3520. $enc = str_replace('\\', '', $enc);
  3521. if (eregi('^(ISO-8859-1|US-ASCII|UTF-8)$', $enc)) {
  3522. $this->xml_encoding = strtoupper($enc);
  3523. } else {
  3524. $this->xml_encoding = 'US-ASCII';
  3525. }
  3526. } else {
  3527. // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
  3528. $this->xml_encoding = 'ISO-8859-1';
  3529. }
  3530. }
  3531. $this->headers[$k] = $v;
  3532. $this->request .= "$k: $v\r\n";
  3533. $this->debug("$k: $v");
  3534. }
  3535. } elseif (is_array($HTTP_SERVER_VARS)) {
  3536. $this->debug("In parse_http_headers, use HTTP_SERVER_VARS");
  3537. foreach ($HTTP_SERVER_VARS as $k => $v) {
  3538. if (substr($k, 0, 5) == 'HTTP_') {
  3539. $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5));
  3540. } else {
  3541. $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k);
  3542. }
  3543. if ($k == 'soapaction') {
  3544. // get SOAPAction header
  3545. $k = 'SOAPAction';
  3546. $v = str_replace('"', '', $v);
  3547. $v = str_replace('\\', '', $v);
  3548. $this->SOAPAction = $v;
  3549. } else if ($k == 'content-type') {
  3550. // get the character encoding of the incoming request
  3551. if (strpos($v, '=')) {
  3552. $enc = substr(strstr($v, '='), 1);
  3553. $enc = str_replace('"', '', $enc);
  3554. $enc = str_replace('\\', '', $enc);
  3555. if (eregi('^(ISO-8859-1|US-ASCII|UTF-8)$', $enc)) {
  3556. $this->xml_encoding = strtoupper($enc);
  3557. } else {
  3558. $this->xml_encoding = 'US-ASCII';
  3559. }
  3560. } else {
  3561. // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
  3562. $this->xml_encoding = 'ISO-8859-1';
  3563. }
  3564. }
  3565. $this->headers[$k] = $v;
  3566. $this->request .= "$k: $v\r\n";
  3567. $this->debug("$k: $v");
  3568. }
  3569. } else {
  3570. $this->debug("In parse_http_headers, HTTP headers not accessible");
  3571. $this->setError("HTTP headers not accessible");
  3572. }
  3573. }
  3574. /**
  3575. * parses a request
  3576. *
  3577. * The following fields are set by this function (when successful)
  3578. *
  3579. * headers
  3580. * request
  3581. * xml_encoding
  3582. * SOAPAction
  3583. * request
  3584. * requestSOAP
  3585. * methodURI
  3586. * methodname
  3587. * methodparams
  3588. * requestHeaders
  3589. * document
  3590. *
  3591. * This sets the fault field on error
  3592. *
  3593. * @param string $data XML string
  3594. * @access private
  3595. */
  3596. function parse_request($data='') {
  3597. $this->debug('entering parse_request()');
  3598. $this->parse_http_headers();
  3599. $this->debug('got character encoding: '.$this->xml_encoding);
  3600. // uncompress if necessary
  3601. if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] != '') {
  3602. $this->debug('got content encoding: ' . $this->headers['content-encoding']);
  3603. if ($this->headers['content-encoding'] == 'deflate' || $this->headers['content-encoding'] == 'gzip') {
  3604. // if decoding works, use it. else assume data wasn't gzencoded
  3605. if (function_exists('gzuncompress')) {
  3606. if ($this->headers['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
  3607. $data = $degzdata;
  3608. } elseif ($this->headers['content-encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))) {
  3609. $data = $degzdata;
  3610. } else {
  3611. $this->fault('SOAP-ENV:Client', 'Errors occurred when trying to decode the data');
  3612. return;
  3613. }
  3614. } else {
  3615. $this->fault('SOAP-ENV:Client', 'This Server does not support compressed data');
  3616. return;
  3617. }
  3618. }
  3619. }
  3620. $this->request .= "\r\n".$data;
  3621. $data = $this->parseRequest($this->headers, $data);
  3622. $this->requestSOAP = $data;
  3623. $this->debug('leaving parse_request');
  3624. }
  3625. /**
  3626. * invokes a PHP function for the requested SOAP method
  3627. *
  3628. * The following fields are set by this function (when successful)
  3629. *
  3630. * methodreturn
  3631. *
  3632. * Note that the PHP function that is called may also set the following
  3633. * fields to affect the response sent to the client
  3634. *
  3635. * responseHeaders
  3636. * outgoing_headers
  3637. *
  3638. * This sets the fault field on error
  3639. *
  3640. * @access private
  3641. */
  3642. function invoke_method() {
  3643. $this->debug('in invoke_method, methodname=' . $this->methodname . ' methodURI=' . $this->methodURI . ' SOAPAction=' . $this->SOAPAction);
  3644. if ($this->wsdl) {
  3645. if ($this->opData = $this->wsdl->getOperationData($this->methodname)) {
  3646. $this->debug('in invoke_method, found WSDL operation=' . $this->methodname);
  3647. $this->appendDebug('opData=' . $this->varDump($this->opData));
  3648. } elseif ($this->opData = $this->wsdl->getOperationDataForSoapAction($this->SOAPAction)) {
  3649. // Note: hopefully this case will only be used for doc/lit, since rpc services should have wrapper element
  3650. $this->debug('in invoke_method, found WSDL soapAction=' . $this->SOAPAction . ' for operation=' . $this->opData['name']);
  3651. $this->appendDebug('opData=' . $this->varDump($this->opData));
  3652. $this->methodname = $this->opData['name'];
  3653. } else {
  3654. $this->debug('in invoke_method, no WSDL for operation=' . $this->methodname);
  3655. $this->fault('SOAP-ENV:Client', "Operation '" . $this->methodname . "' is not defined in the WSDL for this service");
  3656. return;
  3657. }
  3658. } else {
  3659. $this->debug('in invoke_method, no WSDL to validate method');
  3660. }
  3661. // if a . is present in $this->methodname, we see if there is a class in scope,
  3662. // which could be referred to. We will also distinguish between two deliminators,
  3663. // to allow methods to be called a the class or an instance
  3664. $class = '';
  3665. $method = '';
  3666. if (strpos($this->methodname, '..') > 0) {
  3667. $delim = '..';
  3668. } else if (strpos($this->methodname, '.') > 0) {
  3669. $delim = '.';
  3670. } else {
  3671. $delim = '';
  3672. }
  3673. if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1 &&
  3674. class_exists(substr($this->methodname, 0, strpos($this->methodname, $delim)))) {
  3675. // get the class and method name
  3676. $class = substr($this->methodname, 0, strpos($this->methodname, $delim));
  3677. $method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim));
  3678. $this->debug("in invoke_method, class=$class method=$method delim=$delim");
  3679. }
  3680. // does method exist?
  3681. if ($class == '') {
  3682. if (!function_exists($this->methodname)) {
  3683. $this->debug("in invoke_method, function '$this->methodname' not found!");
  3684. $this->result = 'fault: method not found';
  3685. $this->fault('SOAP-ENV:Client',"method '$this->methodname' not defined in service");
  3686. return;
  3687. }
  3688. } else {
  3689. $method_to_compare = (substr(phpversion(), 0, 2) == '4.') ? strtolower($method) : $method;
  3690. if (!in_array($method_to_compare, get_class_methods($class))) {
  3691. $this->debug("in invoke_method, method '$this->methodname' not found in class '$class'!");
  3692. $this->result = 'fault: method not found';
  3693. $this->fault('SOAP-ENV:Client',"method '$this->methodname' not defined in service");
  3694. return;
  3695. }
  3696. }
  3697. // evaluate message, getting back parameters
  3698. // verify that request parameters match the method's signature
  3699. if(! $this->verify_method($this->methodname,$this->methodparams)){
  3700. // debug
  3701. $this->debug('ERROR: request not verified against method signature');
  3702. $this->result = 'fault: request failed validation against method signature';
  3703. // return fault
  3704. $this->fault('SOAP-ENV:Client',"Operation '$this->methodname' not defined in service.");
  3705. return;
  3706. }
  3707. // if there are parameters to pass
  3708. $this->debug('in invoke_method, params:');
  3709. $this->appendDebug($this->varDump($this->methodparams));
  3710. $this->debug("in invoke_method, calling '$this->methodname'");
  3711. if (!function_exists('call_user_func_array')) {
  3712. if ($class == '') {
  3713. $this->debug('in invoke_method, calling function using eval()');
  3714. $funcCall = "\$this->methodreturn = $this->methodname(";
  3715. } else {
  3716. if ($delim == '..') {
  3717. $this->debug('in invoke_method, calling class method using eval()');
  3718. $funcCall = "\$this->methodreturn = ".$class."::".$method."(";
  3719. } else {
  3720. $this->debug('in invoke_method, calling instance method using eval()');
  3721. // generate unique instance name
  3722. $instname = "\$inst_".time();
  3723. $funcCall = $instname." = new ".$class."(); ";
  3724. $funcCall .= "\$this->methodreturn = ".$instname."->".$method."(";
  3725. }
  3726. }
  3727. if ($this->methodparams) {
  3728. foreach ($this->methodparams as $param) {
  3729. if (is_array($param) || is_object($param)) {
  3730. $this->fault('SOAP-ENV:Client', 'NuSOAP does not handle complexType parameters correctly when using eval; call_user_func_array must be available');
  3731. return;
  3732. }
  3733. $funcCall .= "\"$param\",";
  3734. }
  3735. $funcCall = substr($funcCall, 0, -1);
  3736. }
  3737. $funcCall .= ');';
  3738. $this->debug('in invoke_method, function call: '.$funcCall);
  3739. @eval($funcCall);
  3740. } else {
  3741. if ($class == '') {
  3742. $this->debug('in invoke_method, calling function using call_user_func_array()');
  3743. $call_arg = "$this->methodname"; // straight assignment changes $this->methodname to lower case after call_user_func_array()
  3744. } elseif ($delim == '..') {
  3745. $this->debug('in invoke_method, calling class method using call_user_func_array()');
  3746. $call_arg = array ($class, $method);
  3747. } else {
  3748. $this->debug('in invoke_method, calling instance method using call_user_func_array()');
  3749. $instance = new $class ();
  3750. $call_arg = array(&$instance, $method);
  3751. }
  3752. if (is_array($this->methodparams)) {
  3753. $this->methodreturn = call_user_func_array($call_arg, array_values($this->methodparams));
  3754. } else {
  3755. $this->methodreturn = call_user_func_array($call_arg, array());
  3756. }
  3757. }
  3758. $this->debug('in invoke_method, methodreturn:');
  3759. $this->appendDebug($this->varDump($this->methodreturn));
  3760. $this->debug("in invoke_method, called method $this->methodname, received data of type ".gettype($this->methodreturn));
  3761. }
  3762. /**
  3763. * serializes the return value from a PHP function into a full SOAP Envelope
  3764. *
  3765. * The following fields are set by this function (when successful)
  3766. *
  3767. * responseSOAP
  3768. *
  3769. * This sets the fault field on error
  3770. *
  3771. * @access private
  3772. */
  3773. function serialize_return() {
  3774. $this->debug('Entering serialize_return methodname: ' . $this->methodname . ' methodURI: ' . $this->methodURI);
  3775. // if fault
  3776. if (isset($this->methodreturn) && ((get_class($this->methodreturn) == 'soap_fault') || (get_class($this->methodreturn) == 'nusoap_fault'))) {
  3777. $this->debug('got a fault object from method');
  3778. $this->fault = $this->methodreturn;
  3779. return;
  3780. } elseif ($this->methodreturnisliteralxml) {
  3781. $return_val = $this->methodreturn;
  3782. // returned value(s)
  3783. } else {
  3784. $this->debug('got a(n) '.gettype($this->methodreturn).' from method');
  3785. $this->debug('serializing return value');
  3786. if($this->wsdl){
  3787. if (sizeof($this->opData['output']['parts']) > 1) {
  3788. $this->debug('more than one output part, so use the method return unchanged');
  3789. $opParams = $this->methodreturn;
  3790. } elseif (sizeof($this->opData['output']['parts']) == 1) {
  3791. $this->debug('exactly one output part, so wrap the method return in a simple array');
  3792. // TODO: verify that it is not already wrapped!
  3793. //foreach ($this->opData['output']['parts'] as $name => $type) {
  3794. // $this->debug('wrap in element named ' . $name);
  3795. //}
  3796. $opParams = array($this->methodreturn);
  3797. }
  3798. $return_val = $this->wsdl->serializeRPCParameters($this->methodname,'output',$opParams);
  3799. $this->appendDebug($this->wsdl->getDebug());
  3800. $this->wsdl->clearDebug();
  3801. if($errstr = $this->wsdl->getError()){
  3802. $this->debug('got wsdl error: '.$errstr);
  3803. $this->fault('SOAP-ENV:Server', 'unable to serialize result');
  3804. return;
  3805. }
  3806. } else {
  3807. if (isset($this->methodreturn)) {
  3808. $return_val = $this->serialize_val($this->methodreturn, 'return');
  3809. } else {
  3810. $return_val = '';
  3811. $this->debug('in absence of WSDL, assume void return for backward compatibility');
  3812. }
  3813. }
  3814. }
  3815. $this->debug('return value:');
  3816. $this->appendDebug($this->varDump($return_val));
  3817. $this->debug('serializing response');
  3818. if ($this->wsdl) {
  3819. $this->debug('have WSDL for serialization: style is ' . $this->opData['style']);
  3820. if ($this->opData['style'] == 'rpc') {
  3821. $this->debug('style is rpc for serialization: use is ' . $this->opData['output']['use']);
  3822. if ($this->opData['output']['use'] == 'literal') {
  3823. // http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html R2735 says rpc/literal accessor elements should not be in a namespace
  3824. $payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
  3825. } else {
  3826. $payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
  3827. }
  3828. } else {
  3829. $this->debug('style is not rpc for serialization: assume document');
  3830. $payload = $return_val;
  3831. }
  3832. } else {
  3833. $this->debug('do not have WSDL for serialization: assume rpc/encoded');
  3834. $payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
  3835. }
  3836. $this->result = 'successful';
  3837. if($this->wsdl){
  3838. //if($this->debug_flag){
  3839. $this->appendDebug($this->wsdl->getDebug());
  3840. // }
  3841. if (isset($opData['output']['encodingStyle'])) {
  3842. $encodingStyle = $opData['output']['encodingStyle'];
  3843. } else {
  3844. $encodingStyle = '';
  3845. }
  3846. // Added: In case we use a WSDL, return a serialized env. WITH the usedNamespaces.
  3847. $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders,$this->wsdl->usedNamespaces,$this->opData['style'],$this->opData['output']['use'],$encodingStyle);
  3848. } else {
  3849. $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders);
  3850. }
  3851. $this->debug("Leaving serialize_return");
  3852. }
  3853. /**
  3854. * sends an HTTP response
  3855. *
  3856. * The following fields are set by this function (when successful)
  3857. *
  3858. * outgoing_headers
  3859. * response
  3860. *
  3861. * @access private
  3862. */
  3863. function send_response() {
  3864. $this->debug('Enter send_response');
  3865. if ($this->fault) {
  3866. $payload = $this->fault->serialize();
  3867. $this->outgoing_headers[] = "HTTP/1.0 500 Internal Server Error";
  3868. $this->outgoing_headers[] = "Status: 500 Internal Server Error";
  3869. } else {
  3870. $payload = $this->responseSOAP;
  3871. // Some combinations of PHP+Web server allow the Status
  3872. // to come through as a header. Since OK is the default
  3873. // just do nothing.
  3874. // $this->outgoing_headers[] = "HTTP/1.0 200 OK";
  3875. // $this->outgoing_headers[] = "Status: 200 OK";
  3876. }
  3877. // add debug data if in debug mode
  3878. if(isset($this->debug_flag) && $this->debug_flag){
  3879. $payload .= $this->getDebugAsXMLComment();
  3880. }
  3881. $this->outgoing_headers[] = "Server: $this->title Server v$this->version";
  3882. ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev);
  3883. $this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".$rev[1].")";
  3884. // Let the Web server decide about this
  3885. //$this->outgoing_headers[] = "Connection: Close\r\n";
  3886. $payload = $this->getHTTPBody($payload);
  3887. $type = $this->getHTTPContentType();
  3888. $charset = $this->getHTTPContentTypeCharset();
  3889. $this->outgoing_headers[] = "Content-Type: $type" . ($charset ? '; charset=' . $charset : '');
  3890. //begin code to compress payload - by John
  3891. // NOTE: there is no way to know whether the Web server will also compress
  3892. // this data.
  3893. if (strlen($payload) > 1024 && isset($this->headers) && isset($this->headers['accept-encoding'])) {
  3894. if (strstr($this->headers['accept-encoding'], 'gzip')) {
  3895. if (function_exists('gzencode')) {
  3896. if (isset($this->debug_flag) && $this->debug_flag) {
  3897. $payload .= "<!-- Content being gzipped -->";
  3898. }
  3899. $this->outgoing_headers[] = "Content-Encoding: gzip";
  3900. $payload = gzencode($payload);
  3901. } else {
  3902. if (isset($this->debug_flag) && $this->debug_flag) {
  3903. $payload .= "<!-- Content will not be gzipped: no gzencode -->";
  3904. }
  3905. }
  3906. } elseif (strstr($this->headers['accept-encoding'], 'deflate')) {
  3907. // Note: MSIE requires gzdeflate output (no Zlib header and checksum),
  3908. // instead of gzcompress output,
  3909. // which conflicts with HTTP 1.1 spec (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5)
  3910. if (function_exists('gzdeflate')) {
  3911. if (isset($this->debug_flag) && $this->debug_flag) {
  3912. $payload .= "<!-- Content being deflated -->";
  3913. }
  3914. $this->outgoing_headers[] = "Content-Encoding: deflate";
  3915. $payload = gzdeflate($payload);
  3916. } else {
  3917. if (isset($this->debug_flag) && $this->debug_flag) {
  3918. $payload .= "<!-- Content will not be deflated: no gzcompress -->";
  3919. }
  3920. }
  3921. }
  3922. }
  3923. //end code
  3924. $this->outgoing_headers[] = "Content-Length: ".strlen($payload);
  3925. reset($this->outgoing_headers);
  3926. foreach($this->outgoing_headers as $hdr){
  3927. header($hdr, false);
  3928. }
  3929. print $payload;
  3930. $this->response = join("\r\n",$this->outgoing_headers)."\r\n\r\n".$payload;
  3931. }
  3932. /**
  3933. * takes the value that was created by parsing the request
  3934. * and compares to the method's signature, if available.
  3935. *
  3936. * @param string $operation The operation to be invoked
  3937. * @param array $request The array of parameter values
  3938. * @return boolean Whether the operation was found
  3939. * @access private
  3940. */
  3941. function verify_method($operation,$request){
  3942. if(isset($this->wsdl) && is_object($this->wsdl)){
  3943. if($this->wsdl->getOperationData($operation)){
  3944. return true;
  3945. }
  3946. } elseif(isset($this->operations[$operation])){
  3947. return true;
  3948. }
  3949. return false;
  3950. }
  3951. /**
  3952. * processes SOAP message received from client
  3953. *
  3954. * @param array $headers The HTTP headers
  3955. * @param string $data unprocessed request data from client
  3956. * @return mixed value of the message, decoded into a PHP type
  3957. * @access private
  3958. */
  3959. function parseRequest($headers, $data) {
  3960. $this->debug('Entering parseRequest() for data of length ' . strlen($data) . ' and type ' . $headers['content-type']);
  3961. if (!strstr($headers['content-type'], 'text/xml')) {
  3962. $this->setError('Request not of type text/xml');
  3963. return false;
  3964. }
  3965. if (strpos($headers['content-type'], '=')) {
  3966. $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1));
  3967. $this->debug('Got response encoding: ' . $enc);
  3968. if(eregi('^(ISO-8859-1|US-ASCII|UTF-8)$',$enc)){
  3969. $this->xml_encoding = strtoupper($enc);
  3970. } else {
  3971. $this->xml_encoding = 'US-ASCII';
  3972. }
  3973. } else {
  3974. // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
  3975. $this->xml_encoding = 'ISO-8859-1';
  3976. }
  3977. $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating nusoap_parser');
  3978. // parse response, get soap parser obj
  3979. $parser = new nusoap_parser($data,$this->xml_encoding,'',$this->decode_utf8);
  3980. // parser debug
  3981. $this->debug("parser debug: \n".$parser->getDebug());
  3982. // if fault occurred during message parsing
  3983. if($err = $parser->getError()){
  3984. $this->result = 'fault: error in msg parsing: '.$err;
  3985. $this->fault('SOAP-ENV:Client',"error in msg parsing:\n".$err);
  3986. // else successfully parsed request into soapval object
  3987. } else {
  3988. // get/set methodname
  3989. $this->methodURI = $parser->root_struct_namespace;
  3990. $this->methodname = $parser->root_struct_name;
  3991. $this->debug('methodname: '.$this->methodname.' methodURI: '.$this->methodURI);
  3992. $this->debug('calling parser->get_soapbody()');
  3993. $this->methodparams = $parser->get_soapbody();
  3994. // get SOAP headers
  3995. $this->requestHeaders = $parser->getHeaders();
  3996. // get SOAP Header
  3997. $this->requestHeader = $parser->get_soapheader();
  3998. // add document for doclit support
  3999. $this->document = $parser->document;
  4000. }
  4001. }
  4002. /**
  4003. * gets the HTTP body for the current response.
  4004. *
  4005. * @param string $soapmsg The SOAP payload
  4006. * @return string The HTTP body, which includes the SOAP payload
  4007. * @access private
  4008. */
  4009. function getHTTPBody($soapmsg) {
  4010. return $soapmsg;
  4011. }
  4012. /**
  4013. * gets the HTTP content type for the current response.
  4014. *
  4015. * Note: getHTTPBody must be called before this.
  4016. *
  4017. * @return string the HTTP content type for the current response.
  4018. * @access private
  4019. */
  4020. function getHTTPContentType() {
  4021. return 'text/xml';
  4022. }
  4023. /**
  4024. * gets the HTTP content type charset for the current response.
  4025. * returns false for non-text content types.
  4026. *
  4027. * Note: getHTTPBody must be called before this.
  4028. *
  4029. * @return string the HTTP content type charset for the current response.
  4030. * @access private
  4031. */
  4032. function getHTTPContentTypeCharset() {
  4033. return $this->soap_defencoding;
  4034. }
  4035. /**
  4036. * add a method to the dispatch map (this has been replaced by the register method)
  4037. *
  4038. * @param string $methodname
  4039. * @param string $in array of input values
  4040. * @param string $out array of output values
  4041. * @access public
  4042. * @deprecated
  4043. */
  4044. function add_to_map($methodname,$in,$out){
  4045. $this->operations[$methodname] = array('name' => $methodname,'in' => $in,'out' => $out);
  4046. }
  4047. /**
  4048. * register a service function with the server
  4049. *
  4050. * @param string $name the name of the PHP function, class.method or class..method
  4051. * @param array $in assoc array of input values: key = param name, value = param type
  4052. * @param array $out assoc array of output values: key = param name, value = param type
  4053. * @param mixed $namespace the element namespace for the method or false
  4054. * @param mixed $soapaction the soapaction for the method or false
  4055. * @param mixed $style optional (rpc|document) or false Note: when 'document' is specified, parameter and return wrappers are created for you automatically
  4056. * @param mixed $use optional (encoded|literal) or false
  4057. * @param string $documentation optional Description to include in WSDL
  4058. * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
  4059. * @access public
  4060. */
  4061. function register($name,$in=array(),$out=array(),$namespace=false,$soapaction=false,$style=false,$use=false,$documentation='',$encodingStyle=''){
  4062. global $HTTP_SERVER_VARS;
  4063. if($this->externalWSDLURL){
  4064. die('You cannot bind to an external WSDL file, and register methods outside of it! Please choose either WSDL or no WSDL.');
  4065. }
  4066. if (! $name) {
  4067. die('You must specify a name when you register an operation');
  4068. }
  4069. if (!is_array($in)) {
  4070. die('You must provide an array for operation inputs');
  4071. }
  4072. if (!is_array($out)) {
  4073. die('You must provide an array for operation outputs');
  4074. }
  4075. if(false == $namespace) {
  4076. }
  4077. if(false == $soapaction) {
  4078. if (isset($_SERVER)) {
  4079. $SERVER_NAME = $_SERVER['SERVER_NAME'];
  4080. $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
  4081. $HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off');
  4082. } elseif (isset($HTTP_SERVER_VARS)) {
  4083. $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME'];
  4084. $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME'];
  4085. $HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off';
  4086. } else {
  4087. $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
  4088. }
  4089. if ($HTTPS == '1' || $HTTPS == 'on') {
  4090. $SCHEME = 'https';
  4091. } else {
  4092. $SCHEME = 'http';
  4093. }
  4094. $soapaction = "$SCHEME://$SERVER_NAME$SCRIPT_NAME/$name";
  4095. }
  4096. if(false == $style) {
  4097. $style = "rpc";
  4098. }
  4099. if(false == $use) {
  4100. $use = "encoded";
  4101. }
  4102. if ($use == 'encoded' && $encodingStyle = '') {
  4103. $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
  4104. }
  4105. $this->operations[$name] = array(
  4106. 'name' => $name,
  4107. 'in' => $in,
  4108. 'out' => $out,
  4109. 'namespace' => $namespace,
  4110. 'soapaction' => $soapaction,
  4111. 'style' => $style);
  4112. if($this->wsdl){
  4113. $this->wsdl->addOperation($name,$in,$out,$namespace,$soapaction,$style,$use,$documentation,$encodingStyle);
  4114. }
  4115. return true;
  4116. }
  4117. /**
  4118. * Specify a fault to be returned to the client.
  4119. * This also acts as a flag to the server that a fault has occured.
  4120. *
  4121. * @param string $faultcode
  4122. * @param string $faultstring
  4123. * @param string $faultactor
  4124. * @param string $faultdetail
  4125. * @access public
  4126. */
  4127. function fault($faultcode,$faultstring,$faultactor='',$faultdetail=''){
  4128. if ($faultdetail == '' && $this->debug_flag) {
  4129. $faultdetail = $this->getDebug();
  4130. }
  4131. $this->fault = new nusoap_fault($faultcode,$faultactor,$faultstring,$faultdetail);
  4132. $this->fault->soap_defencoding = $this->soap_defencoding;
  4133. }
  4134. /**
  4135. * Sets up wsdl object.
  4136. * Acts as a flag to enable internal WSDL generation
  4137. *
  4138. * @param string $serviceName, name of the service
  4139. * @param mixed $namespace optional 'tns' service namespace or false
  4140. * @param mixed $endpoint optional URL of service endpoint or false
  4141. * @param string $style optional (rpc|document) WSDL style (also specified by operation)
  4142. * @param string $transport optional SOAP transport
  4143. * @param mixed $schemaTargetNamespace optional 'types' targetNamespace for service schema or false
  4144. */
  4145. function configureWSDL($serviceName,$namespace = false,$endpoint = false,$style='rpc', $transport = 'http://schemas.xmlsoap.org/soap/http', $schemaTargetNamespace = false)
  4146. {
  4147. global $HTTP_SERVER_VARS;
  4148. if (isset($_SERVER)) {
  4149. $SERVER_NAME = $_SERVER['SERVER_NAME'];
  4150. $SERVER_PORT = $_SERVER['SERVER_PORT'];
  4151. $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
  4152. $HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off');
  4153. } elseif (isset($HTTP_SERVER_VARS)) {
  4154. $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME'];
  4155. $SERVER_PORT = $HTTP_SERVER_VARS['SERVER_PORT'];
  4156. $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME'];
  4157. $HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off';
  4158. } else {
  4159. $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
  4160. }
  4161. // If server name has port number attached then strip it (else port number gets duplicated in WSDL output) (occurred using lighttpd and FastCGI)
  4162. $colon = strpos($SERVER_NAME,":");
  4163. if ($colon) {
  4164. $SERVER_NAME = substr($SERVER_NAME, 0, $colon);
  4165. }
  4166. if ($SERVER_PORT == 80) {
  4167. $SERVER_PORT = '';
  4168. } else {
  4169. $SERVER_PORT = ':' . $SERVER_PORT;
  4170. }
  4171. if(false == $namespace) {
  4172. $namespace = "http://$SERVER_NAME/soap/$serviceName";
  4173. }
  4174. if(false == $endpoint) {
  4175. if ($HTTPS == '1' || $HTTPS == 'on') {
  4176. $SCHEME = 'https';
  4177. } else {
  4178. $SCHEME = 'http';
  4179. }
  4180. $endpoint = "$SCHEME://$SERVER_NAME$SERVER_PORT$SCRIPT_NAME";
  4181. }
  4182. if(false == $schemaTargetNamespace) {
  4183. $schemaTargetNamespace = $namespace;
  4184. }
  4185. $this->wsdl = new wsdl;
  4186. $this->wsdl->serviceName = $serviceName;
  4187. $this->wsdl->endpoint = $endpoint;
  4188. $this->wsdl->namespaces['tns'] = $namespace;
  4189. $this->wsdl->namespaces['soap'] = 'http://schemas.xmlsoap.org/wsdl/soap/';
  4190. $this->wsdl->namespaces['wsdl'] = 'http://schemas.xmlsoap.org/wsdl/';
  4191. if ($schemaTargetNamespace != $namespace) {
  4192. $this->wsdl->namespaces['types'] = $schemaTargetNamespace;
  4193. }
  4194. $this->wsdl->schemas[$schemaTargetNamespace][0] = new nusoap_xmlschema('', '', $this->wsdl->namespaces);
  4195. if ($style == 'document') {
  4196. $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaInfo['elementFormDefault'] = 'qualified';
  4197. }
  4198. $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaTargetNamespace = $schemaTargetNamespace;
  4199. $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/soap/encoding/'][0] = array('location' => '', 'loaded' => true);
  4200. $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/wsdl/'][0] = array('location' => '', 'loaded' => true);
  4201. $this->wsdl->bindings[$serviceName.'Binding'] = array(
  4202. 'name'=>$serviceName.'Binding',
  4203. 'style'=>$style,
  4204. 'transport'=>$transport,
  4205. 'portType'=>$serviceName.'PortType');
  4206. $this->wsdl->ports[$serviceName.'Port'] = array(
  4207. 'binding'=>$serviceName.'Binding',
  4208. 'location'=>$endpoint,
  4209. 'bindingType'=>'http://schemas.xmlsoap.org/wsdl/soap/');
  4210. }
  4211. }
  4212. /**
  4213. * Backward compatibility
  4214. */
  4215. class soap_server extends nusoap_server {
  4216. }
  4217. ?><?php
  4218. /**
  4219. * parses a WSDL file, allows access to it's data, other utility methods.
  4220. * also builds WSDL structures programmatically.
  4221. *
  4222. * @author Dietrich Ayala <dietrich@ganx4.com>
  4223. * @author Scott Nichol <snichol@users.sourceforge.net>
  4224. * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $
  4225. * @access public
  4226. */
  4227. class wsdl extends nusoap_base {
  4228. // URL or filename of the root of this WSDL
  4229. var $wsdl;
  4230. // define internal arrays of bindings, ports, operations, messages, etc.
  4231. var $schemas = array();
  4232. var $currentSchema;
  4233. var $message = array();
  4234. var $complexTypes = array();
  4235. var $messages = array();
  4236. var $currentMessage;
  4237. var $currentOperation;
  4238. var $portTypes = array();
  4239. var $currentPortType;
  4240. var $bindings = array();
  4241. var $currentBinding;
  4242. var $ports = array();
  4243. var $currentPort;
  4244. var $opData = array();
  4245. var $status = '';
  4246. var $documentation = false;
  4247. var $endpoint = '';
  4248. // array of wsdl docs to import
  4249. var $import = array();
  4250. // parser vars
  4251. var $parser;
  4252. var $position = 0;
  4253. var $depth = 0;
  4254. var $depth_array = array();
  4255. // for getting wsdl
  4256. var $proxyhost = '';
  4257. var $proxyport = '';
  4258. var $proxyusername = '';
  4259. var $proxypassword = '';
  4260. var $timeout = 0;
  4261. var $response_timeout = 30;
  4262. var $curl_options = array(); // User-specified cURL options
  4263. var $use_curl = false; // whether to always try to use cURL
  4264. // for HTTP authentication
  4265. var $username = ''; // Username for HTTP authentication
  4266. var $password = ''; // Password for HTTP authentication
  4267. var $authtype = ''; // Type of HTTP authentication
  4268. var $certRequest = array(); // Certificate for HTTP SSL authentication
  4269. /**
  4270. * constructor
  4271. *
  4272. * @param string $wsdl WSDL document URL
  4273. * @param string $proxyhost
  4274. * @param string $proxyport
  4275. * @param string $proxyusername
  4276. * @param string $proxypassword
  4277. * @param integer $timeout set the connection timeout
  4278. * @param integer $response_timeout set the response timeout
  4279. * @param array $curl_options user-specified cURL options
  4280. * @param boolean $use_curl try to use cURL
  4281. * @access public
  4282. */
  4283. function wsdl($wsdl = '',$proxyhost=false,$proxyport=false,$proxyusername=false,$proxypassword=false,$timeout=0,$response_timeout=30,$curl_options=null,$use_curl=false){
  4284. parent::nusoap_base();
  4285. $this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout");
  4286. $this->proxyhost = $proxyhost;
  4287. $this->proxyport = $proxyport;
  4288. $this->proxyusername = $proxyusername;
  4289. $this->proxypassword = $proxypassword;
  4290. $this->timeout = $timeout;
  4291. $this->response_timeout = $response_timeout;
  4292. if (is_array($curl_options))
  4293. $this->curl_options = $curl_options;
  4294. $this->use_curl = $use_curl;
  4295. $this->fetchWSDL($wsdl);
  4296. }
  4297. /**
  4298. * fetches the WSDL document and parses it
  4299. *
  4300. * @access public
  4301. */
  4302. function fetchWSDL($wsdl) {
  4303. $this->debug("parse and process WSDL path=$wsdl");
  4304. $this->wsdl = $wsdl;
  4305. // parse wsdl file
  4306. if ($this->wsdl != "") {
  4307. $this->parseWSDL($this->wsdl);
  4308. }
  4309. // imports
  4310. // TODO: handle imports more properly, grabbing them in-line and nesting them
  4311. $imported_urls = array();
  4312. $imported = 1;
  4313. while ($imported > 0) {
  4314. $imported = 0;
  4315. // Schema imports
  4316. foreach ($this->schemas as $ns => $list) {
  4317. foreach ($list as $xs) {
  4318. $wsdlparts = parse_url($this->wsdl); // this is bogusly simple!
  4319. foreach ($xs->imports as $ns2 => $list2) {
  4320. for ($ii = 0; $ii < count($list2); $ii++) {
  4321. if (! $list2[$ii]['loaded']) {
  4322. $this->schemas[$ns]->imports[$ns2][$ii]['loaded'] = true;
  4323. $url = $list2[$ii]['location'];
  4324. if ($url != '') {
  4325. $urlparts = parse_url($url);
  4326. if (!isset($urlparts['host'])) {
  4327. $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' .$wsdlparts['port'] : '') .
  4328. substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
  4329. }
  4330. if (! in_array($url, $imported_urls)) {
  4331. $this->parseWSDL($url);
  4332. $imported++;
  4333. $imported_urls[] = $url;
  4334. }
  4335. } else {
  4336. $this->debug("Unexpected scenario: empty URL for unloaded import");
  4337. }
  4338. }
  4339. }
  4340. }
  4341. }
  4342. }
  4343. // WSDL imports
  4344. $wsdlparts = parse_url($this->wsdl); // this is bogusly simple!
  4345. foreach ($this->import as $ns => $list) {
  4346. for ($ii = 0; $ii < count($list); $ii++) {
  4347. if (! $list[$ii]['loaded']) {
  4348. $this->import[$ns][$ii]['loaded'] = true;
  4349. $url = $list[$ii]['location'];
  4350. if ($url != '') {
  4351. $urlparts = parse_url($url);
  4352. if (!isset($urlparts['host'])) {
  4353. $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') .
  4354. substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
  4355. }
  4356. if (! in_array($url, $imported_urls)) {
  4357. $this->parseWSDL($url);
  4358. $imported++;
  4359. $imported_urls[] = $url;
  4360. }
  4361. } else {
  4362. $this->debug("Unexpected scenario: empty URL for unloaded import");
  4363. }
  4364. }
  4365. }
  4366. }
  4367. }
  4368. // add new data to operation data
  4369. foreach($this->bindings as $binding => $bindingData) {
  4370. if (isset($bindingData['operations']) && is_array($bindingData['operations'])) {
  4371. foreach($bindingData['operations'] as $operation => $data) {
  4372. $this->debug('post-parse data gathering for ' . $operation);
  4373. $this->bindings[$binding]['operations'][$operation]['input'] =
  4374. isset($this->bindings[$binding]['operations'][$operation]['input']) ?
  4375. array_merge($this->bindings[$binding]['operations'][$operation]['input'], $this->portTypes[ $bindingData['portType'] ][$operation]['input']) :
  4376. $this->portTypes[ $bindingData['portType'] ][$operation]['input'];
  4377. $this->bindings[$binding]['operations'][$operation]['output'] =
  4378. isset($this->bindings[$binding]['operations'][$operation]['output']) ?
  4379. array_merge($this->bindings[$binding]['operations'][$operation]['output'], $this->portTypes[ $bindingData['portType'] ][$operation]['output']) :
  4380. $this->portTypes[ $bindingData['portType'] ][$operation]['output'];
  4381. if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ])){
  4382. $this->bindings[$binding]['operations'][$operation]['input']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ];
  4383. }
  4384. if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ])){
  4385. $this->bindings[$binding]['operations'][$operation]['output']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ];
  4386. }
  4387. // Set operation style if necessary, but do not override one already provided
  4388. if (isset($bindingData['style']) && !isset($this->bindings[$binding]['operations'][$operation]['style'])) {
  4389. $this->bindings[$binding]['operations'][$operation]['style'] = $bindingData['style'];
  4390. }
  4391. $this->bindings[$binding]['operations'][$operation]['transport'] = isset($bindingData['transport']) ? $bindingData['transport'] : '';
  4392. $this->bindings[$binding]['operations'][$operation]['documentation'] = isset($this->portTypes[ $bindingData['portType'] ][$operation]['documentation']) ? $this->portTypes[ $bindingData['portType'] ][$operation]['documentation'] : '';
  4393. $this->bindings[$binding]['operations'][$operation]['endpoint'] = isset($bindingData['endpoint']) ? $bindingData['endpoint'] : '';
  4394. }
  4395. }
  4396. }
  4397. }
  4398. /**
  4399. * parses the wsdl document
  4400. *
  4401. * @param string $wsdl path or URL
  4402. * @access private
  4403. */
  4404. function parseWSDL($wsdl = '') {
  4405. $this->debug("parse WSDL at path=$wsdl");
  4406. if ($wsdl == '') {
  4407. $this->debug('no wsdl passed to parseWSDL()!!');
  4408. $this->setError('no wsdl passed to parseWSDL()!!');
  4409. return false;
  4410. }
  4411. // parse $wsdl for url format
  4412. $wsdl_props = parse_url($wsdl);
  4413. if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'http' || $wsdl_props['scheme'] == 'https')) {
  4414. $this->debug('getting WSDL http(s) URL ' . $wsdl);
  4415. // get wsdl
  4416. $tr = new soap_transport_http($wsdl, $this->curl_options, $this->use_curl);
  4417. $tr->request_method = 'GET';
  4418. $tr->useSOAPAction = false;
  4419. if($this->proxyhost && $this->proxyport){
  4420. $tr->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword);
  4421. }
  4422. if ($this->authtype != '') {
  4423. $tr->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest);
  4424. }
  4425. $tr->setEncoding('gzip, deflate');
  4426. $wsdl_string = $tr->send('', $this->timeout, $this->response_timeout);
  4427. //$this->debug("WSDL request\n" . $tr->outgoing_payload);
  4428. //$this->debug("WSDL response\n" . $tr->incoming_payload);
  4429. $this->appendDebug($tr->getDebug());
  4430. // catch errors
  4431. if($err = $tr->getError() ){
  4432. $errstr = 'HTTP ERROR: '.$err;
  4433. $this->debug($errstr);
  4434. $this->setError($errstr);
  4435. unset($tr);
  4436. return false;
  4437. }
  4438. unset($tr);
  4439. $this->debug("got WSDL URL");
  4440. } else {
  4441. // $wsdl is not http(s), so treat it as a file URL or plain file path
  4442. if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'file') && isset($wsdl_props['path'])) {
  4443. $path = isset($wsdl_props['host']) ? ($wsdl_props['host'] . ':' . $wsdl_props['path']) : $wsdl_props['path'];
  4444. } else {
  4445. $path = $wsdl;
  4446. }
  4447. $this->debug('getting WSDL file ' . $path);
  4448. if ($fp = @fopen($path, 'r')) {
  4449. $wsdl_string = '';
  4450. while ($data = fread($fp, 32768)) {
  4451. $wsdl_string .= $data;
  4452. }
  4453. fclose($fp);
  4454. } else {
  4455. $errstr = "Bad path to WSDL file $path";
  4456. $this->debug($errstr);
  4457. $this->setError($errstr);
  4458. return false;
  4459. }
  4460. }
  4461. $this->debug('Parse WSDL');
  4462. // end new code added
  4463. // Create an XML parser.
  4464. $this->parser = xml_parser_create();
  4465. // Set the options for parsing the XML data.
  4466. // xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  4467. xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
  4468. // Set the object for the parser.
  4469. xml_set_object($this->parser, $this);
  4470. // Set the element handlers for the parser.
  4471. xml_set_element_handler($this->parser, 'start_element', 'end_element');
  4472. xml_set_character_data_handler($this->parser, 'character_data');
  4473. // Parse the XML file.
  4474. if (!xml_parse($this->parser, $wsdl_string, true)) {
  4475. // Display an error message.
  4476. $errstr = sprintf(
  4477. 'XML error parsing WSDL from %s on line %d: %s',
  4478. $wsdl,
  4479. xml_get_current_line_number($this->parser),
  4480. xml_error_string(xml_get_error_code($this->parser))
  4481. );
  4482. $this->debug($errstr);
  4483. $this->debug("XML payload:\n" . $wsdl_string);
  4484. $this->setError($errstr);
  4485. return false;
  4486. }
  4487. // free the parser
  4488. xml_parser_free($this->parser);
  4489. $this->debug('Parsing WSDL done');
  4490. // catch wsdl parse errors
  4491. if($this->getError()){
  4492. return false;
  4493. }
  4494. return true;
  4495. }
  4496. /**
  4497. * start-element handler
  4498. *
  4499. * @param string $parser XML parser object
  4500. * @param string $name element name
  4501. * @param string $attrs associative array of attributes
  4502. * @access private
  4503. */
  4504. function start_element($parser, $name, $attrs)
  4505. {
  4506. if ($this->status == 'schema') {
  4507. $this->currentSchema->schemaStartElement($parser, $name, $attrs);
  4508. $this->appendDebug($this->currentSchema->getDebug());
  4509. $this->currentSchema->clearDebug();
  4510. } elseif (ereg('schema$', $name)) {
  4511. $this->debug('Parsing WSDL schema');
  4512. // $this->debug("startElement for $name ($attrs[name]). status = $this->status (".$this->getLocalPart($name).")");
  4513. $this->status = 'schema';
  4514. $this->currentSchema = new nusoap_xmlschema('', '', $this->namespaces);
  4515. $this->currentSchema->schemaStartElement($parser, $name, $attrs);
  4516. $this->appendDebug($this->currentSchema->getDebug());
  4517. $this->currentSchema->clearDebug();
  4518. } else {
  4519. // position in the total number of elements, starting from 0
  4520. $pos = $this->position++;
  4521. $depth = $this->depth++;
  4522. // set self as current value for this depth
  4523. $this->depth_array[$depth] = $pos;
  4524. $this->message[$pos] = array('cdata' => '');
  4525. // process attributes
  4526. if (count($attrs) > 0) {
  4527. // register namespace declarations
  4528. foreach($attrs as $k => $v) {
  4529. if (ereg("^xmlns", $k)) {
  4530. if ($ns_prefix = substr(strrchr($k, ':'), 1)) {
  4531. $this->namespaces[$ns_prefix] = $v;
  4532. } else {
  4533. $this->namespaces['ns' . (count($this->namespaces) + 1)] = $v;
  4534. }
  4535. if ($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema') {
  4536. $this->XMLSchemaVersion = $v;
  4537. $this->namespaces['xsi'] = $v . '-instance';
  4538. }
  4539. }
  4540. }
  4541. // expand each attribute prefix to its namespace
  4542. foreach($attrs as $k => $v) {
  4543. $k = strpos($k, ':') ? $this->expandQname($k) : $k;
  4544. if ($k != 'location' && $k != 'soapAction' && $k != 'namespace') {
  4545. $v = strpos($v, ':') ? $this->expandQname($v) : $v;
  4546. }
  4547. $eAttrs[$k] = $v;
  4548. }
  4549. $attrs = $eAttrs;
  4550. } else {
  4551. $attrs = array();
  4552. }
  4553. // get element prefix, namespace and name
  4554. if (ereg(':', $name)) {
  4555. // get ns prefix
  4556. $prefix = substr($name, 0, strpos($name, ':'));
  4557. // get ns
  4558. $namespace = isset($this->namespaces[$prefix]) ? $this->namespaces[$prefix] : '';
  4559. // get unqualified name
  4560. $name = substr(strstr($name, ':'), 1);
  4561. }
  4562. // process attributes, expanding any prefixes to namespaces
  4563. // find status, register data
  4564. switch ($this->status) {
  4565. case 'message':
  4566. if ($name == 'part') {
  4567. if (isset($attrs['type'])) {
  4568. $this->debug("msg " . $this->currentMessage . ": found part (with type) $attrs[name]: " . implode(',', $attrs));
  4569. $this->messages[$this->currentMessage][$attrs['name']] = $attrs['type'];
  4570. }
  4571. if (isset($attrs['element'])) {
  4572. $this->debug("msg " . $this->currentMessage . ": found part (with element) $attrs[name]: " . implode(',', $attrs));
  4573. $this->messages[$this->currentMessage][$attrs['name']] = $attrs['element'] . '^';
  4574. }
  4575. }
  4576. break;
  4577. case 'portType':
  4578. switch ($name) {
  4579. case 'operation':
  4580. $this->currentPortOperation = $attrs['name'];
  4581. $this->debug("portType $this->currentPortType operation: $this->currentPortOperation");
  4582. if (isset($attrs['parameterOrder'])) {
  4583. $this->portTypes[$this->currentPortType][$attrs['name']]['parameterOrder'] = $attrs['parameterOrder'];
  4584. }
  4585. break;
  4586. case 'documentation':
  4587. $this->documentation = true;
  4588. break;
  4589. // merge input/output data
  4590. default:
  4591. $m = isset($attrs['message']) ? $this->getLocalPart($attrs['message']) : '';
  4592. $this->portTypes[$this->currentPortType][$this->currentPortOperation][$name]['message'] = $m;
  4593. break;
  4594. }
  4595. break;
  4596. case 'binding':
  4597. switch ($name) {
  4598. case 'binding':
  4599. // get ns prefix
  4600. if (isset($attrs['style'])) {
  4601. $this->bindings[$this->currentBinding]['prefix'] = $prefix;
  4602. }
  4603. $this->bindings[$this->currentBinding] = array_merge($this->bindings[$this->currentBinding], $attrs);
  4604. break;
  4605. case 'header':
  4606. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs;
  4607. break;
  4608. case 'operation':
  4609. if (isset($attrs['soapAction'])) {
  4610. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['soapAction'] = $attrs['soapAction'];
  4611. }
  4612. if (isset($attrs['style'])) {
  4613. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['style'] = $attrs['style'];
  4614. }
  4615. if (isset($attrs['name'])) {
  4616. $this->currentOperation = $attrs['name'];
  4617. $this->debug("current binding operation: $this->currentOperation");
  4618. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['name'] = $attrs['name'];
  4619. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['binding'] = $this->currentBinding;
  4620. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['endpoint'] = isset($this->bindings[$this->currentBinding]['endpoint']) ? $this->bindings[$this->currentBinding]['endpoint'] : '';
  4621. }
  4622. break;
  4623. case 'input':
  4624. $this->opStatus = 'input';
  4625. break;
  4626. case 'output':
  4627. $this->opStatus = 'output';
  4628. break;
  4629. case 'body':
  4630. if (isset($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus])) {
  4631. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = array_merge($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus], $attrs);
  4632. } else {
  4633. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = $attrs;
  4634. }
  4635. break;
  4636. }
  4637. break;
  4638. case 'service':
  4639. switch ($name) {
  4640. case 'port':
  4641. $this->currentPort = $attrs['name'];
  4642. $this->debug('current port: ' . $this->currentPort);
  4643. $this->ports[$this->currentPort]['binding'] = $this->getLocalPart($attrs['binding']);
  4644. break;
  4645. case 'address':
  4646. $this->ports[$this->currentPort]['location'] = $attrs['location'];
  4647. $this->ports[$this->currentPort]['bindingType'] = $namespace;
  4648. $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['bindingType'] = $namespace;
  4649. $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['endpoint'] = $attrs['location'];
  4650. break;
  4651. }
  4652. break;
  4653. }
  4654. // set status
  4655. switch ($name) {
  4656. case 'import':
  4657. if (isset($attrs['location'])) {
  4658. $this->import[$attrs['namespace']][] = array('location' => $attrs['location'], 'loaded' => false);
  4659. $this->debug('parsing import ' . $attrs['namespace']. ' - ' . $attrs['location'] . ' (' . count($this->import[$attrs['namespace']]).')');
  4660. } else {
  4661. $this->import[$attrs['namespace']][] = array('location' => '', 'loaded' => true);
  4662. if (! $this->getPrefixFromNamespace($attrs['namespace'])) {
  4663. $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace'];
  4664. }
  4665. $this->debug('parsing import ' . $attrs['namespace']. ' - [no location] (' . count($this->import[$attrs['namespace']]).')');
  4666. }
  4667. break;
  4668. //wait for schema
  4669. //case 'types':
  4670. // $this->status = 'schema';
  4671. // break;
  4672. case 'message':
  4673. $this->status = 'message';
  4674. $this->messages[$attrs['name']] = array();
  4675. $this->currentMessage = $attrs['name'];
  4676. break;
  4677. case 'portType':
  4678. $this->status = 'portType';
  4679. $this->portTypes[$attrs['name']] = array();
  4680. $this->currentPortType = $attrs['name'];
  4681. break;
  4682. case "binding":
  4683. if (isset($attrs['name'])) {
  4684. // get binding name
  4685. if (strpos($attrs['name'], ':')) {
  4686. $this->currentBinding = $this->getLocalPart($attrs['name']);
  4687. } else {
  4688. $this->currentBinding = $attrs['name'];
  4689. }
  4690. $this->status = 'binding';
  4691. $this->bindings[$this->currentBinding]['portType'] = $this->getLocalPart($attrs['type']);
  4692. $this->debug("current binding: $this->currentBinding of portType: " . $attrs['type']);
  4693. }
  4694. break;
  4695. case 'service':
  4696. $this->serviceName = $attrs['name'];
  4697. $this->status = 'service';
  4698. $this->debug('current service: ' . $this->serviceName);
  4699. break;
  4700. case 'definitions':
  4701. foreach ($attrs as $name => $value) {
  4702. $this->wsdl_info[$name] = $value;
  4703. }
  4704. break;
  4705. }
  4706. }
  4707. }
  4708. /**
  4709. * end-element handler
  4710. *
  4711. * @param string $parser XML parser object
  4712. * @param string $name element name
  4713. * @access private
  4714. */
  4715. function end_element($parser, $name){
  4716. // unset schema status
  4717. if (/*ereg('types$', $name) ||*/ ereg('schema$', $name)) {
  4718. $this->status = "";
  4719. $this->appendDebug($this->currentSchema->getDebug());
  4720. $this->currentSchema->clearDebug();
  4721. $this->schemas[$this->currentSchema->schemaTargetNamespace][] = $this->currentSchema;
  4722. $this->debug('Parsing WSDL schema done');
  4723. }
  4724. if ($this->status == 'schema') {
  4725. $this->currentSchema->schemaEndElement($parser, $name);
  4726. } else {
  4727. // bring depth down a notch
  4728. $this->depth--;
  4729. }
  4730. // end documentation
  4731. if ($this->documentation) {
  4732. //TODO: track the node to which documentation should be assigned; it can be a part, message, etc.
  4733. //$this->portTypes[$this->currentPortType][$this->currentPortOperation]['documentation'] = $this->documentation;
  4734. $this->documentation = false;
  4735. }
  4736. }
  4737. /**
  4738. * element content handler
  4739. *
  4740. * @param string $parser XML parser object
  4741. * @param string $data element content
  4742. * @access private
  4743. */
  4744. function character_data($parser, $data)
  4745. {
  4746. $pos = isset($this->depth_array[$this->depth]) ? $this->depth_array[$this->depth] : 0;
  4747. if (isset($this->message[$pos]['cdata'])) {
  4748. $this->message[$pos]['cdata'] .= $data;
  4749. }
  4750. if ($this->documentation) {
  4751. $this->documentation .= $data;
  4752. }
  4753. }
  4754. /**
  4755. * if authenticating, set user credentials here
  4756. *
  4757. * @param string $username
  4758. * @param string $password
  4759. * @param string $authtype (basic|digest|certificate|ntlm)
  4760. * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
  4761. * @access public
  4762. */
  4763. function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) {
  4764. $this->debug("setCredentials username=$username authtype=$authtype certRequest=");
  4765. $this->appendDebug($this->varDump($certRequest));
  4766. $this->username = $username;
  4767. $this->password = $password;
  4768. $this->authtype = $authtype;
  4769. $this->certRequest = $certRequest;
  4770. }
  4771. function getBindingData($binding)
  4772. {
  4773. if (is_array($this->bindings[$binding])) {
  4774. return $this->bindings[$binding];
  4775. }
  4776. }
  4777. /**
  4778. * returns an assoc array of operation names => operation data
  4779. *
  4780. * @param string $bindingType eg: soap, smtp, dime (only soap and soap12 are currently supported)
  4781. * @return array
  4782. * @access public
  4783. */
  4784. function getOperations($bindingType = 'soap') {
  4785. $ops = array();
  4786. if ($bindingType == 'soap') {
  4787. $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
  4788. } elseif ($bindingType == 'soap12') {
  4789. $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
  4790. }
  4791. // loop thru ports
  4792. foreach($this->ports as $port => $portData) {
  4793. // binding type of port matches parameter
  4794. if ($portData['bindingType'] == $bindingType) {
  4795. //$this->debug("getOperations for port $port");
  4796. //$this->debug("port data: " . $this->varDump($portData));
  4797. //$this->debug("bindings: " . $this->varDump($this->bindings[ $portData['binding'] ]));
  4798. // merge bindings
  4799. if (isset($this->bindings[ $portData['binding'] ]['operations'])) {
  4800. $ops = array_merge ($ops, $this->bindings[ $portData['binding'] ]['operations']);
  4801. }
  4802. }
  4803. }
  4804. return $ops;
  4805. }
  4806. /**
  4807. * returns an associative array of data necessary for calling an operation
  4808. *
  4809. * @param string $operation name of operation
  4810. * @param string $bindingType type of binding eg: soap, soap12
  4811. * @return array
  4812. * @access public
  4813. */
  4814. function getOperationData($operation, $bindingType = 'soap')
  4815. {
  4816. if ($bindingType == 'soap') {
  4817. $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
  4818. } elseif ($bindingType == 'soap12') {
  4819. $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
  4820. }
  4821. // loop thru ports
  4822. foreach($this->ports as $port => $portData) {
  4823. // binding type of port matches parameter
  4824. if ($portData['bindingType'] == $bindingType) {
  4825. // get binding
  4826. //foreach($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
  4827. foreach(array_keys($this->bindings[ $portData['binding'] ]['operations']) as $bOperation) {
  4828. // note that we could/should also check the namespace here
  4829. if ($operation == $bOperation) {
  4830. $opData = $this->bindings[ $portData['binding'] ]['operations'][$operation];
  4831. return $opData;
  4832. }
  4833. }
  4834. }
  4835. }
  4836. }
  4837. /**
  4838. * returns an associative array of data necessary for calling an operation
  4839. *
  4840. * @param string $soapAction soapAction for operation
  4841. * @param string $bindingType type of binding eg: soap, soap12
  4842. * @return array
  4843. * @access public
  4844. */
  4845. function getOperationDataForSoapAction($soapAction, $bindingType = 'soap') {
  4846. if ($bindingType == 'soap') {
  4847. $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
  4848. } elseif ($bindingType == 'soap12') {
  4849. $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
  4850. }
  4851. // loop thru ports
  4852. foreach($this->ports as $port => $portData) {
  4853. // binding type of port matches parameter
  4854. if ($portData['bindingType'] == $bindingType) {
  4855. // loop through operations for the binding
  4856. foreach ($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
  4857. if ($opData['soapAction'] == $soapAction) {
  4858. return $opData;
  4859. }
  4860. }
  4861. }
  4862. }
  4863. }
  4864. /**
  4865. * returns an array of information about a given type
  4866. * returns false if no type exists by the given name
  4867. *
  4868. * typeDef = array(
  4869. * 'elements' => array(), // refs to elements array
  4870. * 'restrictionBase' => '',
  4871. * 'phpType' => '',
  4872. * 'order' => '(sequence|all)',
  4873. * 'attrs' => array() // refs to attributes array
  4874. * )
  4875. *
  4876. * @param string $type the type
  4877. * @param string $ns namespace (not prefix) of the type
  4878. * @return mixed
  4879. * @access public
  4880. * @see nusoap_xmlschema
  4881. */
  4882. function getTypeDef($type, $ns) {
  4883. $this->debug("in getTypeDef: type=$type, ns=$ns");
  4884. if ((! $ns) && isset($this->namespaces['tns'])) {
  4885. $ns = $this->namespaces['tns'];
  4886. $this->debug("in getTypeDef: type namespace forced to $ns");
  4887. }
  4888. if (!isset($this->schemas[$ns])) {
  4889. foreach ($this->schemas as $ns0 => $schema0) {
  4890. if (strcasecmp($ns, $ns0) == 0) {
  4891. $this->debug("in getTypeDef: replacing schema namespace $ns with $ns0");
  4892. $ns = $ns0;
  4893. break;
  4894. }
  4895. }
  4896. }
  4897. if (isset($this->schemas[$ns])) {
  4898. $this->debug("in getTypeDef: have schema for namespace $ns");
  4899. for ($i = 0; $i < count($this->schemas[$ns]); $i++) {
  4900. $xs = &$this->schemas[$ns][$i];
  4901. $t = $xs->getTypeDef($type);
  4902. //$this->appendDebug($xs->getDebug());
  4903. //$xs->clearDebug();
  4904. if ($t) {
  4905. if (!isset($t['phpType'])) {
  4906. // get info for type to tack onto the element
  4907. $uqType = substr($t['type'], strrpos($t['type'], ':') + 1);
  4908. $ns = substr($t['type'], 0, strrpos($t['type'], ':'));
  4909. $etype = $this->getTypeDef($uqType, $ns);
  4910. if ($etype) {
  4911. $this->debug("found type for [element] $type:");
  4912. $this->debug($this->varDump($etype));
  4913. if (isset($etype['phpType'])) {
  4914. $t['phpType'] = $etype['phpType'];
  4915. }
  4916. if (isset($etype['elements'])) {
  4917. $t['elements'] = $etype['elements'];
  4918. }
  4919. if (isset($etype['attrs'])) {
  4920. $t['attrs'] = $etype['attrs'];
  4921. }
  4922. }
  4923. }
  4924. return $t;
  4925. }
  4926. }
  4927. } else {
  4928. $this->debug("in getTypeDef: do not have schema for namespace $ns");
  4929. }
  4930. return false;
  4931. }
  4932. /**
  4933. * prints html description of services
  4934. *
  4935. * @access private
  4936. */
  4937. function webDescription(){
  4938. global $HTTP_SERVER_VARS;
  4939. if (isset($_SERVER)) {
  4940. $PHP_SELF = $_SERVER['PHP_SELF'];
  4941. } elseif (isset($HTTP_SERVER_VARS)) {
  4942. $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
  4943. } else {
  4944. $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
  4945. }
  4946. $b = '
  4947. <html><head><title>NuSOAP: '.$this->serviceName.'</title>
  4948. <style type="text/css">
  4949. body { font-family: arial; color: #000000; background-color: #ffffff; margin: 0px 0px 0px 0px; }
  4950. p { font-family: arial; color: #000000; margin-top: 0px; margin-bottom: 12px; }
  4951. pre { background-color: silver; padding: 5px; font-family: Courier New; font-size: x-small; color: #000000;}
  4952. ul { margin-top: 10px; margin-left: 20px; }
  4953. li { list-style-type: none; margin-top: 10px; color: #000000; }
  4954. .content{
  4955. margin-left: 0px; padding-bottom: 2em; }
  4956. .nav {
  4957. padding-top: 10px; padding-bottom: 10px; padding-left: 15px; font-size: .70em;
  4958. margin-top: 10px; margin-left: 0px; color: #000000;
  4959. background-color: #ccccff; width: 20%; margin-left: 20px; margin-top: 20px; }
  4960. .title {
  4961. font-family: arial; font-size: 26px; color: #ffffff;
  4962. background-color: #999999; width: 105%; margin-left: 0px;
  4963. padding-top: 10px; padding-bottom: 10px; padding-left: 15px;}
  4964. .hidden {
  4965. position: absolute; visibility: hidden; z-index: 200; left: 250px; top: 100px;
  4966. font-family: arial; overflow: hidden; width: 600;
  4967. padding: 20px; font-size: 10px; background-color: #999999;
  4968. layer-background-color:#FFFFFF; }
  4969. a,a:active { color: charcoal; font-weight: bold; }
  4970. a:visited { color: #666666; font-weight: bold; }
  4971. a:hover { color: cc3300; font-weight: bold; }
  4972. </style>
  4973. <script language="JavaScript" type="text/javascript">
  4974. <!--
  4975. // POP-UP CAPTIONS...
  4976. function lib_bwcheck(){ //Browsercheck (needed)
  4977. this.ver=navigator.appVersion
  4978. this.agent=navigator.userAgent
  4979. this.dom=document.getElementById?1:0
  4980. this.opera5=this.agent.indexOf("Opera 5")>-1
  4981. this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0;
  4982. this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
  4983. this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
  4984. this.ie=this.ie4||this.ie5||this.ie6
  4985. this.mac=this.agent.indexOf("Mac")>-1
  4986. this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0;
  4987. this.ns4=(document.layers && !this.dom)?1:0;
  4988. this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5)
  4989. return this
  4990. }
  4991. var bw = new lib_bwcheck()
  4992. //Makes crossbrowser object.
  4993. function makeObj(obj){
  4994. this.evnt=bw.dom? document.getElementById(obj):bw.ie4?document.all[obj]:bw.ns4?document.layers[obj]:0;
  4995. if(!this.evnt) return false
  4996. this.css=bw.dom||bw.ie4?this.evnt.style:bw.ns4?this.evnt:0;
  4997. this.wref=bw.dom||bw.ie4?this.evnt:bw.ns4?this.css.document:0;
  4998. this.writeIt=b_writeIt;
  4999. return this
  5000. }
  5001. // A unit of measure that will be added when setting the position of a layer.
  5002. //var px = bw.ns4||window.opera?"":"px";
  5003. function b_writeIt(text){
  5004. if (bw.ns4){this.wref.write(text);this.wref.close()}
  5005. else this.wref.innerHTML = text
  5006. }
  5007. //Shows the messages
  5008. var oDesc;
  5009. function popup(divid){
  5010. if(oDesc = new makeObj(divid)){
  5011. oDesc.css.visibility = "visible"
  5012. }
  5013. }
  5014. function popout(){ // Hides message
  5015. if(oDesc) oDesc.css.visibility = "hidden"
  5016. }
  5017. //-->
  5018. </script>
  5019. </head>
  5020. <body>
  5021. <div class=content>
  5022. <br><br>
  5023. <div class=title>'.$this->serviceName.'</div>
  5024. <div class=nav>
  5025. <p>View the <a href="'.$PHP_SELF.'?wsdl">WSDL</a> for the service.
  5026. Click on an operation name to view it&apos;s details.</p>
  5027. <ul>';
  5028. foreach($this->getOperations() as $op => $data){
  5029. $b .= "<li><a href='#' onclick=\"popout();popup('$op')\">$op</a></li>";
  5030. // create hidden div
  5031. $b .= "<div id='$op' class='hidden'>
  5032. <a href='#' onclick='popout()'><font color='#ffffff'>Close</font></a><br><br>";
  5033. foreach($data as $donnie => $marie){ // loop through opdata
  5034. if($donnie == 'input' || $donnie == 'output'){ // show input/output data
  5035. $b .= "<font color='white'>".ucfirst($donnie).':</font><br>';
  5036. foreach($marie as $captain => $tenille){ // loop through data
  5037. if($captain == 'parts'){ // loop thru parts
  5038. $b .= "&nbsp;&nbsp;$captain:<br>";
  5039. //if(is_array($tenille)){
  5040. foreach($tenille as $joanie => $chachi){
  5041. $b .= "&nbsp;&nbsp;&nbsp;&nbsp;$joanie: $chachi<br>";
  5042. }
  5043. //}
  5044. } else {
  5045. $b .= "&nbsp;&nbsp;$captain: $tenille<br>";
  5046. }
  5047. }
  5048. } else {
  5049. $b .= "<font color='white'>".ucfirst($donnie).":</font> $marie<br>";
  5050. }
  5051. }
  5052. $b .= '</div>';
  5053. }
  5054. $b .= '
  5055. <ul>
  5056. </div>
  5057. </div></body></html>';
  5058. return $b;
  5059. }
  5060. /**
  5061. * serialize the parsed wsdl
  5062. *
  5063. * @param mixed $debug whether to put debug=1 in endpoint URL
  5064. * @return string serialization of WSDL
  5065. * @access public
  5066. */
  5067. function serialize($debug = 0)
  5068. {
  5069. $xml = '<?xml version="1.0" encoding="ISO-8859-1"?>';
  5070. $xml .= "\n<definitions";
  5071. foreach($this->namespaces as $k => $v) {
  5072. $xml .= " xmlns:$k=\"$v\"";
  5073. }
  5074. // 10.9.02 - add poulter fix for wsdl and tns declarations
  5075. if (isset($this->namespaces['wsdl'])) {
  5076. $xml .= " xmlns=\"" . $this->namespaces['wsdl'] . "\"";
  5077. }
  5078. if (isset($this->namespaces['tns'])) {
  5079. $xml .= " targetNamespace=\"" . $this->namespaces['tns'] . "\"";
  5080. }
  5081. $xml .= '>';
  5082. // imports
  5083. if (sizeof($this->import) > 0) {
  5084. foreach($this->import as $ns => $list) {
  5085. foreach ($list as $ii) {
  5086. if ($ii['location'] != '') {
  5087. $xml .= '<import location="' . $ii['location'] . '" namespace="' . $ns . '" />';
  5088. } else {
  5089. $xml .= '<import namespace="' . $ns . '" />';
  5090. }
  5091. }
  5092. }
  5093. }
  5094. // types
  5095. if (count($this->schemas)>=1) {
  5096. $xml .= "\n<types>\n";
  5097. foreach ($this->schemas as $ns => $list) {
  5098. foreach ($list as $xs) {
  5099. $xml .= $xs->serializeSchema();
  5100. }
  5101. }
  5102. $xml .= '</types>';
  5103. }
  5104. // messages
  5105. if (count($this->messages) >= 1) {
  5106. foreach($this->messages as $msgName => $msgParts) {
  5107. $xml .= "\n<message name=\"" . $msgName . '">';
  5108. if(is_array($msgParts)){
  5109. foreach($msgParts as $partName => $partType) {
  5110. // print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'<br>';
  5111. if (strpos($partType, ':')) {
  5112. $typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType));
  5113. } elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) {
  5114. // print 'checking typemap: '.$this->XMLSchemaVersion.'<br>';
  5115. $typePrefix = 'xsd';
  5116. } else {
  5117. foreach($this->typemap as $ns => $types) {
  5118. if (isset($types[$partType])) {
  5119. $typePrefix = $this->getPrefixFromNamespace($ns);
  5120. }
  5121. }
  5122. if (!isset($typePrefix)) {
  5123. die("$partType has no namespace!");
  5124. }
  5125. }
  5126. $ns = $this->getNamespaceFromPrefix($typePrefix);
  5127. $localPart = $this->getLocalPart($partType);
  5128. $typeDef = $this->getTypeDef($localPart, $ns);
  5129. if ($typeDef['typeClass'] == 'element') {
  5130. $elementortype = 'element';
  5131. if (substr($localPart, -1) == '^') {
  5132. $localPart = substr($localPart, 0, -1);
  5133. }
  5134. } else {
  5135. $elementortype = 'type';
  5136. }
  5137. $xml .= "\n" . ' <part name="' . $partName . '" ' . $elementortype . '="' . $typePrefix . ':' . $localPart . '" />';
  5138. }
  5139. }
  5140. $xml .= '</message>';
  5141. }
  5142. }
  5143. // bindings & porttypes
  5144. if (count($this->bindings) >= 1) {
  5145. $binding_xml = '';
  5146. $portType_xml = '';
  5147. foreach($this->bindings as $bindingName => $attrs) {
  5148. $binding_xml .= "\n<binding name=\"" . $bindingName . '" type="tns:' . $attrs['portType'] . '">';
  5149. $binding_xml .= "\n" . ' <soap:binding style="' . $attrs['style'] . '" transport="' . $attrs['transport'] . '"/>';
  5150. $portType_xml .= "\n<portType name=\"" . $attrs['portType'] . '">';
  5151. foreach($attrs['operations'] as $opName => $opParts) {
  5152. $binding_xml .= "\n" . ' <operation name="' . $opName . '">';
  5153. $binding_xml .= "\n" . ' <soap:operation soapAction="' . $opParts['soapAction'] . '" style="'. $opParts['style'] . '"/>';
  5154. if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') {
  5155. $enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"';
  5156. } else {
  5157. $enc_style = '';
  5158. }
  5159. $binding_xml .= "\n" . ' <input><soap:body use="' . $opParts['input']['use'] . '" namespace="' . $opParts['input']['namespace'] . '"' . $enc_style . '/></input>';
  5160. if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') {
  5161. $enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"';
  5162. } else {
  5163. $enc_style = '';
  5164. }
  5165. $binding_xml .= "\n" . ' <output><soap:body use="' . $opParts['output']['use'] . '" namespace="' . $opParts['output']['namespace'] . '"' . $enc_style . '/></output>';
  5166. $binding_xml .= "\n" . ' </operation>';
  5167. $portType_xml .= "\n" . ' <operation name="' . $opParts['name'] . '"';
  5168. if (isset($opParts['parameterOrder'])) {
  5169. $portType_xml .= ' parameterOrder="' . $opParts['parameterOrder'] . '"';
  5170. }
  5171. $portType_xml .= '>';
  5172. if(isset($opParts['documentation']) && $opParts['documentation'] != '') {
  5173. $portType_xml .= "\n" . ' <documentation>' . htmlspecialchars($opParts['documentation']) . '</documentation>';
  5174. }
  5175. $portType_xml .= "\n" . ' <input message="tns:' . $opParts['input']['message'] . '"/>';
  5176. $portType_xml .= "\n" . ' <output message="tns:' . $opParts['output']['message'] . '"/>';
  5177. $portType_xml .= "\n" . ' </operation>';
  5178. }
  5179. $portType_xml .= "\n" . '</portType>';
  5180. $binding_xml .= "\n" . '</binding>';
  5181. }
  5182. $xml .= $portType_xml . $binding_xml;
  5183. }
  5184. // services
  5185. $xml .= "\n<service name=\"" . $this->serviceName . '">';
  5186. if (count($this->ports) >= 1) {
  5187. foreach($this->ports as $pName => $attrs) {
  5188. $xml .= "\n" . ' <port name="' . $pName . '" binding="tns:' . $attrs['binding'] . '">';
  5189. $xml .= "\n" . ' <soap:address location="' . $attrs['location'] . ($debug ? '?debug=1' : '') . '"/>';
  5190. $xml .= "\n" . ' </port>';
  5191. }
  5192. }
  5193. $xml .= "\n" . '</service>';
  5194. return $xml . "\n</definitions>";
  5195. }
  5196. /**
  5197. * determine whether a set of parameters are unwrapped
  5198. * when they are expect to be wrapped, Microsoft-style.
  5199. *
  5200. * @param string $type the type (element name) of the wrapper
  5201. * @param array $parameters the parameter values for the SOAP call
  5202. * @return boolean whether they parameters are unwrapped (and should be wrapped)
  5203. * @access private
  5204. */
  5205. function parametersMatchWrapped($type, &$parameters) {
  5206. $this->debug("in parametersMatchWrapped type=$type, parameters=");
  5207. $this->appendDebug($this->varDump($parameters));
  5208. // split type into namespace:unqualified-type
  5209. if (strpos($type, ':')) {
  5210. $uqType = substr($type, strrpos($type, ':') + 1);
  5211. $ns = substr($type, 0, strrpos($type, ':'));
  5212. $this->debug("in parametersMatchWrapped: got a prefixed type: $uqType, $ns");
  5213. if ($this->getNamespaceFromPrefix($ns)) {
  5214. $ns = $this->getNamespaceFromPrefix($ns);
  5215. $this->debug("in parametersMatchWrapped: expanded prefixed type: $uqType, $ns");
  5216. }
  5217. } else {
  5218. // TODO: should the type be compared to types in XSD, and the namespace
  5219. // set to XSD if the type matches?
  5220. $this->debug("in parametersMatchWrapped: No namespace for type $type");
  5221. $ns = '';
  5222. $uqType = $type;
  5223. }
  5224. // get the type information
  5225. if (!$typeDef = $this->getTypeDef($uqType, $ns)) {
  5226. $this->debug("in parametersMatchWrapped: $type ($uqType) is not a supported type.");
  5227. return false;
  5228. }
  5229. $this->debug("in parametersMatchWrapped: found typeDef=");
  5230. $this->appendDebug($this->varDump($typeDef));
  5231. if (substr($uqType, -1) == '^') {
  5232. $uqType = substr($uqType, 0, -1);
  5233. }
  5234. $phpType = $typeDef['phpType'];
  5235. $arrayType = (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '');
  5236. $this->debug("in parametersMatchWrapped: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: $arrayType");
  5237. // we expect a complexType or element of complexType
  5238. if ($phpType != 'struct') {
  5239. $this->debug("in parametersMatchWrapped: not a struct");
  5240. return false;
  5241. }
  5242. // see whether the parameter names match the elements
  5243. if (isset($typeDef['elements']) && is_array($typeDef['elements'])) {
  5244. $elements = 0;
  5245. $matches = 0;
  5246. $change = false;
  5247. if ($this->isArraySimpleOrStruct($parameters) == 'arraySimple' && count($parameters) == count($typeDef['elements'])) {
  5248. $this->debug("in parametersMatchWrapped: (wrapped return value kludge) correct number of elements in simple array, so change array and wrap");
  5249. $change = true;
  5250. }
  5251. foreach ($typeDef['elements'] as $name => $attrs) {
  5252. if ($change) {
  5253. $this->debug("in parametersMatchWrapped: change parameter $element to name $name");
  5254. $parameters[$name] = $parameters[$elements];
  5255. unset($parameters[$elements]);
  5256. $matches++;
  5257. } elseif (isset($parameters[$name])) {
  5258. $this->debug("in parametersMatchWrapped: have parameter named $name");
  5259. $matches++;
  5260. } else {
  5261. $this->debug("in parametersMatchWrapped: do not have parameter named $name");
  5262. }
  5263. $elements++;
  5264. }
  5265. $this->debug("in parametersMatchWrapped: $matches parameter names match $elements wrapped parameter names");
  5266. if ($matches == 0) {
  5267. return false;
  5268. }
  5269. return true;
  5270. }
  5271. // since there are no elements for the type, if the user passed no
  5272. // parameters, the parameters match wrapped.
  5273. $this->debug("in parametersMatchWrapped: no elements type $ns:$uqType");
  5274. return count($parameters) == 0;
  5275. }
  5276. /**
  5277. * serialize PHP values according to a WSDL message definition
  5278. * contrary to the method name, this is not limited to RPC
  5279. *
  5280. * TODO
  5281. * - multi-ref serialization
  5282. * - validate PHP values against type definitions, return errors if invalid
  5283. *
  5284. * @param string $operation operation name
  5285. * @param string $direction (input|output)
  5286. * @param mixed $parameters parameter value(s)
  5287. * @param string $bindingType (soap|soap12)
  5288. * @return mixed parameters serialized as XML or false on error (e.g. operation not found)
  5289. * @access public
  5290. */
  5291. function serializeRPCParameters($operation, $direction, $parameters, $bindingType = 'soap') {
  5292. $this->debug("in serializeRPCParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion, bindingType=$bindingType");
  5293. $this->appendDebug('parameters=' . $this->varDump($parameters));
  5294. if ($direction != 'input' && $direction != 'output') {
  5295. $this->debug('The value of the \$direction argument needs to be either "input" or "output"');
  5296. $this->setError('The value of the \$direction argument needs to be either "input" or "output"');
  5297. return false;
  5298. }
  5299. if (!$opData = $this->getOperationData($operation, $bindingType)) {
  5300. $this->debug('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType);
  5301. $this->setError('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType);
  5302. return false;
  5303. }
  5304. $this->debug('in serializeRPCParameters: opData:');
  5305. $this->appendDebug($this->varDump($opData));
  5306. // Get encoding style for output and set to current
  5307. $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
  5308. if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
  5309. $encodingStyle = $opData['output']['encodingStyle'];
  5310. $enc_style = $encodingStyle;
  5311. }
  5312. // set input params
  5313. $xml = '';
  5314. if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
  5315. $parts = &$opData[$direction]['parts'];
  5316. $part_count = sizeof($parts);
  5317. $style = $opData['style'];
  5318. $use = $opData[$direction]['use'];
  5319. $this->debug("have $part_count part(s) to serialize using $style/$use");
  5320. if (is_array($parameters)) {
  5321. $parametersArrayType = $this->isArraySimpleOrStruct($parameters);
  5322. $parameter_count = count($parameters);
  5323. $this->debug("have $parameter_count parameter(s) provided as $parametersArrayType to serialize");
  5324. // check for Microsoft-style wrapped parameters
  5325. if ($style == 'document' && $use == 'literal' && $part_count == 1 && isset($parts['parameters'])) {
  5326. $this->debug('check whether the caller has wrapped the parameters');
  5327. if ((($parametersArrayType == 'arrayStruct' || $parameter_count == 0) && !isset($parameters['parameters'])) || ($direction == 'output' && $parametersArrayType == 'arraySimple' && $parameter_count == 1)) {
  5328. $this->debug('check whether caller\'s parameters match the wrapped ones');
  5329. if ($this->parametersMatchWrapped($parts['parameters'], $parameters)) {
  5330. $this->debug('wrap the parameters for the caller');
  5331. $parameters = array('parameters' => $parameters);
  5332. $parameter_count = 1;
  5333. }
  5334. }
  5335. }
  5336. foreach ($parts as $name => $type) {
  5337. $this->debug("serializing part $name of type $type");
  5338. // Track encoding style
  5339. if (isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
  5340. $encodingStyle = $opData[$direction]['encodingStyle'];
  5341. $enc_style = $encodingStyle;
  5342. } else {
  5343. $enc_style = false;
  5344. }
  5345. // NOTE: add error handling here
  5346. // if serializeType returns false, then catch global error and fault
  5347. if ($parametersArrayType == 'arraySimple') {
  5348. $p = array_shift($parameters);
  5349. $this->debug('calling serializeType w/indexed param');
  5350. $xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
  5351. } elseif (isset($parameters[$name])) {
  5352. $this->debug('calling serializeType w/named param');
  5353. $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
  5354. } else {
  5355. // TODO: only send nillable
  5356. $this->debug('calling serializeType w/null param');
  5357. $xml .= $this->serializeType($name, $type, null, $use, $enc_style);
  5358. }
  5359. }
  5360. } else {
  5361. $this->debug('no parameters passed.');
  5362. }
  5363. }
  5364. $this->debug("serializeRPCParameters returning: $xml");
  5365. return $xml;
  5366. }
  5367. /**
  5368. * serialize a PHP value according to a WSDL message definition
  5369. *
  5370. * TODO
  5371. * - multi-ref serialization
  5372. * - validate PHP values against type definitions, return errors if invalid
  5373. *
  5374. * @param string $operation operation name
  5375. * @param string $direction (input|output)
  5376. * @param mixed $parameters parameter value(s)
  5377. * @return mixed parameters serialized as XML or false on error (e.g. operation not found)
  5378. * @access public
  5379. * @deprecated
  5380. */
  5381. function serializeParameters($operation, $direction, $parameters)
  5382. {
  5383. $this->debug("in serializeParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion");
  5384. $this->appendDebug('parameters=' . $this->varDump($parameters));
  5385. if ($direction != 'input' && $direction != 'output') {
  5386. $this->debug('The value of the \$direction argument needs to be either "input" or "output"');
  5387. $this->setError('The value of the \$direction argument needs to be either "input" or "output"');
  5388. return false;
  5389. }
  5390. if (!$opData = $this->getOperationData($operation)) {
  5391. $this->debug('Unable to retrieve WSDL data for operation: ' . $operation);
  5392. $this->setError('Unable to retrieve WSDL data for operation: ' . $operation);
  5393. return false;
  5394. }
  5395. $this->debug('opData:');
  5396. $this->appendDebug($this->varDump($opData));
  5397. // Get encoding style for output and set to current
  5398. $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
  5399. if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
  5400. $encodingStyle = $opData['output']['encodingStyle'];
  5401. $enc_style = $encodingStyle;
  5402. }
  5403. // set input params
  5404. $xml = '';
  5405. if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
  5406. $use = $opData[$direction]['use'];
  5407. $this->debug("use=$use");
  5408. $this->debug('got ' . count($opData[$direction]['parts']) . ' part(s)');
  5409. if (is_array($parameters)) {
  5410. $parametersArrayType = $this->isArraySimpleOrStruct($parameters);
  5411. $this->debug('have ' . $parametersArrayType . ' parameters');
  5412. foreach($opData[$direction]['parts'] as $name => $type) {
  5413. $this->debug('serializing part "'.$name.'" of type "'.$type.'"');
  5414. // Track encoding style
  5415. if(isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
  5416. $encodingStyle = $opData[$direction]['encodingStyle'];
  5417. $enc_style = $encodingStyle;
  5418. } else {
  5419. $enc_style = false;
  5420. }
  5421. // NOTE: add error handling here
  5422. // if serializeType returns false, then catch global error and fault
  5423. if ($parametersArrayType == 'arraySimple') {
  5424. $p = array_shift($parameters);
  5425. $this->debug('calling serializeType w/indexed param');
  5426. $xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
  5427. } elseif (isset($parameters[$name])) {
  5428. $this->debug('calling serializeType w/named param');
  5429. $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
  5430. } else {
  5431. // TODO: only send nillable
  5432. $this->debug('calling serializeType w/null param');
  5433. $xml .= $this->serializeType($name, $type, null, $use, $enc_style);
  5434. }
  5435. }
  5436. } else {
  5437. $this->debug('no parameters passed.');
  5438. }
  5439. }
  5440. $this->debug("serializeParameters returning: $xml");
  5441. return $xml;
  5442. }
  5443. /**
  5444. * serializes a PHP value according a given type definition
  5445. *
  5446. * @param string $name name of value (part or element)
  5447. * @param string $type XML schema type of value (type or element)
  5448. * @param mixed $value a native PHP value (parameter value)
  5449. * @param string $use use for part (encoded|literal)
  5450. * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
  5451. * @param boolean $unqualified a kludge for what should be XML namespace form handling
  5452. * @return string value serialized as an XML string
  5453. * @access private
  5454. */
  5455. function serializeType($name, $type, $value, $use='encoded', $encodingStyle=false, $unqualified=false)
  5456. {
  5457. $this->debug("in serializeType: name=$name, type=$type, use=$use, encodingStyle=$encodingStyle, unqualified=" . ($unqualified ? "unqualified" : "qualified"));
  5458. $this->appendDebug("value=" . $this->varDump($value));
  5459. if($use == 'encoded' && $encodingStyle) {
  5460. $encodingStyle = ' SOAP-ENV:encodingStyle="' . $encodingStyle . '"';
  5461. }
  5462. // if a soapval has been supplied, let its type override the WSDL
  5463. if (is_object($value) && get_class($value) == 'soapval') {
  5464. if ($value->type_ns) {
  5465. $type = $value->type_ns . ':' . $value->type;
  5466. $forceType = true;
  5467. $this->debug("in serializeType: soapval overrides type to $type");
  5468. } elseif ($value->type) {
  5469. $type = $value->type;
  5470. $forceType = true;
  5471. $this->debug("in serializeType: soapval overrides type to $type");
  5472. } else {
  5473. $forceType = false;
  5474. $this->debug("in serializeType: soapval does not override type");
  5475. }
  5476. $attrs = $value->attributes;
  5477. $value = $value->value;
  5478. $this->debug("in serializeType: soapval overrides value to $value");
  5479. if ($attrs) {
  5480. if (!is_array($value)) {
  5481. $value['!'] = $value;
  5482. }
  5483. foreach ($attrs as $n => $v) {
  5484. $value['!' . $n] = $v;
  5485. }
  5486. $this->debug("in serializeType: soapval provides attributes");
  5487. }
  5488. } else {
  5489. $forceType = false;
  5490. }
  5491. $xml = '';
  5492. if (strpos($type, ':')) {
  5493. $uqType = substr($type, strrpos($type, ':') + 1);
  5494. $ns = substr($type, 0, strrpos($type, ':'));
  5495. $this->debug("in serializeType: got a prefixed type: $uqType, $ns");
  5496. if ($this->getNamespaceFromPrefix($ns)) {
  5497. $ns = $this->getNamespaceFromPrefix($ns);
  5498. $this->debug("in serializeType: expanded prefixed type: $uqType, $ns");
  5499. }
  5500. if($ns == $this->XMLSchemaVersion || $ns == 'http://schemas.xmlsoap.org/soap/encoding/'){
  5501. $this->debug('in serializeType: type namespace indicates XML Schema or SOAP Encoding type');
  5502. if ($unqualified && $use == 'literal') {
  5503. $elementNS = " xmlns=\"\"";
  5504. } else {
  5505. $elementNS = '';
  5506. }
  5507. if (is_null($value)) {
  5508. if ($use == 'literal') {
  5509. // TODO: depends on minOccurs
  5510. $xml = "<$name$elementNS/>";
  5511. } else {
  5512. // TODO: depends on nillable, which should be checked before calling this method
  5513. $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>";
  5514. }
  5515. $this->debug("in serializeType: returning: $xml");
  5516. return $xml;
  5517. }
  5518. if ($uqType == 'Array') {
  5519. // JBoss/Axis does this sometimes
  5520. return $this->serialize_val($value, $name, false, false, false, false, $use);
  5521. }
  5522. if ($uqType == 'boolean') {
  5523. if ((is_string($value) && $value == 'false') || (! $value)) {
  5524. $value = 'false';
  5525. } else {
  5526. $value = 'true';
  5527. }
  5528. }
  5529. if ($uqType == 'string' && gettype($value) == 'string') {
  5530. $value = $this->expandEntities($value);
  5531. }
  5532. if (($uqType == 'long' || $uqType == 'unsignedLong') && gettype($value) == 'double') {
  5533. $value = sprintf("%.0lf", $value);
  5534. }
  5535. // it's a scalar
  5536. // TODO: what about null/nil values?
  5537. // check type isn't a custom type extending xmlschema namespace
  5538. if (!$this->getTypeDef($uqType, $ns)) {
  5539. if ($use == 'literal') {
  5540. if ($forceType) {
  5541. $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value</$name>";
  5542. } else {
  5543. $xml = "<$name$elementNS>$value</$name>";
  5544. }
  5545. } else {
  5546. $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value</$name>";
  5547. }
  5548. $this->debug("in serializeType: returning: $xml");
  5549. return $xml;
  5550. }
  5551. $this->debug('custom type extends XML Schema or SOAP Encoding namespace (yuck)');
  5552. } else if ($ns == 'http://xml.apache.org/xml-soap') {
  5553. $this->debug('in serializeType: appears to be Apache SOAP type');
  5554. if ($uqType == 'Map') {
  5555. $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap');
  5556. if (! $tt_prefix) {
  5557. $this->debug('in serializeType: Add namespace for Apache SOAP type');
  5558. $tt_prefix = 'ns' . rand(1000, 9999);
  5559. $this->namespaces[$tt_prefix] = 'http://xml.apache.org/xml-soap';
  5560. // force this to be added to usedNamespaces
  5561. $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap');
  5562. }
  5563. $contents = '';
  5564. foreach($value as $k => $v) {
  5565. $this->debug("serializing map element: key $k, value $v");
  5566. $contents .= '<item>';
  5567. $contents .= $this->serialize_val($k,'key',false,false,false,false,$use);
  5568. $contents .= $this->serialize_val($v,'value',false,false,false,false,$use);
  5569. $contents .= '</item>';
  5570. }
  5571. if ($use == 'literal') {
  5572. if ($forceType) {
  5573. $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\">$contents</$name>";
  5574. } else {
  5575. $xml = "<$name>$contents</$name>";
  5576. }
  5577. } else {
  5578. $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\"$encodingStyle>$contents</$name>";
  5579. }
  5580. $this->debug("in serializeType: returning: $xml");
  5581. return $xml;
  5582. }
  5583. $this->debug('in serializeType: Apache SOAP type, but only support Map');
  5584. }
  5585. } else {
  5586. // TODO: should the type be compared to types in XSD, and the namespace
  5587. // set to XSD if the type matches?
  5588. $this->debug("in serializeType: No namespace for type $type");
  5589. $ns = '';
  5590. $uqType = $type;
  5591. }
  5592. if(!$typeDef = $this->getTypeDef($uqType, $ns)){
  5593. $this->setError("$type ($uqType) is not a supported type.");
  5594. $this->debug("in serializeType: $type ($uqType) is not a supported type.");
  5595. return false;
  5596. } else {
  5597. $this->debug("in serializeType: found typeDef");
  5598. $this->appendDebug('typeDef=' . $this->varDump($typeDef));
  5599. if (substr($uqType, -1) == '^') {
  5600. $uqType = substr($uqType, 0, -1);
  5601. }
  5602. }
  5603. $phpType = $typeDef['phpType'];
  5604. $this->debug("in serializeType: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: " . (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '') );
  5605. // if php type == struct, map value to the <all> element names
  5606. if ($phpType == 'struct') {
  5607. if (isset($typeDef['typeClass']) && $typeDef['typeClass'] == 'element') {
  5608. $elementName = $uqType;
  5609. if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
  5610. $elementNS = " xmlns=\"$ns\"";
  5611. } else {
  5612. $elementNS = " xmlns=\"\"";
  5613. }
  5614. } else {
  5615. $elementName = $name;
  5616. if ($unqualified) {
  5617. $elementNS = " xmlns=\"\"";
  5618. } else {
  5619. $elementNS = '';
  5620. }
  5621. }
  5622. if (is_null($value)) {
  5623. if ($use == 'literal') {
  5624. // TODO: depends on minOccurs
  5625. $xml = "<$elementName$elementNS/>";
  5626. } else {
  5627. $xml = "<$elementName$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>";
  5628. }
  5629. $this->debug("in serializeType: returning: $xml");
  5630. return $xml;
  5631. }
  5632. if (is_object($value)) {
  5633. $value = get_object_vars($value);
  5634. }
  5635. if (is_array($value)) {
  5636. $elementAttrs = $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType);
  5637. if ($use == 'literal') {
  5638. if ($forceType) {
  5639. $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">";
  5640. } else {
  5641. $xml = "<$elementName$elementNS$elementAttrs>";
  5642. }
  5643. } else {
  5644. $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>";
  5645. }
  5646. $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle);
  5647. $xml .= "</$elementName>";
  5648. } else {
  5649. $this->debug("in serializeType: phpType is struct, but value is not an array");
  5650. $this->setError("phpType is struct, but value is not an array: see debug output for details");
  5651. $xml = '';
  5652. }
  5653. } elseif ($phpType == 'array') {
  5654. if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
  5655. $elementNS = " xmlns=\"$ns\"";
  5656. } else {
  5657. if ($unqualified) {
  5658. $elementNS = " xmlns=\"\"";
  5659. } else {
  5660. $elementNS = '';
  5661. }
  5662. }
  5663. if (is_null($value)) {
  5664. if ($use == 'literal') {
  5665. // TODO: depends on minOccurs
  5666. $xml = "<$name$elementNS/>";
  5667. } else {
  5668. $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" .
  5669. $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .
  5670. ":Array\" " .
  5671. $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .
  5672. ':arrayType="' .
  5673. $this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) .
  5674. ':' .
  5675. $this->getLocalPart($typeDef['arrayType'])."[0]\"/>";
  5676. }
  5677. $this->debug("in serializeType: returning: $xml");
  5678. return $xml;
  5679. }
  5680. if (isset($typeDef['multidimensional'])) {
  5681. $nv = array();
  5682. foreach($value as $v) {
  5683. $cols = ',' . sizeof($v);
  5684. $nv = array_merge($nv, $v);
  5685. }
  5686. $value = $nv;
  5687. } else {
  5688. $cols = '';
  5689. }
  5690. if (is_array($value) && sizeof($value) >= 1) {
  5691. $rows = sizeof($value);
  5692. $contents = '';
  5693. foreach($value as $k => $v) {
  5694. $this->debug("serializing array element: $k, $v of type: $typeDef[arrayType]");
  5695. //if (strpos($typeDef['arrayType'], ':') ) {
  5696. if (!in_array($typeDef['arrayType'],$this->typemap['http://www.w3.org/2001/XMLSchema'])) {
  5697. $contents .= $this->serializeType('item', $typeDef['arrayType'], $v, $use);
  5698. } else {
  5699. $contents .= $this->serialize_val($v, 'item', $typeDef['arrayType'], null, $this->XMLSchemaVersion, false, $use);
  5700. }
  5701. }
  5702. } else {
  5703. $rows = 0;
  5704. $contents = null;
  5705. }
  5706. // TODO: for now, an empty value will be serialized as a zero element
  5707. // array. Revisit this when coding the handling of null/nil values.
  5708. if ($use == 'literal') {
  5709. $xml = "<$name$elementNS>"
  5710. .$contents
  5711. ."</$name>";
  5712. } else {
  5713. $xml = "<$name$elementNS xsi:type=\"".$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/').':Array" '.
  5714. $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/')
  5715. .':arrayType="'
  5716. .$this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType']))
  5717. .":".$this->getLocalPart($typeDef['arrayType'])."[$rows$cols]\">"
  5718. .$contents
  5719. ."</$name>";
  5720. }
  5721. } elseif ($phpType == 'scalar') {
  5722. if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
  5723. $elementNS = " xmlns=\"$ns\"";
  5724. } else {
  5725. if ($unqualified) {
  5726. $elementNS = " xmlns=\"\"";
  5727. } else {
  5728. $elementNS = '';
  5729. }
  5730. }
  5731. if ($use == 'literal') {
  5732. if ($forceType) {
  5733. $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value</$name>";
  5734. } else {
  5735. $xml = "<$name$elementNS>$value</$name>";
  5736. }
  5737. } else {
  5738. $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value</$name>";
  5739. }
  5740. }
  5741. $this->debug("in serializeType: returning: $xml");
  5742. return $xml;
  5743. }
  5744. /**
  5745. * serializes the attributes for a complexType
  5746. *
  5747. * @param array $typeDef our internal representation of an XML schema type (or element)
  5748. * @param mixed $value a native PHP value (parameter value)
  5749. * @param string $ns the namespace of the type
  5750. * @param string $uqType the local part of the type
  5751. * @return string value serialized as an XML string
  5752. * @access private
  5753. */
  5754. function serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType) {
  5755. $xml = '';
  5756. if (isset($typeDef['attrs']) && is_array($typeDef['attrs'])) {
  5757. $this->debug("serialize attributes for XML Schema type $ns:$uqType");
  5758. if (is_array($value)) {
  5759. $xvalue = $value;
  5760. } elseif (is_object($value)) {
  5761. $xvalue = get_object_vars($value);
  5762. } else {
  5763. $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
  5764. $xvalue = array();
  5765. }
  5766. foreach ($typeDef['attrs'] as $aName => $attrs) {
  5767. if (isset($xvalue['!' . $aName])) {
  5768. $xname = '!' . $aName;
  5769. $this->debug("value provided for attribute $aName with key $xname");
  5770. } elseif (isset($xvalue[$aName])) {
  5771. $xname = $aName;
  5772. $this->debug("value provided for attribute $aName with key $xname");
  5773. } elseif (isset($attrs['default'])) {
  5774. $xname = '!' . $aName;
  5775. $xvalue[$xname] = $attrs['default'];
  5776. $this->debug('use default value of ' . $xvalue[$aName] . ' for attribute ' . $aName);
  5777. } else {
  5778. $xname = '';
  5779. $this->debug("no value provided for attribute $aName");
  5780. }
  5781. if ($xname) {
  5782. $xml .= " $aName=\"" . $this->expandEntities($xvalue[$xname]) . "\"";
  5783. }
  5784. }
  5785. } else {
  5786. $this->debug("no attributes to serialize for XML Schema type $ns:$uqType");
  5787. }
  5788. if (isset($typeDef['extensionBase'])) {
  5789. $ns = $this->getPrefix($typeDef['extensionBase']);
  5790. $uqType = $this->getLocalPart($typeDef['extensionBase']);
  5791. if ($this->getNamespaceFromPrefix($ns)) {
  5792. $ns = $this->getNamespaceFromPrefix($ns);
  5793. }
  5794. if ($typeDef = $this->getTypeDef($uqType, $ns)) {
  5795. $this->debug("serialize attributes for extension base $ns:$uqType");
  5796. $xml .= $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType);
  5797. } else {
  5798. $this->debug("extension base $ns:$uqType is not a supported type");
  5799. }
  5800. }
  5801. return $xml;
  5802. }
  5803. /**
  5804. * serializes the elements for a complexType
  5805. *
  5806. * @param array $typeDef our internal representation of an XML schema type (or element)
  5807. * @param mixed $value a native PHP value (parameter value)
  5808. * @param string $ns the namespace of the type
  5809. * @param string $uqType the local part of the type
  5810. * @param string $use use for part (encoded|literal)
  5811. * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
  5812. * @return string value serialized as an XML string
  5813. * @access private
  5814. */
  5815. function serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use='encoded', $encodingStyle=false) {
  5816. $xml = '';
  5817. if (isset($typeDef['elements']) && is_array($typeDef['elements'])) {
  5818. $this->debug("in serializeComplexTypeElements, serialize elements for XML Schema type $ns:$uqType");
  5819. if (is_array($value)) {
  5820. $xvalue = $value;
  5821. } elseif (is_object($value)) {
  5822. $xvalue = get_object_vars($value);
  5823. } else {
  5824. $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
  5825. $xvalue = array();
  5826. }
  5827. // toggle whether all elements are present - ideally should validate against schema
  5828. if (count($typeDef['elements']) != count($xvalue)){
  5829. $optionals = true;
  5830. }
  5831. foreach ($typeDef['elements'] as $eName => $attrs) {
  5832. if (!isset($xvalue[$eName])) {
  5833. if (isset($attrs['default'])) {
  5834. $xvalue[$eName] = $attrs['default'];
  5835. $this->debug('use default value of ' . $xvalue[$eName] . ' for element ' . $eName);
  5836. }
  5837. }
  5838. // if user took advantage of a minOccurs=0, then only serialize named parameters
  5839. if (isset($optionals)
  5840. && (!isset($xvalue[$eName]))
  5841. && ( (!isset($attrs['nillable'])) || $attrs['nillable'] != 'true')
  5842. ){
  5843. if (isset($attrs['minOccurs']) && $attrs['minOccurs'] <> '0') {
  5844. $this->debug("apparent error: no value provided for element $eName with minOccurs=" . $attrs['minOccurs']);
  5845. }
  5846. // do nothing
  5847. $this->debug("no value provided for complexType element $eName and element is not nillable, so serialize nothing");
  5848. } else {
  5849. // get value
  5850. if (isset($xvalue[$eName])) {
  5851. $v = $xvalue[$eName];
  5852. } else {
  5853. $v = null;
  5854. }
  5855. if (isset($attrs['form'])) {
  5856. $unqualified = ($attrs['form'] == 'unqualified');
  5857. } else {
  5858. $unqualified = false;
  5859. }
  5860. if (isset($attrs['maxOccurs']) && ($attrs['maxOccurs'] == 'unbounded' || $attrs['maxOccurs'] > 1) && isset($v) && is_array($v) && $this->isArraySimpleOrStruct($v) == 'arraySimple') {
  5861. $vv = $v;
  5862. foreach ($vv as $k => $v) {
  5863. if (isset($attrs['type']) || isset($attrs['ref'])) {
  5864. // serialize schema-defined type
  5865. $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
  5866. } else {
  5867. // serialize generic type (can this ever really happen?)
  5868. $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
  5869. $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
  5870. }
  5871. }
  5872. } else {
  5873. if (isset($attrs['type']) || isset($attrs['ref'])) {
  5874. // serialize schema-defined type
  5875. $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
  5876. } else {
  5877. // serialize generic type (can this ever really happen?)
  5878. $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
  5879. $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
  5880. }
  5881. }
  5882. }
  5883. }
  5884. } else {
  5885. $this->debug("no elements to serialize for XML Schema type $ns:$uqType");
  5886. }
  5887. if (isset($typeDef['extensionBase'])) {
  5888. $ns = $this->getPrefix($typeDef['extensionBase']);
  5889. $uqType = $this->getLocalPart($typeDef['extensionBase']);
  5890. if ($this->getNamespaceFromPrefix($ns)) {
  5891. $ns = $this->getNamespaceFromPrefix($ns);
  5892. }
  5893. if ($typeDef = $this->getTypeDef($uqType, $ns)) {
  5894. $this->debug("serialize elements for extension base $ns:$uqType");
  5895. $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle);
  5896. } else {
  5897. $this->debug("extension base $ns:$uqType is not a supported type");
  5898. }
  5899. }
  5900. return $xml;
  5901. }
  5902. /**
  5903. * adds an XML Schema complex type to the WSDL types
  5904. *
  5905. * @param string $name
  5906. * @param string $typeClass (complexType|simpleType|attribute)
  5907. * @param string $phpType currently supported are array and struct (php assoc array)
  5908. * @param string $compositor (all|sequence|choice)
  5909. * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
  5910. * @param array $elements e.g. array ( name => array(name=>'',type=>'') )
  5911. * @param array $attrs e.g. array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'xsd:string[]'))
  5912. * @param string $arrayType as namespace:name (xsd:string)
  5913. * @see nusoap_xmlschema
  5914. * @access public
  5915. */
  5916. function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType='') {
  5917. if (count($elements) > 0) {
  5918. $eElements = array();
  5919. foreach($elements as $n => $e){
  5920. // expand each element
  5921. $ee = array();
  5922. foreach ($e as $k => $v) {
  5923. $k = strpos($k,':') ? $this->expandQname($k) : $k;
  5924. $v = strpos($v,':') ? $this->expandQname($v) : $v;
  5925. $ee[$k] = $v;
  5926. }
  5927. $eElements[$n] = $ee;
  5928. }
  5929. $elements = $eElements;
  5930. }
  5931. if (count($attrs) > 0) {
  5932. foreach($attrs as $n => $a){
  5933. // expand each attribute
  5934. foreach ($a as $k => $v) {
  5935. $k = strpos($k,':') ? $this->expandQname($k) : $k;
  5936. $v = strpos($v,':') ? $this->expandQname($v) : $v;
  5937. $aa[$k] = $v;
  5938. }
  5939. $eAttrs[$n] = $aa;
  5940. }
  5941. $attrs = $eAttrs;
  5942. }
  5943. $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
  5944. $arrayType = strpos($arrayType,':') ? $this->expandQname($arrayType) : $arrayType;
  5945. $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
  5946. $this->schemas[$typens][0]->addComplexType($name,$typeClass,$phpType,$compositor,$restrictionBase,$elements,$attrs,$arrayType);
  5947. }
  5948. /**
  5949. * adds an XML Schema simple type to the WSDL types
  5950. *
  5951. * @param string $name
  5952. * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
  5953. * @param string $typeClass (should always be simpleType)
  5954. * @param string $phpType (should always be scalar)
  5955. * @param array $enumeration array of values
  5956. * @see nusoap_xmlschema
  5957. * @access public
  5958. */
  5959. function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
  5960. $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
  5961. $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
  5962. $this->schemas[$typens][0]->addSimpleType($name, $restrictionBase, $typeClass, $phpType, $enumeration);
  5963. }
  5964. /**
  5965. * adds an element to the WSDL types
  5966. *
  5967. * @param array $attrs attributes that must include name and type
  5968. * @see nusoap_xmlschema
  5969. * @access public
  5970. */
  5971. function addElement($attrs) {
  5972. $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
  5973. $this->schemas[$typens][0]->addElement($attrs);
  5974. }
  5975. /**
  5976. * register an operation with the server
  5977. *
  5978. * @param string $name operation (method) name
  5979. * @param array $in assoc array of input values: key = param name, value = param type
  5980. * @param array $out assoc array of output values: key = param name, value = param type
  5981. * @param string $namespace optional The namespace for the operation
  5982. * @param string $soapaction optional The soapaction for the operation
  5983. * @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
  5984. * @param string $use (encoded|literal) optional The use for the parameters (cannot mix right now)
  5985. * @param string $documentation optional The description to include in the WSDL
  5986. * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
  5987. * @access public
  5988. */
  5989. function addOperation($name, $in = false, $out = false, $namespace = false, $soapaction = false, $style = 'rpc', $use = 'encoded', $documentation = '', $encodingStyle = ''){
  5990. if ($use == 'encoded' && $encodingStyle == '') {
  5991. $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
  5992. }
  5993. if ($style == 'document') {
  5994. $elements = array();
  5995. foreach ($in as $n => $t) {
  5996. $elements[$n] = array('name' => $n, 'type' => $t);
  5997. }
  5998. $this->addComplexType($name . 'RequestType', 'complexType', 'struct', 'all', '', $elements);
  5999. $this->addElement(array('name' => $name, 'type' => $name . 'RequestType'));
  6000. $in = array('parameters' => 'tns:' . $name . '^');
  6001. $elements = array();
  6002. foreach ($out as $n => $t) {
  6003. $elements[$n] = array('name' => $n, 'type' => $t);
  6004. }
  6005. $this->addComplexType($name . 'ResponseType', 'complexType', 'struct', 'all', '', $elements);
  6006. $this->addElement(array('name' => $name . 'Response', 'type' => $name . 'ResponseType', 'form' => 'qualified'));
  6007. $out = array('parameters' => 'tns:' . $name . 'Response' . '^');
  6008. }
  6009. // get binding
  6010. $this->bindings[ $this->serviceName . 'Binding' ]['operations'][$name] =
  6011. array(
  6012. 'name' => $name,
  6013. 'binding' => $this->serviceName . 'Binding',
  6014. 'endpoint' => $this->endpoint,
  6015. 'soapAction' => $soapaction,
  6016. 'style' => $style,
  6017. 'input' => array(
  6018. 'use' => $use,
  6019. 'namespace' => $namespace,
  6020. 'encodingStyle' => $encodingStyle,
  6021. 'message' => $name . 'Request',
  6022. 'parts' => $in),
  6023. 'output' => array(
  6024. 'use' => $use,
  6025. 'namespace' => $namespace,
  6026. 'encodingStyle' => $encodingStyle,
  6027. 'message' => $name . 'Response',
  6028. 'parts' => $out),
  6029. 'namespace' => $namespace,
  6030. 'transport' => 'http://schemas.xmlsoap.org/soap/http',
  6031. 'documentation' => $documentation);
  6032. // add portTypes
  6033. // add messages
  6034. if($in)
  6035. {
  6036. foreach($in as $pName => $pType)
  6037. {
  6038. if(strpos($pType,':')) {
  6039. $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
  6040. }
  6041. $this->messages[$name.'Request'][$pName] = $pType;
  6042. }
  6043. } else {
  6044. $this->messages[$name.'Request']= '0';
  6045. }
  6046. if($out)
  6047. {
  6048. foreach($out as $pName => $pType)
  6049. {
  6050. if(strpos($pType,':')) {
  6051. $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
  6052. }
  6053. $this->messages[$name.'Response'][$pName] = $pType;
  6054. }
  6055. } else {
  6056. $this->messages[$name.'Response']= '0';
  6057. }
  6058. return true;
  6059. }
  6060. }
  6061. ?><?php
  6062. /**
  6063. *
  6064. * nusoap_parser class parses SOAP XML messages into native PHP values
  6065. *
  6066. * @author Dietrich Ayala <dietrich@ganx4.com>
  6067. * @author Scott Nichol <snichol@users.sourceforge.net>
  6068. * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $
  6069. * @access public
  6070. */
  6071. class nusoap_parser extends nusoap_base {
  6072. var $xml = '';
  6073. var $xml_encoding = '';
  6074. var $method = '';
  6075. var $root_struct = '';
  6076. var $root_struct_name = '';
  6077. var $root_struct_namespace = '';
  6078. var $root_header = '';
  6079. var $document = ''; // incoming SOAP body (text)
  6080. // determines where in the message we are (envelope,header,body,method)
  6081. var $status = '';
  6082. var $position = 0;
  6083. var $depth = 0;
  6084. var $default_namespace = '';
  6085. var $namespaces = array();
  6086. var $message = array();
  6087. var $parent = '';
  6088. var $fault = false;
  6089. var $fault_code = '';
  6090. var $fault_str = '';
  6091. var $fault_detail = '';
  6092. var $depth_array = array();
  6093. var $debug_flag = true;
  6094. var $soapresponse = NULL; // parsed SOAP Body
  6095. var $soapheader = NULL; // parsed SOAP Header
  6096. var $responseHeaders = ''; // incoming SOAP headers (text)
  6097. var $body_position = 0;
  6098. // for multiref parsing:
  6099. // array of id => pos
  6100. var $ids = array();
  6101. // array of id => hrefs => pos
  6102. var $multirefs = array();
  6103. // toggle for auto-decoding element content
  6104. var $decode_utf8 = true;
  6105. /**
  6106. * constructor that actually does the parsing
  6107. *
  6108. * @param string $xml SOAP message
  6109. * @param string $encoding character encoding scheme of message
  6110. * @param string $method method for which XML is parsed (unused?)
  6111. * @param string $decode_utf8 whether to decode UTF-8 to ISO-8859-1
  6112. * @access public
  6113. */
  6114. function nusoap_parser($xml,$encoding='UTF-8',$method='',$decode_utf8=true){
  6115. parent::nusoap_base();
  6116. $this->xml = $xml;
  6117. $this->xml_encoding = $encoding;
  6118. $this->method = $method;
  6119. $this->decode_utf8 = $decode_utf8;
  6120. // Check whether content has been read.
  6121. if(!empty($xml)){
  6122. // Check XML encoding
  6123. $pos_xml = strpos($xml, '<?xml');
  6124. if ($pos_xml !== FALSE) {
  6125. $xml_decl = substr($xml, $pos_xml, strpos($xml, '?>', $pos_xml + 2) - $pos_xml + 1);
  6126. if (preg_match("/encoding=[\"']([^\"']*)[\"']/", $xml_decl, $res)) {
  6127. $xml_encoding = $res[1];
  6128. if (strtoupper($xml_encoding) != $encoding) {
  6129. $err = "Charset from HTTP Content-Type '" . $encoding . "' does not match encoding from XML declaration '" . $xml_encoding . "'";
  6130. $this->debug($err);
  6131. if ($encoding != 'ISO-8859-1' || strtoupper($xml_encoding) != 'UTF-8') {
  6132. $this->setError($err);
  6133. return;
  6134. }
  6135. // when HTTP says ISO-8859-1 (the default) and XML says UTF-8 (the typical), assume the other endpoint is just sloppy and proceed
  6136. } else {
  6137. $this->debug('Charset from HTTP Content-Type matches encoding from XML declaration');
  6138. }
  6139. } else {
  6140. $this->debug('No encoding specified in XML declaration');
  6141. }
  6142. } else {
  6143. $this->debug('No XML declaration');
  6144. }
  6145. $this->debug('Entering nusoap_parser(), length='.strlen($xml).', encoding='.$encoding);
  6146. // Create an XML parser - why not xml_parser_create_ns?
  6147. $this->parser = xml_parser_create($this->xml_encoding);
  6148. // Set the options for parsing the XML data.
  6149. //xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  6150. xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
  6151. xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->xml_encoding);
  6152. // Set the object for the parser.
  6153. xml_set_object($this->parser, $this);
  6154. // Set the element handlers for the parser.
  6155. xml_set_element_handler($this->parser, 'start_element','end_element');
  6156. xml_set_character_data_handler($this->parser,'character_data');
  6157. // Parse the XML file.
  6158. if(!xml_parse($this->parser,$xml,true)){
  6159. // Display an error message.
  6160. $err = sprintf('XML error parsing SOAP payload on line %d: %s',
  6161. xml_get_current_line_number($this->parser),
  6162. xml_error_string(xml_get_error_code($this->parser)));
  6163. $this->debug($err);
  6164. $this->debug("XML payload:\n" . $xml);
  6165. $this->setError($err);
  6166. } else {
  6167. $this->debug('parsed successfully, found root struct: '.$this->root_struct.' of name '.$this->root_struct_name);
  6168. // get final value
  6169. $this->soapresponse = $this->message[$this->root_struct]['result'];
  6170. // get header value
  6171. if($this->root_header != '' && isset($this->message[$this->root_header]['result'])){
  6172. $this->soapheader = $this->message[$this->root_header]['result'];
  6173. }
  6174. // resolve hrefs/ids
  6175. if(sizeof($this->multirefs) > 0){
  6176. foreach($this->multirefs as $id => $hrefs){
  6177. $this->debug('resolving multirefs for id: '.$id);
  6178. $idVal = $this->buildVal($this->ids[$id]);
  6179. if (is_array($idVal) && isset($idVal['!id'])) {
  6180. unset($idVal['!id']);
  6181. }
  6182. foreach($hrefs as $refPos => $ref){
  6183. $this->debug('resolving href at pos '.$refPos);
  6184. $this->multirefs[$id][$refPos] = $idVal;
  6185. }
  6186. }
  6187. }
  6188. }
  6189. xml_parser_free($this->parser);
  6190. } else {
  6191. $this->debug('xml was empty, didn\'t parse!');
  6192. $this->setError('xml was empty, didn\'t parse!');
  6193. }
  6194. }
  6195. /**
  6196. * start-element handler
  6197. *
  6198. * @param resource $parser XML parser object
  6199. * @param string $name element name
  6200. * @param array $attrs associative array of attributes
  6201. * @access private
  6202. */
  6203. function start_element($parser, $name, $attrs) {
  6204. // position in a total number of elements, starting from 0
  6205. // update class level pos
  6206. $pos = $this->position++;
  6207. // and set mine
  6208. $this->message[$pos] = array('pos' => $pos,'children'=>'','cdata'=>'');
  6209. // depth = how many levels removed from root?
  6210. // set mine as current global depth and increment global depth value
  6211. $this->message[$pos]['depth'] = $this->depth++;
  6212. // else add self as child to whoever the current parent is
  6213. if($pos != 0){
  6214. $this->message[$this->parent]['children'] .= '|'.$pos;
  6215. }
  6216. // set my parent
  6217. $this->message[$pos]['parent'] = $this->parent;
  6218. // set self as current parent
  6219. $this->parent = $pos;
  6220. // set self as current value for this depth
  6221. $this->depth_array[$this->depth] = $pos;
  6222. // get element prefix
  6223. if(strpos($name,':')){
  6224. // get ns prefix
  6225. $prefix = substr($name,0,strpos($name,':'));
  6226. // get unqualified name
  6227. $name = substr(strstr($name,':'),1);
  6228. }
  6229. // set status
  6230. if($name == 'Envelope'){
  6231. $this->status = 'envelope';
  6232. } elseif($name == 'Header' && $this->status = 'envelope'){
  6233. $this->root_header = $pos;
  6234. $this->status = 'header';
  6235. } elseif($name == 'Body' && $this->status = 'envelope'){
  6236. $this->status = 'body';
  6237. $this->body_position = $pos;
  6238. // set method
  6239. } elseif($this->status == 'body' && $pos == ($this->body_position+1)){
  6240. $this->status = 'method';
  6241. $this->root_struct_name = $name;
  6242. $this->root_struct = $pos;
  6243. $this->message[$pos]['type'] = 'struct';
  6244. $this->debug("found root struct $this->root_struct_name, pos $this->root_struct");
  6245. }
  6246. // set my status
  6247. $this->message[$pos]['status'] = $this->status;
  6248. // set name
  6249. $this->message[$pos]['name'] = htmlspecialchars($name);
  6250. // set attrs
  6251. $this->message[$pos]['attrs'] = $attrs;
  6252. // loop through atts, logging ns and type declarations
  6253. $attstr = '';
  6254. foreach($attrs as $key => $value){
  6255. $key_prefix = $this->getPrefix($key);
  6256. $key_localpart = $this->getLocalPart($key);
  6257. // if ns declarations, add to class level array of valid namespaces
  6258. if($key_prefix == 'xmlns'){
  6259. if(ereg('^http://www.w3.org/[0-9]{4}/XMLSchema$',$value)){
  6260. $this->XMLSchemaVersion = $value;
  6261. $this->namespaces['xsd'] = $this->XMLSchemaVersion;
  6262. $this->namespaces['xsi'] = $this->XMLSchemaVersion.'-instance';
  6263. }
  6264. $this->namespaces[$key_localpart] = $value;
  6265. // set method namespace
  6266. if($name == $this->root_struct_name){
  6267. $this->methodNamespace = $value;
  6268. }
  6269. // if it's a type declaration, set type
  6270. } elseif($key_localpart == 'type'){
  6271. if (isset($this->message[$pos]['type']) && $this->message[$pos]['type'] == 'array') {
  6272. // do nothing: already processed arrayType
  6273. } else {
  6274. $value_prefix = $this->getPrefix($value);
  6275. $value_localpart = $this->getLocalPart($value);
  6276. $this->message[$pos]['type'] = $value_localpart;
  6277. $this->message[$pos]['typePrefix'] = $value_prefix;
  6278. if(isset($this->namespaces[$value_prefix])){
  6279. $this->message[$pos]['type_namespace'] = $this->namespaces[$value_prefix];
  6280. } else if(isset($attrs['xmlns:'.$value_prefix])) {
  6281. $this->message[$pos]['type_namespace'] = $attrs['xmlns:'.$value_prefix];
  6282. }
  6283. // should do something here with the namespace of specified type?
  6284. }
  6285. } elseif($key_localpart == 'arrayType'){
  6286. $this->message[$pos]['type'] = 'array';
  6287. /* do arrayType ereg here
  6288. [1] arrayTypeValue ::= atype asize
  6289. [2] atype ::= QName rank*
  6290. [3] rank ::= '[' (',')* ']'
  6291. [4] asize ::= '[' length~ ']'
  6292. [5] length ::= nextDimension* Digit+
  6293. [6] nextDimension ::= Digit+ ','
  6294. */
  6295. $expr = '([A-Za-z0-9_]+):([A-Za-z]+[A-Za-z0-9_]+)\[([0-9]+),?([0-9]*)\]';
  6296. if(ereg($expr,$value,$regs)){
  6297. $this->message[$pos]['typePrefix'] = $regs[1];
  6298. $this->message[$pos]['arrayTypePrefix'] = $regs[1];
  6299. if (isset($this->namespaces[$regs[1]])) {
  6300. $this->message[$pos]['arrayTypeNamespace'] = $this->namespaces[$regs[1]];
  6301. } else if (isset($attrs['xmlns:'.$regs[1]])) {
  6302. $this->message[$pos]['arrayTypeNamespace'] = $attrs['xmlns:'.$regs[1]];
  6303. }
  6304. $this->message[$pos]['arrayType'] = $regs[2];
  6305. $this->message[$pos]['arraySize'] = $regs[3];
  6306. $this->message[$pos]['arrayCols'] = $regs[4];
  6307. }
  6308. // specifies nil value (or not)
  6309. } elseif ($key_localpart == 'nil'){
  6310. $this->message[$pos]['nil'] = ($value == 'true' || $value == '1');
  6311. // some other attribute
  6312. } elseif ($key != 'href' && $key != 'xmlns' && $key_localpart != 'encodingStyle' && $key_localpart != 'root') {
  6313. $this->message[$pos]['xattrs']['!' . $key] = $value;
  6314. }
  6315. if ($key == 'xmlns') {
  6316. $this->default_namespace = $value;
  6317. }
  6318. // log id
  6319. if($key == 'id'){
  6320. $this->ids[$value] = $pos;
  6321. }
  6322. // root
  6323. if($key_localpart == 'root' && $value == 1){
  6324. $this->status = 'method';
  6325. $this->root_struct_name = $name;
  6326. $this->root_struct = $pos;
  6327. $this->debug("found root struct $this->root_struct_name, pos $pos");
  6328. }
  6329. // for doclit
  6330. $attstr .= " $key=\"$value\"";
  6331. }
  6332. // get namespace - must be done after namespace atts are processed
  6333. if(isset($prefix)){
  6334. $this->message[$pos]['namespace'] = $this->namespaces[$prefix];
  6335. $this->default_namespace = $this->namespaces[$prefix];
  6336. } else {
  6337. $this->message[$pos]['namespace'] = $this->default_namespace;
  6338. }
  6339. if($this->status == 'header'){
  6340. if ($this->root_header != $pos) {
  6341. $this->responseHeaders .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>";
  6342. }
  6343. } elseif($this->root_struct_name != ''){
  6344. $this->document .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>";
  6345. }
  6346. }
  6347. /**
  6348. * end-element handler
  6349. *
  6350. * @param resource $parser XML parser object
  6351. * @param string $name element name
  6352. * @access private
  6353. */
  6354. function end_element($parser, $name) {
  6355. // position of current element is equal to the last value left in depth_array for my depth
  6356. $pos = $this->depth_array[$this->depth--];
  6357. // get element prefix
  6358. if(strpos($name,':')){
  6359. // get ns prefix
  6360. $prefix = substr($name,0,strpos($name,':'));
  6361. // get unqualified name
  6362. $name = substr(strstr($name,':'),1);
  6363. }
  6364. // build to native type
  6365. if(isset($this->body_position) && $pos > $this->body_position){
  6366. // deal w/ multirefs
  6367. if(isset($this->message[$pos]['attrs']['href'])){
  6368. // get id
  6369. $id = substr($this->message[$pos]['attrs']['href'],1);
  6370. // add placeholder to href array
  6371. $this->multirefs[$id][$pos] = 'placeholder';
  6372. // add set a reference to it as the result value
  6373. $this->message[$pos]['result'] =& $this->multirefs[$id][$pos];
  6374. // build complexType values
  6375. } elseif($this->message[$pos]['children'] != ''){
  6376. // if result has already been generated (struct/array)
  6377. if(!isset($this->message[$pos]['result'])){
  6378. $this->message[$pos]['result'] = $this->buildVal($pos);
  6379. }
  6380. // build complexType values of attributes and possibly simpleContent
  6381. } elseif (isset($this->message[$pos]['xattrs'])) {
  6382. if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) {
  6383. $this->message[$pos]['xattrs']['!'] = null;
  6384. } elseif (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') {
  6385. if (isset($this->message[$pos]['type'])) {
  6386. $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'] : '');
  6387. } else {
  6388. $parent = $this->message[$pos]['parent'];
  6389. if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
  6390. $this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
  6391. } else {
  6392. $this->message[$pos]['xattrs']['!'] = $this->message[$pos]['cdata'];
  6393. }
  6394. }
  6395. }
  6396. $this->message[$pos]['result'] = $this->message[$pos]['xattrs'];
  6397. // set value of simpleType (or nil complexType)
  6398. } else {
  6399. //$this->debug('adding data for scalar value '.$this->message[$pos]['name'].' of value '.$this->message[$pos]['cdata']);
  6400. if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) {
  6401. $this->message[$pos]['xattrs']['!'] = null;
  6402. } elseif (isset($this->message[$pos]['type'])) {
  6403. $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'] : '');
  6404. } else {
  6405. $parent = $this->message[$pos]['parent'];
  6406. if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
  6407. $this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
  6408. } else {
  6409. $this->message[$pos]['result'] = $this->message[$pos]['cdata'];
  6410. }
  6411. }
  6412. /* add value to parent's result, if parent is struct/array
  6413. $parent = $this->message[$pos]['parent'];
  6414. if($this->message[$parent]['type'] != 'map'){
  6415. if(strtolower($this->message[$parent]['type']) == 'array'){
  6416. $this->message[$parent]['result'][] = $this->message[$pos]['result'];
  6417. } else {
  6418. $this->message[$parent]['result'][$this->message[$pos]['name']] = $this->message[$pos]['result'];
  6419. }
  6420. }
  6421. */
  6422. }
  6423. }
  6424. // for doclit
  6425. if($this->status == 'header'){
  6426. if ($this->root_header != $pos) {
  6427. $this->responseHeaders .= "</" . (isset($prefix) ? $prefix . ':' : '') . "$name>";
  6428. }
  6429. } elseif($pos >= $this->root_struct){
  6430. $this->document .= "</" . (isset($prefix) ? $prefix . ':' : '') . "$name>";
  6431. }
  6432. // switch status
  6433. if($pos == $this->root_struct){
  6434. $this->status = 'body';
  6435. $this->root_struct_namespace = $this->message[$pos]['namespace'];
  6436. } elseif($name == 'Body'){
  6437. $this->status = 'envelope';
  6438. } elseif($name == 'Header'){
  6439. $this->status = 'envelope';
  6440. } elseif($name == 'Envelope'){
  6441. //
  6442. }
  6443. // set parent back to my parent
  6444. $this->parent = $this->message[$pos]['parent'];
  6445. }
  6446. /**
  6447. * element content handler
  6448. *
  6449. * @param resource $parser XML parser object
  6450. * @param string $data element content
  6451. * @access private
  6452. */
  6453. function character_data($parser, $data){
  6454. $pos = $this->depth_array[$this->depth];
  6455. if ($this->xml_encoding=='UTF-8'){
  6456. // TODO: add an option to disable this for folks who want
  6457. // raw UTF-8 that, e.g., might not map to iso-8859-1
  6458. // TODO: this can also be handled with xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "ISO-8859-1");
  6459. if($this->decode_utf8){
  6460. $data = utf8_decode($data);
  6461. }
  6462. }
  6463. $this->message[$pos]['cdata'] .= $data;
  6464. // for doclit
  6465. if($this->status == 'header'){
  6466. $this->responseHeaders .= $data;
  6467. } else {
  6468. $this->document .= $data;
  6469. }
  6470. }
  6471. /**
  6472. * get the parsed message (SOAP Body)
  6473. *
  6474. * @return mixed
  6475. * @access public
  6476. * @deprecated use get_soapbody instead
  6477. */
  6478. function get_response(){
  6479. return $this->soapresponse;
  6480. }
  6481. /**
  6482. * get the parsed SOAP Body (NULL if there was none)
  6483. *
  6484. * @return mixed
  6485. * @access public
  6486. */
  6487. function get_soapbody(){
  6488. return $this->soapresponse;
  6489. }
  6490. /**
  6491. * get the parsed SOAP Header (NULL if there was none)
  6492. *
  6493. * @return mixed
  6494. * @access public
  6495. */
  6496. function get_soapheader(){
  6497. return $this->soapheader;
  6498. }
  6499. /**
  6500. * get the unparsed SOAP Header
  6501. *
  6502. * @return string XML or empty if no Header
  6503. * @access public
  6504. */
  6505. function getHeaders(){
  6506. return $this->responseHeaders;
  6507. }
  6508. /**
  6509. * decodes simple types into PHP variables
  6510. *
  6511. * @param string $value value to decode
  6512. * @param string $type XML type to decode
  6513. * @param string $typens XML type namespace to decode
  6514. * @return mixed PHP value
  6515. * @access private
  6516. */
  6517. function decodeSimple($value, $type, $typens) {
  6518. // TODO: use the namespace!
  6519. if ((!isset($type)) || $type == 'string' || $type == 'long' || $type == 'unsignedLong') {
  6520. return (string) $value;
  6521. }
  6522. if ($type == 'int' || $type == 'integer' || $type == 'short' || $type == 'byte') {
  6523. return (int) $value;
  6524. }
  6525. if ($type == 'float' || $type == 'double' || $type == 'decimal') {
  6526. return (double) $value;
  6527. }
  6528. if ($type == 'boolean') {
  6529. if (strtolower($value) == 'false' || strtolower($value) == 'f') {
  6530. return false;
  6531. }
  6532. return (boolean) $value;
  6533. }
  6534. if ($type == 'base64' || $type == 'base64Binary') {
  6535. $this->debug('Decode base64 value');
  6536. return base64_decode($value);
  6537. }
  6538. // obscure numeric types
  6539. if ($type == 'nonPositiveInteger' || $type == 'negativeInteger'
  6540. || $type == 'nonNegativeInteger' || $type == 'positiveInteger'
  6541. || $type == 'unsignedInt'
  6542. || $type == 'unsignedShort' || $type == 'unsignedByte') {
  6543. return (int) $value;
  6544. }
  6545. // bogus: parser treats array with no elements as a simple type
  6546. if ($type == 'array') {
  6547. return array();
  6548. }
  6549. // everything else
  6550. return (string) $value;
  6551. }
  6552. /**
  6553. * builds response structures for compound values (arrays/structs)
  6554. * and scalars
  6555. *
  6556. * @param integer $pos position in node tree
  6557. * @return mixed PHP value
  6558. * @access private
  6559. */
  6560. function buildVal($pos){
  6561. if(!isset($this->message[$pos]['type'])){
  6562. $this->message[$pos]['type'] = '';
  6563. }
  6564. $this->debug('in buildVal() for '.$this->message[$pos]['name']."(pos $pos) of type ".$this->message[$pos]['type']);
  6565. // if there are children...
  6566. if($this->message[$pos]['children'] != ''){
  6567. $this->debug('in buildVal, there are children');
  6568. $children = explode('|',$this->message[$pos]['children']);
  6569. array_shift($children); // knock off empty
  6570. // md array
  6571. if(isset($this->message[$pos]['arrayCols']) && $this->message[$pos]['arrayCols'] != ''){
  6572. $r=0; // rowcount
  6573. $c=0; // colcount
  6574. foreach($children as $child_pos){
  6575. $this->debug("in buildVal, got an MD array element: $r, $c");
  6576. $params[$r][] = $this->message[$child_pos]['result'];
  6577. $c++;
  6578. if($c == $this->message[$pos]['arrayCols']){
  6579. $c = 0;
  6580. $r++;
  6581. }
  6582. }
  6583. // array
  6584. } elseif($this->message[$pos]['type'] == 'array' || $this->message[$pos]['type'] == 'Array'){
  6585. $this->debug('in buildVal, adding array '.$this->message[$pos]['name']);
  6586. foreach($children as $child_pos){
  6587. $params[] = &$this->message[$child_pos]['result'];
  6588. }
  6589. // apache Map type: java hashtable
  6590. } elseif($this->message[$pos]['type'] == 'Map' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap'){
  6591. $this->debug('in buildVal, Java Map '.$this->message[$pos]['name']);
  6592. foreach($children as $child_pos){
  6593. $kv = explode("|",$this->message[$child_pos]['children']);
  6594. $params[$this->message[$kv[1]]['result']] = &$this->message[$kv[2]]['result'];
  6595. }
  6596. // generic compound type
  6597. //} elseif($this->message[$pos]['type'] == 'SOAPStruct' || $this->message[$pos]['type'] == 'struct') {
  6598. } else {
  6599. // Apache Vector type: treat as an array
  6600. $this->debug('in buildVal, adding Java Vector or generic compound type '.$this->message[$pos]['name']);
  6601. if ($this->message[$pos]['type'] == 'Vector' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap') {
  6602. $notstruct = 1;
  6603. } else {
  6604. $notstruct = 0;
  6605. }
  6606. //
  6607. foreach($children as $child_pos){
  6608. if($notstruct){
  6609. $params[] = &$this->message[$child_pos]['result'];
  6610. } else {
  6611. if (isset($params[$this->message[$child_pos]['name']])) {
  6612. // de-serialize repeated element name into an array
  6613. if ((!is_array($params[$this->message[$child_pos]['name']])) || (!isset($params[$this->message[$child_pos]['name']][0]))) {
  6614. $params[$this->message[$child_pos]['name']] = array($params[$this->message[$child_pos]['name']]);
  6615. }
  6616. $params[$this->message[$child_pos]['name']][] = &$this->message[$child_pos]['result'];
  6617. } else {
  6618. $params[$this->message[$child_pos]['name']] = &$this->message[$child_pos]['result'];
  6619. }
  6620. }
  6621. }
  6622. }
  6623. if (isset($this->message[$pos]['xattrs'])) {
  6624. $this->debug('in buildVal, handling attributes');
  6625. foreach ($this->message[$pos]['xattrs'] as $n => $v) {
  6626. $params[$n] = $v;
  6627. }
  6628. }
  6629. // handle simpleContent
  6630. if (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') {
  6631. $this->debug('in buildVal, handling simpleContent');
  6632. if (isset($this->message[$pos]['type'])) {
  6633. $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
  6634. } else {
  6635. $parent = $this->message[$pos]['parent'];
  6636. if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
  6637. $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
  6638. } else {
  6639. $params['!'] = $this->message[$pos]['cdata'];
  6640. }
  6641. }
  6642. }
  6643. $ret = is_array($params) ? $params : array();
  6644. $this->debug('in buildVal, return:');
  6645. $this->appendDebug($this->varDump($ret));
  6646. return $ret;
  6647. } else {
  6648. $this->debug('in buildVal, no children, building scalar');
  6649. $cdata = isset($this->message[$pos]['cdata']) ? $this->message[$pos]['cdata'] : '';
  6650. if (isset($this->message[$pos]['type'])) {
  6651. $ret = $this->decodeSimple($cdata, $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
  6652. $this->debug("in buildVal, return: $ret");
  6653. return $ret;
  6654. }
  6655. $parent = $this->message[$pos]['parent'];
  6656. if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
  6657. $ret = $this->decodeSimple($cdata, $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
  6658. $this->debug("in buildVal, return: $ret");
  6659. return $ret;
  6660. }
  6661. $ret = $this->message[$pos]['cdata'];
  6662. $this->debug("in buildVal, return: $ret");
  6663. return $ret;
  6664. }
  6665. }
  6666. }
  6667. /**
  6668. * Backward compatibility
  6669. */
  6670. class soap_parser extends nusoap_parser {
  6671. }
  6672. ?><?php
  6673. /**
  6674. *
  6675. * [nu]soapclient higher level class for easy usage.
  6676. *
  6677. * usage:
  6678. *
  6679. * // instantiate client with server info
  6680. * $soapclient = new nusoap_client( string path [ ,mixed wsdl] );
  6681. *
  6682. * // call method, get results
  6683. * echo $soapclient->call( string methodname [ ,array parameters] );
  6684. *
  6685. * // bye bye client
  6686. * unset($soapclient);
  6687. *
  6688. * @author Dietrich Ayala <dietrich@ganx4.com>
  6689. * @author Scott Nichol <snichol@users.sourceforge.net>
  6690. * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $
  6691. * @access public
  6692. */
  6693. class nusoap_client extends nusoap_base {
  6694. var $username = ''; // Username for HTTP authentication
  6695. var $password = ''; // Password for HTTP authentication
  6696. var $authtype = ''; // Type of HTTP authentication
  6697. var $certRequest = array(); // Certificate for HTTP SSL authentication
  6698. var $requestHeaders = false; // SOAP headers in request (text)
  6699. var $responseHeaders = ''; // SOAP headers from response (incomplete namespace resolution) (text)
  6700. var $responseHeader = NULL; // SOAP Header from response (parsed)
  6701. var $document = ''; // SOAP body response portion (incomplete namespace resolution) (text)
  6702. var $endpoint;
  6703. var $forceEndpoint = ''; // overrides WSDL endpoint
  6704. var $proxyhost = '';
  6705. var $proxyport = '';
  6706. var $proxyusername = '';
  6707. var $proxypassword = '';
  6708. var $xml_encoding = ''; // character set encoding of incoming (response) messages
  6709. var $http_encoding = false;
  6710. var $timeout = 0; // HTTP connection timeout
  6711. var $response_timeout = 30; // HTTP response timeout
  6712. var $endpointType = ''; // soap|wsdl, empty for WSDL initialization error
  6713. var $persistentConnection = false;
  6714. var $defaultRpcParams = false; // This is no longer used
  6715. var $request = ''; // HTTP request
  6716. var $response = ''; // HTTP response
  6717. var $responseData = ''; // SOAP payload of response
  6718. var $cookies = array(); // Cookies from response or for request
  6719. var $decode_utf8 = true; // toggles whether the parser decodes element content w/ utf8_decode()
  6720. var $operations = array(); // WSDL operations, empty for WSDL initialization error
  6721. var $curl_options = array(); // User-specified cURL options
  6722. var $bindingType = ''; // WSDL operation binding type
  6723. var $use_curl = false; // whether to always try to use cURL
  6724. /*
  6725. * fault related variables
  6726. */
  6727. /**
  6728. * @var fault
  6729. * @access public
  6730. */
  6731. var $fault;
  6732. /**
  6733. * @var faultcode
  6734. * @access public
  6735. */
  6736. var $faultcode;
  6737. /**
  6738. * @var faultstring
  6739. * @access public
  6740. */
  6741. var $faultstring;
  6742. /**
  6743. * @var faultdetail
  6744. * @access public
  6745. */
  6746. var $faultdetail;
  6747. /**
  6748. * constructor
  6749. *
  6750. * @param mixed $endpoint SOAP server or WSDL URL (string), or wsdl instance (object)
  6751. * @param bool $wsdl optional, set to true if using WSDL
  6752. * @param int $portName optional portName in WSDL document
  6753. * @param string $proxyhost
  6754. * @param string $proxyport
  6755. * @param string $proxyusername
  6756. * @param string $proxypassword
  6757. * @param integer $timeout set the connection timeout
  6758. * @param integer $response_timeout set the response timeout
  6759. * @access public
  6760. */
  6761. function nusoap_client($endpoint,$wsdl = false,$proxyhost = false,$proxyport = false,$proxyusername = false, $proxypassword = false, $timeout = 0, $response_timeout = 30){
  6762. parent::nusoap_base();
  6763. $this->endpoint = $endpoint;
  6764. $this->proxyhost = $proxyhost;
  6765. $this->proxyport = $proxyport;
  6766. $this->proxyusername = $proxyusername;
  6767. $this->proxypassword = $proxypassword;
  6768. $this->timeout = $timeout;
  6769. $this->response_timeout = $response_timeout;
  6770. $this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout");
  6771. $this->appendDebug('endpoint=' . $this->varDump($endpoint));
  6772. // make values
  6773. if($wsdl){
  6774. if (is_object($endpoint) && (get_class($endpoint) == 'wsdl')) {
  6775. $this->wsdl = $endpoint;
  6776. $this->endpoint = $this->wsdl->wsdl;
  6777. $this->wsdlFile = $this->endpoint;
  6778. $this->debug('existing wsdl instance created from ' . $this->endpoint);
  6779. $this->checkWSDL();
  6780. } else {
  6781. $this->wsdlFile = $this->endpoint;
  6782. $this->wsdl = null;
  6783. $this->debug('will use lazy evaluation of wsdl from ' . $this->endpoint);
  6784. }
  6785. $this->endpointType = 'wsdl';
  6786. } else {
  6787. $this->debug("instantiate SOAP with endpoint at $endpoint");
  6788. $this->endpointType = 'soap';
  6789. }
  6790. }
  6791. /**
  6792. * calls method, returns PHP native type
  6793. *
  6794. * @param string $operation SOAP server URL or path
  6795. * @param mixed $params An array, associative or simple, of the parameters
  6796. * for the method call, or a string that is the XML
  6797. * for the call. For rpc style, this call will
  6798. * wrap the XML in a tag named after the method, as
  6799. * well as the SOAP Envelope and Body. For document
  6800. * style, this will only wrap with the Envelope and Body.
  6801. * IMPORTANT: when using an array with document style,
  6802. * in which case there
  6803. * is really one parameter, the root of the fragment
  6804. * used in the call, which encloses what programmers
  6805. * normally think of parameters. A parameter array
  6806. * *must* include the wrapper.
  6807. * @param string $namespace optional method namespace (WSDL can override)
  6808. * @param string $soapAction optional SOAPAction value (WSDL can override)
  6809. * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers, or associative array
  6810. * @param boolean $rpcParams optional (no longer used)
  6811. * @param string $style optional (rpc|document) the style to use when serializing parameters (WSDL can override)
  6812. * @param string $use optional (encoded|literal) the use when serializing parameters (WSDL can override)
  6813. * @return mixed response from SOAP call
  6814. * @access public
  6815. */
  6816. function call($operation,$params=array(),$namespace='http://tempuri.org',$soapAction='',$headers=false,$rpcParams=null,$style='rpc',$use='encoded'){
  6817. $this->operation = $operation;
  6818. $this->fault = false;
  6819. $this->setError('');
  6820. $this->request = '';
  6821. $this->response = '';
  6822. $this->responseData = '';
  6823. $this->faultstring = '';
  6824. $this->faultcode = '';
  6825. $this->opData = array();
  6826. $this->debug("call: operation=$operation, namespace=$namespace, soapAction=$soapAction, rpcParams=$rpcParams, style=$style, use=$use, endpointType=$this->endpointType");
  6827. $this->appendDebug('params=' . $this->varDump($params));
  6828. $this->appendDebug('headers=' . $this->varDump($headers));
  6829. if ($headers) {
  6830. $this->requestHeaders = $headers;
  6831. }
  6832. if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) {
  6833. $this->loadWSDL();
  6834. if ($this->getError())
  6835. return false;
  6836. }
  6837. // serialize parameters
  6838. if($this->endpointType == 'wsdl' && $opData = $this->getOperationData($operation)){
  6839. // use WSDL for operation
  6840. $this->opData = $opData;
  6841. $this->debug("found operation");
  6842. $this->appendDebug('opData=' . $this->varDump($opData));
  6843. if (isset($opData['soapAction'])) {
  6844. $soapAction = $opData['soapAction'];
  6845. }
  6846. if (! $this->forceEndpoint) {
  6847. $this->endpoint = $opData['endpoint'];
  6848. } else {
  6849. $this->endpoint = $this->forceEndpoint;
  6850. }
  6851. $namespace = isset($opData['input']['namespace']) ? $opData['input']['namespace'] : $namespace;
  6852. $style = $opData['style'];
  6853. $use = $opData['input']['use'];
  6854. // add ns to ns array
  6855. if($namespace != '' && !isset($this->wsdl->namespaces[$namespace])){
  6856. $nsPrefix = 'ns' . rand(1000, 9999);
  6857. $this->wsdl->namespaces[$nsPrefix] = $namespace;
  6858. }
  6859. $nsPrefix = $this->wsdl->getPrefixFromNamespace($namespace);
  6860. // serialize payload
  6861. if (is_string($params)) {
  6862. $this->debug("serializing param string for WSDL operation $operation");
  6863. $payload = $params;
  6864. } elseif (is_array($params)) {
  6865. $this->debug("serializing param array for WSDL operation $operation");
  6866. $payload = $this->wsdl->serializeRPCParameters($operation,'input',$params,$this->bindingType);
  6867. } else {
  6868. $this->debug('params must be array or string');
  6869. $this->setError('params must be array or string');
  6870. return false;
  6871. }
  6872. $usedNamespaces = $this->wsdl->usedNamespaces;
  6873. if (isset($opData['input']['encodingStyle'])) {
  6874. $encodingStyle = $opData['input']['encodingStyle'];
  6875. } else {
  6876. $encodingStyle = '';
  6877. }
  6878. $this->appendDebug($this->wsdl->getDebug());
  6879. $this->wsdl->clearDebug();
  6880. if ($errstr = $this->wsdl->getError()) {
  6881. $this->debug('got wsdl error: '.$errstr);
  6882. $this->setError('wsdl error: '.$errstr);
  6883. return false;
  6884. }
  6885. } elseif($this->endpointType == 'wsdl') {
  6886. // operation not in WSDL
  6887. $this->appendDebug($this->wsdl->getDebug());
  6888. $this->wsdl->clearDebug();
  6889. $this->setError( 'operation '.$operation.' not present.');
  6890. $this->debug("operation '$operation' not present.");
  6891. return false;
  6892. } else {
  6893. // no WSDL
  6894. //$this->namespaces['ns1'] = $namespace;
  6895. $nsPrefix = 'ns' . rand(1000, 9999);
  6896. // serialize
  6897. $payload = '';
  6898. if (is_string($params)) {
  6899. $this->debug("serializing param string for operation $operation");
  6900. $payload = $params;
  6901. } elseif (is_array($params)) {
  6902. $this->debug("serializing param array for operation $operation");
  6903. foreach($params as $k => $v){
  6904. $payload .= $this->serialize_val($v,$k,false,false,false,false,$use);
  6905. }
  6906. } else {
  6907. $this->debug('params must be array or string');
  6908. $this->setError('params must be array or string');
  6909. return false;
  6910. }
  6911. $usedNamespaces = array();
  6912. if ($use == 'encoded') {
  6913. $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
  6914. } else {
  6915. $encodingStyle = '';
  6916. }
  6917. }
  6918. // wrap RPC calls with method element
  6919. if ($style == 'rpc') {
  6920. if ($use == 'literal') {
  6921. $this->debug("wrapping RPC request with literal method element");
  6922. if ($namespace) {
  6923. // http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html R2735 says rpc/literal accessor elements should not be in a namespace
  6924. $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" .
  6925. $payload .
  6926. "</$nsPrefix:$operation>";
  6927. } else {
  6928. $payload = "<$operation>" . $payload . "</$operation>";
  6929. }
  6930. } else {
  6931. $this->debug("wrapping RPC request with encoded method element");
  6932. if ($namespace) {
  6933. $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" .
  6934. $payload .
  6935. "</$nsPrefix:$operation>";
  6936. } else {
  6937. $payload = "<$operation>" .
  6938. $payload .
  6939. "</$operation>";
  6940. }
  6941. }
  6942. }
  6943. // serialize envelope
  6944. $soapmsg = $this->serializeEnvelope($payload,$this->requestHeaders,$usedNamespaces,$style,$use,$encodingStyle);
  6945. $this->debug("endpoint=$this->endpoint, soapAction=$soapAction, namespace=$namespace, style=$style, use=$use, encodingStyle=$encodingStyle");
  6946. $this->debug('SOAP message length=' . strlen($soapmsg) . ' contents (max 1000 bytes)=' . substr($soapmsg, 0, 1000));
  6947. // send
  6948. $return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout);
  6949. if($errstr = $this->getError()){
  6950. $this->debug('Error: '.$errstr);
  6951. return false;
  6952. } else {
  6953. $this->return = $return;
  6954. $this->debug('sent message successfully and got a(n) '.gettype($return));
  6955. $this->appendDebug('return=' . $this->varDump($return));
  6956. // fault?
  6957. if(is_array($return) && isset($return['faultcode'])){
  6958. $this->debug('got fault');
  6959. $this->setError($return['faultcode'].': '.$return['faultstring']);
  6960. $this->fault = true;
  6961. foreach($return as $k => $v){
  6962. $this->$k = $v;
  6963. $this->debug("$k = $v<br>");
  6964. }
  6965. return $return;
  6966. } elseif ($style == 'document') {
  6967. // NOTE: if the response is defined to have multiple parts (i.e. unwrapped),
  6968. // we are only going to return the first part here...sorry about that
  6969. return $return;
  6970. } else {
  6971. // array of return values
  6972. if(is_array($return)){
  6973. // multiple 'out' parameters, which we return wrapped up
  6974. // in the array
  6975. if(sizeof($return) > 1){
  6976. return $return;
  6977. }
  6978. // single 'out' parameter (normally the return value)
  6979. $return = array_shift($return);
  6980. $this->debug('return shifted value: ');
  6981. $this->appendDebug($this->varDump($return));
  6982. return $return;
  6983. // nothing returned (ie, echoVoid)
  6984. } else {
  6985. return "";
  6986. }
  6987. }
  6988. }
  6989. }
  6990. /**
  6991. * check WSDL passed as an instance or pulled from an endpoint
  6992. *
  6993. * @access private
  6994. */
  6995. function checkWSDL() {
  6996. $this->appendDebug($this->wsdl->getDebug());
  6997. $this->wsdl->clearDebug();
  6998. $this->debug('checkWSDL');
  6999. // catch errors
  7000. if ($errstr = $this->wsdl->getError()) {
  7001. $this->debug('got wsdl error: '.$errstr);
  7002. $this->setError('wsdl error: '.$errstr);
  7003. } elseif ($this->operations = $this->wsdl->getOperations('soap')) {
  7004. $this->bindingType = 'soap';
  7005. $this->debug('got '.count($this->operations).' operations from wsdl '.$this->wsdlFile.' for binding type '.$this->bindingType);
  7006. } elseif ($this->operations = $this->wsdl->getOperations('soap12')) {
  7007. $this->bindingType = 'soap12';
  7008. $this->debug('got '.count($this->operations).' operations from wsdl '.$this->wsdlFile.' for binding type '.$this->bindingType);
  7009. $this->debug('**************** WARNING: SOAP 1.2 BINDING *****************');
  7010. } else {
  7011. $this->debug('getOperations returned false');
  7012. $this->setError('no operations defined in the WSDL document!');
  7013. }
  7014. }
  7015. /**
  7016. * instantiate wsdl object and parse wsdl file
  7017. *
  7018. * @access public
  7019. */
  7020. function loadWSDL() {
  7021. $this->debug('instantiating wsdl class with doc: '.$this->wsdlFile);
  7022. $this->wsdl =& new wsdl('',$this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword,$this->timeout,$this->response_timeout,$this->curl_options,$this->use_curl);
  7023. $this->wsdl->setCredentials($this->username, $this->password, $this->authtype, $this->certRequest);
  7024. $this->wsdl->fetchWSDL($this->wsdlFile);
  7025. $this->checkWSDL();
  7026. }
  7027. /**
  7028. * get available data pertaining to an operation
  7029. *
  7030. * @param string $operation operation name
  7031. * @return array array of data pertaining to the operation
  7032. * @access public
  7033. */
  7034. function getOperationData($operation){
  7035. if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) {
  7036. $this->loadWSDL();
  7037. if ($this->getError())
  7038. return false;
  7039. }
  7040. if(isset($this->operations[$operation])){
  7041. return $this->operations[$operation];
  7042. }
  7043. $this->debug("No data for operation: $operation");
  7044. }
  7045. /**
  7046. * send the SOAP message
  7047. *
  7048. * Note: if the operation has multiple return values
  7049. * the return value of this method will be an array
  7050. * of those values.
  7051. *
  7052. * @param string $msg a SOAPx4 soapmsg object
  7053. * @param string $soapaction SOAPAction value
  7054. * @param integer $timeout set connection timeout in seconds
  7055. * @param integer $response_timeout set response timeout in seconds
  7056. * @return mixed native PHP types.
  7057. * @access private
  7058. */
  7059. function send($msg, $soapaction = '', $timeout=0, $response_timeout=30) {
  7060. $this->checkCookies();
  7061. // detect transport
  7062. switch(true){
  7063. // http(s)
  7064. case ereg('^http',$this->endpoint):
  7065. $this->debug('transporting via HTTP');
  7066. if($this->persistentConnection == true && is_object($this->persistentConnection)){
  7067. $http =& $this->persistentConnection;
  7068. } else {
  7069. $http = new soap_transport_http($this->endpoint, $this->curl_options, $this->use_curl);
  7070. if ($this->persistentConnection) {
  7071. $http->usePersistentConnection();
  7072. }
  7073. }
  7074. $http->setContentType($this->getHTTPContentType(), $this->getHTTPContentTypeCharset());
  7075. $http->setSOAPAction($soapaction);
  7076. if($this->proxyhost && $this->proxyport){
  7077. $http->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword);
  7078. }
  7079. if($this->authtype != '') {
  7080. $http->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest);
  7081. }
  7082. if($this->http_encoding != ''){
  7083. $http->setEncoding($this->http_encoding);
  7084. }
  7085. $this->debug('sending message, length='.strlen($msg));
  7086. if(ereg('^http:',$this->endpoint)){
  7087. //if(strpos($this->endpoint,'http:')){
  7088. $this->responseData = $http->send($msg,$timeout,$response_timeout,$this->cookies);
  7089. } elseif(ereg('^https',$this->endpoint)){
  7090. //} elseif(strpos($this->endpoint,'https:')){
  7091. //if(phpversion() == '4.3.0-dev'){
  7092. //$response = $http->send($msg,$timeout,$response_timeout);
  7093. //$this->request = $http->outgoing_payload;
  7094. //$this->response = $http->incoming_payload;
  7095. //} else
  7096. $this->responseData = $http->sendHTTPS($msg,$timeout,$response_timeout,$this->cookies);
  7097. } else {
  7098. $this->setError('no http/s in endpoint url');
  7099. }
  7100. $this->request = $http->outgoing_payload;
  7101. $this->response = $http->incoming_payload;
  7102. $this->appendDebug($http->getDebug());
  7103. $this->UpdateCookies($http->incoming_cookies);
  7104. // save transport object if using persistent connections
  7105. if ($this->persistentConnection) {
  7106. $http->clearDebug();
  7107. if (!is_object($this->persistentConnection)) {
  7108. $this->persistentConnection = $http;
  7109. }
  7110. }
  7111. if($err = $http->getError()){
  7112. $this->setError('HTTP Error: '.$err);
  7113. return false;
  7114. } elseif($this->getError()){
  7115. return false;
  7116. } else {
  7117. $this->debug('got response, length='. strlen($this->responseData).' type='.$http->incoming_headers['content-type']);
  7118. return $this->parseResponse($http->incoming_headers, $this->responseData);
  7119. }
  7120. break;
  7121. default:
  7122. $this->setError('no transport found, or selected transport is not yet supported!');
  7123. return false;
  7124. break;
  7125. }
  7126. }
  7127. /**
  7128. * processes SOAP message returned from server
  7129. *
  7130. * @param array $headers The HTTP headers
  7131. * @param string $data unprocessed response data from server
  7132. * @return mixed value of the message, decoded into a PHP type
  7133. * @access private
  7134. */
  7135. function parseResponse($headers, $data) {
  7136. $this->debug('Entering parseResponse() for data of length ' . strlen($data) . ' headers:');
  7137. $this->appendDebug($this->varDump($headers));
  7138. if (!strstr($headers['content-type'], 'text/xml')) {
  7139. $this->setError('Response not of type text/xml: ' . $headers['content-type']);
  7140. return false;
  7141. }
  7142. if (strpos($headers['content-type'], '=')) {
  7143. $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1));
  7144. $this->debug('Got response encoding: ' . $enc);
  7145. if(eregi('^(ISO-8859-1|US-ASCII|UTF-8)$',$enc)){
  7146. $this->xml_encoding = strtoupper($enc);
  7147. } else {
  7148. $this->xml_encoding = 'US-ASCII';
  7149. }
  7150. } else {
  7151. // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
  7152. $this->xml_encoding = 'ISO-8859-1';
  7153. }
  7154. $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating nusoap_parser');
  7155. $parser = new nusoap_parser($data,$this->xml_encoding,$this->operation,$this->decode_utf8);
  7156. // add parser debug data to our debug
  7157. $this->appendDebug($parser->getDebug());
  7158. // if parse errors
  7159. if($errstr = $parser->getError()){
  7160. $this->setError( $errstr);
  7161. // destroy the parser object
  7162. unset($parser);
  7163. return false;
  7164. } else {
  7165. // get SOAP headers
  7166. $this->responseHeaders = $parser->getHeaders();
  7167. // get SOAP headers
  7168. $this->responseHeader = $parser->get_soapheader();
  7169. // get decoded message
  7170. $return = $parser->get_soapbody();
  7171. // add document for doclit support
  7172. $this->document = $parser->document;
  7173. // destroy the parser object
  7174. unset($parser);
  7175. // return decode message
  7176. return $return;
  7177. }
  7178. }
  7179. /**
  7180. * sets user-specified cURL options
  7181. *
  7182. * @param mixed $option The cURL option (always integer?)
  7183. * @param mixed $value The cURL option value
  7184. * @access public
  7185. */
  7186. function setCurlOption($option, $value) {
  7187. $this->debug("setCurlOption option=$option, value=");
  7188. $this->appendDebug($this->varDump($value));
  7189. $this->curl_options[$option] = $value;
  7190. }
  7191. /**
  7192. * sets the SOAP endpoint, which can override WSDL
  7193. *
  7194. * @param string $endpoint The endpoint URL to use, or empty string or false to prevent override
  7195. * @access public
  7196. */
  7197. function setEndpoint($endpoint) {
  7198. $this->debug("setEndpoint(\"$endpoint\")");
  7199. $this->forceEndpoint = $endpoint;
  7200. }
  7201. /**
  7202. * set the SOAP headers
  7203. *
  7204. * @param mixed $headers String of XML with SOAP header content, or array of soapval objects for SOAP headers
  7205. * @access public
  7206. */
  7207. function setHeaders($headers){
  7208. $this->debug("setHeaders headers=");
  7209. $this->appendDebug($this->varDump($headers));
  7210. $this->requestHeaders = $headers;
  7211. }
  7212. /**
  7213. * get the SOAP response headers (namespace resolution incomplete)
  7214. *
  7215. * @return string
  7216. * @access public
  7217. */
  7218. function getHeaders(){
  7219. return $this->responseHeaders;
  7220. }
  7221. /**
  7222. * get the SOAP response Header (parsed)
  7223. *
  7224. * @return mixed
  7225. * @access public
  7226. */
  7227. function getHeader(){
  7228. return $this->responseHeader;
  7229. }
  7230. /**
  7231. * set proxy info here
  7232. *
  7233. * @param string $proxyhost
  7234. * @param string $proxyport
  7235. * @param string $proxyusername
  7236. * @param string $proxypassword
  7237. * @access public
  7238. */
  7239. function setHTTPProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') {
  7240. $this->proxyhost = $proxyhost;
  7241. $this->proxyport = $proxyport;
  7242. $this->proxyusername = $proxyusername;
  7243. $this->proxypassword = $proxypassword;
  7244. }
  7245. /**
  7246. * if authenticating, set user credentials here
  7247. *
  7248. * @param string $username
  7249. * @param string $password
  7250. * @param string $authtype (basic|digest|certificate|ntlm)
  7251. * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
  7252. * @access public
  7253. */
  7254. function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) {
  7255. $this->debug("setCredentials username=$username authtype=$authtype certRequest=");
  7256. $this->appendDebug($this->varDump($certRequest));
  7257. $this->username = $username;
  7258. $this->password = $password;
  7259. $this->authtype = $authtype;
  7260. $this->certRequest = $certRequest;
  7261. }
  7262. /**
  7263. * use HTTP encoding
  7264. *
  7265. * @param string $enc HTTP encoding
  7266. * @access public
  7267. */
  7268. function setHTTPEncoding($enc='gzip, deflate'){
  7269. $this->debug("setHTTPEncoding(\"$enc\")");
  7270. $this->http_encoding = $enc;
  7271. }
  7272. /**
  7273. * Set whether to try to use cURL connections if possible
  7274. *
  7275. * @param boolean $use Whether to try to use cURL
  7276. * @access public
  7277. */
  7278. function setUseCURL($use) {
  7279. $this->debug("setUseCURL($use)");
  7280. $this->use_curl = $use;
  7281. }
  7282. /**
  7283. * use HTTP persistent connections if possible
  7284. *
  7285. * @access public
  7286. */
  7287. function useHTTPPersistentConnection(){
  7288. $this->debug("useHTTPPersistentConnection");
  7289. $this->persistentConnection = true;
  7290. }
  7291. /**
  7292. * gets the default RPC parameter setting.
  7293. * If true, default is that call params are like RPC even for document style.
  7294. * Each call() can override this value.
  7295. *
  7296. * This is no longer used.
  7297. *
  7298. * @return boolean
  7299. * @access public
  7300. * @deprecated
  7301. */
  7302. function getDefaultRpcParams() {
  7303. return $this->defaultRpcParams;
  7304. }
  7305. /**
  7306. * sets the default RPC parameter setting.
  7307. * If true, default is that call params are like RPC even for document style
  7308. * Each call() can override this value.
  7309. *
  7310. * This is no longer used.
  7311. *
  7312. * @param boolean $rpcParams
  7313. * @access public
  7314. * @deprecated
  7315. */
  7316. function setDefaultRpcParams($rpcParams) {
  7317. $this->defaultRpcParams = $rpcParams;
  7318. }
  7319. /**
  7320. * dynamically creates an instance of a proxy class,
  7321. * allowing user to directly call methods from wsdl
  7322. *
  7323. * @return object soap_proxy object
  7324. * @access public
  7325. */
  7326. function getProxy() {
  7327. $r = rand();
  7328. $evalStr = $this->_getProxyClassCode($r);
  7329. //$this->debug("proxy class: $evalStr");
  7330. if ($this->getError()) {
  7331. $this->debug("Error from _getProxyClassCode, so return NULL");
  7332. return null;
  7333. }
  7334. // eval the class
  7335. eval($evalStr);
  7336. // instantiate proxy object
  7337. eval("\$proxy = new nusoap_proxy_$r('');");
  7338. // transfer current wsdl data to the proxy thereby avoiding parsing the wsdl twice
  7339. $proxy->endpointType = 'wsdl';
  7340. $proxy->wsdlFile = $this->wsdlFile;
  7341. $proxy->wsdl = $this->wsdl;
  7342. $proxy->operations = $this->operations;
  7343. $proxy->defaultRpcParams = $this->defaultRpcParams;
  7344. // transfer other state
  7345. $proxy->soap_defencoding = $this->soap_defencoding;
  7346. $proxy->username = $this->username;
  7347. $proxy->password = $this->password;
  7348. $proxy->authtype = $this->authtype;
  7349. $proxy->certRequest = $this->certRequest;
  7350. $proxy->requestHeaders = $this->requestHeaders;
  7351. $proxy->endpoint = $this->endpoint;
  7352. $proxy->forceEndpoint = $this->forceEndpoint;
  7353. $proxy->proxyhost = $this->proxyhost;
  7354. $proxy->proxyport = $this->proxyport;
  7355. $proxy->proxyusername = $this->proxyusername;
  7356. $proxy->proxypassword = $this->proxypassword;
  7357. $proxy->http_encoding = $this->http_encoding;
  7358. $proxy->timeout = $this->timeout;
  7359. $proxy->response_timeout = $this->response_timeout;
  7360. $proxy->persistentConnection = &$this->persistentConnection;
  7361. $proxy->decode_utf8 = $this->decode_utf8;
  7362. $proxy->curl_options = $this->curl_options;
  7363. $proxy->bindingType = $this->bindingType;
  7364. $proxy->use_curl = $this->use_curl;
  7365. return $proxy;
  7366. }
  7367. /**
  7368. * dynamically creates proxy class code
  7369. *
  7370. * @return string PHP/NuSOAP code for the proxy class
  7371. * @access private
  7372. */
  7373. function _getProxyClassCode($r) {
  7374. $this->debug("in getProxy endpointType=$this->endpointType");
  7375. $this->appendDebug("wsdl=" . $this->varDump($this->wsdl));
  7376. if ($this->endpointType != 'wsdl') {
  7377. $evalStr = 'A proxy can only be created for a WSDL client';
  7378. $this->setError($evalStr);
  7379. $evalStr = "echo \"$evalStr\";";
  7380. return $evalStr;
  7381. }
  7382. if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) {
  7383. $this->loadWSDL();
  7384. if ($this->getError()) {
  7385. return "echo \"" . $this->getError() . "\";";
  7386. }
  7387. }
  7388. $evalStr = '';
  7389. foreach ($this->operations as $operation => $opData) {
  7390. if ($operation != '') {
  7391. // create param string and param comment string
  7392. if (sizeof($opData['input']['parts']) > 0) {
  7393. $paramStr = '';
  7394. $paramArrayStr = '';
  7395. $paramCommentStr = '';
  7396. foreach ($opData['input']['parts'] as $name => $type) {
  7397. $paramStr .= "\$$name, ";
  7398. $paramArrayStr .= "'$name' => \$$name, ";
  7399. $paramCommentStr .= "$type \$$name, ";
  7400. }
  7401. $paramStr = substr($paramStr, 0, strlen($paramStr)-2);
  7402. $paramArrayStr = substr($paramArrayStr, 0, strlen($paramArrayStr)-2);
  7403. $paramCommentStr = substr($paramCommentStr, 0, strlen($paramCommentStr)-2);
  7404. } else {
  7405. $paramStr = '';
  7406. $paramArrayStr = '';
  7407. $paramCommentStr = 'void';
  7408. }
  7409. $opData['namespace'] = !isset($opData['namespace']) ? 'http://testuri.com' : $opData['namespace'];
  7410. $evalStr .= "// $paramCommentStr
  7411. function " . str_replace('.', '__', $operation) . "($paramStr) {
  7412. \$params = array($paramArrayStr);
  7413. return \$this->call('$operation', \$params, '".$opData['namespace']."', '".(isset($opData['soapAction']) ? $opData['soapAction'] : '')."');
  7414. }
  7415. ";
  7416. unset($paramStr);
  7417. unset($paramCommentStr);
  7418. }
  7419. }
  7420. $evalStr = 'class nusoap_proxy_'.$r.' extends nusoap_client {
  7421. '.$evalStr.'
  7422. }';
  7423. return $evalStr;
  7424. }
  7425. /**
  7426. * dynamically creates proxy class code
  7427. *
  7428. * @return string PHP/NuSOAP code for the proxy class
  7429. * @access public
  7430. */
  7431. function getProxyClassCode() {
  7432. $r = rand();
  7433. return $this->_getProxyClassCode($r);
  7434. }
  7435. /**
  7436. * gets the HTTP body for the current request.
  7437. *
  7438. * @param string $soapmsg The SOAP payload
  7439. * @return string The HTTP body, which includes the SOAP payload
  7440. * @access private
  7441. */
  7442. function getHTTPBody($soapmsg) {
  7443. return $soapmsg;
  7444. }
  7445. /**
  7446. * gets the HTTP content type for the current request.
  7447. *
  7448. * Note: getHTTPBody must be called before this.
  7449. *
  7450. * @return string the HTTP content type for the current request.
  7451. * @access private
  7452. */
  7453. function getHTTPContentType() {
  7454. return 'text/xml';
  7455. }
  7456. /**
  7457. * gets the HTTP content type charset for the current request.
  7458. * returns false for non-text content types.
  7459. *
  7460. * Note: getHTTPBody must be called before this.
  7461. *
  7462. * @return string the HTTP content type charset for the current request.
  7463. * @access private
  7464. */
  7465. function getHTTPContentTypeCharset() {
  7466. return $this->soap_defencoding;
  7467. }
  7468. /*
  7469. * whether or not parser should decode utf8 element content
  7470. *
  7471. * @return always returns true
  7472. * @access public
  7473. */
  7474. function decodeUTF8($bool){
  7475. $this->decode_utf8 = $bool;
  7476. return true;
  7477. }
  7478. /**
  7479. * adds a new Cookie into $this->cookies array
  7480. *
  7481. * @param string $name Cookie Name
  7482. * @param string $value Cookie Value
  7483. * @return boolean if cookie-set was successful returns true, else false
  7484. * @access public
  7485. */
  7486. function setCookie($name, $value) {
  7487. if (strlen($name) == 0) {
  7488. return false;
  7489. }
  7490. $this->cookies[] = array('name' => $name, 'value' => $value);
  7491. return true;
  7492. }
  7493. /**
  7494. * gets all Cookies
  7495. *
  7496. * @return array with all internal cookies
  7497. * @access public
  7498. */
  7499. function getCookies() {
  7500. return $this->cookies;
  7501. }
  7502. /**
  7503. * checks all Cookies and delete those which are expired
  7504. *
  7505. * @return boolean always return true
  7506. * @access private
  7507. */
  7508. function checkCookies() {
  7509. if (sizeof($this->cookies) == 0) {
  7510. return true;
  7511. }
  7512. $this->debug('checkCookie: check ' . sizeof($this->cookies) . ' cookies');
  7513. $curr_cookies = $this->cookies;
  7514. $this->cookies = array();
  7515. foreach ($curr_cookies as $cookie) {
  7516. if (! is_array($cookie)) {
  7517. $this->debug('Remove cookie that is not an array');
  7518. continue;
  7519. }
  7520. if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) {
  7521. if (strtotime($cookie['expires']) > time()) {
  7522. $this->cookies[] = $cookie;
  7523. } else {
  7524. $this->debug('Remove expired cookie ' . $cookie['name']);
  7525. }
  7526. } else {
  7527. $this->cookies[] = $cookie;
  7528. }
  7529. }
  7530. $this->debug('checkCookie: '.sizeof($this->cookies).' cookies left in array');
  7531. return true;
  7532. }
  7533. /**
  7534. * updates the current cookies with a new set
  7535. *
  7536. * @param array $cookies new cookies with which to update current ones
  7537. * @return boolean always return true
  7538. * @access private
  7539. */
  7540. function UpdateCookies($cookies) {
  7541. if (sizeof($this->cookies) == 0) {
  7542. // no existing cookies: take whatever is new
  7543. if (sizeof($cookies) > 0) {
  7544. $this->debug('Setting new cookie(s)');
  7545. $this->cookies = $cookies;
  7546. }
  7547. return true;
  7548. }
  7549. if (sizeof($cookies) == 0) {
  7550. // no new cookies: keep what we've got
  7551. return true;
  7552. }
  7553. // merge
  7554. foreach ($cookies as $newCookie) {
  7555. if (!is_array($newCookie)) {
  7556. continue;
  7557. }
  7558. if ((!isset($newCookie['name'])) || (!isset($newCookie['value']))) {
  7559. continue;
  7560. }
  7561. $newName = $newCookie['name'];
  7562. $found = false;
  7563. for ($i = 0; $i < count($this->cookies); $i++) {
  7564. $cookie = $this->cookies[$i];
  7565. if (!is_array($cookie)) {
  7566. continue;
  7567. }
  7568. if (!isset($cookie['name'])) {
  7569. continue;
  7570. }
  7571. if ($newName != $cookie['name']) {
  7572. continue;
  7573. }
  7574. $newDomain = isset($newCookie['domain']) ? $newCookie['domain'] : 'NODOMAIN';
  7575. $domain = isset($cookie['domain']) ? $cookie['domain'] : 'NODOMAIN';
  7576. if ($newDomain != $domain) {
  7577. continue;
  7578. }
  7579. $newPath = isset($newCookie['path']) ? $newCookie['path'] : 'NOPATH';
  7580. $path = isset($cookie['path']) ? $cookie['path'] : 'NOPATH';
  7581. if ($newPath != $path) {
  7582. continue;
  7583. }
  7584. $this->cookies[$i] = $newCookie;
  7585. $found = true;
  7586. $this->debug('Update cookie ' . $newName . '=' . $newCookie['value']);
  7587. break;
  7588. }
  7589. if (! $found) {
  7590. $this->debug('Add cookie ' . $newName . '=' . $newCookie['value']);
  7591. $this->cookies[] = $newCookie;
  7592. }
  7593. }
  7594. return true;
  7595. }
  7596. }
  7597. if (!extension_loaded('soap')) {
  7598. /**
  7599. * For backwards compatiblity, define soapclient unless the PHP SOAP extension is loaded.
  7600. */
  7601. class soapclient extends nusoap_client {
  7602. }
  7603. }
  7604. ?>