Source for file nusoap.php

Documentation is available at nusoap.php

  1. <?php
  2.  
  3. /*
  4. $Id: fsource_nusoap__nusoap.php.html,v 1.2 2010/04/26 20:25:21 snichol Exp $
  5.  
  6. NuSOAP - Web Services Toolkit for PHP
  7.  
  8. Copyright (c) 2002 NuSphere Corporation
  9.  
  10. This library is free software; you can redistribute it and/or
  11. modify it under the terms of the GNU Lesser General Public
  12. License as published by the Free Software Foundation; either
  13. version 2.1 of the License, or (at your option) any later version.
  14.  
  15. This library is distributed in the hope that it will be useful,
  16. but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. Lesser General Public License for more details.
  19.  
  20. You should have received a copy of the GNU Lesser General Public
  21. License along with this library; if not, write to the Free Software
  22. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  23.  
  24. The NuSOAP project home is:
  25. http://sourceforge.net/projects/nusoap/
  26.  
  27. The primary support for NuSOAP is the Help forum on the project home page.
  28.  
  29. If you have any questions or comments, please email:
  30.  
  31. Dietrich Ayala
  32. dietrich@ganx4.com
  33. http://dietrich.ganx4.com/nusoap
  34.  
  35. NuSphere Corporation
  36. http://www.nusphere.com
  37.  
  38. */
  39.  
  40. /*
  41. * Some of the standards implmented in whole or part by NuSOAP:
  42. *
  43. * SOAP 1.1 (http://www.w3.org/TR/2000/NOTE-SOAP-20000508/)
  44. * WSDL 1.1 (http://www.w3.org/TR/2001/NOTE-wsdl-20010315)
  45. * SOAP Messages With Attachments (http://www.w3.org/TR/SOAP-attachments)
  46. * XML 1.0 (http://www.w3.org/TR/2006/REC-xml-20060816/)
  47. * Namespaces in XML 1.0 (http://www.w3.org/TR/2006/REC-xml-names-20060816/)
  48. * XML Schema 1.0 (http://www.w3.org/TR/xmlschema-0/)
  49. * RFC 2045 Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies
  50. * RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1
  51. * RFC 2617 HTTP Authentication: Basic and Digest Access Authentication
  52. */
  53.  
  54. /* load classes
  55. // necessary classes
  56. require_once('class.soapclient.php');
  57. require_once('class.soap_val.php');
  58. require_once('class.soap_parser.php');
  59. require_once('class.soap_fault.php');
  60.  
  61. // transport classes
  62. require_once('class.soap_transport_http.php');
  63.  
  64. // optional add-on classes
  65. require_once('class.xmlschema.php');
  66. require_once('class.wsdl.php');
  67.  
  68. // server class
  69. require_once('class.soap_server.php');*/
  70.  
  71. // class variable emulation
  72. // cf. http://www.webkreator.com/php/techniques/php-static-class-variables.html
  73.  
  74. $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'] = 9;
  75.  
  76. /**
  77. *
  78. * nusoap_base
  79. *
  80. * @author Dietrich Ayala <dietrich@ganx4.com>
  81. * @author Scott Nichol <snichol@users.sourceforge.net>
  82. * @version $Id: fsource_nusoap__nusoap.php.html,v 1.2 2010/04/26 20:25:21 snichol Exp $
  83. * @access public
  84. */
  85. class nusoap_base {
  86. /**
  87. * Identification for HTTP headers.
  88. *
  89. * @var string
  90. * @access private
  91. */
  92. var $title = 'NuSOAP';
  93. /**
  94. * Version for HTTP headers.
  95. *
  96. * @var string
  97. * @access private
  98. */
  99. var $version = '0.9.5';
  100. /**
  101. * CVS revision for HTTP headers.
  102. *
  103. * @var string
  104. * @access private
  105. */
  106. var $revision = '$Revision: 1.2 $';
  107. /**
  108. * Current error string (manipulated by getError/setError)
  109. *
  110. * @var string
  111. * @access private
  112. */
  113. var $error_str = '';
  114. /**
  115. * Current debug string (manipulated by debug/appendDebug/clearDebug/getDebug/getDebugAsXMLComment)
  116. *
  117. * @var string
  118. * @access private
  119. */
  120. var $debug_str = '';
  121. /**
  122. * toggles automatic encoding of special characters as entities
  123. * (should always be true, I think)
  124. *
  125. * @var boolean
  126. * @access private
  127. */
  128. var $charencoding = true;
  129. /**
  130. * the debug level for this instance
  131. *
  132. * @var integer
  133. * @access private
  134. */
  135. var $debugLevel;
  136.  
  137. /**
  138. * set schema version
  139. *
  140. * @var string
  141. * @access public
  142. */
  143. var $XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema';
  144. /**
  145. * charset encoding for outgoing messages
  146. *
  147. * @var string
  148. * @access public
  149. */
  150. var $soap_defencoding = 'ISO-8859-1';
  151. //var $soap_defencoding = 'UTF-8';
  152.  
  153.  
  154. /**
  155. * namespaces in an array of prefix => uri
  156. *
  157. * this is "seeded" by a set of constants, but it may be altered by code
  158. *
  159. * @var array
  160. * @access public
  161. */
  162. var $namespaces = array(
  163. 'SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/',
  164. 'xsd' => 'http://www.w3.org/2001/XMLSchema',
  165. 'xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
  166. 'SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/'
  167. );
  168.  
  169. /**
  170. * namespaces used in the current context, e.g. during serialization
  171. *
  172. * @var array
  173. * @access private
  174. */
  175. var $usedNamespaces = array();
  176.  
  177. /**
  178. * XML Schema types in an array of uri => (array of xml type => php type)
  179. * is this legacy yet?
  180. * no, this is used by the nusoap_xmlschema class to verify type => namespace mappings.
  181. * @var array
  182. * @access public
  183. */
  184. var $typemap = array(
  185. 'http://www.w3.org/2001/XMLSchema' => array(
  186. 'string'=>'string','boolean'=>'boolean','float'=>'double','double'=>'double','decimal'=>'double',
  187. 'duration'=>'','dateTime'=>'string','time'=>'string','date'=>'string','gYearMonth'=>'',
  188. 'gYear'=>'','gMonthDay'=>'','gDay'=>'','gMonth'=>'','hexBinary'=>'string','base64Binary'=>'string',
  189. // abstract "any" types
  190. 'anyType'=>'string','anySimpleType'=>'string',
  191. // derived datatypes
  192. 'normalizedString'=>'string','token'=>'string','language'=>'','NMTOKEN'=>'','NMTOKENS'=>'','Name'=>'','NCName'=>'','ID'=>'',
  193. 'IDREF'=>'','IDREFS'=>'','ENTITY'=>'','ENTITIES'=>'','integer'=>'integer','nonPositiveInteger'=>'integer',
  194. 'negativeInteger'=>'integer','long'=>'integer','int'=>'integer','short'=>'integer','byte'=>'integer','nonNegativeInteger'=>'integer',
  195. 'unsignedLong'=>'','unsignedInt'=>'','unsignedShort'=>'','unsignedByte'=>'','positiveInteger'=>''),
  196. 'http://www.w3.org/2000/10/XMLSchema' => array(
  197. 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double',
  198. 'float'=>'double','dateTime'=>'string',
  199. 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'),
  200. 'http://www.w3.org/1999/XMLSchema' => array(
  201. 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double',
  202. 'float'=>'double','dateTime'=>'string',
  203. 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'),
  204. 'http://soapinterop.org/xsd' => array('SOAPStruct'=>'struct'),
  205. 'http://schemas.xmlsoap.org/soap/encoding/' => array('base64'=>'string','array'=>'array','Array'=>'array'),
  206. 'http://xml.apache.org/xml-soap' => array('Map')
  207. );
  208.  
  209. /**
  210. * XML entities to convert
  211. *
  212. * @var array
  213. * @access public
  214. * @deprecated
  215. * @see expandEntities
  216. */
  217. var $xmlEntities = array('quot' => '"','amp' => '&',
  218. 'lt' => '<','gt' => '>','apos' => "'");
  219.  
  220. /**
  221. * constructor
  222. *
  223. * @access public
  224. */
  225. function nusoap_base() {
  226. $this->debugLevel = $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'];
  227. }
  228.  
  229. /**
  230. * gets the global debug level, which applies to future instances
  231. *
  232. * @return integer Debug level 0-9, where 0 turns off
  233. * @access public
  234. */
  235. function getGlobalDebugLevel() {
  236. return $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'];
  237. }
  238.  
  239. /**
  240. * sets the global debug level, which applies to future instances
  241. *
  242. * @param int $level Debug level 0-9, where 0 turns off
  243. * @access public
  244. */
  245. function setGlobalDebugLevel($level) {
  246. $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'] = $level;
  247. }
  248.  
  249. /**
  250. * gets the debug level for this instance
  251. *
  252. * @return int Debug level 0-9, where 0 turns off
  253. * @access public
  254. */
  255. function getDebugLevel() {
  256. return $this->debugLevel;
  257. }
  258.  
  259. /**
  260. * sets the debug level for this instance
  261. *
  262. * @param int $level Debug level 0-9, where 0 turns off
  263. * @access public
  264. */
  265. function setDebugLevel($level) {
  266. $this->debugLevel = $level;
  267. }
  268.  
  269. /**
  270. * adds debug data to the instance debug string with formatting
  271. *
  272. * @param string $string debug data
  273. * @access private
  274. */
  275. function debug($string){
  276. if ($this->debugLevel > 0) {
  277. $this->appendDebug($this->getmicrotime().' '.get_class($this).": $string\n");
  278. }
  279. }
  280.  
  281. /**
  282. * adds debug data to the instance debug string without formatting
  283. *
  284. * @param string $string debug data
  285. * @access public
  286. */
  287. function appendDebug($string){
  288. if ($this->debugLevel > 0) {
  289. // it would be nice to use a memory stream here to use
  290. // memory more efficiently
  291. $this->debug_str .= $string;
  292. }
  293. }
  294.  
  295. /**
  296. * clears the current debug data for this instance
  297. *
  298. * @access public
  299. */
  300. function clearDebug() {
  301. // it would be nice to use a memory stream here to use
  302. // memory more efficiently
  303. $this->debug_str = '';
  304. }
  305.  
  306. /**
  307. * gets the current debug data for this instance
  308. *
  309. * @return debug data
  310. * @access public
  311. */
  312. function &getDebug() {
  313. // it would be nice to use a memory stream here to use
  314. // memory more efficiently
  315. return $this->debug_str;
  316. }
  317.  
  318. /**
  319. * gets the current debug data for this instance as an XML comment
  320. * this may change the contents of the debug data
  321. *
  322. * @return debug data as an XML comment
  323. * @access public
  324. */
  325. function &getDebugAsXMLComment() {
  326. // it would be nice to use a memory stream here to use
  327. // memory more efficiently
  328. while (strpos($this->debug_str, '--')) {
  329. $this->debug_str = str_replace('--', '- -', $this->debug_str);
  330. }
  331. $ret = "<!--\n" . $this->debug_str . "\n-->";
  332. return $ret;
  333. }
  334.  
  335. /**
  336. * expands entities, e.g. changes '<' to '&lt;'.
  337. *
  338. * @param string $val The string in which to expand entities.
  339. * @access private
  340. */
  341. function expandEntities($val) {
  342. if ($this->charencoding) {
  343. $val = str_replace('&', '&amp;', $val);
  344. $val = str_replace("'", '&apos;', $val);
  345. $val = str_replace('"', '&quot;', $val);
  346. $val = str_replace('<', '&lt;', $val);
  347. $val = str_replace('>', '&gt;', $val);
  348. }
  349. return $val;
  350. }
  351.  
  352. /**
  353. * returns error string if present
  354. *
  355. * @return mixed error string or false
  356. * @access public
  357. */
  358. function getError(){
  359. if($this->error_str != ''){
  360. return $this->error_str;
  361. }
  362. return false;
  363. }
  364.  
  365. /**
  366. * sets error string
  367. *
  368. * @return boolean $string error string
  369. * @access private
  370. */
  371. function setError($str){
  372. $this->error_str = $str;
  373. }
  374.  
  375. /**
  376. * detect if array is a simple array or a struct (associative array)
  377. *
  378. * @param mixed $val The PHP array
  379. * @return string (arraySimple|arrayStruct)
  380. * @access private
  381. */
  382. function isArraySimpleOrStruct($val) {
  383. $keyList = array_keys($val);
  384. foreach ($keyList as $keyListValue) {
  385. if (!is_int($keyListValue)) {
  386. return 'arrayStruct';
  387. }
  388. }
  389. return 'arraySimple';
  390. }
  391.  
  392. /**
  393. * serializes PHP values in accordance w/ section 5. Type information is
  394. * not serialized if $use == 'literal'.
  395. *
  396. * @param mixed $val The value to serialize
  397. * @param string $name The name (local part) of the XML element
  398. * @param string $type The XML schema type (local part) for the element
  399. * @param string $name_ns The namespace for the name of the XML element
  400. * @param string $type_ns The namespace for the type of the element
  401. * @param array $attributes The attributes to serialize as name=>value pairs
  402. * @param string $use The WSDL "use" (encoded|literal)
  403. * @param boolean $soapval Whether this is called from soapval.
  404. * @return string The serialized element, possibly with child elements
  405. * @access public
  406. */
  407. function serialize_val($val,$name=false,$type=false,$name_ns=false,$type_ns=false,$attributes=false,$use='encoded',$soapval=false) {
  408. $this->debug("in serialize_val: name=$name, type=$type, name_ns=$name_ns, type_ns=$type_ns, use=$use, soapval=$soapval");
  409. $this->appendDebug('value=' . $this->varDump($val));
  410. $this->appendDebug('attributes=' . $this->varDump($attributes));
  411. if (is_object($val) && get_class($val) == 'soapval' && (! $soapval)) {
  412. $this->debug("serialize_val: serialize soapval");
  413. $xml = $val->serialize($use);
  414. $this->appendDebug($val->getDebug());
  415. $val->clearDebug();
  416. $this->debug("serialize_val of soapval returning $xml");
  417. return $xml;
  418. }
  419. // force valid name if necessary
  420. if (is_numeric($name)) {
  421. $name = '__numeric_' . $name;
  422. } elseif (! $name) {
  423. $name = 'noname';
  424. }
  425. // if name has ns, add ns prefix to name
  426. $xmlns = '';
  427. if($name_ns){
  428. $prefix = 'nu'.rand(1000,9999);
  429. $name = $prefix.':'.$name;
  430. $xmlns .= " xmlns:$prefix=\"$name_ns\"";
  431. }
  432. // if type is prefixed, create type prefix
  433. if($type_ns != '' && $type_ns == $this->namespaces['xsd']){
  434. // need to fix this. shouldn't default to xsd if no ns specified
  435. // w/o checking against typemap
  436. $type_prefix = 'xsd';
  437. } elseif($type_ns){
  438. $type_prefix = 'ns'.rand(1000,9999);
  439. $xmlns .= " xmlns:$type_prefix=\"$type_ns\"";
  440. }
  441. // serialize attributes if present
  442. $atts = '';
  443. if($attributes){
  444. foreach($attributes as $k => $v){
  445. $atts .= " $k=\"".$this->expandEntities($v).'"';
  446. }
  447. }
  448. // serialize null value
  449. if (is_null($val)) {
  450. $this->debug("serialize_val: serialize null");
  451. if ($use == 'literal') {
  452. // TODO: depends on minOccurs
  453. $xml = "<$name$xmlns$atts/>";
  454. $this->debug("serialize_val returning $xml");
  455. return $xml;
  456. } else {
  457. if (isset($type) && isset($type_prefix)) {
  458. $type_str = " xsi:type=\"$type_prefix:$type\"";
  459. } else {
  460. $type_str = '';
  461. }
  462. $xml = "<$name$xmlns$type_str$atts xsi:nil=\"true\"/>";
  463. $this->debug("serialize_val returning $xml");
  464. return $xml;
  465. }
  466. }
  467. // serialize if an xsd built-in primitive type
  468. if($type != '' && isset($this->typemap[$this->XMLSchemaVersion][$type])){
  469. $this->debug("serialize_val: serialize xsd built-in primitive type");
  470. if (is_bool($val)) {
  471. if ($type == 'boolean') {
  472. $val = $val ? 'true' : 'false';
  473. } elseif (! $val) {
  474. $val = 0;
  475. }
  476. } else if (is_string($val)) {
  477. $val = $this->expandEntities($val);
  478. }
  479. if ($use == 'literal') {
  480. $xml = "<$name$xmlns$atts>$val</$name>";
  481. $this->debug("serialize_val returning $xml");
  482. return $xml;
  483. } else {
  484. $xml = "<$name$xmlns xsi:type=\"xsd:$type\"$atts>$val</$name>";
  485. $this->debug("serialize_val returning $xml");
  486. return $xml;
  487. }
  488. }
  489. // detect type and serialize
  490. $xml = '';
  491. switch(true) {
  492. case (is_bool($val) || $type == 'boolean'):
  493. $this->debug("serialize_val: serialize boolean");
  494. if ($type == 'boolean') {
  495. $val = $val ? 'true' : 'false';
  496. } elseif (! $val) {
  497. $val = 0;
  498. }
  499. if ($use == 'literal') {
  500. $xml .= "<$name$xmlns$atts>$val</$name>";
  501. } else {
  502. $xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val</$name>";
  503. }
  504. break;
  505. case (is_int($val) || is_long($val) || $type == 'int'):
  506. $this->debug("serialize_val: serialize int");
  507. if ($use == 'literal') {
  508. $xml .= "<$name$xmlns$atts>$val</$name>";
  509. } else {
  510. $xml .= "<$name$xmlns xsi:type=\"xsd:int\"$atts>$val</$name>";
  511. }
  512. break;
  513. case (is_float($val)|| is_double($val) || $type == 'float'):
  514. $this->debug("serialize_val: serialize float");
  515. if ($use == 'literal') {
  516. $xml .= "<$name$xmlns$atts>$val</$name>";
  517. } else {
  518. $xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val</$name>";
  519. }
  520. break;
  521. case (is_string($val) || $type == 'string'):
  522. $this->debug("serialize_val: serialize string");
  523. $val = $this->expandEntities($val);
  524. if ($use == 'literal') {
  525. $xml .= "<$name$xmlns$atts>$val</$name>";
  526. } else {
  527. $xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val</$name>";
  528. }
  529. break;
  530. case is_object($val):
  531. $this->debug("serialize_val: serialize object");
  532. if (get_class($val) == 'soapval') {
  533. $this->debug("serialize_val: serialize soapval object");
  534. $pXml = $val->serialize($use);
  535. $this->appendDebug($val->getDebug());
  536. $val->clearDebug();
  537. } else {
  538. if (! $name) {
  539. $name = get_class($val);
  540. $this->debug("In serialize_val, used class name $name as element name");
  541. } else {
  542. $this->debug("In serialize_val, do not override name $name for element name for class " . get_class($val));
  543. }
  544. foreach(get_object_vars($val) as $k => $v){
  545. $pXml = isset($pXml) ? $pXml.$this->serialize_val($v,$k,false,false,false,false,$use) : $this->serialize_val($v,$k,false,false,false,false,$use);
  546. }
  547. }
  548. if(isset($type) && isset($type_prefix)){
  549. $type_str = " xsi:type=\"$type_prefix:$type\"";
  550. } else {
  551. $type_str = '';
  552. }
  553. if ($use == 'literal') {
  554. $xml .= "<$name$xmlns$atts>$pXml</$name>";
  555. } else {
  556. $xml .= "<$name$xmlns$type_str$atts>$pXml</$name>";
  557. }
  558. break;
  559. break;
  560. case (is_array($val) || $type):
  561. // detect if struct or array
  562. $valueType = $this->isArraySimpleOrStruct($val);
  563. if($valueType=='arraySimple' || preg_match('/^ArrayOf/',$type)){
  564. $this->debug("serialize_val: serialize array");
  565. $i = 0;
  566. if(is_array($val) && count($val)> 0){
  567. foreach($val as $v){
  568. if(is_object($v) && get_class($v) == 'soapval'){
  569. $tt_ns = $v->type_ns;
  570. $tt = $v->type;
  571. } elseif (is_array($v)) {
  572. $tt = $this->isArraySimpleOrStruct($v);
  573. } else {
  574. $tt = gettype($v);
  575. }
  576. $array_types[$tt] = 1;
  577. // TODO: for literal, the name should be $name
  578. $xml .= $this->serialize_val($v,'item',false,false,false,false,$use);
  579. ++$i;
  580. }
  581. if(count($array_types) > 1){
  582. $array_typename = 'xsd:anyType';
  583. } elseif(isset($tt) && isset($this->typemap[$this->XMLSchemaVersion][$tt])) {
  584. if ($tt == 'integer') {
  585. $tt = 'int';
  586. }
  587. $array_typename = 'xsd:'.$tt;
  588. } elseif(isset($tt) && $tt == 'arraySimple'){
  589. $array_typename = 'SOAP-ENC:Array';
  590. } elseif(isset($tt) && $tt == 'arrayStruct'){
  591. $array_typename = 'unnamed_struct_use_soapval';
  592. } else {
  593. // if type is prefixed, create type prefix
  594. if ($tt_ns != '' && $tt_ns == $this->namespaces['xsd']){
  595. $array_typename = 'xsd:' . $tt;
  596. } elseif ($tt_ns) {
  597. $tt_prefix = 'ns' . rand(1000, 9999);
  598. $array_typename = "$tt_prefix:$tt";
  599. $xmlns .= " xmlns:$tt_prefix=\"$tt_ns\"";
  600. } else {
  601. $array_typename = $tt;
  602. }
  603. }
  604. $array_type = $i;
  605. if ($use == 'literal') {
  606. $type_str = '';
  607. } else if (isset($type) && isset($type_prefix)) {
  608. $type_str = " xsi:type=\"$type_prefix:$type\"";
  609. } else {
  610. $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"".$array_typename."[$array_type]\"";
  611. }
  612. // empty array
  613. } else {
  614. if ($use == 'literal') {
  615. $type_str = '';
  616. } else if (isset($type) && isset($type_prefix)) {
  617. $type_str = " xsi:type=\"$type_prefix:$type\"";
  618. } else {
  619. $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"xsd:anyType[0]\"";
  620. }
  621. }
  622. // TODO: for array in literal, there is no wrapper here
  623. $xml = "<$name$xmlns$type_str$atts>".$xml."</$name>";
  624. } else {
  625. // got a struct
  626. $this->debug("serialize_val: serialize struct");
  627. if(isset($type) && isset($type_prefix)){
  628. $type_str = " xsi:type=\"$type_prefix:$type\"";
  629. } else {
  630. $type_str = '';
  631. }
  632. if ($use == 'literal') {
  633. $xml .= "<$name$xmlns$atts>";
  634. } else {
  635. $xml .= "<$name$xmlns$type_str$atts>";
  636. }
  637. foreach($val as $k => $v){
  638. // Apache Map
  639. if ($type == 'Map' && $type_ns == 'http://xml.apache.org/xml-soap') {
  640. $xml .= '<item>';
  641. $xml .= $this->serialize_val($k,'key',false,false,false,false,$use);
  642. $xml .= $this->serialize_val($v,'value',false,false,false,false,$use);
  643. $xml .= '</item>';
  644. } else {
  645. $xml .= $this->serialize_val($v,$k,false,false,false,false,$use);
  646. }
  647. }
  648. $xml .= "</$name>";
  649. }
  650. break;
  651. default:
  652. $this->debug("serialize_val: serialize unknown");
  653. $xml .= 'not detected, got '.gettype($val).' for '.$val;
  654. break;
  655. }
  656. $this->debug("serialize_val returning $xml");
  657. return $xml;
  658. }
  659.  
  660. /**
  661. * serializes a message
  662. *
  663. * @param string $body the XML of the SOAP body
  664. * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers, or associative array
  665. * @param array $namespaces optional the namespaces used in generating the body and headers
  666. * @param string $style optional (rpc|document)
  667. * @param string $use optional (encoded|literal)
  668. * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
  669. * @return string the message
  670. * @access public
  671. */
  672. function serializeEnvelope($body,$headers=false,$namespaces=array(),$style='rpc',$use='encoded',$encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'){
  673. // TODO: add an option to automatically run utf8_encode on $body and $headers
  674. // if $this->soap_defencoding is UTF-8. Not doing this automatically allows
  675. // one to send arbitrary UTF-8 characters, not just characters that map to ISO-8859-1
  676.  
  677. $this->debug("In serializeEnvelope length=" . strlen($body) . " body (max 1000 characters)=" . substr($body, 0, 1000) . " style=$style use=$use encodingStyle=$encodingStyle");
  678. $this->debug("headers:");
  679. $this->appendDebug($this->varDump($headers));
  680. $this->debug("namespaces:");
  681. $this->appendDebug($this->varDump($namespaces));
  682.  
  683. // serialize namespaces
  684. $ns_string = '';
  685. foreach(array_merge($this->namespaces,$namespaces) as $k => $v){
  686. $ns_string .= " xmlns:$k=\"$v\"";
  687. }
  688. if($encodingStyle) {
  689. $ns_string = " SOAP-ENV:encodingStyle=\"$encodingStyle\"$ns_string";
  690. }
  691.  
  692. // serialize headers
  693. if($headers){
  694. if (is_array($headers)) {
  695. $xml = '';
  696. foreach ($headers as $k => $v) {
  697. if (is_object($v) && get_class($v) == 'soapval') {
  698. $xml .= $this->serialize_val($v, false, false, false, false, false, $use);
  699. } else {
  700. $xml .= $this->serialize_val($v, $k, false, false, false, false, $use);
  701. }
  702. }
  703. $headers = $xml;
  704. $this->debug("In serializeEnvelope, serialized array of headers to $headers");
  705. }
  706. $headers = "<SOAP-ENV:Header>".$headers."</SOAP-ENV:Header>";
  707. }
  708. // serialize envelope
  709. return
  710. '<?xml version="1.0" encoding="'.$this->soap_defencoding .'"?'.">".
  711. '<SOAP-ENV:Envelope'.$ns_string.">".
  712. $headers.
  713. "<SOAP-ENV:Body>".
  714. $body.
  715. "</SOAP-ENV:Body>".
  716. "</SOAP-ENV:Envelope>";
  717. }
  718.  
  719. /**
  720. * formats a string to be inserted into an HTML stream
  721. *
  722. * @param string $str The string to format
  723. * @return string The formatted string
  724. * @access public
  725. * @deprecated
  726. */
  727. function formatDump($str){
  728. $str = htmlspecialchars($str);
  729. return nl2br($str);
  730. }
  731.  
  732. /**
  733. * contracts (changes namespace to prefix) a qualified name
  734. *
  735. * @param string $qname qname
  736. * @return string contracted qname
  737. * @access private
  738. */
  739. function contractQname($qname){
  740. // get element namespace
  741. //$this->xdebug("Contract $qname");
  742. if (strrpos($qname, ':')) {
  743. // get unqualified name
  744. $name = substr($qname, strrpos($qname, ':') + 1);
  745. // get ns
  746. $ns = substr($qname, 0, strrpos($qname, ':'));
  747. $p = $this->getPrefixFromNamespace($ns);
  748. if ($p) {
  749. return $p . ':' . $name;
  750. }
  751. return $qname;
  752. } else {
  753. return $qname;
  754. }
  755. }
  756.  
  757. /**
  758. * expands (changes prefix to namespace) a qualified name
  759. *
  760. * @param string $qname qname
  761. * @return string expanded qname
  762. * @access private
  763. */
  764. function expandQname($qname){
  765. // get element prefix
  766. if(strpos($qname,':') && !preg_match('/^http:\/\//',$qname)){
  767. // get unqualified name
  768. $name = substr(strstr($qname,':'),1);
  769. // get ns prefix
  770. $prefix = substr($qname,0,strpos($qname,':'));
  771. if(isset($this->namespaces[$prefix])){
  772. return $this->namespaces[$prefix].':'.$name;
  773. } else {
  774. return $qname;
  775. }
  776. } else {
  777. return $qname;
  778. }
  779. }
  780.  
  781. /**
  782. * returns the local part of a prefixed string
  783. * returns the original string, if not prefixed
  784. *
  785. * @param string $str The prefixed string
  786. * @return string The local part
  787. * @access public
  788. */
  789. function getLocalPart($str){
  790. if($sstr = strrchr($str,':')){
  791. // get unqualified name
  792. return substr( $sstr, 1 );
  793. } else {
  794. return $str;
  795. }
  796. }
  797.  
  798. /**
  799. * returns the prefix part of a prefixed string
  800. * returns false, if not prefixed
  801. *
  802. * @param string $str The prefixed string
  803. * @return mixed The prefix or false if there is no prefix
  804. * @access public
  805. */
  806. function getPrefix($str){
  807. if($pos = strrpos($str,':')){
  808. // get prefix
  809. return substr($str,0,$pos);
  810. }
  811. return false;
  812. }
  813.  
  814. /**
  815. * pass it a prefix, it returns a namespace
  816. *
  817. * @param string $prefix The prefix
  818. * @return mixed The namespace, false if no namespace has the specified prefix
  819. * @access public
  820. */
  821. function getNamespaceFromPrefix($prefix){
  822. if (isset($this->namespaces[$prefix])) {
  823. return $this->namespaces[$prefix];
  824. }
  825. //$this->setError("No namespace registered for prefix '$prefix'");
  826. return false;
  827. }
  828.  
  829. /**
  830. * returns the prefix for a given namespace (or prefix)
  831. * or false if no prefixes registered for the given namespace
  832. *
  833. * @param string $ns The namespace
  834. * @return mixed The prefix, false if the namespace has no prefixes
  835. * @access public
  836. */
  837. function getPrefixFromNamespace($ns) {
  838. foreach ($this->namespaces as $p => $n) {
  839. if ($ns == $n || $ns == $p) {
  840. $this->usedNamespaces[$p] = $n;
  841. return $p;
  842. }
  843. }
  844. return false;
  845. }
  846.  
  847. /**
  848. * returns the time in ODBC canonical form with microseconds
  849. *
  850. * @return string The time in ODBC canonical form with microseconds
  851. * @access public
  852. */
  853. function getmicrotime() {
  854. if (function_exists('gettimeofday')) {
  855. $tod = gettimeofday();
  856. $sec = $tod['sec'];
  857. $usec = $tod['usec'];
  858. } else {
  859. $sec = time();
  860. $usec = 0;
  861. }
  862. return strftime('%Y-%m-%d %H:%M:%S', $sec) . '.' . sprintf('%06d', $usec);
  863. }
  864.  
  865. /**
  866. * Returns a string with the output of var_dump
  867. *
  868. * @param mixed $data The variable to var_dump
  869. * @return string The output of var_dump
  870. * @access public
  871. */
  872. function varDump($data) {
  873. ob_start();
  874. var_dump($data);
  875. $ret_val = ob_get_contents();
  876. ob_end_clean();
  877. return $ret_val;
  878. }
  879.  
  880. /**
  881. * represents the object as a string
  882. *
  883. * @return string
  884. * @access public
  885. */
  886. function __toString() {
  887. return $this->varDump($this);
  888. }
  889. }
  890.  
  891. // XML Schema Datatype Helper Functions
  892. //xsd:dateTime helpers
  893.  
  894.  
  895.  
  896. /**
  897. * convert unix timestamp to ISO 8601 compliant date string
  898. *
  899. * @param int $timestamp Unix time stamp
  900. * @param boolean $utc Whether the time stamp is UTC or local
  901. * @return mixed ISO 8601 date string or false
  902. * @access public
  903. */
  904. function timestamp_to_iso8601($timestamp,$utc=true){
  905. $datestr = date('Y-m-d\TH:i:sO',$timestamp);
  906. $pos = strrpos($datestr, "+");
  907. if ($pos === FALSE) {
  908. $pos = strrpos($datestr, "-");
  909. }
  910. if ($pos !== FALSE) {
  911. if (strlen($datestr) == $pos + 5) {
  912. $datestr = substr($datestr, 0, $pos + 3) . ':' . substr($datestr, -2);
  913. }
  914. }
  915. if($utc){
  916. $pattern = '/'.
  917. '([0-9]{4})-'. // centuries & years CCYY-
  918. '([0-9]{2})-'. // months MM-
  919. '([0-9]{2})'. // days DD
  920. 'T'. // separator T
  921. '([0-9]{2}):'. // hours hh:
  922. '([0-9]{2}):'. // minutes mm:
  923. '([0-9]{2})(\.[0-9]*)?'. // seconds ss.ss...
  924. '(Z|[+\-][0-9]{2}:?[0-9]{2})?'. // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
  925. '/';
  926.  
  927. if(preg_match($pattern,$datestr,$regs)){
  928. return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',$regs[1],$regs[2],$regs[3],$regs[4],$regs[5],$regs[6]);
  929. }
  930. return false;
  931. } else {
  932. return $datestr;
  933. }
  934. }
  935.  
  936. /**
  937. * convert ISO 8601 compliant date string to unix timestamp
  938. *
  939. * @param string $datestr ISO 8601 compliant date string
  940. * @return mixed Unix timestamp (int) or false
  941. * @access public
  942. */
  943. function iso8601_to_timestamp($datestr){
  944. $pattern = '/'.
  945. '([0-9]{4})-'. // centuries & years CCYY-
  946. '([0-9]{2})-'. // months MM-
  947. '([0-9]{2})'. // days DD
  948. 'T'. // separator T
  949. '([0-9]{2}):'. // hours hh:
  950. '([0-9]{2}):'. // minutes mm:
  951. '([0-9]{2})(\.[0-9]+)?'. // seconds ss.ss...
  952. '(Z|[+\-][0-9]{2}:?[0-9]{2})?'. // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
  953. '/';
  954. if(preg_match($pattern,$datestr,$regs)){
  955. // not utc
  956. if($regs[8] != 'Z'){
  957. $op = substr($regs[8],0,1);
  958. $h = substr($regs[8],1,2);
  959. $m = substr($regs[8],strlen($regs[8])-2,2);
  960. if($op == '-'){
  961. $regs[4] = $regs[4] + $h;
  962. $regs[5] = $regs[5] + $m;
  963. } elseif($op == '+'){
  964. $regs[4] = $regs[4] - $h;
  965. $regs[5] = $regs[5] - $m;
  966. }
  967. }
  968. return gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
  969. // return strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z");
  970. } else {
  971. return false;
  972. }
  973. }
  974.  
  975. /**
  976. * sleeps some number of microseconds
  977. *
  978. * @param string $usec the number of microseconds to sleep
  979. * @access public
  980. * @deprecated
  981. */
  982. function usleepWindows($usec)
  983. {
  984. $start = gettimeofday();
  985. do
  986. {
  987. $stop = gettimeofday();
  988. $timePassed = 1000000 * ($stop['sec'] - $start['sec'])
  989. + $stop['usec'] - $start['usec'];
  990. }
  991. while ($timePassed < $usec);
  992. }
  993.  
  994. ?><?php
  995.  
  996.  
  997.  
  998. /**
  999. * Contains information for a SOAP fault.
  1000. * Mainly used for returning faults from deployed functions
  1001. * in a server instance.
  1002. * @author Dietrich Ayala <dietrich@ganx4.com>
  1003. * @version $Id: fsource_nusoap__nusoap.php.html,v 1.2 2010/04/26 20:25:21 snichol Exp $
  1004. * @access public
  1005. */
  1006. class nusoap_fault extends nusoap_base {
  1007. /**
  1008. * The fault code (client|server)
  1009. * @var string
  1010. * @access private
  1011. */
  1012. var $faultcode;
  1013. /**
  1014. * The fault actor
  1015. * @var string
  1016. * @access private
  1017. */
  1018. var $faultactor;
  1019. /**
  1020. * The fault string, a description of the fault
  1021. * @var string
  1022. * @access private
  1023. */
  1024. var $faultstring;
  1025. /**
  1026. * The fault detail, typically a string or array of string
  1027. * @var mixed
  1028. * @access private
  1029. */
  1030. var $faultdetail;
  1031.  
  1032. /**
  1033. * constructor
  1034. *
  1035. * @param string $faultcode (SOAP-ENV:Client | SOAP-ENV:Server)
  1036. * @param string $faultactor only used when msg routed between multiple actors
  1037. * @param string $faultstring human readable error message
  1038. * @param mixed $faultdetail detail, typically a string or array of string
  1039. */
  1040. function nusoap_fault($faultcode,$faultactor='',$faultstring='',$faultdetail=''){
  1041. parent::nusoap_base();
  1042. $this->faultcode = $faultcode;
  1043. $this->faultactor = $faultactor;
  1044. $this->faultstring = $faultstring;
  1045. $this->faultdetail = $faultdetail;
  1046. }
  1047.  
  1048. /**
  1049. * serialize a fault
  1050. *
  1051. * @return string The serialization of the fault instance.
  1052. * @access public
  1053. */
  1054. function serialize(){
  1055. $ns_string = '';
  1056. foreach($this->namespaces as $k => $v){
  1057. $ns_string .= "\n xmlns:$k=\"$v\"";
  1058. }
  1059. $return_msg =
  1060. '<?xml version="1.0" encoding="'.$this->soap_defencoding.'"?>'.
  1061. '<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"'.$ns_string.">\n".
  1062. '<SOAP-ENV:Body>'.
  1063. '<SOAP-ENV:Fault>'.
  1064. $this->serialize_val($this->faultcode, 'faultcode').
  1065. $this->serialize_val($this->faultactor, 'faultactor').
  1066. $this->serialize_val($this->faultstring, 'faultstring').
  1067. $this->serialize_val($this->faultdetail, 'detail').
  1068. '</SOAP-ENV:Fault>'.
  1069. '</SOAP-ENV:Body>'.
  1070. '</SOAP-ENV:Envelope>';
  1071. return $return_msg;
  1072. }
  1073. }
  1074.  
  1075. /**
  1076. * Backward compatibility
  1077. */
  1078. class soap_fault extends nusoap_fault {
  1079. }
  1080.  
  1081. ?><?php
  1082.  
  1083.  
  1084.  
  1085. /**
  1086. * parses an XML Schema, allows access to it's data, other utility methods.
  1087. * imperfect, no validation... yet, but quite functional.
  1088. *
  1089. * @author Dietrich Ayala <dietrich@ganx4.com>
  1090. * @author Scott Nichol <snichol@users.sourceforge.net>
  1091. * @version $Id: fsource_nusoap__nusoap.php.html,v 1.2 2010/04/26 20:25:21 snichol Exp $
  1092. * @access public
  1093. */
  1094. class nusoap_xmlschema extends nusoap_base {
  1095. // files
  1096. var $schema = '';
  1097. var $xml = '';
  1098. // namespaces
  1099. var $enclosingNamespaces;
  1100. // schema info
  1101. var $schemaInfo = array();
  1102. var $schemaTargetNamespace = '';
  1103. // types, elements, attributes defined by the schema
  1104. var $attributes = array();
  1105. var $complexTypes = array();
  1106. var $complexTypeStack = array();
  1107. var $currentComplexType = null;
  1108. var $elements = array();
  1109. var $elementStack = array();
  1110. var $currentElement = null;
  1111. var $simpleTypes = array();
  1112. var $simpleTypeStack = array();
  1113. var $currentSimpleType = null;
  1114. // imports
  1115. var $imports = array();
  1116. // parser vars
  1117. var $parser;
  1118. var $position = 0;
  1119. var $depth = 0;
  1120. var $depth_array = array();
  1121. var $message = array();
  1122. var $defaultNamespace = array();
  1123. /**
  1124. * constructor
  1125. *
  1126. * @param string $schema schema document URI
  1127. * @param string $xml xml document URI
  1128. * @param string $namespaces namespaces defined in enclosing XML
  1129. * @access public
  1130. */
  1131. function nusoap_xmlschema($schema='',$xml='',$namespaces=array()){
  1132. parent::nusoap_base();
  1133. $this->debug('nusoap_xmlschema class instantiated, inside constructor');
  1134. // files
  1135. $this->schema = $schema;
  1136. $this->xml = $xml;
  1137.  
  1138. // namespaces
  1139. $this->enclosingNamespaces = $namespaces;
  1140. $this->namespaces = array_merge($this->namespaces, $namespaces);
  1141.  
  1142. // parse schema file
  1143. if($schema != ''){
  1144. $this->debug('initial schema file: '.$schema);
  1145. $this->parseFile($schema, 'schema');
  1146. }
  1147.  
  1148. // parse xml file
  1149. if($xml != ''){
  1150. $this->debug('initial xml file: '.$xml);
  1151. $this->parseFile($xml, 'xml');
  1152. }
  1153.  
  1154. }
  1155.  
  1156. /**
  1157. * parse an XML file
  1158. *
  1159. * @param string $xml path/URL to XML file
  1160. * @param string $type (schema | xml)
  1161. * @return boolean
  1162. * @access public
  1163. */
  1164. function parseFile($xml,$type){
  1165. // parse xml file
  1166. if($xml != ""){
  1167. $xmlStr = @join("",@file($xml));
  1168. if($xmlStr == ""){
  1169. $msg = 'Error reading XML from '.$xml;
  1170. $this->setError($msg);
  1171. $this->debug($msg);
  1172. return false;
  1173. } else {
  1174. $this->debug("parsing $xml");
  1175. $this->parseString($xmlStr,$type);
  1176. $this->debug("done parsing $xml");
  1177. return true;
  1178. }
  1179. }
  1180. return false;
  1181. }
  1182.  
  1183. /**
  1184. * parse an XML string
  1185. *
  1186. * @param string $xml path or URL
  1187. * @param string $type (schema|xml)
  1188. * @access private
  1189. */
  1190. function parseString($xml,$type){
  1191. // parse xml string
  1192. if($xml != ""){
  1193.  
  1194. // Create an XML parser.
  1195. $this->parser = xml_parser_create();
  1196. // Set the options for parsing the XML data.
  1197. xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
  1198.  
  1199. // Set the object for the parser.
  1200. xml_set_object($this->parser, $this);
  1201.  
  1202. // Set the element handlers for the parser.
  1203. if($type == "schema"){
  1204. xml_set_element_handler($this->parser, 'schemaStartElement','schemaEndElement');
  1205. xml_set_character_data_handler($this->parser,'schemaCharacterData');
  1206. } elseif($type == "xml"){
  1207. xml_set_element_handler($this->parser, 'xmlStartElement','xmlEndElement');
  1208. xml_set_character_data_handler($this->parser,'xmlCharacterData');
  1209. }
  1210.  
  1211. // Parse the XML file.
  1212. if(!xml_parse($this->parser,$xml,true)){
  1213. // Display an error message.
  1214. $errstr = sprintf('XML error parsing XML schema on line %d: %s',
  1215. xml_get_current_line_number($this->parser),
  1216. xml_error_string(xml_get_error_code($this->parser))
  1217. );
  1218. $this->debug($errstr);
  1219. $this->debug("XML payload:\n" . $xml);
  1220. $this->setError($errstr);
  1221. }
  1222. xml_parser_free($this->parser);
  1223. } else{
  1224. $this->debug('no xml passed to parseString()!!');
  1225. $this->setError('no xml passed to parseString()!!');
  1226. }
  1227. }
  1228.  
  1229. /**
  1230. * gets a type name for an unnamed type
  1231. *
  1232. * @param string Element name
  1233. * @return string A type name for an unnamed type
  1234. * @access private
  1235. */
  1236. function CreateTypeName($ename) {
  1237. $scope = '';
  1238. for ($i = 0; $i < count($this->complexTypeStack); $i++) {
  1239. $scope .= $this->complexTypeStack[$i] . '_';
  1240. }
  1241. return $scope . $ename . '_ContainedType';
  1242. }
  1243. /**
  1244. * start-element handler
  1245. *
  1246. * @param string $parser XML parser object
  1247. * @param string $name element name
  1248. * @param string $attrs associative array of attributes
  1249. * @access private
  1250. */
  1251. function schemaStartElement($parser, $name, $attrs) {
  1252. // position in the total number of elements, starting from 0
  1253. $pos = $this->position++;
  1254. $depth = $this->depth++;
  1255. // set self as current value for this depth
  1256. $this->depth_array[$depth] = $pos;
  1257. $this->message[$pos] = array('cdata' => '');
  1258. if ($depth > 0) {
  1259. $this->defaultNamespace[$pos] = $this->defaultNamespace[$this->depth_array[$depth - 1]];
  1260. } else {
  1261. $this->defaultNamespace[$pos] = false;
  1262. }
  1263.  
  1264. // get element prefix
  1265. if($prefix = $this->getPrefix($name)){
  1266. // get unqualified name
  1267. $name = $this->getLocalPart($name);
  1268. } else {
  1269. $prefix = '';
  1270. }
  1271. // loop thru attributes, expanding, and registering namespace declarations
  1272. if(count($attrs) > 0){
  1273. foreach($attrs as $k => $v){
  1274. // if ns declarations, add to class level array of valid namespaces
  1275. if(preg_match('/^xmlns/',$k)){
  1276. //$this->xdebug("$k: $v");
  1277. //$this->xdebug('ns_prefix: '.$this->getPrefix($k));
  1278. if($ns_prefix = substr(strrchr($k,':'),1)){
  1279. //$this->xdebug("Add namespace[$ns_prefix] = $v");
  1280. $this->namespaces[$ns_prefix] = $v;
  1281. } else {
  1282. $this->defaultNamespace[$pos] = $v;
  1283. if (! $this->getPrefixFromNamespace($v)) {
  1284. $this->namespaces['ns'.(count($this->namespaces)+1)] = $v;
  1285. }
  1286. }
  1287. if($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema'){
  1288. $this->XMLSchemaVersion = $v;
  1289. $this->namespaces['xsi'] = $v.'-instance';
  1290. }
  1291. }
  1292. }
  1293. foreach($attrs as $k => $v){
  1294. // expand each attribute
  1295. $k = strpos($k,':') ? $this->expandQname($k) : $k;
  1296. $v = strpos($v,':') ? $this->expandQname($v) : $v;
  1297. $eAttrs[$k] = $v;
  1298. }
  1299. $attrs = $eAttrs;
  1300. } else {
  1301. $attrs = array();
  1302. }
  1303. // find status, register data
  1304. switch($name){
  1305. case 'all': // (optional) compositor content for a complexType
  1306. case 'choice':
  1307. case 'group':
  1308. case 'sequence':
  1309. //$this->xdebug("compositor $name for currentComplexType: $this->currentComplexType and currentElement: $this->currentElement");
  1310. $this->complexTypes[$this->currentComplexType]['compositor'] = $name;
  1311. //if($name == 'all' || $name == 'sequence'){
  1312. // $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
  1313. //}
  1314. break;
  1315. case 'attribute': // complexType attribute
  1316. //$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']);
  1317. $this->xdebug("parsing attribute:");
  1318. $this->appendDebug($this->varDump($attrs));
  1319. if (!isset($attrs['form'])) {
  1320. // TODO: handle globals
  1321. $attrs['form'] = $this->schemaInfo['attributeFormDefault'];
  1322. }
  1323. if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) {
  1324. $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
  1325. if (!strpos($v, ':')) {
  1326. // no namespace in arrayType attribute value...
  1327. if ($this->defaultNamespace[$pos]) {
  1328. // ...so use the default
  1329. $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'] = $this->defaultNamespace[$pos] . ':' . $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
  1330. }
  1331. }
  1332. }
  1333. if(isset($attrs['name'])){
  1334. $this->attributes[$attrs['name']] = $attrs;
  1335. $aname = $attrs['name'];
  1336. } elseif(isset($attrs['ref']) && $attrs['ref'] == 'http://schemas.xmlsoap.org/soap/encoding/:arrayType'){
  1337. if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) {
  1338. $aname = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
  1339. } else {
  1340. $aname = '';
  1341. }
  1342. } elseif(isset($attrs['ref'])){
  1343. $aname = $attrs['ref'];
  1344. $this->attributes[$attrs['ref']] = $attrs;
  1345. }
  1346. if($this->currentComplexType){ // This should *always* be
  1347. $this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs;
  1348. }
  1349. // arrayType attribute
  1350. if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']) || $this->getLocalPart($aname) == 'arrayType'){
  1351. $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
  1352. $prefix = $this->getPrefix($aname);
  1353. if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])){
  1354. $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];
  1355. } else {
  1356. $v = '';
  1357. }
  1358. if(strpos($v,'[,]')){
  1359. $this->complexTypes[$this->currentComplexType]['multidimensional'] = true;
  1360. }
  1361. $v = substr($v,0,strpos($v,'[')); // clip the []
  1362. if(!strpos($v,':') && isset($this->typemap[$this->XMLSchemaVersion][$v])){
  1363. $v = $this->XMLSchemaVersion.':'.$v;
  1364. }
  1365. $this->complexTypes[$this->currentComplexType]['arrayType'] = $v;
  1366. }
  1367. break;
  1368. case 'complexContent': // (optional) content for a complexType
  1369. $this->xdebug("do nothing for element $name");
  1370. break;
  1371. case 'complexType':
  1372. array_push($this->complexTypeStack, $this->currentComplexType);
  1373. if(isset($attrs['name'])){
  1374. // TODO: what is the scope of named complexTypes that appear
  1375. // nested within other c complexTypes?
  1376. $this->xdebug('processing named complexType '.$attrs['name']);
  1377. //$this->currentElement = false;
  1378. $this->currentComplexType = $attrs['name'];
  1379. $this->complexTypes[$this->currentComplexType] = $attrs;
  1380. $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';
  1381. // This is for constructs like
  1382. // <complexType name="ListOfString" base="soap:Array">
  1383. // <sequence>
  1384. // <element name="string" type="xsd:string"
  1385. // minOccurs="0" maxOccurs="unbounded" />
  1386. // </sequence>
  1387. // </complexType>
  1388. if(isset($attrs['base']) && preg_match('/:Array$/',$attrs['base'])){
  1389. $this->xdebug('complexType is unusual array');
  1390. $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
  1391. } else {
  1392. $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
  1393. }
  1394. } else {
  1395. $name = $this->CreateTypeName($this->currentElement);
  1396. $this->xdebug('processing unnamed complexType for element ' . $this->currentElement . ' named ' . $name);
  1397. $this->currentComplexType = $name;
  1398. //$this->currentElement = false;
  1399. $this->complexTypes[$this->currentComplexType] = $attrs;
  1400. $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';
  1401. // This is for constructs like
  1402. // <complexType name="ListOfString" base="soap:Array">
  1403. // <sequence>
  1404. // <element name="string" type="xsd:string"
  1405. // minOccurs="0" maxOccurs="unbounded" />
  1406. // </sequence>
  1407. // </complexType>
  1408. if(isset($attrs['base']) && preg_match('/:Array$/',$attrs['base'])){
  1409. $this->xdebug('complexType is unusual array');
  1410. $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
  1411. } else {
  1412. $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';
  1413. }
  1414. }
  1415. $this->complexTypes[$this->currentComplexType]['simpleContent'] = 'false';
  1416. break;
  1417. case 'element':
  1418. array_push($this->elementStack, $this->currentElement);
  1419. if (!isset($attrs['form'])) {
  1420. if ($this->currentComplexType) {
  1421. $attrs['form'] = $this->schemaInfo['elementFormDefault'];
  1422. } else {
  1423. // global
  1424. $attrs['form'] = 'qualified';
  1425. }
  1426. }
  1427. if(isset($attrs['type'])){
  1428. $this->xdebug("processing typed element ".$attrs['name']." of type ".$attrs['type']);
  1429. if (! $this->getPrefix($attrs['type'])) {
  1430. if ($this->defaultNamespace[$pos]) {
  1431. $attrs['type'] = $this->defaultNamespace[$pos] . ':' . $attrs['type'];
  1432. $this->xdebug('used default namespace to make type ' . $attrs['type']);
  1433. }
  1434. }
  1435. // This is for constructs like
  1436. // <complexType name="ListOfString" base="soap:Array">
  1437. // <sequence>
  1438. // <element name="string" type="xsd:string"
  1439. // minOccurs="0" maxOccurs="unbounded" />
  1440. // </sequence>
  1441. // </complexType>
  1442. if ($this->currentComplexType && $this->complexTypes[$this->currentComplexType]['phpType'] == 'array') {
  1443. $this->xdebug('arrayType for unusual array is ' . $attrs['type']);
  1444. $this->complexTypes[$this->currentComplexType]['arrayType'] = $attrs['type'];
  1445. }
  1446. $this->currentElement = $attrs['name'];
  1447. $ename = $attrs['name'];
  1448. } elseif(isset($attrs['ref'])){
  1449. $this->xdebug("processing element as ref to ".$attrs['ref']);
  1450. $this->currentElement = "ref to ".$attrs['ref'];
  1451. $ename = $this->getLocalPart($attrs['ref']);
  1452. } else {
  1453. $type = $this->CreateTypeName($this->currentComplexType . '_' . $attrs['name']);
  1454. $this->xdebug("processing untyped element " . $attrs['name'] . ' type ' . $type);
  1455. $this->currentElement = $attrs['name'];
  1456. $attrs['type'] = $this->schemaTargetNamespace . ':' . $type;
  1457. $ename = $attrs['name'];
  1458. }
  1459. if (isset($ename) && $this->currentComplexType) {
  1460. $this->xdebug("add element $ename to complexType $this->currentComplexType");
  1461. $this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs;
  1462. } elseif (!isset($attrs['ref'])) {
  1463. $this->xdebug("add element $ename to elements array");
  1464. $this->elements[ $attrs['name'] ] = $attrs;
  1465. $this->elements[ $attrs['name'] ]['typeClass'] = 'element';
  1466. }
  1467. break;
  1468. case 'enumeration': // restriction value list member
  1469. $this->xdebug('enumeration ' . $attrs['value']);
  1470. if ($this->currentSimpleType) {
  1471. $this->simpleTypes[$this->currentSimpleType]['enumeration'][] = $attrs['value'];
  1472. } elseif ($this->currentComplexType) {
  1473. $this->complexTypes[$this->currentComplexType]['enumeration'][] = $attrs['value'];
  1474. }
  1475. break;
  1476. case 'extension': // simpleContent or complexContent type extension
  1477. $this->xdebug('extension ' . $attrs['base']);
  1478. if ($this->currentComplexType) {
  1479. $ns = $this->getPrefix($attrs['base']);
  1480. if ($ns == '') {
  1481. $this->complexTypes[$this->currentComplexType]['extensionBase'] = $this->schemaTargetNamespace . ':' . $attrs['base'];
  1482. } else {
  1483. $this->complexTypes[$this->currentComplexType]['extensionBase'] = $attrs['base'];
  1484. }
  1485. } else {
  1486. $this->xdebug('no current complexType to set extensionBase');
  1487. }
  1488. break;
  1489. case 'import':
  1490. if (isset($attrs['schemaLocation'])) {
  1491. $this->xdebug('import namespace ' . $attrs['namespace'] . ' from ' . $attrs['schemaLocation']);
  1492. $this->imports[$attrs['namespace']][] = array('location' => $attrs['schemaLocation'], 'loaded' => false);
  1493. } else {
  1494. $this->xdebug('import namespace ' . $attrs['namespace']);
  1495. $this->imports[$attrs['namespace']][] = array('location' => '', 'loaded' => true);
  1496. if (! $this->getPrefixFromNamespace($attrs['namespace'])) {
  1497. $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace'];
  1498. }
  1499. }
  1500. break;
  1501. case 'include':
  1502. if (isset($attrs['schemaLocation'])) {
  1503. $this->xdebug('include into namespace ' . $this->schemaTargetNamespace . ' from ' . $attrs['schemaLocation']);
  1504. $this->imports[$this->schemaTargetNamespace][] = array('location' => $attrs['schemaLocation'], 'loaded' => false);
  1505. } else {
  1506. $this->xdebug('ignoring invalid XML Schema construct: include without schemaLocation attribute');
  1507. }
  1508. break;
  1509. case 'list': // simpleType value list
  1510. $this->xdebug("do nothing for element $name");
  1511. break;
  1512. case 'restriction': // simpleType, simpleContent or complexContent value restriction
  1513. $this->xdebug('restriction ' . $attrs['base']);
  1514. if($this->currentSimpleType){
  1515. $this->simpleTypes[$this->currentSimpleType]['type'] = $attrs['base'];
  1516. } elseif($this->currentComplexType){
  1517. $this->complexTypes[$this->currentComplexType]['restrictionBase'] = $attrs['base'];
  1518. if(strstr($attrs['base'],':') == ':Array'){
  1519. $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';
  1520. }
  1521. }
  1522. break;
  1523. case 'schema':
  1524. $this->schemaInfo = $attrs;
  1525. $this->schemaInfo['schemaVersion'] = $this->getNamespaceFromPrefix($prefix);
  1526. if (isset($attrs['targetNamespace'])) {
  1527. $this->schemaTargetNamespace = $attrs['targetNamespace'];
  1528. }
  1529. if (!isset($attrs['elementFormDefault'])) {
  1530. $this->schemaInfo['elementFormDefault'] = 'unqualified';
  1531. }
  1532. if (!isset($attrs['attributeFormDefault'])) {
  1533. $this->schemaInfo['attributeFormDefault'] = 'unqualified';
  1534. }
  1535. break;
  1536. case 'simpleContent': // (optional) content for a complexType
  1537. if ($this->currentComplexType) { // This should *always* be
  1538. $this->complexTypes[$this->currentComplexType]['simpleContent'] = 'true';
  1539. } else {
  1540. $this->xdebug("do nothing for element $name because there is no current complexType");
  1541. }
  1542. break;
  1543. case 'simpleType':
  1544. array_push($this->simpleTypeStack, $this->currentSimpleType);
  1545. if(isset($attrs['name'])){
  1546. $this->xdebug("processing simpleType for name " . $attrs['name']);
  1547. $this->currentSimpleType = $attrs['name'];
  1548. $this->simpleTypes[ $attrs['name'] ] = $attrs;
  1549. $this->simpleTypes[ $attrs['name'] ]['typeClass'] = 'simpleType';
  1550. $this->simpleTypes[ $attrs['name'] ]['phpType'] = 'scalar';
  1551. } else {
  1552. $name = $this->CreateTypeName($this->currentComplexType . '_' . $this->currentElement);
  1553. $this->xdebug('processing unnamed simpleType for element ' . $this->currentElement . ' named ' . $name);
  1554. $this->currentSimpleType = $name;
  1555. //$this->currentElement = false;
  1556. $this->simpleTypes[$this->currentSimpleType] = $attrs;
  1557. $this->simpleTypes[$this->currentSimpleType]['phpType'] = 'scalar';
  1558. }
  1559. break;
  1560. case 'union': // simpleType type list
  1561. $this->xdebug("do nothing for element $name");
  1562. break;
  1563. default:
  1564. $this->xdebug("do not have any logic to process element $name");
  1565. }
  1566. }
  1567.  
  1568. /**
  1569. * end-element handler
  1570. *
  1571. * @param string $parser XML parser object
  1572. * @param string $name element name
  1573. * @access private
  1574. */
  1575. function schemaEndElement($parser, $name) {
  1576. // bring depth down a notch
  1577. $this->depth--;
  1578. // position of current element is equal to the last value left in depth_array for my depth
  1579. if(isset($this->depth_array[$this->depth])){
  1580. $pos = $this->depth_array[$this->depth];
  1581. }
  1582. // get element prefix
  1583. if ($prefix = $this->getPrefix($name)){
  1584. // get unqualified name
  1585. $name = $this->getLocalPart($name);
  1586. } else {
  1587. $prefix = '';
  1588. }
  1589. // move on...
  1590. if($name == 'complexType'){
  1591. $this->xdebug('done processing complexType ' . ($this->currentComplexType ? $this->currentComplexType : '(unknown)'));
  1592. $this->xdebug($this->varDump($this->complexTypes[$this->currentComplexType]));
  1593. $this->currentComplexType = array_pop($this->complexTypeStack);
  1594. //$this->currentElement = false;
  1595. }
  1596. if($name == 'element'){
  1597. $this->xdebug('done processing element ' . ($this->currentElement ? $this->currentElement : '(unknown)'));
  1598. $this->currentElement = array_pop($this->elementStack);
  1599. }
  1600. if($name == 'simpleType'){
  1601. $this->xdebug('done processing simpleType ' . ($this->currentSimpleType ? $this->currentSimpleType : '(unknown)'));
  1602. $this->xdebug($this->varDump($this->simpleTypes[$this->currentSimpleType]));
  1603. $this->currentSimpleType = array_pop($this->simpleTypeStack);
  1604. }
  1605. }
  1606.  
  1607. /**
  1608. * element content handler
  1609. *
  1610. * @param string $parser XML parser object
  1611. * @param string $data element content
  1612. * @access private
  1613. */
  1614. function schemaCharacterData($parser, $data){
  1615. $pos = $this->depth_array[$this->depth - 1];
  1616. $this->message[$pos]['cdata'] .= $data;
  1617. }
  1618.  
  1619. /**
  1620. * serialize the schema
  1621. *
  1622. * @access public
  1623. */
  1624. function serializeSchema(){
  1625.  
  1626. $schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion);
  1627. $xml = '';
  1628. // imports
  1629. if (sizeof($this->imports) > 0) {
  1630. foreach($this->imports as $ns => $list) {
  1631. foreach ($list as $ii) {
  1632. if ($ii['location'] != '') {
  1633. $xml .= " <$schemaPrefix:import location=\"" . $ii['location'] . '" namespace="' . $ns . "\" />\n";
  1634. } else {
  1635. $xml .= " <$schemaPrefix:import namespace=\"" . $ns . "\" />\n";
  1636. }
  1637. }
  1638. }
  1639. }
  1640. // complex types
  1641. foreach($this->complexTypes as $typeName => $attrs){
  1642. $contentStr = '';
  1643. // serialize child elements
  1644. if(isset($attrs['elements']) && (count($attrs['elements']) > 0)){
  1645. foreach($attrs['elements'] as $element => $eParts){
  1646. if(isset($eParts['ref'])){
  1647. $contentStr .= " <$schemaPrefix:element ref=\"$element\"/>\n";
  1648. } else {
  1649. $contentStr .= " <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\"";
  1650. foreach ($eParts as $aName => $aValue) {
  1651. // handle, e.g., abstract, default, form, minOccurs, maxOccurs, nillable
  1652. if ($aName != 'name' && $aName != 'type') {
  1653. $contentStr .= " $aName=\"$aValue\"";
  1654. }
  1655. }
  1656. $contentStr .= "/>\n";
  1657. }
  1658. }
  1659. // compositor wraps elements
  1660. if (isset($attrs['compositor']) && ($attrs['compositor'] != '')) {
  1661. $contentStr = " <$schemaPrefix:$attrs[compositor]>\n".$contentStr." </$schemaPrefix:$attrs[compositor]>\n";
  1662. }
  1663. }
  1664. // attributes
  1665. if(isset($attrs['attrs']) && (count($attrs['attrs']) >= 1)){
  1666. foreach($attrs['attrs'] as $attr => $aParts){
  1667. $contentStr .= " <$schemaPrefix:attribute";
  1668. foreach ($aParts as $a => $v) {
  1669. if ($a == 'ref' || $a == 'type') {
  1670. $contentStr .= " $a=\"".$this->contractQName($v).'"';
  1671. } elseif ($a == 'http://schemas.xmlsoap.org/wsdl/:arrayType') {
  1672. $this->usedNamespaces['wsdl'] = $this->namespaces['wsdl'];
  1673. $contentStr .= ' wsdl:arrayType="'.$this->contractQName($v).'"';
  1674. } else {
  1675. $contentStr .= " $a=\"$v\"";
  1676. }
  1677. }
  1678. $contentStr .= "/>\n";
  1679. }
  1680. }
  1681. // if restriction
  1682. if (isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != ''){
  1683. $contentStr = " <$schemaPrefix:restriction base=\"".$this->contractQName($attrs['restrictionBase'])."\">\n".$contentStr." </$schemaPrefix:restriction>\n";
  1684. // complex or simple content
  1685. if ((isset($attrs['elements']) && count($attrs['elements']) > 0) || (isset($attrs['attrs']) && count($attrs['attrs']) > 0)){
  1686. $contentStr = " <$schemaPrefix:complexContent>\n".$contentStr." </$schemaPrefix:complexContent>\n";
  1687. }
  1688. }
  1689. // finalize complex type
  1690. if($contentStr != ''){
  1691. $contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." </$schemaPrefix:complexType>\n";
  1692. } else {
  1693. $contentStr = " <$schemaPrefix:complexType name=\"$typeName\"/>\n";
  1694. }
  1695. $xml .= $contentStr;
  1696. }
  1697. // simple types
  1698. if(isset($this->simpleTypes) && count($this->simpleTypes) > 0){
  1699. foreach($this->simpleTypes as $typeName => $eParts){
  1700. $xml .= " <$schemaPrefix:simpleType name=\"$typeName\">\n <$schemaPrefix:restriction base=\"".$this->contractQName($eParts['type'])."\">\n";
  1701. if (isset($eParts['enumeration'])) {
  1702. foreach ($eParts['enumeration'] as $e) {
  1703. $xml .= " <$schemaPrefix:enumeration value=\"$e\"/>\n";
  1704. }
  1705. }
  1706. $xml .= " </$schemaPrefix:restriction>\n </$schemaPrefix:simpleType>";
  1707. }
  1708. }
  1709. // elements
  1710. if(isset($this->elements) && count($this->elements) > 0){
  1711. foreach($this->elements as $element => $eParts){
  1712. $xml .= " <$schemaPrefix:element name=\"$element\" type=\"".$this->contractQName($eParts['type'])."\"/>\n";
  1713. }
  1714. }
  1715. // attributes
  1716. if(isset($this->attributes) && count($this->attributes) > 0){
  1717. foreach($this->attributes as $attr => $aParts){
  1718. $xml .= " <$schemaPrefix:attribute name=\"$attr\" type=\"".$this->contractQName($aParts['type'])."\"\n/>";
  1719. }
  1720. }
  1721. // finish 'er up
  1722. $attr = '';
  1723. foreach ($this->schemaInfo as $k => $v) {
  1724. if ($k == 'elementFormDefault' || $k == 'attributeFormDefault') {
  1725. $attr .= " $k=\"$v\"";
  1726. }
  1727. }
  1728. $el = "<$schemaPrefix:schema$attr targetNamespace=\"$this->schemaTargetNamespace\"\n";
  1729. foreach (array_diff($this->usedNamespaces, $this->enclosingNamespaces) as $nsp => $ns) {
  1730. $el .= " xmlns:$nsp=\"$ns\"";
  1731. }
  1732. $xml = $el . ">\n".$xml."</$schemaPrefix:schema>\n";
  1733. return $xml;
  1734. }
  1735.  
  1736. /**
  1737. * adds debug data to the clas level debug string
  1738. *
  1739. * @param string $string debug data
  1740. * @access private
  1741. */
  1742. function xdebug($string){
  1743. $this->debug('<' . $this->schemaTargetNamespace . '> '.$string);
  1744. }
  1745.  
  1746. /**
  1747. * get the PHP type of a user defined type in the schema
  1748. * PHP type is kind of a misnomer since it actually returns 'struct' for assoc. arrays
  1749. * returns false if no type exists, or not w/ the given namespace
  1750. * else returns a string that is either a native php type, or 'struct'
  1751. *
  1752. * @param string $type name of defined type
  1753. * @param string $ns namespace of type
  1754. * @return mixed
  1755. * @access public
  1756. * @deprecated
  1757. */
  1758. function getPHPType($type,$ns){
  1759. if(isset($this->typemap[$ns][$type])){
  1760. //print "found type '$type' and ns $ns in typemap<br>";
  1761. return $this->typemap[$ns][$type];
  1762. } elseif(isset($this->complexTypes[$type])){
  1763. //print "getting type '$type' and ns $ns from complexTypes array<br>";
  1764. return $this->complexTypes[$type]['phpType'];
  1765. }
  1766. return false;
  1767. }
  1768.  
  1769. /**
  1770. * returns an associative array of information about a given type
  1771. * returns false if no type exists by the given name
  1772. *
  1773. * For a complexType typeDef = array(
  1774. * 'restrictionBase' => '',
  1775. * 'phpType' => '',
  1776. * 'compositor' => '(sequence|all)',
  1777. * 'elements' => array(), // refs to elements array
  1778. * 'attrs' => array() // refs to attributes array
  1779. * ... and so on (see addComplexType)
  1780. * )
  1781. *
  1782. * For simpleType or element, the array has different keys.
  1783. *
  1784. * @param string $type
  1785. * @return mixed
  1786. * @access public
  1787. * @see addComplexType
  1788. * @see addSimpleType
  1789. * @see addElement
  1790. */
  1791. function getTypeDef($type){
  1792. //$this->debug("in getTypeDef for type $type");
  1793. if (substr($type, -1) == '^') {
  1794. $is_element = 1;
  1795. $type = substr($type, 0, -1);
  1796. } else {
  1797. $is_element = 0;
  1798. }
  1799.  
  1800. if((! $is_element) && isset($this->complexTypes[$type])){
  1801. $this->xdebug("in getTypeDef, found complexType $type");
  1802. return $this->complexTypes[$type];
  1803. } elseif((! $is_element) && isset($this->simpleTypes[$type])){
  1804. $this->xdebug("in getTypeDef, found simpleType $type");
  1805. if (!isset($this->simpleTypes[$type]['phpType'])) {
  1806. // get info for type to tack onto the simple type
  1807. // TODO: can this ever really apply (i.e. what is a simpleType really?)
  1808. $uqType = substr($this->simpleTypes[$type]['type'], strrpos($this->simpleTypes[$type]['type'], ':') + 1);
  1809. $ns = substr($this->simpleTypes[$type]['type'], 0, strrpos($this->simpleTypes[$type]['type'], ':'));
  1810. $etype = $this->getTypeDef($uqType);
  1811. if ($etype) {
  1812. $this->xdebug("in getTypeDef, found type for simpleType $type:");
  1813. $this->xdebug($this->varDump($etype));
  1814. if (isset($etype['phpType'])) {
  1815. $this->simpleTypes[$type]['phpType'] = $etype['phpType'];
  1816. }
  1817. if (isset($etype['elements'])) {
  1818. $this->simpleTypes[$type]['elements'] = $etype['elements'];
  1819. }
  1820. }
  1821. }
  1822. return $this->simpleTypes[$type];
  1823. } elseif(isset($this->elements[$type])){
  1824. $this->xdebug("in getTypeDef, found element $type");
  1825. if (!isset($this->elements[$type]['phpType'])) {
  1826. // get info for type to tack onto the element
  1827. $uqType = substr($this->elements[$type]['type'], strrpos($this->elements[$type]['type'], ':') + 1);
  1828. $ns = substr($this->elements[$type]['type'], 0, strrpos($this->elements[$type]['type'], ':'));
  1829. $etype = $this->getTypeDef($uqType);
  1830. if ($etype) {
  1831. $this->xdebug("in getTypeDef, found type for element $type:");
  1832. $this->xdebug($this->varDump($etype));
  1833. if (isset($etype['phpType'])) {
  1834. $this->elements[$type]['phpType'] = $etype['phpType'];
  1835. }
  1836. if (isset($etype['elements'])) {
  1837. $this->elements[$type]['elements'] = $etype['elements'];
  1838. }
  1839. if (isset($etype['extensionBase'])) {
  1840. $this->elements[$type]['extensionBase'] = $etype['extensionBase'];
  1841. }
  1842. } elseif ($ns == 'http://www.w3.org/2001/XMLSchema') {
  1843. $this->xdebug("in getTypeDef, element $type is an XSD type");
  1844. $this->elements[$type]['phpType'] = 'scalar';
  1845. }
  1846. }
  1847. return $this->elements[$type];
  1848. } elseif(isset($this->attributes[$type])){
  1849. $this->xdebug("in getTypeDef, found attribute $type");
  1850. return $this->attributes[$type];
  1851. } elseif (preg_match('/_ContainedType$/', $type)) {
  1852. $this->xdebug("in getTypeDef, have an untyped element $type");
  1853. $typeDef['typeClass'] = 'simpleType';
  1854. $typeDef['phpType'] = 'scalar';
  1855. $typeDef['type'] = 'http://www.w3.org/2001/XMLSchema:string';
  1856. return $typeDef;
  1857. }
  1858. $this->xdebug("in getTypeDef, did not find $type");
  1859. return false;
  1860. }
  1861.  
  1862. /**
  1863. * returns a sample serialization of a given type, or false if no type by the given name
  1864. *
  1865. * @param string $type name of type
  1866. * @return mixed
  1867. * @access public
  1868. * @deprecated
  1869. */
  1870. function serializeTypeDef($type){
  1871. //print "in sTD() for type $type<br>";
  1872. if($typeDef = $this->getTypeDef($type)){
  1873. $str .= '<'.$type;
  1874. if(is_array($typeDef['attrs'])){
  1875. foreach($typeDef['attrs'] as $attName => $data){
  1876. $str .= " $attName=\"{type = ".$data['type']."}\"";
  1877. }
  1878. }
  1879. $str .= " xmlns=\"".$this->schema['targetNamespace']."\"";
  1880. if(count($typeDef['elements']) > 0){
  1881. $str .= ">";
  1882. foreach($typeDef['elements'] as $element => $eData){
  1883. $str .= $this->serializeTypeDef($element);
  1884. }
  1885. $str .= "</$type>";
  1886. } elseif($typeDef['typeClass'] == 'element') {
  1887. $str .= "></$type>";
  1888. } else {
  1889. $str .= "/>";
  1890. }
  1891. return $str;
  1892. }
  1893. return false;
  1894. }
  1895.  
  1896. /**
  1897. * returns HTML form elements that allow a user
  1898. * to enter values for creating an instance of the given type.
  1899. *
  1900. * @param string $name name for type instance
  1901. * @param string $type name of type
  1902. * @return string
  1903. * @access public
  1904. * @deprecated
  1905. */
  1906. function typeToForm($name,$type){
  1907. // get typedef
  1908. if($typeDef = $this->getTypeDef($type)){
  1909. // if struct
  1910. if($typeDef['phpType'] == 'struct'){
  1911. $buffer .= '<table>';
  1912. foreach($typeDef['elements'] as $child => $childDef){
  1913. $buffer .= "
  1914. <tr><td align='right'>$childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):</td>
  1915. <td><input type='text' name='parameters[".$name."][$childDef[name]]'></td></tr>";
  1916. }
  1917. $buffer .= '</table>';
  1918. // if array
  1919. } elseif($typeDef['phpType'] == 'array'){
  1920. $buffer .= '<table>';
  1921. for($i=0;$i < 3; $i++){
  1922. $buffer .= "
  1923. <tr><td align='right'>array item (type: $typeDef[arrayType]):</td>
  1924. <td><input type='text' name='parameters[".$name."][]'></td></tr>";
  1925. }
  1926. $buffer .= '</table>';
  1927. // if scalar
  1928. } else {
  1929. $buffer .= "<input type='text' name='parameters[$name]'>";
  1930. }
  1931. } else {
  1932. $buffer .= "<input type='text' name='parameters[$name]'>";
  1933. }
  1934. return $buffer;
  1935. }
  1936. /**
  1937. * adds a complex type to the schema
  1938. *
  1939. * example: array
  1940. *
  1941. * addType(
  1942. * 'ArrayOfstring',
  1943. * 'complexType',
  1944. * 'array',
  1945. * '',
  1946. * 'SOAP-ENC:Array',
  1947. * array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'string[]'),
  1948. * 'xsd:string'
  1949. * );
  1950. *
  1951. * example: PHP associative array ( SOAP Struct )
  1952. *
  1953. * addType(
  1954. * 'SOAPStruct',
  1955. * 'complexType',
  1956. * 'struct',
  1957. * 'all',
  1958. * array('myVar'=> array('name'=>'myVar','type'=>'string')
  1959. * );
  1960. *
  1961. * @param name
  1962. * @param typeClass (complexType|simpleType|attribute)
  1963. * @param phpType: currently supported are array and struct (php assoc array)
  1964. * @param compositor (all|sequence|choice)
  1965. * @param restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
  1966. * @param elements = array ( name = array(name=>'',type=>'') )
  1967. * @param attrs = array(
  1968. * array(
  1969. * 'ref' => "http://schemas.xmlsoap.org/soap/encoding/:arrayType",
  1970. * "http://schemas.xmlsoap.org/wsdl/:arrayType" => "string[]"
  1971. * )
  1972. * )
  1973. * @param arrayType: namespace:name (http://www.w3.org/2001/XMLSchema:string)
  1974. * @access public
  1975. * @see getTypeDef
  1976. */
  1977. function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType=''){
  1978. $this->complexTypes[$name] = array(
  1979. 'name' => $name,
  1980. 'typeClass' => $typeClass,
  1981. 'phpType' => $phpType,
  1982. 'compositor'=> $compositor,
  1983. 'restrictionBase' => $restrictionBase,
  1984. 'elements' => $elements,
  1985. 'attrs' => $attrs,
  1986. 'arrayType' => $arrayType
  1987. );
  1988. $this->xdebug("addComplexType $name:");
  1989. $this->appendDebug($this->varDump($this->complexTypes[$name]));
  1990. }
  1991. /**
  1992. * adds a simple type to the schema
  1993. *
  1994. * @param string $name
  1995. * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
  1996. * @param string $typeClass (should always be simpleType)
  1997. * @param string $phpType (should always be scalar)
  1998. * @param array $enumeration array of values
  1999. * @access public
  2000. * @see nusoap_xmlschema
  2001. * @see getTypeDef
  2002. */
  2003. function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
  2004. $this->simpleTypes[$name] = array(
  2005. 'name' => $name,
  2006. 'typeClass' => $typeClass,
  2007. 'phpType' => $phpType,
  2008. 'type' => $restrictionBase,
  2009. 'enumeration' => $enumeration
  2010. );
  2011. $this->xdebug("addSimpleType $name:");
  2012. $this->appendDebug($this->varDump($this->simpleTypes[$name]));
  2013. }
  2014.  
  2015. /**
  2016. * adds an element to the schema
  2017. *
  2018. * @param array $attrs attributes that must include name and type
  2019. * @see nusoap_xmlschema
  2020. * @access public
  2021. */
  2022. function addElement($attrs) {
  2023. if (! $this->getPrefix($attrs['type'])) {
  2024. $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type'];
  2025. }
  2026. $this->elements[ $attrs['name'] ] = $attrs;
  2027. $this->elements[ $attrs['name'] ]['typeClass'] = 'element';
  2028. $this->xdebug("addElement " . $attrs['name']);
  2029. $this->appendDebug($this->varDump($this->elements[ $attrs['name'] ]));
  2030. }
  2031. }
  2032.  
  2033. /**
  2034. * Backward compatibility
  2035. */
  2036. class XMLSchema extends nusoap_xmlschema {
  2037. }
  2038.  
  2039. ?><?php
  2040.  
  2041.  
  2042.  
  2043. /**
  2044. * For creating serializable abstractions of native PHP types. This class
  2045. * allows element name/namespace, XSD type, and XML attributes to be
  2046. * associated with a value. This is extremely useful when WSDL is not
  2047. * used, but is also useful when WSDL is used with polymorphic types, including
  2048. * xsd:anyType and user-defined types.
  2049. *
  2050. * @author Dietrich Ayala <dietrich@ganx4.com>
  2051. * @version $Id: fsource_nusoap__nusoap.php.html,v 1.2 2010/04/26 20:25:21 snichol Exp $
  2052. * @access public
  2053. */
  2054. class soapval extends nusoap_base {
  2055. /**
  2056. * The XML element name
  2057. *
  2058. * @var string
  2059. * @access private
  2060. */
  2061. var $name;
  2062. /**
  2063. * The XML type name (string or false)
  2064. *
  2065. * @var mixed
  2066. * @access private
  2067. */
  2068. var $type;
  2069. /**
  2070. * The PHP value
  2071. *
  2072. * @var mixed
  2073. * @access private
  2074. */
  2075. var $value;
  2076. /**
  2077. * The XML element namespace (string or false)
  2078. *
  2079. * @var mixed
  2080. * @access private
  2081. */
  2082. var $element_ns;
  2083. /**
  2084. * The XML type namespace (string or false)
  2085. *
  2086. * @var mixed
  2087. * @access private
  2088. */
  2089. var $type_ns;
  2090. /**
  2091. * The XML element attributes (array or false)
  2092. *
  2093. * @var mixed
  2094. * @access private
  2095. */
  2096. var $attributes;
  2097.  
  2098. /**
  2099. * constructor
  2100. *
  2101. * @param string $name optional name
  2102. * @param mixed $type optional type name
  2103. * @param mixed $value optional value
  2104. * @param mixed $element_ns optional namespace of value
  2105. * @param mixed $type_ns optional namespace of type
  2106. * @param mixed $attributes associative array of attributes to add to element serialization
  2107. * @access public
  2108. */
  2109. function soapval($name='soapval',$type=false,$value=-1,$element_ns=false,$type_ns=false,$attributes=false) {
  2110. parent::nusoap_base();
  2111. $this->name = $name;
  2112. $this->type = $type;
  2113. $this->value = $value;
  2114. $this->element_ns = $element_ns;
  2115. $this->type_ns = $type_ns;
  2116. $this->attributes = $attributes;
  2117. }
  2118.  
  2119. /**
  2120. * return serialized value
  2121. *
  2122. * @param string $use The WSDL use value (encoded|literal)
  2123. * @return string XML data
  2124. * @access public
  2125. */
  2126. function serialize($use='encoded') {
  2127. return $this->serialize_val($this->value, $this->name, $this->type, $this->element_ns, $this->type_ns, $this->attributes, $use, true);
  2128. }
  2129.  
  2130. /**
  2131. * decodes a soapval object into a PHP native type
  2132. *
  2133. * @return mixed
  2134. * @access public
  2135. */
  2136. function decode(){
  2137. return $this->value;
  2138. }
  2139. }
  2140.  
  2141.  
  2142.  
  2143. ?><?php
  2144.  
  2145.  
  2146.  
  2147. /**
  2148. * transport class for sending/receiving data via HTTP and HTTPS
  2149. * NOTE: PHP must be compiled with the CURL extension for HTTPS support
  2150. *
  2151. * @author Dietrich Ayala <dietrich@ganx4.com>
  2152. * @author Scott Nichol <snichol@users.sourceforge.net>
  2153. * @version $Id: fsource_nusoap__nusoap.php.html,v 1.2 2010/04/26 20:25:21 snichol Exp $
  2154. * @access public
  2155. */
  2156. class soap_transport_http extends nusoap_base {
  2157.  
  2158. var $url = '';
  2159. var $uri = '';
  2160. var $digest_uri = '';
  2161. var $scheme = '';
  2162. var $host = '';
  2163. var $port = '';
  2164. var $path = '';
  2165. var $request_method = 'POST';
  2166. var $protocol_version = '1.0';
  2167. var $encoding = '';
  2168. var $outgoing_headers = array();
  2169. var $incoming_headers = array();
  2170. var $incoming_cookies = array();
  2171. var $outgoing_payload = '';
  2172. var $incoming_payload = '';
  2173. var $response_status_line; // HTTP response status line
  2174. var $useSOAPAction = true;
  2175. var $persistentConnection = false;
  2176. var $ch = false; // cURL handle
  2177. var $ch_options = array(); // cURL custom options
  2178. var $use_curl = false; // force cURL use
  2179. var $proxy = null; // proxy information (associative array)
  2180. var $username = '';
  2181. var $password = '';
  2182. var $authtype = '';
  2183. var $digestRequest = array();
  2184. var $certRequest = array(); // keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional)
  2185. // cainfofile: certificate authority file, e.g. '$pathToPemFiles/rootca.pem'
  2186. // sslcertfile: SSL certificate file, e.g. '$pathToPemFiles/mycert.pem'
  2187. // sslkeyfile: SSL key file, e.g. '$pathToPemFiles/mykey.pem'
  2188. // passphrase: SSL key password/passphrase
  2189. // certpassword: SSL certificate password
  2190. // verifypeer: default is 1
  2191. // verifyhost: default is 1
  2192.  
  2193.  
  2194. /**
  2195. * constructor
  2196. *
  2197. * @param string $url The URL to which to connect
  2198. * @param array $curl_options User-specified cURL options
  2199. * @param boolean $use_curl Whether to try to force cURL use
  2200. * @access public
  2201. */
  2202. function soap_transport_http($url, $curl_options = NULL, $use_curl = false){
  2203. parent::nusoap_base();
  2204. $this->debug("ctor url=$url use_curl=$use_curl curl_options:");
  2205. $this->appendDebug($this->varDump($curl_options));
  2206. $this->setURL($url);
  2207. if (is_array($curl_options)) {
  2208. $this->ch_options = $curl_options;
  2209. }
  2210. $this->use_curl = $use_curl;
  2211. preg_match('/\$Revisio' . 'n: ([^ ]+)/', $this->revision, $rev);
  2212. $this->setHeader('User-Agent', $this->title.'/'.$this->version.' ('.$rev[1].')');
  2213. }
  2214.  
  2215. /**
  2216. * sets a cURL option
  2217. *
  2218. * @param mixed $option The cURL option (always integer?)
  2219. * @param mixed $value The cURL option value
  2220. * @access private
  2221. */
  2222. function setCurlOption($option, $value) {
  2223. $this->debug("setCurlOption option=$option, value=");
  2224. $this->appendDebug($this->varDump($value));
  2225. curl_setopt($this->ch, $option, $value);
  2226. }
  2227.  
  2228. /**
  2229. * sets an HTTP header
  2230. *
  2231. * @param string $name The name of the header
  2232. * @param string $value The value of the header
  2233. * @access private
  2234. */
  2235. function setHeader($name, $value) {
  2236. $this->outgoing_headers[$name] = $value;
  2237. $this->debug("set header $name: $value");
  2238. }
  2239.  
  2240. /**
  2241. * unsets an HTTP header
  2242. *
  2243. * @param string $name The name of the header
  2244. * @access private
  2245. */
  2246. function unsetHeader($name) {
  2247. if (isset($this->outgoing_headers[$name])) {
  2248. $this->debug("unset header $name");
  2249. unset($this->outgoing_headers[$name]);
  2250. }
  2251. }
  2252.  
  2253. /**
  2254. * sets the URL to which to connect
  2255. *
  2256. * @param string $url The URL to which to connect
  2257. * @access private
  2258. */
  2259. function setURL($url) {
  2260. $this->url = $url;
  2261.  
  2262. $u = parse_url($url);
  2263. foreach($u as $k => $v){
  2264. $this->debug("parsed URL $k = $v");
  2265. $this->$k = $v;
  2266. }
  2267. // add any GET params to path
  2268. if(isset($u['query']) && $u['query'] != ''){
  2269. $this->path .= '?' . $u['query'];
  2270. }
  2271. // set default port
  2272. if(!isset($u['port'])){
  2273. if($u['scheme'] == 'https'){
  2274. $this->port = 443;
  2275. } else {
  2276. $this->port = 80;
  2277. }
  2278. }
  2279. $this->uri = $this->path;
  2280. $this->digest_uri = $this->uri;
  2281. // build headers
  2282. if (!isset($u['port'])) {
  2283. $this->setHeader('Host', $this->host);
  2284. } else {
  2285. $this->setHeader('Host', $this->host.':'.$this->port);
  2286. }
  2287.  
  2288. if (isset($u['user']) && $u['user'] != '') {
  2289. $this->setCredentials(urldecode($u['user']), isset($u['pass']) ? urldecode($u['pass']) : '');
  2290. }
  2291. }
  2292.  
  2293. /**
  2294. * gets the I/O method to use
  2295. *
  2296. * @return string I/O method to use (socket|curl|unknown)
  2297. * @access private
  2298. */
  2299. function io_method() {
  2300. if ($this->use_curl || ($this->scheme == 'https') || ($this->scheme == 'http' && $this->authtype == 'ntlm') || ($this->scheme == 'http' && is_array($this->proxy) && $this->proxy['authtype'] == 'ntlm'))
  2301. return 'curl';
  2302. if (($this->scheme == 'http' || $this->scheme == 'ssl') && $this->authtype != 'ntlm' && (!is_array($this->proxy) || $this->proxy['authtype'] != 'ntlm'))
  2303. return 'socket';
  2304. return 'unknown';
  2305. }
  2306.  
  2307. /**
  2308. * establish an HTTP connection
  2309. *
  2310. * @param integer $timeout set connection timeout in seconds
  2311. * @param integer $response_timeout set response timeout in seconds
  2312. * @return boolean true if connected, false if not
  2313. * @access private
  2314. */
  2315. function connect($connection_timeout=0,$response_timeout=30){
  2316. // For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like
  2317. // "regular" socket.
  2318. // TODO: disabled for now because OpenSSL must be *compiled* in (not just
  2319. // loaded), and until PHP5 stream_get_wrappers is not available.
  2320. // if ($this->scheme == 'https') {
  2321. // if (version_compare(phpversion(), '4.3.0') >= 0) {
  2322. // if (extension_loaded('openssl')) {
  2323. // $this->scheme = 'ssl';
  2324. // $this->debug('Using SSL over OpenSSL');
  2325. // }
  2326. // }
  2327. // }
  2328. $this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port");
  2329. if ($this->io_method() == 'socket') {
  2330. if (!is_array($this->proxy)) {
  2331. $host = $this->host;
  2332. $port = $this->port;
  2333. } else {
  2334. $host = $this->proxy['host'];
  2335. $port = $this->proxy['port'];
  2336. }
  2337.  
  2338. // use persistent connection
  2339. if($this->persistentConnection && isset($this->fp) && is_resource($this->fp)){
  2340. if (!feof($this->fp)) {
  2341. $this->debug('Re-use persistent connection');
  2342. return true;
  2343. }
  2344. fclose($this->fp);
  2345. $this->debug('Closed persistent connection at EOF');
  2346. }
  2347.  
  2348. // munge host if using OpenSSL
  2349. if ($this->scheme == 'ssl') {
  2350. $host = 'ssl://' . $host;
  2351. }
  2352. $this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout);
  2353.  
  2354. // open socket
  2355. if($connection_timeout > 0){
  2356. $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str, $connection_timeout);
  2357. } else {
  2358. $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str);
  2359. }
  2360. // test pointer
  2361. if(!$this->fp) {
  2362. $msg = 'Couldn\'t open socket connection to server ' . $this->url;
  2363. if ($this->errno) {
  2364. $msg .= ', Error ('.$this->errno.'): '.$this->error_str;
  2365. } else {
  2366. $msg .= ' prior to connect(). This is often a problem looking up the host name.';
  2367. }
  2368. $this->debug($msg);
  2369. $this->setError($msg);
  2370. return false;
  2371. }
  2372. // set response timeout
  2373. $this->debug('set response timeout to ' . $response_timeout);
  2374. socket_set_timeout( $this->fp, $response_timeout);
  2375.  
  2376. $this->debug('socket connected');
  2377. return true;
  2378. } else if ($this->io_method() == 'curl') {
  2379. if (!extension_loaded('curl')) {
  2380. // $this->setError('cURL Extension, or OpenSSL extension w/ PHP version >= 4.3 is required for HTTPS');
  2381. $this->setError('The PHP cURL Extension is required for HTTPS or NLTM. You will need to re-build or update your PHP to include cURL or change php.ini to load the PHP cURL extension.');
  2382. return false;
  2383. }
  2384. // Avoid warnings when PHP does not have these options
  2385. if (defined('CURLOPT_CONNECTIONTIMEOUT'))
  2386. $CURLOPT_CONNECTIONTIMEOUT = CURLOPT_CONNECTIONTIMEOUT;
  2387. else
  2388. $CURLOPT_CONNECTIONTIMEOUT = 78;
  2389. if (defined('CURLOPT_HTTPAUTH'))
  2390. $CURLOPT_HTTPAUTH = CURLOPT_HTTPAUTH;
  2391. else
  2392. $CURLOPT_HTTPAUTH = 107;
  2393. if (defined('CURLOPT_PROXYAUTH'))
  2394. $CURLOPT_PROXYAUTH = CURLOPT_PROXYAUTH;
  2395. else
  2396. $CURLOPT_PROXYAUTH = 111;
  2397. if (defined('CURLAUTH_BASIC'))
  2398. $CURLAUTH_BASIC = CURLAUTH_BASIC;
  2399. else
  2400. $CURLAUTH_BASIC = 1;
  2401. if (defined('CURLAUTH_DIGEST'))
  2402. $CURLAUTH_DIGEST = CURLAUTH_DIGEST;
  2403. else
  2404. $CURLAUTH_DIGEST = 2;
  2405. if (defined('CURLAUTH_NTLM'))
  2406. $CURLAUTH_NTLM = CURLAUTH_NTLM;
  2407. else
  2408. $CURLAUTH_NTLM = 8;
  2409.  
  2410. $this->debug('connect using cURL');
  2411. // init CURL
  2412. $this->ch = curl_init();
  2413. // set url
  2414. $hostURL = ($this->port != '') ? "$this->scheme://$this->host:$this->port" : "$this->scheme://$this->host";
  2415. // add path
  2416. $hostURL .= $this->path;
  2417. $this->setCurlOption(CURLOPT_URL, $hostURL);
  2418. // follow location headers (re-directs)
  2419. if (ini_get('safe_mode') || ini_get('open_basedir')) {
  2420. $this->debug('safe_mode or open_basedir set, so do not set CURLOPT_FOLLOWLOCATION');
  2421. $this->debug('safe_mode = ');
  2422. $this->appendDebug($this->varDump(ini_get('safe_mode')));
  2423. $this->debug('open_basedir = ');
  2424. $this->appendDebug($this->varDump(ini_get('open_basedir')));
  2425. } else {
  2426. $this->setCurlOption(CURLOPT_FOLLOWLOCATION, 1);
  2427. }
  2428. // ask for headers in the response output
  2429. $this->setCurlOption(CURLOPT_HEADER, 1);
  2430. // ask for the response output as the return value
  2431. $this->setCurlOption(CURLOPT_RETURNTRANSFER, 1);
  2432. // encode
  2433. // We manage this ourselves through headers and encoding
  2434. // if(function_exists('gzuncompress')){
  2435. // $this->setCurlOption(CURLOPT_ENCODING, 'deflate');
  2436. // }
  2437. // persistent connection
  2438. if ($this->persistentConnection) {
  2439. // I believe the following comment is now bogus, having applied to
  2440. // the code when it used CURLOPT_CUSTOMREQUEST to send the request.
  2441. // The way we send data, we cannot use persistent connections, since
  2442. // there will be some "junk" at the end of our request.
  2443. //$this->setCurlOption(CURL_HTTP_VERSION_1_1, true);
  2444. $this->persistentConnection = false;
  2445. $this->setHeader('Connection', 'close');
  2446. }
  2447. // set timeouts
  2448. if ($connection_timeout != 0) {
  2449. $this->setCurlOption($CURLOPT_CONNECTIONTIMEOUT, $connection_timeout);
  2450. }
  2451. if ($response_timeout != 0) {
  2452. $this->setCurlOption(CURLOPT_TIMEOUT, $response_timeout);
  2453. }
  2454.  
  2455. if ($this->scheme == 'https') {
  2456. $this->debug('set cURL SSL verify options');
  2457. // recent versions of cURL turn on peer/host checking by default,
  2458. // while PHP binaries are not compiled with a default location for the
  2459. // CA cert bundle, so disable peer/host checking.
  2460. //$this->setCurlOption(CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt');
  2461. $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 0);
  2462. $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 0);
  2463. // support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo)
  2464. if ($this->authtype == 'certificate') {
  2465. $this->debug('set cURL certificate options');
  2466. if (isset($this->certRequest['cainfofile'])) {
  2467. $this->setCurlOption(CURLOPT_CAINFO, $this->certRequest['cainfofile']);
  2468. }
  2469. if (isset($this->certRequest['verifypeer'])) {
  2470. $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, $this->certRequest['verifypeer']);
  2471. } else {
  2472. $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 1);
  2473. }
  2474. if (isset($this->certRequest['verifyhost'])) {
  2475. $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, $this->certRequest['verifyhost']);
  2476. } else {
  2477. $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 1);
  2478. }
  2479. if (isset($this->certRequest['sslcertfile'])) {
  2480. $this->setCurlOption(CURLOPT_SSLCERT, $this->certRequest['sslcertfile']);
  2481. }
  2482. if (isset($this->certRequest['sslkeyfile'])) {
  2483. $this->setCurlOption(CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']);
  2484. }
  2485. if (isset($this->certRequest['passphrase'])) {
  2486. $this->setCurlOption(CURLOPT_SSLKEYPASSWD, $this->certRequest['passphrase']);
  2487. }
  2488. if (isset($this->certRequest['certpassword'])) {
  2489. $this->setCurlOption(CURLOPT_SSLCERTPASSWD, $this->certRequest['certpassword']);
  2490. }
  2491. }
  2492. }
  2493. if ($this->authtype && ($this->authtype != 'certificate')) {
  2494. if ($this->username) {
  2495. $this->debug('set cURL username/password');
  2496. $this->setCurlOption(CURLOPT_USERPWD, "$this->username:$this->password");
  2497. }
  2498. if ($this->authtype == 'basic') {
  2499. $this->debug('set cURL for Basic authentication');
  2500. $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_BASIC);
  2501. }
  2502. if ($this->authtype == 'digest') {
  2503. $this->debug('set cURL for digest authentication');
  2504. $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_DIGEST);
  2505. }
  2506. if ($this->authtype == 'ntlm') {
  2507. $this->debug('set cURL for NTLM authentication');
  2508. $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_NTLM);
  2509. }
  2510. }
  2511. if (is_array($this->proxy)) {
  2512. $this->debug('set cURL proxy options');
  2513. if ($this->proxy['port'] != '') {
  2514. $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host'].':'.$this->proxy['port']);
  2515. } else {
  2516. $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host']);
  2517. }
  2518. if ($this->proxy['username'] || $this->proxy['password']) {
  2519. $this->debug('set cURL proxy authentication options');
  2520. $this->setCurlOption(CURLOPT_PROXYUSERPWD, $this->proxy['username'].':'.$this->proxy['password']);
  2521. if ($this->proxy['authtype'] == 'basic') {
  2522. $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_BASIC);
  2523. }
  2524. if ($this->proxy['authtype'] == 'ntlm') {
  2525. $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_NTLM);
  2526. }
  2527. }
  2528. }
  2529. $this->debug('cURL connection set up');
  2530. return true;
  2531. } else {
  2532. $this->setError('Unknown scheme ' . $this->scheme);
  2533. $this->debug('Unknown scheme ' . $this->scheme);
  2534. return false;
  2535. }
  2536. }
  2537.  
  2538. /**
  2539. * sends the SOAP request and gets the SOAP response via HTTP[S]
  2540. *
  2541. * @param string $data message data
  2542. * @param integer $timeout set connection timeout in seconds
  2543. * @param integer $response_timeout set response timeout in seconds
  2544. * @param array $cookies cookies to send
  2545. * @return string data
  2546. * @access public
  2547. */
  2548. function send($data, $timeout=0, $response_timeout=30, $cookies=NULL) {
  2549. $this->debug('entered send() with data of length: '.strlen($data));
  2550.  
  2551. $this->tryagain = true;
  2552. $tries = 0;
  2553. while ($this->tryagain) {
  2554. $this->tryagain = false;
  2555. if ($tries++ < 2) {
  2556. // make connnection
  2557. if (!$this->connect($timeout, $response_timeout)){
  2558. return false;
  2559. }
  2560. // send request
  2561. if (!$this->sendRequest($data, $cookies)){
  2562. return false;
  2563. }
  2564. // get response
  2565. $respdata = $this->getResponse();
  2566. } else {
  2567. $this->setError("Too many tries to get an OK response ($this->response_status_line)");
  2568. }
  2569. }
  2570. $this->debug('end of send()');
  2571. return $respdata;
  2572. }
  2573.  
  2574.  
  2575. /**
  2576. * sends the SOAP request and gets the SOAP response via HTTPS using CURL
  2577. *
  2578. * @param string $data message data
  2579. * @param integer $timeout set connection timeout in seconds
  2580. * @param integer $response_timeout set response timeout in seconds
  2581. * @param array $cookies cookies to send
  2582. * @return string data
  2583. * @access public
  2584. * @deprecated
  2585. */
  2586. function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) {
  2587. return $this->send($data, $timeout, $response_timeout, $cookies);
  2588. }
  2589. /**
  2590. * if authenticating, set user credentials here
  2591. *
  2592. * @param string $username
  2593. * @param string $password
  2594. * @param string $authtype (basic|digest|certificate|ntlm)
  2595. * @param array $digestRequest (keys must be nonce, nc, realm, qop)
  2596. * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
  2597. * @access public
  2598. */
  2599. function setCredentials($username, $password, $authtype = 'basic', $digestRequest = array(), $certRequest = array()) {
  2600. $this->debug("setCredentials username=$username authtype=$authtype digestRequest=");
  2601. $this->appendDebug($this->varDump($digestRequest));
  2602. $this->debug("certRequest=");
  2603. $this->appendDebug($this->varDump($certRequest));
  2604. // cf. RFC 2617
  2605. if ($authtype == 'basic') {
  2606. $this->setHeader('Authorization', 'Basic '.base64_encode(str_replace(':','',$username).':'.$password));
  2607. } elseif ($authtype == 'digest') {
  2608. if (isset($digestRequest['nonce'])) {
  2609. $digestRequest['nc'] = isset($digestRequest['nc']) ? $digestRequest['nc']++ : 1;
  2610. // calculate the Digest hashes (calculate code based on digest implementation found at: http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html)
  2611. // A1 = unq(username-value) ":" unq(realm-value) ":" passwd
  2612. $A1 = $username. ':' . (isset($digestRequest['realm']) ? $digestRequest['realm'] : '') . ':' . $password;
  2613. // H(A1) = MD5(A1)
  2614. $HA1 = md5($A1);
  2615. // A2 = Method ":" digest-uri-value
  2616. $A2 = $this->request_method . ':' . $this->digest_uri;
  2617. // H(A2)
  2618. $HA2 = md5($A2);
  2619. // KD(secret, data) = H(concat(secret, ":", data))
  2620. // if qop == auth:
  2621. // request-digest = <"> < KD ( H(A1), unq(nonce-value)
  2622. // ":" nc-value
  2623. // ":" unq(cnonce-value)
  2624. // ":" unq(qop-value)
  2625. // ":" H(A2)
  2626. // ) <">
  2627. // if qop is missing,
  2628. // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <">
  2629. $unhashedDigest = '';
  2630. $nonce = isset($digestRequest['nonce']) ? $digestRequest['nonce'] : '';
  2631. $cnonce = $nonce;
  2632. if ($digestRequest['qop'] != '') {
  2633. $unhashedDigest = $HA1 . ':' . $nonce . ':' . sprintf("%08d", $digestRequest['nc']) . ':' . $cnonce . ':' . $digestRequest['qop'] . ':' . $HA2;
  2634. } else {
  2635. $unhashedDigest = $HA1 . ':' . $nonce . ':' . $HA2;
  2636. }
  2637. $hashedDigest = md5($unhashedDigest);
  2638. $opaque = '';
  2639. if (isset($digestRequest['opaque'])) {
  2640. $opaque = ', opaque="' . $digestRequest['opaque'] . '"';
  2641. }
  2642.  
  2643. $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 . '"');
  2644. }
  2645. } elseif ($authtype == 'certificate') {
  2646. $this->certRequest = $certRequest;
  2647. $this->debug('Authorization header not set for certificate');
  2648. } elseif ($authtype == 'ntlm') {
  2649. // do nothing
  2650. $this->debug('Authorization header not set for ntlm');
  2651. }
  2652. $this->username = $username;
  2653. $this->password = $password;
  2654. $this->authtype = $authtype;
  2655. $this->digestRequest = $digestRequest;
  2656. }
  2657. /**
  2658. * set the soapaction value
  2659. *
  2660. * @param string $soapaction
  2661. * @access public
  2662. */
  2663. function setSOAPAction($soapaction) {
  2664. $this->setHeader('SOAPAction', '"' . $soapaction . '"');
  2665. }
  2666. /**
  2667. * use http encoding
  2668. *
  2669. * @param string $enc encoding style. supported values: gzip, deflate, or both
  2670. * @access public
  2671. */
  2672. function setEncoding($enc='gzip, deflate') {
  2673. if (function_exists('gzdeflate')) {
  2674. $this->protocol_version = '1.1';
  2675. $this->setHeader('Accept-Encoding', $enc);
  2676. if (!isset($this->outgoing_headers['Connection'])) {
  2677. $this->setHeader('Connection', 'close');
  2678. $this->persistentConnection = false;
  2679. }
  2680. // deprecated as of PHP 5.3.0
  2681. //set_magic_quotes_runtime(0);
  2682. $this->encoding = $enc;
  2683. }
  2684. }
  2685. /**
  2686. * set proxy info here
  2687. *
  2688. * @param string $proxyhost use an empty string to remove proxy
  2689. * @param string $proxyport
  2690. * @param string $proxyusername
  2691. * @param string $proxypassword
  2692. * @param string $proxyauthtype (basic|ntlm)
  2693. * @access public
  2694. */
  2695. function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 'basic') {
  2696. if ($proxyhost) {
  2697. $this->proxy = array(
  2698. 'host' => $proxyhost,
  2699. 'port' => $proxyport,
  2700. 'username' => $proxyusername,
  2701. 'password' => $proxypassword,
  2702. 'authtype' => $proxyauthtype
  2703. );
  2704. if ($proxyusername != '' && $proxypassword != '' && $proxyauthtype = 'basic') {
  2705. $this->setHeader('Proxy-Authorization', ' Basic '.base64_encode($proxyusername.':'.$proxypassword));
  2706. }
  2707. } else {
  2708. $this->debug('remove proxy');
  2709. $proxy = null;
  2710. unsetHeader('Proxy-Authorization');
  2711. }
  2712. }
  2713.  
  2714. /**
  2715. * Test if the given string starts with a header that is to be skipped.
  2716. * Skippable headers result from chunked transfer and proxy requests.
  2717. *
  2718. * @param string $data The string to check.
  2719. * @returns boolean Whether a skippable header was found.
  2720. * @access private
  2721. */
  2722. function isSkippableCurlHeader(&$data) {
  2723. $skipHeaders = array( 'HTTP/1.1 100',
  2724. 'HTTP/1.0 301',
  2725. 'HTTP/1.1 301',
  2726. 'HTTP/1.0 302',
  2727. 'HTTP/1.1 302',
  2728. 'HTTP/1.0 401',
  2729. 'HTTP/1.1 401',
  2730. 'HTTP/1.0 200 Connection established');
  2731. foreach ($skipHeaders as $hd) {
  2732. $prefix = substr($data, 0, strlen($hd));
  2733. if ($prefix == $hd) return true;
  2734. }
  2735.  
  2736. return false;
  2737. }
  2738.  
  2739. /**
  2740. * decode a string that is encoded w/ "chunked' transfer encoding
  2741. * as defined in RFC2068 19.4.6
  2742. *
  2743. * @param string $buffer
  2744. * @param string $lb
  2745. * @returns string
  2746. * @access public
  2747. * @deprecated
  2748. */
  2749. function decodeChunked($buffer, $lb){
  2750. // length := 0
  2751. $length = 0;
  2752. $new = '';
  2753. // read chunk-size, chunk-extension (if any) and CRLF
  2754. // get the position of the linebreak
  2755. $chunkend = strpos($buffer, $lb);
  2756. if ($chunkend == FALSE) {
  2757. $this->debug('no linebreak found in decodeChunked');
  2758. return $new;
  2759. }
  2760. $temp = substr($buffer,0,$chunkend);
  2761. $chunk_size = hexdec( trim($temp) );
  2762. $chunkstart = $chunkend + strlen($lb);
  2763. // while (chunk-size > 0) {
  2764. while ($chunk_size > 0) {
  2765. $this->debug("chunkstart: $chunkstart chunk_size: $chunk_size");
  2766. $chunkend = strpos( $buffer, $lb, $chunkstart + $chunk_size);
  2767. // Just in case we got a broken connection
  2768. if ($chunkend == FALSE) {
  2769. $chunk = substr($buffer,$chunkstart);
  2770. // append chunk-data to entity-body
  2771. $new .= $chunk;
  2772. $length += strlen($chunk);
  2773. break;
  2774. }
  2775. // read chunk-data and CRLF
  2776. $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart);
  2777. // append chunk-data to entity-body
  2778. $new .= $chunk;
  2779. // length := length + chunk-size
  2780. $length += strlen($chunk);
  2781. // read chunk-size and CRLF
  2782. $chunkstart = $chunkend + strlen($lb);
  2783. $chunkend = strpos($buffer, $lb, $chunkstart) + strlen($lb);
  2784. if ($chunkend == FALSE) {
  2785. break; //Just in case we got a broken connection
  2786. }
  2787. $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);
  2788. $chunk_size = hexdec( trim($temp) );
  2789. $chunkstart = $chunkend;
  2790. }
  2791. return $new;
  2792. }
  2793. /**
  2794. * Writes the payload, including HTTP headers, to $this->outgoing_payload.
  2795. *
  2796. * @param string $data HTTP body
  2797. * @param string $cookie_str data for HTTP Cookie header
  2798. * @return void
  2799. * @access private
  2800. */
  2801. function buildPayload($data, $cookie_str = '') {
  2802. // Note: for cURL connections, $this->outgoing_payload is ignored,
  2803. // as is the Content-Length header, but these are still created as
  2804. // debugging guides.
  2805.  
  2806. // add content-length header
  2807. if ($this->request_method != 'GET') {
  2808. $this->setHeader('Content-Length', strlen($data));
  2809. }
  2810.  
  2811. // start building outgoing payload:
  2812. if ($this->proxy) {
  2813. $uri = $this->url;
  2814. } else {
  2815. $uri = $this->uri;
  2816. }
  2817. $req = "$this->request_method $uri HTTP/$this->protocol_version";
  2818. $this->debug("HTTP request: $req");
  2819. $this->outgoing_payload = "$req\r\n";
  2820.  
  2821. // loop thru headers, serializing
  2822. foreach($this->outgoing_headers as $k => $v){
  2823. $hdr = $k.': '.$v;
  2824. $this->debug("HTTP header: $hdr");
  2825. $this->outgoing_payload .= "$hdr\r\n";
  2826. }
  2827.  
  2828. // add any cookies
  2829. if ($cookie_str != '') {
  2830. $hdr = 'Cookie: '.$cookie_str;
  2831. $this->debug("HTTP header: $hdr");
  2832. $this->outgoing_payload .= "$hdr\r\n";
  2833. }
  2834.  
  2835. // header/body separator
  2836. $this->outgoing_payload .= "\r\n";
  2837. // add data
  2838. $this->outgoing_payload .= $data;
  2839. }
  2840.  
  2841. /**
  2842. * sends the SOAP request via HTTP[S]
  2843. *
  2844. * @param string $data message data
  2845. * @param array $cookies cookies to send
  2846. * @return boolean true if OK, false if problem
  2847. * @access private
  2848. */
  2849. function sendRequest($data, $cookies = NULL) {
  2850. // build cookie string
  2851. $cookie_str = $this->getCookiesForRequest($cookies, (($this->scheme == 'ssl') || ($this->scheme == 'https')));
  2852.  
  2853. // build payload
  2854. $this->buildPayload($data, $cookie_str);
  2855.  
  2856. if ($this->io_method() == 'socket') {
  2857. // send payload
  2858. if(!fputs($this->fp, $this->outgoing_payload, strlen($this->outgoing_payload))) {
  2859. $this->setError('couldn\'t write message data to socket');
  2860. $this->debug('couldn\'t write message data to socket');
  2861. return false;
  2862. }
  2863. $this->debug('wrote data to socket, length = ' . strlen($this->outgoing_payload));
  2864. return true;
  2865. } else if ($this->io_method() == 'curl') {
  2866. // set payload
  2867. // cURL does say this should only be the verb, and in fact it
  2868. // turns out that the URI and HTTP version are appended to this, which
  2869. // some servers refuse to work with (so we no longer use this method!)
  2870. //$this->setCurlOption(CURLOPT_CUSTOMREQUEST, $this->outgoing_payload);
  2871. $curl_headers = array();
  2872. foreach($this->outgoing_headers as $k => $v){
  2873. if ($k == 'Connection' || $k == 'Content-Length' || $k == 'Host' || $k == 'Authorization' || $k == 'Proxy-Authorization') {
  2874. $this->debug("Skip cURL header $k: $v");
  2875. } else {
  2876. $curl_headers[] = "$k: $v";
  2877. }
  2878. }
  2879. if ($cookie_str != '') {
  2880. $curl_headers[] = 'Cookie: ' . $cookie_str;
  2881. }
  2882. $this->setCurlOption(CURLOPT_HTTPHEADER, $curl_headers);
  2883. $this->debug('set cURL HTTP headers');
  2884. if ($this->request_method == "POST") {
  2885. $this->setCurlOption(CURLOPT_POST, 1);
  2886. $this->setCurlOption(CURLOPT_POSTFIELDS, $data);
  2887. $this->debug('set cURL POST data');
  2888. } else {
  2889. }
  2890. // insert custom user-set cURL options
  2891. foreach ($this->ch_options as $key => $val) {
  2892. $this->setCurlOption($key, $val);
  2893. }
  2894.  
  2895. $this->debug('set cURL payload');
  2896. return true;
  2897. }
  2898. }
  2899.  
  2900. /**
  2901. * gets the SOAP response via HTTP[S]
  2902. *
  2903. * @return string the response (also sets member variables like incoming_payload)
  2904. * @access private
  2905. */
  2906. function getResponse(){
  2907. $this->incoming_payload = '';
  2908. if ($this->io_method() == 'socket') {
  2909. // loop until headers have been retrieved
  2910. $data = '';
  2911. while (!isset($lb)){
  2912.  
  2913. // We might EOF during header read.
  2914. if(feof($this->fp)) {
  2915. $this->incoming_payload = $data;
  2916. $this->debug('found no headers before EOF after length ' . strlen($data));
  2917. $this->debug("received before EOF:\n" . $data);
  2918. $this->setError('server failed to send headers');
  2919. return false;
  2920. }
  2921.  
  2922. $tmp = fgets($this->fp, 256);
  2923. $tmplen = strlen($tmp);
  2924. $this->debug("read line of $tmplen bytes: " . trim($tmp));
  2925.  
  2926. if ($tmplen == 0) {
  2927. $this->incoming_payload = $data;
  2928. $this->debug('socket read of headers timed out after length ' . strlen($data));
  2929. $this->debug("read before timeout: " . $data);
  2930. $this->setError('socket read of headers timed out');
  2931. return false;
  2932. }
  2933.  
  2934. $data .= $tmp;
  2935. $pos = strpos($data,"\r\n\r\n");
  2936. if($pos > 1){
  2937. $lb = "\r\n";
  2938. } else {
  2939. $pos = strpos($data,"\n\n");
  2940. if($pos > 1){
  2941. $lb = "\n";
  2942. }
  2943. }
  2944. // remove 100 headers
  2945. if (isset($lb) && preg_match('/^HTTP\/1.1 100/',$data)) {
  2946. unset($lb);
  2947. $data = '';
  2948. }//
  2949. }
  2950. // store header data
  2951. $this->incoming_payload .= $data;
  2952. $this->debug('found end of headers after length ' . strlen($data));
  2953. // process headers
  2954. $header_data = trim(substr($data,0,$pos));
  2955. $header_array = explode($lb,$header_data);
  2956. $this->incoming_headers = array();
  2957. $this->incoming_cookies = array();
  2958. foreach($header_array as $header_line){
  2959. $arr = explode(':',$header_line, 2);
  2960. if(count($arr) > 1){
  2961. $header_name = strtolower(trim($arr[0]));
  2962. $this->incoming_headers[$header_name] = trim($arr[1]);
  2963. if ($header_name == 'set-cookie') {
  2964. // TODO: allow multiple cookies from parseCookie
  2965. $cookie = $this->parseCookie(trim($arr[1]));
  2966. if ($cookie) {
  2967. $this->incoming_cookies[] = $cookie;
  2968. $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']);
  2969. } else {
  2970. $this->debug('did not find cookie in ' . trim($arr[1]));
  2971. }
  2972. }
  2973. } else if (isset($header_name)) {
  2974. // append continuation line to previous header
  2975. $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line;
  2976. }
  2977. }
  2978. // loop until msg has been received
  2979. if (isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked') {
  2980. $content_length = 2147483647; // ignore any content-length header
  2981. $chunked = true;
  2982. $this->debug("want to read chunked content");
  2983. } elseif (isset($this->incoming_headers['content-length'])) {
  2984. $content_length = $this->incoming_headers['content-length'];
  2985. $chunked = false;
  2986. $this->debug("want to read content of length $content_length");
  2987. } else {
  2988. $content_length = 2147483647;
  2989. $chunked = false;
  2990. $this->debug("want to read content to EOF");
  2991. }
  2992. $data = '';
  2993. do {
  2994. if ($chunked) {
  2995. $tmp = fgets($this->fp, 256);
  2996. $tmplen = strlen($tmp);
  2997. $this->debug("read chunk line of $tmplen bytes");
  2998. if ($tmplen == 0) {
  2999. $this->incoming_payload = $data;
  3000. $this->debug('socket read of chunk length timed out after length ' . strlen($data));
  3001. $this->debug("read before timeout:\n" . $data);
  3002. $this->setError('socket read of chunk length timed out');
  3003. return false;
  3004. }
  3005. $content_length = hexdec(trim($tmp));
  3006. $this->debug("chunk length $content_length");
  3007. }
  3008. $strlen = 0;
  3009. while (($strlen < $content_length) && (!feof($this->fp))) {
  3010. $readlen = min(8192, $content_length - $strlen);
  3011. $tmp = fread($this->fp, $readlen);
  3012. $tmplen = strlen($tmp);
  3013. $this->debug("read buffer of $tmplen bytes");
  3014. if (($tmplen == 0) && (!feof($this->fp))) {
  3015. $this->incoming_payload = $data;
  3016. $this->debug('socket read of body timed out after length ' . strlen($data));
  3017. $this->debug("read before timeout:\n" . $data);
  3018. $this->setError('socket read of body timed out');
  3019. return false;
  3020. }
  3021. $strlen += $tmplen;
  3022. $data .= $tmp;
  3023. }
  3024. if ($chunked && ($content_length > 0)) {
  3025. $tmp = fgets($this->fp, 256);
  3026. $tmplen = strlen($tmp);
  3027. $this->debug("read chunk terminator of $tmplen bytes");
  3028. if ($tmplen == 0) {
  3029. $this->incoming_payload = $data;
  3030. $this->debug('socket read of chunk terminator timed out after length ' . strlen($data));
  3031. $this->debug("read before timeout:\n" . $data);
  3032. $this->setError('socket read of chunk terminator timed out');
  3033. return false;
  3034. }
  3035. }
  3036. } while ($chunked && ($content_length > 0) && (!feof($this->fp)));
  3037. if (feof($this->fp)) {
  3038. $this->debug('read to EOF');
  3039. }
  3040. $this->debug('read body of length ' . strlen($data));
  3041. $this->incoming_payload .= $data;
  3042. $this->debug('received a total of '.strlen($this->incoming_payload).' bytes of data from server');
  3043. // close filepointer
  3044. if(
  3045. (isset($this->incoming_headers['connection']) && strtolower($this->incoming_headers['connection']) == 'close') ||
  3046. (! $this->persistentConnection) || feof($this->fp)){
  3047. fclose($this->fp);
  3048. $this->fp = false;
  3049. $this->debug('closed socket');
  3050. }
  3051. // connection was closed unexpectedly
  3052. if($this->incoming_payload == ''){
  3053. $this->setError('no response from server');
  3054. return false;
  3055. }
  3056. // decode transfer-encoding
  3057. // if(isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked'){
  3058. // if(!$data = $this->decodeChunked($data, $lb)){
  3059. // $this->setError('Decoding of chunked data failed');
  3060. // return false;
  3061. // }
  3062. //print "<pre>\nde-chunked:\n---------------\n$data\n\n---------------\n</pre>";
  3063. // set decoded payload
  3064. // $this->incoming_payload = $header_data.$lb.$lb.$data;
  3065. // }
  3066. } else if ($this->io_method() == 'curl') {
  3067. // send and receive
  3068. $this->debug('send and receive with cURL');
  3069. $this->incoming_payload = curl_exec($this->ch);
  3070. $data = $this->incoming_payload;
  3071.  
  3072. $cErr = curl_error($this->ch);
  3073. if ($cErr != '') {
  3074. $err = 'cURL ERROR: '.curl_errno($this->ch).': '.$cErr.'<br>';
  3075. // TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE
  3076. foreach(curl_getinfo($this->ch) as $k => $v){
  3077. $err .= "$k: $v<br>";
  3078. }
  3079. $this->debug($err);
  3080. $this->setError($err);
  3081. curl_close($this->ch);
  3082. return false;
  3083. } else {
  3084. //echo '<pre>';
  3085. //var_dump(curl_getinfo($this->ch));
  3086. //echo '</pre>';
  3087. }
  3088. // close curl
  3089. $this->debug('No cURL error, closing cURL');
  3090. curl_close($this->ch);
  3091. // try removing skippable headers
  3092. $savedata = $data;
  3093. while ($this->isSkippableCurlHeader($data)) {
  3094. $this->debug("Found HTTP header to skip");
  3095. if ($pos = strpos($data,"\r\n\r\n")) {
  3096. $data = ltrim(substr($data,$pos));
  3097. } elseif($pos = strpos($data,"\n\n") ) {
  3098. $data = ltrim(substr($data,$pos));
  3099. }
  3100. }
  3101.  
  3102. if ($data == '') {
  3103. // have nothing left; just remove 100 header(s)
  3104. $data = $savedata;
  3105. while (preg_match('/^HTTP\/1.1 100/',$data)) {
  3106. if ($pos = strpos($data,"\r\n\r\n")) {
  3107. $data = ltrim(substr($data,$pos));
  3108. } elseif($pos = strpos($data,"\n\n") ) {
  3109. $data = ltrim(substr($data,$pos));
  3110. }
  3111. }
  3112. }
  3113. // separate content from HTTP headers
  3114. if ($pos = strpos($data,"\r\n\r\n")) {
  3115. $lb = "\r\n";
  3116. } elseif( $pos = strpos($data,"\n\n")) {
  3117. $lb = "\n";
  3118. } else {
  3119. $this->debug('no proper separation of headers and document');
  3120. $this->setError('no proper separation of headers and document');
  3121. return false;
  3122. }
  3123. $header_data = trim(substr($data,0,$pos));
  3124. $header_array = explode($lb,$header_data);
  3125. $data = ltrim(substr($data,$pos));
  3126. $this->debug('found proper separation of headers and document');
  3127. $this->debug('cleaned data, stringlen: '.strlen($data));
  3128. // clean headers
  3129. foreach ($header_array as $header_line) {
  3130. $arr = explode(':',$header_line,2);
  3131. if(count($arr) > 1){
  3132. $header_name = strtolower(trim($arr[0]));
  3133. $this->incoming_headers[$header_name] = trim($arr[1]);
  3134. if ($header_name == 'set-cookie') {
  3135. // TODO: allow multiple cookies from parseCookie
  3136. $cookie = $this->parseCookie(trim($arr[1]));
  3137. if ($cookie) {
  3138. $this->incoming_cookies[] = $cookie;
  3139. $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']);
  3140. } else {
  3141. $this->debug('did not find cookie in ' . trim($arr[1]));
  3142. }
  3143. }
  3144. } else if (isset($header_name)) {
  3145. // append continuation line to previous header
  3146. $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line;
  3147. }
  3148. }
  3149. }
  3150.  
  3151. $this->response_status_line = $header_array[0];
  3152. $arr = explode(' ', $this->response_status_line, 3);
  3153. $http_version = $arr[0];
  3154. $http_status = intval($arr[1]);
  3155. $http_reason = count($arr) > 2 ? $arr[2] : '';
  3156.  
  3157. // see if we need to resend the request with http digest authentication
  3158. if (isset($this->incoming_headers['location']) && ($http_status == 301 || $http_status == 302)) {
  3159. $this->debug("Got $http_status $http_reason with Location: " . $this->incoming_headers['location']);
  3160. $this->setURL($this->incoming_headers['location']);
  3161. $this->tryagain = true;
  3162. return false;
  3163. }
  3164.  
  3165. // see if we need to resend the request with http digest authentication
  3166. if (isset($this->incoming_headers['www-authenticate']) && $http_status == 401) {
  3167. $this->debug("Got 401 $http_reason with WWW-Authenticate: " . $this->incoming_headers['www-authenticate']);
  3168. if (strstr($this->incoming_headers['www-authenticate'], "Digest ")) {
  3169. $this->debug('Server wants digest authentication');
  3170. // remove "Digest " from our elements
  3171. $digestString = str_replace('Digest ', '', $this->incoming_headers['www-authenticate']);
  3172. // parse elements into array
  3173. $digestElements = explode(',', $digestString);
  3174. foreach ($digestElements as $val) {
  3175. $tempElement = explode('=', trim($val), 2);
  3176. $digestRequest[$tempElement[0]] = str_replace("\"", '', $tempElement[1]);
  3177. }
  3178.  
  3179. // should have (at least) qop, realm, nonce
  3180. if (isset($digestRequest['nonce'])) {
  3181. $this->setCredentials($this->username, $this->password, 'digest', $digestRequest);
  3182. $this->tryagain = true;
  3183. return false;
  3184. }
  3185. }
  3186. $this->debug('HTTP authentication failed');
  3187. $this->setError('HTTP authentication failed');
  3188. return false;
  3189. }
  3190. if (
  3191. ($http_status >= 300 && $http_status <= 307) ||
  3192. ($http_status >= 400 && $http_status <= 417) ||
  3193. ($http_status >= 501 && $http_status <= 505)
  3194. ) {
  3195. $this->setError("Unsupported HTTP response status $http_status $http_reason (soapclient->response has contents of the response)");
  3196. return false;
  3197. }
  3198.  
  3199. // decode content-encoding
  3200. if(isset($this->incoming_headers['content-encoding']) && $this->incoming_headers['content-encoding'] != ''){
  3201. if(strtolower($this->incoming_headers['content-encoding']) == 'deflate' || strtolower($this->incoming_headers['content-encoding']) == 'gzip'){
  3202. // if decoding works, use it. else assume data wasn't gzencoded
  3203. if(function_exists('gzinflate')){
  3204. //$timer->setMarker('starting decoding of gzip/deflated content');
  3205. // IIS 5 requires gzinflate instead of gzuncompress (similar to IE 5 and gzdeflate v. gzcompress)
  3206. // this means there are no Zlib headers, although there should be
  3207. $this->debug('The gzinflate function exists');
  3208. $datalen = strlen($data);
  3209. if ($this->incoming_headers['content-encoding'] == 'deflate') {
  3210. if ($degzdata = @gzinflate($data)) {
  3211. $data = $degzdata;
  3212. $this->debug('The payload has been inflated to ' . strlen($data) . ' bytes');
  3213. if (strlen($data) < $datalen) {
  3214. // test for the case that the payload has been compressed twice
  3215. $this->debug('The inflated payload is smaller than the gzipped one; try again');
  3216. if ($degzdata = @gzinflate($data)) {
  3217. $data = $degzdata;
  3218. $this->debug('The payload has been inflated again to ' . strlen($data) . ' bytes');
  3219. }
  3220. }
  3221. } else {
  3222. $this->debug('Error using gzinflate to inflate the payload');
  3223. $this->setError('Error using gzinflate to inflate the payload');
  3224. }
  3225. } elseif ($this->incoming_headers['content-encoding'] == 'gzip') {
  3226. if ($degzdata = @gzinflate(substr($data, 10))) { // do our best
  3227. $data = $degzdata;
  3228. $this->debug('The payload has been un-gzipped to ' . strlen($data) . ' bytes');
  3229. if (strlen($data) < $datalen) {
  3230. // test for the case that the payload has been compressed twice
  3231. $this->debug('The un-gzipped payload is smaller than the gzipped one; try again');
  3232. if ($degzdata = @gzinflate(substr($data, 10))) {
  3233. $data = $degzdata;
  3234. $this->debug('The payload has been un-gzipped again to ' . strlen($data) . ' bytes');
  3235. }
  3236. }
  3237. } else {
  3238. $this->debug('Error using gzinflate to un-gzip the payload');
  3239. $this->setError('Error using gzinflate to un-gzip the payload');
  3240. }
  3241. }
  3242. //$timer->setMarker('finished decoding of gzip/deflated content');
  3243. //print "<xmp>\nde-inflated:\n---------------\n$data\n-------------\n</xmp>";
  3244. // set decoded payload
  3245. $this->incoming_payload = $header_data.$lb.$lb.$data;
  3246. } else {
  3247. $this->debug('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.');
  3248. $this->setError('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.');
  3249. }
  3250. } else {
  3251. $this->debug('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']);
  3252. $this->setError('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']);
  3253. }
  3254. } else {
  3255. $this->debug('No Content-Encoding header');
  3256. }
  3257. if(strlen($data) == 0){
  3258. $this->debug('no data after headers!');
  3259. $this->setError('no data present after HTTP headers');
  3260. return false;
  3261. }
  3262. return $data;
  3263. }
  3264.  
  3265. /**
  3266. * sets the content-type for the SOAP message to be sent
  3267. *
  3268. * @param string $type the content type, MIME style
  3269. * @param mixed $charset character set used for encoding (or false)
  3270. * @access public
  3271. */
  3272. function setContentType($type, $charset = false) {
  3273. $this->setHeader('Content-Type', $type . ($charset ? '; charset=' . $charset : ''));
  3274. }
  3275.  
  3276. /**
  3277. * specifies that an HTTP persistent connection should be used
  3278. *
  3279. * @return boolean whether the request was honored by this method.
  3280. * @access public
  3281. */
  3282. function usePersistentConnection(){
  3283. if (isset($this->outgoing_headers['Accept-Encoding'])) {
  3284. return false;
  3285. }
  3286. $this->protocol_version = '1.1';
  3287. $this->persistentConnection = true;
  3288. $this->setHeader('Connection', 'Keep-Alive');
  3289. return true;
  3290. }
  3291.  
  3292. /**
  3293. * parse an incoming Cookie into it's parts
  3294. *
  3295. * @param string $cookie_str content of cookie
  3296. * @return array with data of that cookie
  3297. * @access private
  3298. */
  3299. /*
  3300. * TODO: allow a Set-Cookie string to be parsed into multiple cookies
  3301. */
  3302. function parseCookie($cookie_str) {
  3303. $cookie_str = str_replace('; ', ';', $cookie_str) . ';';
  3304. $data = preg_split('/;/', $cookie_str);
  3305. $value_str = $data[0];
  3306.  
  3307. $cookie_param = 'domain=';
  3308. $start = strpos($cookie_str, $cookie_param);
  3309. if ($start > 0) {
  3310. $domain = substr($cookie_str, $start + strlen($cookie_param));
  3311. $domain = substr($domain, 0, strpos($domain, ';'));
  3312. } else {
  3313. $domain = '';
  3314. }
  3315.  
  3316. $cookie_param = 'expires=';
  3317. $start = strpos($cookie_str, $cookie_param);
  3318. if ($start > 0) {
  3319. $expires = substr($cookie_str, $start + strlen($cookie_param));
  3320. $expires = substr($expires, 0, strpos($expires, ';'));
  3321. } else {
  3322. $expires = '';
  3323. }
  3324.  
  3325. $cookie_param = 'path=';
  3326. $start = strpos($cookie_str, $cookie_param);
  3327. if ( $start > 0 ) {
  3328. $path = substr($cookie_str, $start + strlen($cookie_param));
  3329. $path = substr($path, 0, strpos($path, ';'));
  3330. } else {
  3331. $path = '/';
  3332. }
  3333. $cookie_param = ';secure;';
  3334. if (strpos($cookie_str, $cookie_param) !== FALSE) {
  3335. $secure = true;
  3336. } else {
  3337. $secure = false;
  3338. }
  3339.  
  3340. $sep_pos = strpos($value_str, '=');
  3341.  
  3342. if ($sep_pos) {
  3343. $name = substr($value_str, 0, $sep_pos);
  3344. $value = substr($value_str, $sep_pos + 1);
  3345. $cookie= array( 'name' => $name,
  3346. 'value' => $value,
  3347. 'domain' => $domain,
  3348. 'path' => $path,
  3349. 'expires' => $expires,
  3350. 'secure' => $secure
  3351. );
  3352. return $cookie;
  3353. }
  3354. return false;
  3355. }
  3356. /**
  3357. * sort out cookies for the current request
  3358. *
  3359. * @param array $cookies array with all cookies
  3360. * @param boolean $secure is the send-content secure or not?
  3361. * @return string for Cookie-HTTP-Header
  3362. * @access private
  3363. */
  3364. function getCookiesForRequest($cookies, $secure=false) {
  3365. $cookie_str = '';
  3366. if ((! is_null($cookies)) && (is_array($cookies))) {
  3367. foreach ($cookies as $cookie) {
  3368. if (! is_array($cookie)) {
  3369. continue;
  3370. }
  3371. $this->debug("check cookie for validity: ".$cookie['name'].'='.$cookie['value']);
  3372. if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) {
  3373. if (strtotime($cookie['expires']) <= time()) {
  3374. $this->debug('cookie has expired');
  3375. continue;
  3376. }
  3377. }
  3378. if ((isset($cookie['domain'])) && (! empty($cookie['domain']))) {
  3379. $domain = preg_quote($cookie['domain']);
  3380. if (! preg_match("'.*$domain$'i", $this->host)) {
  3381. $this->debug('cookie has different domain');
  3382. continue;
  3383. }
  3384. }
  3385. if ((isset($cookie['path'])) && (! empty($cookie['path']))) {
  3386. $path = preg_quote($cookie['path']);
  3387. if (! preg_match("'^$path.*'i", $this->path)) {
  3388. $this->debug('cookie is for a different path');
  3389. continue;
  3390. }
  3391. }
  3392. if ((! $secure) && (isset($cookie['secure'])) && ($cookie['secure'])) {
  3393. $this->debug('cookie is secure, transport is not');
  3394. continue;
  3395. }
  3396. $cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; ';
  3397. $this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']);
  3398. }
  3399. }
  3400. return $cookie_str;
  3401. }
  3402. }
  3403.  
  3404. ?><?php
  3405.  
  3406.  
  3407.  
  3408. /**
  3409. *
  3410. * nusoap_server allows the user to create a SOAP server
  3411. * that is capable of receiving messages and returning responses
  3412. *
  3413. * @author Dietrich Ayala <dietrich@ganx4.com>
  3414. * @author Scott Nichol <snichol@users.sourceforge.net>
  3415. * @version $Id: fsource_nusoap__nusoap.php.html,v 1.2 2010/04/26 20:25:21 snichol Exp $
  3416. * @access public
  3417. */
  3418. class nusoap_server extends nusoap_base {
  3419. /**
  3420. * HTTP headers of request
  3421. * @var array
  3422. * @access private
  3423. */
  3424. var $headers = array();
  3425. /**
  3426. * HTTP request
  3427. * @var string
  3428. * @access private
  3429. */
  3430. var $request = '';
  3431. /**
  3432. * SOAP headers from request (incomplete namespace resolution; special characters not escaped) (text)
  3433. * @var string
  3434. * @access public
  3435. */
  3436. var $requestHeaders = '';
  3437. /**
  3438. * SOAP Headers from request (parsed)
  3439. * @var mixed
  3440. * @access public
  3441. */
  3442. var $requestHeader = NULL;
  3443. /**
  3444. * SOAP body request portion (incomplete namespace resolution; special characters not escaped) (text)
  3445. * @var string
  3446. * @access public
  3447. */
  3448. var $document = '';
  3449. /**
  3450. * SOAP payload for request (text)
  3451. * @var string
  3452. * @access public
  3453. */
  3454. var $requestSOAP = '';
  3455. /**
  3456. * requested method namespace URI
  3457. * @var string
  3458. * @access private
  3459. */
  3460. var $methodURI = '';
  3461. /**
  3462. * name of method requested
  3463. * @var string
  3464. * @access private
  3465. */
  3466. var $methodname = '';
  3467. /**
  3468. * method parameters from request
  3469. * @var array
  3470. * @access private
  3471. */
  3472. var $methodparams = array();
  3473. /**
  3474. * SOAP Action from request
  3475. * @var string
  3476. * @access private
  3477. */
  3478. var $SOAPAction = '';
  3479. /**
  3480. * character set encoding of incoming (request) messages
  3481. * @var string
  3482. * @access public
  3483. */
  3484. var $xml_encoding = '';
  3485. /**
  3486. * toggles whether the parser decodes element content w/ utf8_decode()
  3487. * @var boolean
  3488. * @access public
  3489. */
  3490. var $decode_utf8 = true;
  3491.  
  3492. /**
  3493. * HTTP headers of response
  3494. * @var array
  3495. * @access public
  3496. */
  3497. var $outgoing_headers = array();
  3498. /**
  3499. * HTTP response
  3500. * @var string
  3501. * @access private
  3502. */
  3503. var $response = '';
  3504. /**
  3505. * SOAP headers for response (text or array of soapval or associative array)
  3506. * @var mixed
  3507. * @access public
  3508. */
  3509. var $responseHeaders = '';
  3510. /**
  3511. * SOAP payload for response (text)
  3512. * @var string
  3513. * @access private
  3514. */
  3515. var $responseSOAP = '';
  3516. /**
  3517. * method return value to place in response
  3518. * @var mixed
  3519. * @access private
  3520. */
  3521. var $methodreturn = false;
  3522. /**
  3523. * whether $methodreturn is a string of literal XML
  3524. * @var boolean
  3525. * @access public
  3526. */
  3527. var $methodreturnisliteralxml = false;
  3528. /**
  3529. * SOAP fault for response (or false)
  3530. * @var mixed
  3531. * @access private
  3532. */
  3533. var $fault = false;
  3534. /**
  3535. * text indication of result (for debugging)
  3536. * @var string
  3537. * @access private
  3538. */
  3539. var $result = 'successful';
  3540.  
  3541. /**
  3542. * assoc array of operations => opData; operations are added by the register()
  3543. * method or by parsing an external WSDL definition
  3544. * @var array
  3545. * @access private
  3546. */
  3547. var $operations = array();
  3548. /**
  3549. * wsdl instance (if one)
  3550. * @var mixed
  3551. * @access private
  3552. */
  3553. var $wsdl = false;
  3554. /**
  3555. * URL for WSDL (if one)
  3556. * @var mixed
  3557. * @access private
  3558. */
  3559. var $externalWSDLURL = false;
  3560. /**
  3561. * whether to append debug to response as XML comment
  3562. * @var boolean
  3563. * @access public
  3564. */
  3565. var $debug_flag = false;
  3566.  
  3567.  
  3568. /**
  3569. * constructor
  3570. * the optional parameter is a path to a WSDL file that you'd like to bind the server instance to.
  3571. *
  3572. * @param mixed $wsdl file path or URL (string), or wsdl instance (object)
  3573. * @access public
  3574. */
  3575. function nusoap_server($wsdl=false){
  3576. parent::nusoap_base();
  3577. // turn on debugging?
  3578. global $debug;
  3579. global $HTTP_SERVER_VARS;
  3580.  
  3581. if (isset($_SERVER)) {
  3582. $this->debug("_SERVER is defined:");
  3583. $this->appendDebug($this->varDump($_SERVER));
  3584. } elseif (isset($HTTP_SERVER_VARS)) {
  3585. $this->debug("HTTP_SERVER_VARS is defined:");
  3586. $this->appendDebug($this->varDump($HTTP_SERVER_VARS));
  3587. } else {
  3588. $this->debug("Neither _SERVER nor HTTP_SERVER_VARS is defined.");
  3589. }
  3590.  
  3591. if (isset($debug)) {
  3592. $this->debug("In nusoap_server, set debug_flag=$debug based on global flag");
  3593. $this->debug_flag = $debug;
  3594. } elseif (isset($_SERVER['QUERY_STRING'])) {
  3595. $qs = explode('&', $_SERVER['QUERY_STRING']);
  3596. foreach ($qs as $v) {
  3597. if (substr($v, 0, 6) == 'debug=') {
  3598. $this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #1");
  3599. $this->debug_flag = substr($v, 6);
  3600. }
  3601. }
  3602. } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
  3603. $qs = explode('&', $HTTP_SERVER_VARS['QUERY_STRING']);
  3604. foreach ($qs as $v) {
  3605. if (substr($v, 0, 6) == 'debug=') {
  3606. $this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #2");
  3607. $this->debug_flag = substr($v, 6);
  3608. }
  3609. }
  3610. }
  3611.  
  3612. // wsdl
  3613. if($wsdl){
  3614. $this->debug("In nusoap_server, WSDL is specified");
  3615. if (is_object($wsdl) && (get_class($wsdl) == 'wsdl')) {
  3616. $this->wsdl = $wsdl;
  3617. $this->externalWSDLURL = $this->wsdl->wsdl;
  3618. $this->debug('Use existing wsdl instance from ' . $this->externalWSDLURL);
  3619. } else {
  3620. $this->debug('Create wsdl from ' . $wsdl);
  3621. $this->wsdl = new wsdl($wsdl);
  3622. $this->externalWSDLURL = $wsdl;
  3623. }
  3624. $this->appendDebug($this->wsdl->getDebug());
  3625. $this->wsdl->clearDebug();
  3626. if($err = $this->wsdl->getError()){
  3627. die('WSDL ERROR: '.$err);
  3628. }
  3629. }
  3630. }
  3631.  
  3632. /**
  3633. * processes request and returns response
  3634. *
  3635. * @param string $data usually is the value of $HTTP_RAW_POST_DATA
  3636. * @access public
  3637. */
  3638. function service($data){
  3639. global $HTTP_SERVER_VARS;
  3640.  
  3641. if (isset($_SERVER['REQUEST_METHOD'])) {
  3642. $rm = $_SERVER['REQUEST_METHOD'];
  3643. } elseif (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
  3644. $rm = $HTTP_SERVER_VARS['REQUEST_METHOD'];
  3645. } else {
  3646. $rm = '';
  3647. }
  3648.  
  3649. if (isset($_SERVER['QUERY_STRING'])) {
  3650. $qs = $_SERVER['QUERY_STRING'];
  3651. } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
  3652. $qs = $HTTP_SERVER_VARS['QUERY_STRING'];
  3653. } else {
  3654. $qs = '';
  3655. }
  3656. $this->debug("In service, request method=$rm query string=$qs strlen(\$data)=" . strlen($data));
  3657.  
  3658. if ($rm == 'POST') {
  3659. $this->debug("In service, invoke the request");
  3660. $this->parse_request($data);
  3661. if (! $this->fault) {
  3662. $this->invoke_method();
  3663. }
  3664. if (! $this->fault) {
  3665. $this->serialize_return();
  3666. }
  3667. $this->send_response();
  3668. } elseif (preg_match('/wsdl/', $qs) ){
  3669. $this->debug("In service, this is a request for WSDL");
  3670. if ($this->externalWSDLURL){
  3671. if (strpos($this->externalWSDLURL, "http://") !== false) { // assume URL
  3672. $this->debug("In service, re-direct for WSDL");
  3673. header('Location: '.$this->externalWSDLURL);
  3674. } else { // assume file
  3675. $this->debug("In service, use file passthru for WSDL");
  3676. header("Content-Type: text/xml\r\n");
  3677. $pos = strpos($this->externalWSDLURL, "file://");
  3678. if ($pos === false) {
  3679. $filename = $this->externalWSDLURL;
  3680. } else {
  3681. $filename = substr($this->externalWSDLURL, $pos + 7);
  3682. }
  3683. $fp = fopen($this->externalWSDLURL, 'r');
  3684. fpassthru($fp);
  3685. }
  3686. } elseif ($this->wsdl) {
  3687. $this->debug("In service, serialize WSDL");
  3688. header("Content-Type: text/xml; charset=ISO-8859-1\r\n");
  3689. print $this->wsdl->serialize($this->debug_flag);
  3690. if ($this->debug_flag) {
  3691. $this->debug('wsdl:');
  3692. $this->appendDebug($this->varDump($this->wsdl));
  3693. print $this->getDebugAsXMLComment();
  3694. }
  3695. } else {
  3696. $this->debug("In service, there is no WSDL");
  3697. header("Content-Type: text/html; charset=ISO-8859-1\r\n");
  3698. print "This service does not provide WSDL";
  3699. }
  3700. } elseif ($this->wsdl) {
  3701. $this->debug("In service, return Web description");
  3702. print $this->wsdl->webDescription();
  3703. } else {
  3704. $this->debug("In service, no Web description");
  3705. header("Content-Type: text/html; charset=ISO-8859-1\r\n");
  3706. print "This service does not provide a Web description";
  3707. }
  3708. }
  3709.  
  3710. /**
  3711. * parses HTTP request headers.
  3712. *
  3713. * The following fields are set by this function (when successful)
  3714. *
  3715. * headers
  3716. * request
  3717. * xml_encoding
  3718. * SOAPAction
  3719. *
  3720. * @access private
  3721. */
  3722. function parse_http_headers() {
  3723. global $HTTP_SERVER_VARS;
  3724.  
  3725. $this->request = '';
  3726. $this->SOAPAction = '';
  3727. if(function_exists('getallheaders')){
  3728. $this->debug("In parse_http_headers, use getallheaders");
  3729. $headers = getallheaders();
  3730. foreach($headers as $k=>$v){
  3731. $k = strtolower($k);
  3732. $this->headers[$k] = $v;
  3733. $this->request .= "$k: $v\r\n";
  3734. $this->debug("$k: $v");
  3735. }
  3736. // get SOAPAction header
  3737. if(isset($this->headers['soapaction'])){
  3738. $this->SOAPAction = str_replace('"','',$this->headers['soapaction']);
  3739. }
  3740. // get the character encoding of the incoming request
  3741. if(isset($this->headers['content-type']) && strpos($this->headers['content-type'],'=')){
  3742. $enc = str_replace('"','',substr(strstr($this->headers["content-type"],'='),1));
  3743. if(preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)){
  3744. $this->xml_encoding = strtoupper($enc);
  3745. } else {
  3746. $this->xml_encoding = 'US-ASCII';
  3747. }
  3748. } else {
  3749. // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
  3750. $this->xml_encoding = 'ISO-8859-1';
  3751. }
  3752. } elseif(isset($_SERVER) && is_array($_SERVER)){
  3753. $this->debug("In parse_http_headers, use _SERVER");
  3754. foreach ($_SERVER as $k => $v) {
  3755. if (substr($k, 0, 5) == 'HTTP_') {
  3756. $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5))));
  3757. } else {
  3758. $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k)));
  3759. }
  3760. if ($k == 'soapaction') {
  3761. // get SOAPAction header
  3762. $k = 'SOAPAction';
  3763. $v = str_replace('"', '', $v);
  3764. $v = str_replace('\\', '', $v);
  3765. $this->SOAPAction = $v;
  3766. } else if ($k == 'content-type') {
  3767. // get the character encoding of the incoming request
  3768. if (strpos($v, '=')) {
  3769. $enc = substr(strstr($v, '='), 1);
  3770. $enc = str_replace('"', '', $enc);
  3771. $enc = str_replace('\\', '', $enc);
  3772. if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)) {
  3773. $this->xml_encoding = strtoupper($enc);
  3774. } else {
  3775. $this->xml_encoding = 'US-ASCII';
  3776. }
  3777. } else {
  3778. // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
  3779. $this->xml_encoding = 'ISO-8859-1';
  3780. }
  3781. }
  3782. $this->headers[$k] = $v;
  3783. $this->request .= "$k: $v\r\n";
  3784. $this->debug("$k: $v");
  3785. }
  3786. } elseif (is_array($HTTP_SERVER_VARS)) {
  3787. $this->debug("In parse_http_headers, use HTTP_SERVER_VARS");
  3788. foreach ($HTTP_SERVER_VARS as $k => $v) {
  3789. if (substr($k, 0, 5) == 'HTTP_') {
  3790. $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5));
  3791. } else {
  3792. $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k);
  3793. }
  3794. if ($k == 'soapaction') {
  3795. // get SOAPAction header
  3796. $k = 'SOAPAction';
  3797. $v = str_replace('"', '', $v);
  3798. $v = str_replace('\\', '', $v);
  3799. $this->SOAPAction = $v;
  3800. } else if ($k == 'content-type') {
  3801. // get the character encoding of the incoming request
  3802. if (strpos($v, '=')) {
  3803. $enc = substr(strstr($v, '='), 1);
  3804. $enc = str_replace('"', '', $enc);
  3805. $enc = str_replace('\\', '', $enc);
  3806. if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)) {
  3807. $this->xml_encoding = strtoupper($enc);
  3808. } else {
  3809. $this->xml_encoding = 'US-ASCII';
  3810. }
  3811. } else {
  3812. // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
  3813. $this->xml_encoding = 'ISO-8859-1';
  3814. }
  3815. }
  3816. $this->headers[$k] = $v;
  3817. $this->request .= "$k: $v\r\n";
  3818. $this->debug("$k: $v");
  3819. }
  3820. } else {
  3821. $this->debug("In parse_http_headers, HTTP headers not accessible");
  3822. $this->setError("HTTP headers not accessible");
  3823. }
  3824. }
  3825.  
  3826. /**
  3827. * parses a request
  3828. *
  3829. * The following fields are set by this function (when successful)
  3830. *
  3831. * headers
  3832. * request
  3833. * xml_encoding
  3834. * SOAPAction
  3835. * request
  3836. * requestSOAP
  3837. * methodURI
  3838. * methodname
  3839. * methodparams
  3840. * requestHeaders
  3841. * document
  3842. *
  3843. * This sets the fault field on error
  3844. *
  3845. * @param string $data XML string
  3846. * @access private
  3847. */
  3848. function parse_request($data='') {
  3849. $this->debug('entering parse_request()');
  3850. $this->parse_http_headers();
  3851. $this->debug('got character encoding: '.$this->xml_encoding);
  3852. // uncompress if necessary
  3853. if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] != '') {
  3854. $this->debug('got content encoding: ' . $this->headers['content-encoding']);
  3855. if ($this->headers['content-encoding'] == 'deflate' || $this->headers['content-encoding'] == 'gzip') {
  3856. // if decoding works, use it. else assume data wasn't gzencoded
  3857. if (function_exists('gzuncompress')) {
  3858. if ($this->headers['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
  3859. $data = $degzdata;
  3860. } elseif ($this->headers['content-encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))) {
  3861. $data = $degzdata;
  3862. } else {
  3863. $this->fault('SOAP-ENV:Client', 'Errors occurred when trying to decode the data');
  3864. return;
  3865. }
  3866. } else {
  3867. $this->fault('SOAP-ENV:Client', 'This Server does not support compressed data');
  3868. return;
  3869. }
  3870. }
  3871. }
  3872. $this->request .= "\r\n".$data;
  3873. $data = $this->parseRequest($this->headers, $data);
  3874. $this->requestSOAP = $data;
  3875. $this->debug('leaving parse_request');
  3876. }
  3877.  
  3878. /**
  3879. * invokes a PHP function for the requested SOAP method
  3880. *
  3881. * The following fields are set by this function (when successful)
  3882. *
  3883. * methodreturn
  3884. *
  3885. * Note that the PHP function that is called may also set the following
  3886. * fields to affect the response sent to the client
  3887. *
  3888. * responseHeaders
  3889. * outgoing_headers
  3890. *
  3891. * This sets the fault field on error
  3892. *
  3893. * @access private
  3894. */
  3895. function invoke_method() {
  3896. $this->debug('in invoke_method, methodname=' . $this->methodname . ' methodURI=' . $this->methodURI . ' SOAPAction=' . $this->SOAPAction);
  3897.  
  3898. //
  3899. // if you are debugging in this area of the code, your service uses a class to implement methods,
  3900. // you use SOAP RPC, and the client is .NET, please be aware of the following...
  3901. // when the .NET wsdl.exe utility generates a proxy, it will remove the '.' or '..' from the
  3902. // method name. that is fine for naming the .NET methods. it is not fine for properly constructing
  3903. // the XML request and reading the XML response. you need to add the RequestElementName and
  3904. // ResponseElementName to the System.Web.Services.Protocols.SoapRpcMethodAttribute that wsdl.exe
  3905. // generates for the method. these parameters are used to specify the correct XML element names
  3906. // for .NET to use, i.e. the names with the '.' in them.
  3907. //
  3908. $orig_methodname = $this->methodname;
  3909. if ($this->wsdl) {
  3910. if ($this->opData = $this->wsdl->getOperationData($this->methodname)) {
  3911. $this->debug('in invoke_method, found WSDL operation=' . $this->methodname);
  3912. $this->appendDebug('opData=' . $this->varDump($this->opData));
  3913. } elseif ($this->opData = $this->wsdl->getOperationDataForSoapAction($this->SOAPAction)) {
  3914. // Note: hopefully this case will only be used for doc/lit, since rpc services should have wrapper element
  3915. $this->debug('in invoke_method, found WSDL soapAction=' . $this->SOAPAction . ' for operation=' . $this->opData['name']);
  3916. $this->appendDebug('opData=' . $this->varDump($this->opData));
  3917. $this->methodname = $this->opData['name'];
  3918. } else {
  3919. $this->debug('in invoke_method, no WSDL for operation=' . $this->methodname);
  3920. $this->fault('SOAP-ENV:Client', "Operation '" . $this->methodname . "' is not defined in the WSDL for this service");
  3921. return;
  3922. }
  3923. } else {
  3924. $this->debug('in invoke_method, no WSDL to validate method');
  3925. }
  3926.  
  3927. // if a . is present in $this->methodname, we see if there is a class in scope,
  3928. // which could be referred to. We will also distinguish between two deliminators,
  3929. // to allow methods to be called a the class or an instance
  3930. if (strpos($this->methodname, '..') > 0) {
  3931. $delim = '..';
  3932. } else if (strpos($this->methodname, '.') > 0) {
  3933. $delim = '.';
  3934. } else {
  3935. $delim = '';
  3936. }
  3937. $this->debug("in invoke_method, delim=$delim");
  3938.  
  3939. $class = '';
  3940. $method = '';
  3941. if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1) {
  3942. $try_class = substr($this->methodname, 0, strpos($this->methodname, $delim));
  3943. if (class_exists($try_class)) {
  3944. // get the class and method name
  3945. $class = $try_class;
  3946. $method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim));
  3947. $this->debug("in invoke_method, class=$class method=$method delim=$delim");
  3948. } else {
  3949. $this->debug("in invoke_method, class=$try_class not found");
  3950. }
  3951. } else {
  3952. $try_class = '';
  3953. $this->debug("in invoke_method, no class to try");
  3954. }
  3955.  
  3956. // does method exist?
  3957. if ($class == '') {
  3958. if (!function_exists($this->methodname)) {
  3959. $this->debug("in invoke_method, function '$this->methodname' not found!");
  3960. $this->result = 'fault: method not found';
  3961. $this->fault('SOAP-ENV:Client',"method '$this->methodname'('$orig_methodname') not defined in service('$try_class' '$delim')");
  3962. return;
  3963. }
  3964. } else {
  3965. $method_to_compare = (substr(phpversion(), 0, 2) == '4.') ? strtolower($method) : $method;
  3966. if (!in_array($method_to_compare, get_class_methods($class))) {
  3967. $this->debug("in invoke_method, method '$this->methodname' not found in class '$class'!");
  3968. $this->result = 'fault: method not found';
  3969. $this->fault('SOAP-ENV:Client',"method '$this->methodname'/'$method_to_compare'('$orig_methodname') not defined in service/'$class'('$try_class' '$delim')");
  3970. return;
  3971. }
  3972. }
  3973.  
  3974. // evaluate message, getting back parameters
  3975. // verify that request parameters match the method's signature
  3976. if(! $this->verify_method($this->methodname,$this->methodparams)){
  3977. // debug
  3978. $this->debug('ERROR: request not verified against method signature');
  3979. $this->result = 'fault: request failed validation against method signature';
  3980. // return fault
  3981. $this->fault('SOAP-ENV:Client',"Operation '$this->methodname' not defined in service.");
  3982. return;
  3983. }
  3984.  
  3985. // if there are parameters to pass
  3986. $this->debug('in invoke_method, params:');
  3987. $this->appendDebug($this->varDump($this->methodparams));
  3988. $this->debug("in invoke_method, calling '$this->methodname'");
  3989. if (!function_exists('call_user_func_array')) {
  3990. if ($class == '') {
  3991. $this->debug('in invoke_method, calling function using eval()');
  3992. $funcCall = "\$this->methodreturn = $this->methodname(";
  3993. } else {
  3994. if ($delim == '..') {
  3995. $this->debug('in invoke_method, calling class method using eval()');
  3996. $funcCall = "\$this->methodreturn = ".$class."::".$method."(";
  3997. } else {
  3998. $this->debug('in invoke_method, calling instance method using eval()');
  3999. // generate unique instance name
  4000. $instname = "\$inst_".time();
  4001. $funcCall = $instname." = new ".$class."(); ";
  4002. $funcCall .= "\$this->methodreturn = ".$instname."->".$method."(";
  4003. }
  4004. }
  4005. if ($this->methodparams) {
  4006. foreach ($this->methodparams as $param) {
  4007. if (is_array($param) || is_object($param)) {
  4008. $this->fault('SOAP-ENV:Client', 'NuSOAP does not handle complexType parameters correctly when using eval; call_user_func_array must be available');
  4009. return;
  4010. }
  4011. $funcCall .= "\"$param\",";
  4012. }
  4013. $funcCall = substr($funcCall, 0, -1);
  4014. }
  4015. $funcCall .= ');';
  4016. $this->debug('in invoke_method, function call: '.$funcCall);
  4017. @eval($funcCall);
  4018. } else {
  4019. if ($class == '') {
  4020. $this->debug('in invoke_method, calling function using call_user_func_array()');
  4021. $call_arg = "$this->methodname"; // straight assignment changes $this->methodname to lower case after call_user_func_array()
  4022. } elseif ($delim == '..') {
  4023. $this->debug('in invoke_method, calling class method using call_user_func_array()');
  4024. $call_arg = array ($class, $method);
  4025. } else {
  4026. $this->debug('in invoke_method, calling instance method using call_user_func_array()');
  4027. $instance = new $class ();
  4028. $call_arg = array(&$instance, $method);
  4029. }
  4030. if (is_array($this->methodparams)) {
  4031. $this->methodreturn = call_user_func_array($call_arg, array_values($this->methodparams));
  4032. } else {
  4033. $this->methodreturn = call_user_func_array($call_arg, array());
  4034. }
  4035. }
  4036. $this->debug('in invoke_method, methodreturn:');
  4037. $this->appendDebug($this->varDump($this->methodreturn));
  4038. $this->debug("in invoke_method, called method $this->methodname, received data of type ".gettype($this->methodreturn));
  4039. }
  4040.  
  4041. /**
  4042. * serializes the return value from a PHP function into a full SOAP Envelope
  4043. *
  4044. * The following fields are set by this function (when successful)
  4045. *
  4046. * responseSOAP
  4047. *
  4048. * This sets the fault field on error
  4049. *
  4050. * @access private
  4051. */
  4052. function serialize_return() {
  4053. $this->debug('Entering serialize_return methodname: ' . $this->methodname . ' methodURI: ' . $this->methodURI);
  4054. // if fault
  4055. if (isset($this->methodreturn) && is_object($this->methodreturn) && ((get_class($this->methodreturn) == 'soap_fault') || (get_class($this->methodreturn) == 'nusoap_fault'))) {
  4056. $this->debug('got a fault object from method');
  4057. $this->fault = $this->methodreturn;
  4058. return;
  4059. } elseif ($this->methodreturnisliteralxml) {
  4060. $return_val = $this->methodreturn;
  4061. // returned value(s)
  4062. } else {
  4063. $this->debug('got a(n) '.gettype($this->methodreturn).' from method');
  4064. $this->debug('serializing return value');
  4065. if($this->wsdl){
  4066. if (sizeof($this->opData['output']['parts']) > 1) {
  4067. $this->debug('more than one output part, so use the method return unchanged');
  4068. $opParams = $this->methodreturn;
  4069. } elseif (sizeof($this->opData['output']['parts']) == 1) {
  4070. $this->debug('exactly one output part, so wrap the method return in a simple array');
  4071. // TODO: verify that it is not already wrapped!
  4072. //foreach ($this->opData['output']['parts'] as $name => $type) {
  4073. // $this->debug('wrap in element named ' . $name);
  4074. //}
  4075. $opParams = array($this->methodreturn);
  4076. }
  4077. $return_val = $this->wsdl->serializeRPCParameters($this->methodname,'output',$opParams);
  4078. $this->appendDebug($this->wsdl->getDebug());
  4079. $this->wsdl->clearDebug();
  4080. if($errstr = $this->wsdl->getError()){
  4081. $this->debug('got wsdl error: '.$errstr);
  4082. $this->fault('SOAP-ENV:Server', 'unable to serialize result');
  4083. return;
  4084. }
  4085. } else {
  4086. if (isset($this->methodreturn)) {
  4087. $return_val = $this->serialize_val($this->methodreturn, 'return');
  4088. } else {
  4089. $return_val = '';
  4090. $this->debug('in absence of WSDL, assume void return for backward compatibility');
  4091. }
  4092. }
  4093. }
  4094. $this->debug('return value:');
  4095. $this->appendDebug($this->varDump($return_val));
  4096.  
  4097. $this->debug('serializing response');
  4098. if ($this->wsdl) {
  4099. $this->debug('have WSDL for serialization: style is ' . $this->opData['style']);
  4100. if ($this->opData['style'] == 'rpc') {
  4101. $this->debug('style is rpc for serialization: use is ' . $this->opData['output']['use']);
  4102. if ($this->opData['output']['use'] == 'literal') {
  4103. // 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
  4104. if ($this->methodURI) {
  4105. $payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
  4106. } else {
  4107. $payload = '<'.$this->methodname.'Response>'.$return_val.'</'.$this->methodname.'Response>';
  4108. }
  4109. } else {
  4110. if ($this->methodURI) {
  4111. $payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
  4112. } else {
  4113. $payload = '<'.$this->methodname.'Response>'.$return_val.'</'.$this->methodname.'Response>';
  4114. }
  4115. }
  4116. } else {
  4117. $this->debug('style is not rpc for serialization: assume document');
  4118. $payload = $return_val;
  4119. }
  4120. } else {
  4121. $this->debug('do not have WSDL for serialization: assume rpc/encoded');
  4122. $payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
  4123. }
  4124. $this->result = 'successful';
  4125. if($this->wsdl){
  4126. //if($this->debug_flag){
  4127. $this->appendDebug($this->wsdl->getDebug());
  4128. // }
  4129. if (isset($this->opData['output']['encodingStyle'])) {
  4130. $encodingStyle = $this->opData['output']['encodingStyle'];
  4131. } else {
  4132. $encodingStyle = '';
  4133. }
  4134. // Added: In case we use a WSDL, return a serialized env. WITH the usedNamespaces.
  4135. $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders,$this->wsdl->usedNamespaces,$this->opData['style'],$this->opData['output']['use'],$encodingStyle);
  4136. } else {
  4137. $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders);
  4138. }
  4139. $this->debug("Leaving serialize_return");
  4140. }
  4141.  
  4142. /**
  4143. * sends an HTTP response
  4144. *
  4145. * The following fields are set by this function (when successful)
  4146. *
  4147. * outgoing_headers
  4148. * response
  4149. *
  4150. * @access private
  4151. */
  4152. function send_response() {
  4153. $this->debug('Enter send_response');
  4154. if ($this->fault) {
  4155. $payload = $this->fault->serialize();
  4156. $this->outgoing_headers[] = "HTTP/1.0 500 Internal Server Error";
  4157. $this->outgoing_headers[] = "Status: 500 Internal Server Error";
  4158. } else {
  4159. $payload = $this->responseSOAP;
  4160. // Some combinations of PHP+Web server allow the Status
  4161. // to come through as a header. Since OK is the default
  4162. // just do nothing.
  4163. // $this->outgoing_headers[] = "HTTP/1.0 200 OK";
  4164. // $this->outgoing_headers[] = "Status: 200 OK";
  4165. }
  4166. // add debug data if in debug mode
  4167. if(isset($this->debug_flag) && $this->debug_flag){
  4168. $payload .= $this->getDebugAsXMLComment();
  4169. }
  4170. $this->outgoing_headers[] = "Server: $this->title Server v$this->version";
  4171. preg_match('/\$Revisio' . 'n: ([^ ]+)/', $this->revision, $rev);
  4172. $this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".$rev[1].")";
  4173. // Let the Web server decide about this
  4174. //$this->outgoing_headers[] = "Connection: Close\r\n";
  4175. $payload = $this->getHTTPBody($payload);
  4176. $type = $this->getHTTPContentType();
  4177. $charset = $this->getHTTPContentTypeCharset();
  4178. $this->outgoing_headers[] = "Content-Type: $type" . ($charset ? '; charset=' . $charset : '');
  4179. //begin code to compress payload - by John
  4180. // NOTE: there is no way to know whether the Web server will also compress
  4181. // this data.
  4182. if (strlen($payload) > 1024 && isset($this->headers) && isset($this->headers['accept-encoding'])) {
  4183. if (strstr($this->headers['accept-encoding'], 'gzip')) {
  4184. if (function_exists('gzencode')) {
  4185. if (isset($this->debug_flag) && $this->debug_flag) {
  4186. $payload .= "<!-- Content being gzipped -->";
  4187. }
  4188. $this->outgoing_headers[] = "Content-Encoding: gzip";
  4189. $payload = gzencode($payload);
  4190. } else {
  4191. if (isset($this->debug_flag) && $this->debug_flag) {
  4192. $payload .= "<!-- Content will not be gzipped: no gzencode -->";
  4193. }
  4194. }
  4195. } elseif (strstr($this->headers['accept-encoding'], 'deflate')) {
  4196. // Note: MSIE requires gzdeflate output (no Zlib header and checksum),
  4197. // instead of gzcompress output,
  4198. // which conflicts with HTTP 1.1 spec (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5)
  4199. if (function_exists('gzdeflate')) {
  4200. if (isset($this->debug_flag) && $this->debug_flag) {
  4201. $payload .= "<!-- Content being deflated -->";
  4202. }
  4203. $this->outgoing_headers[] = "Content-Encoding: deflate";
  4204. $payload = gzdeflate($payload);
  4205. } else {
  4206. if (isset($this->debug_flag) && $this->debug_flag) {
  4207. $payload .= "<!-- Content will not be deflated: no gzcompress -->";
  4208. }
  4209. }
  4210. }
  4211. }
  4212. //end code
  4213. $this->outgoing_headers[] = "Content-Length: ".strlen($payload);
  4214. reset($this->outgoing_headers);
  4215. foreach($this->outgoing_headers as $hdr){
  4216. header($hdr, false);
  4217. }
  4218. print $payload;
  4219. $this->response = join("\r\n",$this->outgoing_headers)."\r\n\r\n".$payload;
  4220. }
  4221.  
  4222. /**
  4223. * takes the value that was created by parsing the request
  4224. * and compares to the method's signature, if available.
  4225. *
  4226. * @param string $operation The operation to be invoked
  4227. * @param array $request The array of parameter values
  4228. * @return boolean Whether the operation was found
  4229. * @access private
  4230. */
  4231. function verify_method($operation,$request){
  4232. if(isset($this->wsdl) && is_object($this->wsdl)){
  4233. if($this->wsdl->getOperationData($operation)){
  4234. return true;
  4235. }
  4236. } elseif(isset($this->operations[$operation])){
  4237. return true;
  4238. }
  4239. return false;
  4240. }
  4241.  
  4242. /**
  4243. * processes SOAP message received from client
  4244. *
  4245. * @param array $headers The HTTP headers
  4246. * @param string $data unprocessed request data from client
  4247. * @return mixed value of the message, decoded into a PHP type
  4248. * @access private
  4249. */
  4250. function parseRequest($headers, $data) {
  4251. $this->debug('Entering parseRequest() for data of length ' . strlen($data) . ' headers:');
  4252. $this->appendDebug($this->varDump($headers));
  4253. if (!isset($headers['content-type'])) {
  4254. $this->setError('Request not of type text/xml (no content-type header)');
  4255. return false;
  4256. }
  4257. if (!strstr($headers['content-type'], 'text/xml')) {
  4258. $this->setError('Request not of type text/xml');
  4259. return false;
  4260. }
  4261. if (strpos($headers['content-type'], '=')) {
  4262. $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1));
  4263. $this->debug('Got response encoding: ' . $enc);
  4264. if(preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)){
  4265. $this->xml_encoding = strtoupper($enc);
  4266. } else {
  4267. $this->xml_encoding = 'US-ASCII';
  4268. }
  4269. } else {
  4270. // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
  4271. $this->xml_encoding = 'ISO-8859-1';
  4272. }
  4273. $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating nusoap_parser');
  4274. // parse response, get soap parser obj
  4275. $parser = new nusoap_parser($data,$this->xml_encoding,'',$this->decode_utf8);
  4276. // parser debug
  4277. $this->debug("parser debug: \n".$parser->getDebug());
  4278. // if fault occurred during message parsing
  4279. if($err = $parser->getError()){
  4280. $this->result = 'fault: error in msg parsing: '.$err;
  4281. $this->fault('SOAP-ENV:Client',"error in msg parsing:\n".$err);
  4282. // else successfully parsed request into soapval object
  4283. } else {
  4284. // get/set methodname
  4285. $this->methodURI = $parser->root_struct_namespace;
  4286. $this->methodname = $parser->root_struct_name;
  4287. $this->debug('methodname: '.$this->methodname.' methodURI: '.$this->methodURI);
  4288. $this->debug('calling parser->get_soapbody()');
  4289. $this->methodparams = $parser->get_soapbody();
  4290. // get SOAP headers
  4291. $this->requestHeaders = $parser->getHeaders();
  4292. // get SOAP Header
  4293. $this->requestHeader = $parser->get_soapheader();
  4294. // add document for doclit support
  4295. $this->document = $parser->document;
  4296. }
  4297. }
  4298.  
  4299. /**
  4300. * gets the HTTP body for the current response.
  4301. *
  4302. * @param string $soapmsg The SOAP payload
  4303. * @return string The HTTP body, which includes the SOAP payload
  4304. * @access private
  4305. */
  4306. function getHTTPBody($soapmsg) {
  4307. return $soapmsg;
  4308. }
  4309. /**
  4310. * gets the HTTP content type for the current response.
  4311. *
  4312. * Note: getHTTPBody must be called before this.
  4313. *
  4314. * @return string the HTTP content type for the current response.
  4315. * @access private
  4316. */
  4317. function getHTTPContentType() {
  4318. return 'text/xml';
  4319. }
  4320. /**
  4321. * gets the HTTP content type charset for the current response.
  4322. * returns false for non-text content types.
  4323. *
  4324. * Note: getHTTPBody must be called before this.
  4325. *
  4326. * @return string the HTTP content type charset for the current response.
  4327. * @access private
  4328. */
  4329. function getHTTPContentTypeCharset() {
  4330. return $this->soap_defencoding;
  4331. }
  4332.  
  4333. /**
  4334. * add a method to the dispatch map (this has been replaced by the register method)
  4335. *
  4336. * @param string $methodname
  4337. * @param string $in array of input values
  4338. * @param string $out array of output values
  4339. * @access public
  4340. * @deprecated
  4341. */
  4342. function add_to_map($methodname,$in,$out){
  4343. $this->operations[$methodname] = array('name' => $methodname,'in' => $in,'out' => $out);
  4344. }
  4345.  
  4346. /**
  4347. * register a service function with the server
  4348. *
  4349. * @param string $name the name of the PHP function, class.method or class..method
  4350. * @param array $in assoc array of input values: key = param name, value = param type
  4351. * @param array $out assoc array of output values: key = param name, value = param type
  4352. * @param mixed $namespace the element namespace for the method or false
  4353. * @param mixed $soapaction the soapaction for the method or false
  4354. * @param mixed $style optional (rpc|document) or false Note: when 'document' is specified, parameter and return wrappers are created for you automatically
  4355. * @param mixed $use optional (encoded|literal) or false
  4356. * @param string $documentation optional Description to include in WSDL
  4357. * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
  4358. * @access public
  4359. */
  4360. function register($name,$in=array(),$out=array(),$namespace=false,$soapaction=false,$style=false,$use=false,$documentation='',$encodingStyle=''){
  4361. global $HTTP_SERVER_VARS;
  4362.  
  4363. if($this->externalWSDLURL){
  4364. die('You cannot bind to an external WSDL file, and register methods outside of it! Please choose either WSDL or no WSDL.');
  4365. }
  4366. if (! $name) {
  4367. die('You must specify a name when you register an operation');
  4368. }
  4369. if (!is_array($in)) {
  4370. die('You must provide an array for operation inputs');
  4371. }
  4372. if (!is_array($out)) {
  4373. die('You must provide an array for operation outputs');
  4374. }
  4375. if(false == $namespace) {
  4376. }
  4377. if(false == $soapaction) {
  4378. if (isset($_SERVER)) {
  4379. $SERVER_NAME = $_SERVER['SERVER_NAME'];
  4380. $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
  4381. $HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off');
  4382. } elseif (isset($HTTP_SERVER_VARS)) {
  4383. $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME'];
  4384. $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME'];
  4385. $HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off';
  4386. } else {
  4387. $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
  4388. }
  4389. if ($HTTPS == '1' || $HTTPS == 'on') {
  4390. $SCHEME = 'https';
  4391. } else {
  4392. $SCHEME = 'http';
  4393. }
  4394. $soapaction = "$SCHEME://$SERVER_NAME$SCRIPT_NAME/$name";
  4395. }
  4396. if(false == $style) {
  4397. $style = "rpc";
  4398. }
  4399. if(false == $use) {
  4400. $use = "encoded";
  4401. }
  4402. if ($use == 'encoded' && $encodingStyle == '') {
  4403. $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
  4404. }
  4405.  
  4406. $this->operations[$name] = array(
  4407. 'name' => $name,
  4408. 'in' => $in,
  4409. 'out' => $out,
  4410. 'namespace' => $namespace,
  4411. 'soapaction' => $soapaction,
  4412. 'style' => $style);
  4413. if($this->wsdl){
  4414. $this->wsdl->addOperation($name,$in,$out,$namespace,$soapaction,$style,$use,$documentation,$encodingStyle);
  4415. }
  4416. return true;
  4417. }
  4418.  
  4419. /**
  4420. * Specify a fault to be returned to the client.
  4421. * This also acts as a flag to the server that a fault has occured.
  4422. *
  4423. * @param string $faultcode
  4424. * @param string $faultstring
  4425. * @param string $faultactor
  4426. * @param string $faultdetail
  4427. * @access public
  4428. */
  4429. function fault($faultcode,$faultstring,$faultactor='',$faultdetail=''){
  4430. if ($faultdetail == '' && $this->debug_flag) {
  4431. $faultdetail = $this->getDebug();
  4432. }
  4433. $this->fault = new nusoap_fault($faultcode,$faultactor,$faultstring,$faultdetail);
  4434. $this->fault->soap_defencoding = $this->soap_defencoding;
  4435. }
  4436.  
  4437. /**
  4438. * Sets up wsdl object.
  4439. * Acts as a flag to enable internal WSDL generation
  4440. *
  4441. * @param string $serviceName, name of the service
  4442. * @param mixed $namespace optional 'tns' service namespace or false
  4443. * @param mixed $endpoint optional URL of service endpoint or false
  4444. * @param string $style optional (rpc|document) WSDL style (also specified by operation)
  4445. * @param string $transport optional SOAP transport
  4446. * @param mixed $schemaTargetNamespace optional 'types' targetNamespace for service schema or false
  4447. */
  4448. function configureWSDL($serviceName,$namespace = false,$endpoint = false,$style='rpc', $transport = 'http://schemas.xmlsoap.org/soap/http', $schemaTargetNamespace = false)
  4449. {
  4450. global $HTTP_SERVER_VARS;
  4451.  
  4452. if (isset($_SERVER)) {
  4453. $SERVER_NAME = $_SERVER['SERVER_NAME'];
  4454. $SERVER_PORT = $_SERVER['SERVER_PORT'];
  4455. $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
  4456. $HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off');
  4457. } elseif (isset($HTTP_SERVER_VARS)) {
  4458. $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME'];
  4459. $SERVER_PORT = $HTTP_SERVER_VARS['SERVER_PORT'];
  4460. $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME'];
  4461. $HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off';
  4462. } else {
  4463. $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
  4464. }
  4465. // If server name has port number attached then strip it (else port number gets duplicated in WSDL output) (occurred using lighttpd and FastCGI)
  4466. $colon = strpos($SERVER_NAME,":");
  4467. if ($colon) {
  4468. $SERVER_NAME = substr($SERVER_NAME, 0, $colon);
  4469. }
  4470. if ($SERVER_PORT == 80) {
  4471. $SERVER_PORT = '';
  4472. } else {
  4473. $SERVER_PORT = ':' . $SERVER_PORT;
  4474. }
  4475. if(false == $namespace) {
  4476. $namespace = "http://$SERVER_NAME/soap/$serviceName";
  4477. }
  4478. if(false == $endpoint) {
  4479. if ($HTTPS == '1' || $HTTPS == 'on') {
  4480. $SCHEME = 'https';
  4481. } else {
  4482. $SCHEME = 'http';
  4483. }
  4484. $endpoint = "$SCHEME://$SERVER_NAME$SERVER_PORT$SCRIPT_NAME";
  4485. }
  4486. if(false == $schemaTargetNamespace) {
  4487. $schemaTargetNamespace = $namespace;
  4488. }
  4489. $this->wsdl = new wsdl;
  4490. $this->wsdl->serviceName = $serviceName;
  4491. $this->wsdl->endpoint = $endpoint;
  4492. $this->wsdl->namespaces['tns'] = $namespace;
  4493. $this->wsdl->namespaces['soap'] = 'http://schemas.xmlsoap.org/wsdl/soap/';
  4494. $this->wsdl->namespaces['wsdl'] = 'http://schemas.xmlsoap.org/wsdl/';
  4495. if ($schemaTargetNamespace != $namespace) {
  4496. $this->wsdl->namespaces['types'] = $schemaTargetNamespace;
  4497. }
  4498. $this->wsdl->schemas[$schemaTargetNamespace][0] = new nusoap_xmlschema('', '', $this->wsdl->namespaces);
  4499. if ($style == 'document') {
  4500. $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaInfo['elementFormDefault'] = 'qualified';
  4501. }
  4502. $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaTargetNamespace = $schemaTargetNamespace;
  4503. $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/soap/encoding/'][0] = array('location' => '', 'loaded' => true);
  4504. $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/wsdl/'][0] = array('location' => '', 'loaded' => true);
  4505. $this->wsdl->bindings[$serviceName.'Binding'] = array(
  4506. 'name'=>$serviceName.'Binding',
  4507. 'style'=>$style,
  4508. 'transport'=>$transport,
  4509. 'portType'=>$serviceName.'PortType');
  4510. $this->wsdl->ports[$serviceName.'Port'] = array(
  4511. 'binding'=>$serviceName.'Binding',
  4512. 'location'=>$endpoint,
  4513. 'bindingType'=>'http://schemas.xmlsoap.org/wsdl/soap/');
  4514. }
  4515. }
  4516.  
  4517. /**
  4518. * Backward compatibility
  4519. */
  4520. class soap_server extends nusoap_server {
  4521. }
  4522.  
  4523. ?><?php
  4524.  
  4525.  
  4526.  
  4527. /**
  4528. * parses a WSDL file, allows access to it's data, other utility methods.
  4529. * also builds WSDL structures programmatically.
  4530. *
  4531. * @author Dietrich Ayala <dietrich@ganx4.com>
  4532. * @author Scott Nichol <snichol@users.sourceforge.net>
  4533. * @version $Id: fsource_nusoap__nusoap.php.html,v 1.2 2010/04/26 20:25:21 snichol Exp $
  4534. * @access public
  4535. */
  4536. class wsdl extends nusoap_base {
  4537. // URL or filename of the root of this WSDL
  4538. var $wsdl;
  4539. // define internal arrays of bindings, ports, operations, messages, etc.
  4540. var $schemas = array();
  4541. var $currentSchema;
  4542. var $message = array();
  4543. var $complexTypes = array();
  4544. var $messages = array();
  4545. var $currentMessage;
  4546. var $currentOperation;
  4547. var $portTypes = array();
  4548. var $currentPortType;
  4549. var $bindings = array();
  4550. var $currentBinding;
  4551. var $ports = array();
  4552. var $currentPort;
  4553. var $opData = array();
  4554. var $status = '';
  4555. var $documentation = false;
  4556. var $endpoint = '';
  4557. // array of wsdl docs to import
  4558. var $import = array();
  4559. // parser vars
  4560. var $parser;
  4561. var $position = 0;
  4562. var $depth = 0;
  4563. var $depth_array = array();
  4564. // for getting wsdl
  4565. var $proxyhost = '';
  4566. var $proxyport = '';
  4567. var $proxyusername = '';
  4568. var $proxypassword = '';
  4569. var $timeout = 0;
  4570. var $response_timeout = 30;
  4571. var $curl_options = array(); // User-specified cURL options
  4572. var $use_curl = false; // whether to always try to use cURL
  4573. // for HTTP authentication
  4574. var $username = ''; // Username for HTTP authentication
  4575. var $password = ''; // Password for HTTP authentication
  4576. var $authtype = ''; // Type of HTTP authentication
  4577. var $certRequest = array(); // Certificate for HTTP SSL authentication
  4578.  
  4579.  
  4580. /**
  4581. * constructor
  4582. *
  4583. * @param string $wsdl WSDL document URL
  4584. * @param string $proxyhost
  4585. * @param string $proxyport
  4586. * @param string $proxyusername
  4587. * @param string $proxypassword
  4588. * @param integer $timeout set the connection timeout
  4589. * @param integer $response_timeout set the response timeout
  4590. * @param array $curl_options user-specified cURL options
  4591. * @param boolean $use_curl try to use cURL
  4592. * @access public
  4593. */
  4594. function wsdl($wsdl = '',$proxyhost=false,$proxyport=false,$proxyusername=false,$proxypassword=false,$timeout=0,$response_timeout=30,$curl_options=null,$use_curl=false){
  4595. parent::nusoap_base();
  4596. $this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout");
  4597. $this->proxyhost = $proxyhost;
  4598. $this->proxyport = $proxyport;
  4599. $this->proxyusername = $proxyusername;
  4600. $this->proxypassword = $proxypassword;
  4601. $this->timeout = $timeout;
  4602. $this->response_timeout = $response_timeout;
  4603. if (is_array($curl_options))
  4604. $this->curl_options = $curl_options;
  4605. $this->use_curl = $use_curl;
  4606. $this->fetchWSDL($wsdl);
  4607. }
  4608.  
  4609. /**
  4610. * fetches the WSDL document and parses it
  4611. *
  4612. * @access public
  4613. */
  4614. function fetchWSDL($wsdl) {
  4615. $this->debug("parse and process WSDL path=$wsdl");
  4616. $this->wsdl = $wsdl;
  4617. // parse wsdl file
  4618. if ($this->wsdl != "") {
  4619. $this->parseWSDL($this->wsdl);
  4620. }
  4621. // imports
  4622. // TODO: handle imports more properly, grabbing them in-line and nesting them
  4623. $imported_urls = array();
  4624. $imported = 1;
  4625. while ($imported > 0) {
  4626. $imported = 0;
  4627. // Schema imports
  4628. foreach ($this->schemas as $ns => $list) {
  4629. foreach ($list as $xs) {
  4630. $wsdlparts = parse_url($this->wsdl); // this is bogusly simple!
  4631. foreach ($xs->imports as $ns2 => $list2) {
  4632. for ($ii = 0; $ii < count($list2); $ii++) {
  4633. if (! $list2[$ii]['loaded']) {
  4634. $this->schemas[$ns]->imports[$ns2][$ii]['loaded'] = true;
  4635. $url = $list2[$ii]['location'];
  4636. if ($url != '') {
  4637. $urlparts = parse_url($url);
  4638. if (!isset($urlparts['host'])) {
  4639. $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' .$wsdlparts['port'] : '') .
  4640. substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
  4641. }
  4642. if (! in_array($url, $imported_urls)) {
  4643. $this->parseWSDL($url);
  4644. $imported++;
  4645. $imported_urls[] = $url;
  4646. }
  4647. } else {
  4648. $this->debug("Unexpected scenario: empty URL for unloaded import");
  4649. }
  4650. }
  4651. }
  4652. }
  4653. }
  4654. }
  4655. // WSDL imports
  4656. $wsdlparts = parse_url($this->wsdl); // this is bogusly simple!
  4657. foreach ($this->import as $ns => $list) {
  4658. for ($ii = 0; $ii < count($list); $ii++) {
  4659. if (! $list[$ii]['loaded']) {
  4660. $this->import[$ns][$ii]['loaded'] = true;
  4661. $url = $list[$ii]['location'];
  4662. if ($url != '') {
  4663. $urlparts = parse_url($url);
  4664. if (!isset($urlparts['host'])) {
  4665. $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') .
  4666. substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
  4667. }
  4668. if (! in_array($url, $imported_urls)) {
  4669. $this->parseWSDL($url);
  4670. $imported++;
  4671. $imported_urls[] = $url;
  4672. }
  4673. } else {
  4674. $this->debug("Unexpected scenario: empty URL for unloaded import");
  4675. }
  4676. }
  4677. }
  4678. }
  4679. }
  4680. // add new data to operation data
  4681. foreach($this->bindings as $binding => $bindingData) {
  4682. if (isset($bindingData['operations']) && is_array($bindingData['operations'])) {
  4683. foreach($bindingData['operations'] as $operation => $data) {
  4684. $this->debug('post-parse data gathering for ' . $operation);
  4685. $this->bindings[$binding]['operations'][$operation]['input'] =
  4686. isset($this->bindings[$binding]['operations'][$operation]['input']) ?
  4687. array_merge($this->bindings[$binding]['operations'][$operation]['input'], $this->portTypes[ $bindingData['portType'] ][$operation]['input']) :
  4688. $this->portTypes[ $bindingData['portType'] ][$operation]['input'];
  4689. $this->bindings[$binding]['operations'][$operation]['output'] =
  4690. isset($this->bindings[$binding]['operations'][$operation]['output']) ?
  4691. array_merge($this->bindings[$binding]['operations'][$operation]['output'], $this->portTypes[ $bindingData['portType'] ][$operation]['output']) :
  4692. $this->portTypes[ $bindingData['portType'] ][$operation]['output'];
  4693. if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ])){
  4694. $this->bindings[$binding]['operations'][$operation]['input']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ];
  4695. }
  4696. if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ])){
  4697. $this->bindings[$binding]['operations'][$operation]['output']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ];
  4698. }
  4699. // Set operation style if necessary, but do not override one already provided
  4700. if (isset($bindingData['style']) && !isset($this->bindings[$binding]['operations'][$operation]['style'])) {
  4701. $this->bindings[$binding]['operations'][$operation]['style'] = $bindingData['style'];
  4702. }
  4703. $this->bindings[$binding]['operations'][$operation]['transport'] = isset($bindingData['transport']) ? $bindingData['transport'] : '';
  4704. $this->bindings[$binding]['operations'][$operation]['documentation'] = isset($this->portTypes[ $bindingData['portType'] ][$operation]['documentation']) ? $this->portTypes[ $bindingData['portType'] ][$operation]['documentation'] : '';
  4705. $this->bindings[$binding]['operations'][$operation]['endpoint'] = isset($bindingData['endpoint']) ? $bindingData['endpoint'] : '';
  4706. }
  4707. }
  4708. }
  4709. }
  4710.  
  4711. /**
  4712. * parses the wsdl document
  4713. *
  4714. * @param string $wsdl path or URL
  4715. * @access private
  4716. */
  4717. function parseWSDL($wsdl = '') {
  4718. $this->debug("parse WSDL at path=$wsdl");
  4719.  
  4720. if ($wsdl == '') {
  4721. $this->debug('no wsdl passed to parseWSDL()!!');
  4722. $this->setError('no wsdl passed to parseWSDL()!!');
  4723. return false;
  4724. }
  4725. // parse $wsdl for url format
  4726. $wsdl_props = parse_url($wsdl);
  4727.  
  4728. if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'http' || $wsdl_props['scheme'] == 'https')) {
  4729. $this->debug('getting WSDL http(s) URL ' . $wsdl);
  4730. // get wsdl
  4731. $tr = new soap_transport_http($wsdl, $this->curl_options, $this->use_curl);
  4732. $tr->request_method = 'GET';
  4733. $tr->useSOAPAction = false;
  4734. if($this->proxyhost && $this->proxyport){
  4735. $tr->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword);
  4736. }
  4737. if ($this->authtype != '') {
  4738. $tr->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest);
  4739. }
  4740. $tr->setEncoding('gzip, deflate');
  4741. $wsdl_string = $tr->send('', $this->timeout, $this->response_timeout);
  4742. //$this->debug("WSDL request\n" . $tr->outgoing_payload);
  4743. //$this->debug("WSDL response\n" . $tr->incoming_payload);
  4744. $this->appendDebug($tr->getDebug());
  4745. // catch errors
  4746. if($err = $tr->getError() ){
  4747. $errstr = 'Getting ' . $wsdl . ' - HTTP ERROR: '.$err;
  4748. $this->debug($errstr);
  4749. $this->setError($errstr);
  4750. unset($tr);
  4751. return false;
  4752. }
  4753. unset($tr);
  4754. $this->debug("got WSDL URL");
  4755. } else {
  4756. // $wsdl is not http(s), so treat it as a file URL or plain file path
  4757. if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'file') && isset($wsdl_props['path'])) {
  4758. $path = isset($wsdl_props['host']) ? ($wsdl_props['host'] . ':' . $wsdl_props['path']) : $wsdl_props['path'];
  4759. } else {
  4760. $path = $wsdl;
  4761. }
  4762. $this->debug('getting WSDL file ' . $path);
  4763. if ($fp = @fopen($path, 'r')) {
  4764. $wsdl_string = '';
  4765. while ($data = fread($fp, 32768)) {
  4766. $wsdl_string .= $data;
  4767. }
  4768. fclose($fp);
  4769. } else {
  4770. $errstr = "Bad path to WSDL file $path";
  4771. $this->debug($errstr);
  4772. $this->setError($errstr);
  4773. return false;
  4774. }
  4775. }
  4776. $this->debug('Parse WSDL');
  4777. // end new code added
  4778. // Create an XML parser.
  4779. $this->parser = xml_parser_create();
  4780. // Set the options for parsing the XML data.
  4781. // xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  4782. xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
  4783. // Set the object for the parser.
  4784. xml_set_object($this->parser, $this);
  4785. // Set the element handlers for the parser.
  4786. xml_set_element_handler($this->parser, 'start_element', 'end_element');
  4787. xml_set_character_data_handler($this->parser, 'character_data');
  4788. // Parse the XML file.
  4789. if (!xml_parse($this->parser, $wsdl_string, true)) {
  4790. // Display an error message.
  4791. $errstr = sprintf(
  4792. 'XML error parsing WSDL from %s on line %d: %s',
  4793. $wsdl,
  4794. xml_get_current_line_number($this->parser),
  4795. xml_error_string(xml_get_error_code($this->parser))
  4796. );
  4797. $this->debug($errstr);
  4798. $this->debug("XML payload:\n" . $wsdl_string);
  4799. $this->setError($errstr);
  4800. return false;
  4801. }
  4802. // free the parser
  4803. xml_parser_free($this->parser);
  4804. $this->debug('Parsing WSDL done');
  4805. // catch wsdl parse errors
  4806. if($this->getError()){
  4807. return false;
  4808. }
  4809. return true;
  4810. }
  4811.  
  4812. /**
  4813. * start-element handler
  4814. *
  4815. * @param string $parser XML parser object
  4816. * @param string $name element name
  4817. * @param string $attrs associative array of attributes
  4818. * @access private
  4819. */
  4820. function start_element($parser, $name, $attrs)
  4821. {
  4822. if ($this->status == 'schema') {
  4823. $this->currentSchema->schemaStartElement($parser, $name, $attrs);
  4824. $this->appendDebug($this->currentSchema->getDebug());
  4825. $this->currentSchema->clearDebug();
  4826. } elseif (preg_match('/schema$/', $name)) {
  4827. $this->debug('Parsing WSDL schema');
  4828. // $this->debug("startElement for $name ($attrs[name]). status = $this->status (".$this->getLocalPart($name).")");
  4829. $this->status = 'schema';
  4830. $this->currentSchema = new nusoap_xmlschema('', '', $this->namespaces);
  4831. $this->currentSchema->schemaStartElement($parser, $name, $attrs);
  4832. $this->appendDebug($this->currentSchema->getDebug());
  4833. $this->currentSchema->clearDebug();
  4834. } else {
  4835. // position in the total number of elements, starting from 0
  4836. $pos = $this->position++;
  4837. $depth = $this->depth++;
  4838. // set self as current value for this depth
  4839. $this->depth_array[$depth] = $pos;
  4840. $this->message[$pos] = array('cdata' => '');
  4841. // process attributes
  4842. if (count($attrs) > 0) {
  4843. // register namespace declarations
  4844. foreach($attrs as $k => $v) {
  4845. if (preg_match('/^xmlns/',$k)) {
  4846. if ($ns_prefix = substr(strrchr($k, ':'), 1)) {
  4847. $this->namespaces[$ns_prefix] = $v;
  4848. } else {
  4849. $this->namespaces['ns' . (count($this->namespaces) + 1)] = $v;
  4850. }
  4851. if ($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema') {
  4852. $this->XMLSchemaVersion = $v;
  4853. $this->namespaces['xsi'] = $v . '-instance';
  4854. }
  4855. }
  4856. }
  4857. // expand each attribute prefix to its namespace
  4858. foreach($attrs as $k => $v) {
  4859. $k = strpos($k, ':') ? $this->expandQname($k) : $k;
  4860. if ($k != 'location' && $k != 'soapAction' && $k != 'namespace') {
  4861. $v = strpos($v, ':') ? $this->expandQname($v) : $v;
  4862. }
  4863. $eAttrs[$k] = $v;
  4864. }
  4865. $attrs = $eAttrs;
  4866. } else {
  4867. $attrs = array();
  4868. }
  4869. // get element prefix, namespace and name
  4870. if (preg_match('/:/', $name)) {
  4871. // get ns prefix
  4872. $prefix = substr($name, 0, strpos($name, ':'));
  4873. // get ns
  4874. $namespace = isset($this->namespaces[$prefix]) ? $this->namespaces[$prefix] : '';
  4875. // get unqualified name
  4876. $name = substr(strstr($name, ':'), 1);
  4877. }
  4878. // process attributes, expanding any prefixes to namespaces
  4879. // find status, register data
  4880. switch ($this->status) {
  4881. case 'message':
  4882. if ($name == 'part') {
  4883. if (isset($attrs['type'])) {
  4884. $this->debug("msg " . $this->currentMessage . ": found part (with type) $attrs[name]: " . implode(',', $attrs));
  4885. $this->messages[$this->currentMessage][$attrs['name']] = $attrs['type'];
  4886. }
  4887. if (isset($attrs['element'])) {
  4888. $this->debug("msg " . $this->currentMessage . ": found part (with element) $attrs[name]: " . implode(',', $attrs));
  4889. $this->messages[$this->currentMessage][$attrs['name']] = $attrs['element'] . '^';
  4890. }
  4891. }
  4892. break;
  4893. case 'portType':
  4894. switch ($name) {
  4895. case 'operation':
  4896. $this->currentPortOperation = $attrs['name'];
  4897. $this->debug("portType $this->currentPortType operation: $this->currentPortOperation");
  4898. if (isset($attrs['parameterOrder'])) {
  4899. $this->portTypes[$this->currentPortType][$attrs['name']]['parameterOrder'] = $attrs['parameterOrder'];
  4900. }
  4901. break;
  4902. case 'documentation':
  4903. $this->documentation = true;
  4904. break;
  4905. // merge input/output data
  4906. default:
  4907. $m = isset($attrs['message']) ? $this->getLocalPart($attrs['message']) : '';
  4908. $this->portTypes[$this->currentPortType][$this->currentPortOperation][$name]['message'] = $m;
  4909. break;
  4910. }
  4911. break;
  4912. case 'binding':
  4913. switch ($name) {
  4914. case 'binding':
  4915. // get ns prefix
  4916. if (isset($attrs['style'])) {
  4917. $this->bindings[$this->currentBinding]['prefix'] = $prefix;
  4918. }
  4919. $this->bindings[$this->currentBinding] = array_merge($this->bindings[$this->currentBinding], $attrs);
  4920. break;
  4921. case 'header':
  4922. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs;
  4923. break;
  4924. case 'operation':
  4925. if (isset($attrs['soapAction'])) {
  4926. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['soapAction'] = $attrs['soapAction'];
  4927. }
  4928. if (isset($attrs['style'])) {
  4929. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['style'] = $attrs['style'];
  4930. }
  4931. if (isset($attrs['name'])) {
  4932. $this->currentOperation = $attrs['name'];
  4933. $this->debug("current binding operation: $this->currentOperation");
  4934. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['name'] = $attrs['name'];
  4935. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['binding'] = $this->currentBinding;
  4936. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['endpoint'] = isset($this->bindings[$this->currentBinding]['endpoint']) ? $this->bindings[$this->currentBinding]['endpoint'] : '';
  4937. }
  4938. break;
  4939. case 'input':
  4940. $this->opStatus = 'input';
  4941. break;
  4942. case 'output':
  4943. $this->opStatus = 'output';
  4944. break;
  4945. case 'body':
  4946. if (isset($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus])) {
  4947. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = array_merge($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus], $attrs);
  4948. } else {
  4949. $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = $attrs;
  4950. }
  4951. break;
  4952. }
  4953. break;
  4954. case 'service':
  4955. switch ($name) {
  4956. case 'port':
  4957. $this->currentPort = $attrs['name'];
  4958. $this->debug('current port: ' . $this->currentPort);
  4959. $this->ports[$this->currentPort]['binding'] = $this->getLocalPart($attrs['binding']);
  4960. break;
  4961. case 'address':
  4962. $this->ports[$this->currentPort]['location'] = $attrs['location'];
  4963. $this->ports[$this->currentPort]['bindingType'] = $namespace;
  4964. $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['bindingType'] = $namespace;
  4965. $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['endpoint'] = $attrs['location'];
  4966. break;
  4967. }
  4968. break;
  4969. }
  4970. // set status
  4971. switch ($name) {
  4972. case 'import':
  4973. if (isset($attrs['location'])) {
  4974. $this->import[$attrs['namespace']][] = array('location' => $attrs['location'], 'loaded' => false);
  4975. $this->debug('parsing import ' . $attrs['namespace']. ' - ' . $attrs['location'] . ' (' . count($this->import[$attrs['namespace']]).')');
  4976. } else {
  4977. $this->import[$attrs['namespace']][] = array('location' => '', 'loaded' => true);
  4978. if (! $this->getPrefixFromNamespace($attrs['namespace'])) {
  4979. $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace'];
  4980. }
  4981. $this->debug('parsing import ' . $attrs['namespace']. ' - [no location] (' . count($this->import[$attrs['namespace']]).')');
  4982. }
  4983. break;
  4984. //wait for schema
  4985. //case 'types':
  4986. // $this->status = 'schema';
  4987. // break;
  4988. case 'message':
  4989. $this->status = 'message';
  4990. $this->messages[$attrs['name']] = array();
  4991. $this->currentMessage = $attrs['name'];
  4992. break;
  4993. case 'portType':
  4994. $this->status = 'portType';
  4995. $this->portTypes[$attrs['name']] = array();
  4996. $this->currentPortType = $attrs['name'];
  4997. break;
  4998. case "binding":
  4999. if (isset($attrs['name'])) {
  5000. // get binding name
  5001. if (strpos($attrs['name'], ':')) {
  5002. $this->currentBinding = $this->getLocalPart($attrs['name']);
  5003. } else {
  5004. $this->currentBinding = $attrs['name'];
  5005. }
  5006. $this->status = 'binding';
  5007. $this->bindings[$this->currentBinding]['portType'] = $this->getLocalPart($attrs['type']);
  5008. $this->debug("current binding: $this->currentBinding of portType: " . $attrs['type']);
  5009. }
  5010. break;
  5011. case 'service':
  5012. $this->serviceName = $attrs['name'];
  5013. $this->status = 'service';
  5014. $this->debug('current service: ' . $this->serviceName);
  5015. break;
  5016. case 'definitions':
  5017. foreach ($attrs as $name => $value) {
  5018. $this->wsdl_info[$name] = $value;
  5019. }
  5020. break;
  5021. }
  5022. }
  5023. }
  5024.  
  5025. /**
  5026. * end-element handler
  5027. *
  5028. * @param string $parser XML parser object
  5029. * @param string $name element name
  5030. * @access private
  5031. */
  5032. function end_element($parser, $name){
  5033. // unset schema status
  5034. if (/*preg_match('/types$/', $name) ||*/ preg_match('/schema$/', $name)) {
  5035. $this->status = "";
  5036. $this->appendDebug($this->currentSchema->getDebug());
  5037. $this->currentSchema->clearDebug();
  5038. $this->schemas[$this->currentSchema->schemaTargetNamespace][] = $this->currentSchema;
  5039. $this->debug('Parsing WSDL schema done');
  5040. }
  5041. if ($this->status == 'schema') {
  5042. $this->currentSchema->schemaEndElement($parser, $name);
  5043. } else {
  5044. // bring depth down a notch
  5045. $this->depth--;
  5046. }
  5047. // end documentation
  5048. if ($this->documentation) {
  5049. //TODO: track the node to which documentation should be assigned; it can be a part, message, etc.
  5050. //$this->portTypes[$this->currentPortType][$this->currentPortOperation]['documentation'] = $this->documentation;
  5051. $this->documentation = false;
  5052. }
  5053. }
  5054.  
  5055. /**
  5056. * element content handler
  5057. *
  5058. * @param string $parser XML parser object
  5059. * @param string $data element content
  5060. * @access private
  5061. */
  5062. function character_data($parser, $data)
  5063. {
  5064. $pos = isset($this->depth_array[$this->depth]) ? $this->depth_array[$this->depth] : 0;
  5065. if (isset($this->message[$pos]['cdata'])) {
  5066. $this->message[$pos]['cdata'] .= $data;
  5067. }
  5068. if ($this->documentation) {
  5069. $this->documentation .= $data;
  5070. }
  5071. }
  5072.  
  5073. /**
  5074. * if authenticating, set user credentials here
  5075. *
  5076. * @param string $username
  5077. * @param string $password
  5078. * @param string $authtype (basic|digest|certificate|ntlm)
  5079. * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
  5080. * @access public
  5081. */
  5082. function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) {
  5083. $this->debug("setCredentials username=$username authtype=$authtype certRequest=");
  5084. $this->appendDebug($this->varDump($certRequest));
  5085. $this->username = $username;
  5086. $this->password = $password;
  5087. $this->authtype = $authtype;
  5088. $this->certRequest = $certRequest;
  5089. }
  5090. function getBindingData($binding)
  5091. {
  5092. if (is_array($this->bindings[$binding])) {
  5093. return $this->bindings[$binding];
  5094. }
  5095. }
  5096. /**
  5097. * returns an assoc array of operation names => operation data
  5098. *
  5099. * @param string $portName WSDL port name
  5100. * @param string $bindingType eg: soap, smtp, dime (only soap and soap12 are currently supported)
  5101. * @return array
  5102. * @access public
  5103. */
  5104. function getOperations($portName = '', $bindingType = 'soap') {
  5105. $ops = array();
  5106. if ($bindingType == 'soap') {
  5107. $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
  5108. } elseif ($bindingType == 'soap12') {
  5109. $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
  5110. } else {
  5111. $this->debug("getOperations bindingType $bindingType may not be supported");
  5112. }
  5113. $this->debug("getOperations for port '$portName' bindingType $bindingType");
  5114. // loop thru ports
  5115. foreach($this->ports as $port => $portData) {
  5116. $this->debug("getOperations checking port $port bindingType " . $portData['bindingType']);
  5117. if ($portName == '' || $port == $portName) {
  5118. // binding type of port matches parameter
  5119. if ($portData['bindingType'] == $bindingType) {
  5120. $this->debug("getOperations found port $port bindingType $bindingType");
  5121. //$this->debug("port data: " . $this->varDump($portData));
  5122. //$this->debug("bindings: " . $this->varDump($this->bindings[ $portData['binding'] ]));
  5123. // merge bindings
  5124. if (isset($this->bindings[ $portData['binding'] ]['operations'])) {
  5125. $ops = array_merge ($ops, $this->bindings[ $portData['binding'] ]['operations']);
  5126. }
  5127. }
  5128. }
  5129. }
  5130. if (count($ops) == 0) {
  5131. $this->debug("getOperations found no operations for port '$portName' bindingType $bindingType");
  5132. }
  5133. return $ops;
  5134. }
  5135. /**
  5136. * returns an associative array of data necessary for calling an operation
  5137. *
  5138. * @param string $operation name of operation
  5139. * @param string $bindingType type of binding eg: soap, soap12
  5140. * @return array
  5141. * @access public
  5142. */
  5143. function getOperationData($operation, $bindingType = 'soap')
  5144. {
  5145. if ($bindingType == 'soap') {
  5146. $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
  5147. } elseif ($bindingType == 'soap12') {
  5148. $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
  5149. }
  5150. // loop thru ports
  5151. foreach($this->ports as $port => $portData) {
  5152. // binding type of port matches parameter
  5153. if ($portData['bindingType'] == $bindingType) {
  5154. // get binding
  5155. //foreach($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
  5156. foreach(array_keys($this->bindings[ $portData['binding'] ]['operations']) as $bOperation) {
  5157. // note that we could/should also check the namespace here
  5158. if ($operation == $bOperation) {
  5159. $opData = $this->bindings[ $portData['binding'] ]['operations'][$operation];
  5160. return $opData;
  5161. }
  5162. }
  5163. }
  5164. }
  5165. }
  5166. /**
  5167. * returns an associative array of data necessary for calling an operation
  5168. *
  5169. * @param string $soapAction soapAction for operation
  5170. * @param string $bindingType type of binding eg: soap, soap12
  5171. * @return array
  5172. * @access public
  5173. */
  5174. function getOperationDataForSoapAction($soapAction, $bindingType = 'soap') {
  5175. if ($bindingType == 'soap') {
  5176. $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
  5177. } elseif ($bindingType == 'soap12') {
  5178. $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
  5179. }
  5180. // loop thru ports
  5181. foreach($this->ports as $port => $portData) {
  5182. // binding type of port matches parameter
  5183. if ($portData['bindingType'] == $bindingType) {
  5184. // loop through operations for the binding
  5185. foreach ($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
  5186. if ($opData['soapAction'] == $soapAction) {
  5187. return $opData;
  5188. }
  5189. }
  5190. }
  5191. }
  5192. }
  5193. /**
  5194. * returns an array of information about a given type
  5195. * returns false if no type exists by the given name
  5196. *
  5197. * typeDef = array(
  5198. * 'elements' => array(), // refs to elements array
  5199. * 'restrictionBase' => '',
  5200. * 'phpType' => '',
  5201. * 'order' => '(sequence|all)',
  5202. * 'attrs' => array() // refs to attributes array
  5203. * )
  5204. *
  5205. * @param string $type the type
  5206. * @param string $ns namespace (not prefix) of the type
  5207. * @return mixed
  5208. * @access public
  5209. * @see nusoap_xmlschema
  5210. */
  5211. function getTypeDef($type, $ns) {
  5212. $this->debug("in getTypeDef: type=$type, ns=$ns");
  5213. if ((! $ns) && isset($this->namespaces['tns'])) {
  5214. $ns = $this->namespaces['tns'];
  5215. $this->debug("in getTypeDef: type namespace forced to $ns");
  5216. }
  5217. if (!isset($this->schemas[$ns])) {
  5218. foreach ($this->schemas as $ns0 => $schema0) {
  5219. if (strcasecmp($ns, $ns0) == 0) {
  5220. $this->debug("in getTypeDef: replacing schema namespace $ns with $ns0");
  5221. $ns = $ns0;
  5222. break;
  5223. }
  5224. }
  5225. }
  5226. if (isset($this->schemas[$ns])) {
  5227. $this->debug("in getTypeDef: have schema for namespace $ns");
  5228. for ($i = 0; $i < count($this->schemas[$ns]); $i++) {
  5229. $xs = &$this->schemas[$ns][$i];
  5230. $t = $xs->getTypeDef($type);
  5231. $this->appendDebug($xs->getDebug());
  5232. $xs->clearDebug();
  5233. if ($t) {
  5234. $this->debug("in getTypeDef: found type $type");
  5235. if (!isset($t['phpType'])) {
  5236. // get info for type to tack onto the element
  5237. $uqType = substr($t['type'], strrpos($t['type'], ':') + 1);
  5238. $ns = substr($t['type'], 0, strrpos($t['type'], ':'));
  5239. $etype = $this->getTypeDef($uqType, $ns);
  5240. if ($etype) {
  5241. $this->debug("found type for [element] $type:");
  5242. $this->debug($this->varDump($etype));
  5243. if (isset($etype['phpType'])) {
  5244. $t['phpType'] = $etype['phpType'];
  5245. }
  5246. if (isset($etype['elements'])) {
  5247. $t['elements'] = $etype['elements'];
  5248. }
  5249. if (isset($etype['attrs'])) {
  5250. $t['attrs'] = $etype['attrs'];
  5251. }
  5252. } else {
  5253. $this->debug("did not find type for [element] $type");
  5254. }
  5255. }
  5256. return $t;
  5257. }
  5258. }
  5259. $this->debug("in getTypeDef: did not find type $type");
  5260. } else {
  5261. $this->debug("in getTypeDef: do not have schema for namespace $ns");
  5262. }
  5263. return false;
  5264. }
  5265.  
  5266. /**
  5267. * prints html description of services
  5268. *
  5269. * @access private
  5270. */
  5271. function webDescription(){
  5272. global $HTTP_SERVER_VARS;
  5273.  
  5274. if (isset($_SERVER)) {
  5275. $PHP_SELF = $_SERVER['PHP_SELF'];
  5276. } elseif (isset($HTTP_SERVER_VARS)) {
  5277. $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
  5278. } else {
  5279. $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
  5280. }
  5281.  
  5282. $b = '
  5283. <html><head><title>NuSOAP: '.$this->serviceName.'</title>
  5284. <style type="text/css">
  5285. body { font-family: arial; color: #000000; background-color: #ffffff; margin: 0px 0px 0px 0px; }
  5286. p { font-family: arial; color: #000000; margin-top: 0px; margin-bottom: 12px; }
  5287. pre { background-color: silver; padding: 5px; font-family: Courier New; font-size: x-small; color: #000000;}
  5288. ul { margin-top: 10px; margin-left: 20px; }
  5289. li { list-style-type: none; margin-top: 10px; color: #000000; }
  5290. .content{
  5291. margin-left: 0px; padding-bottom: 2em; }
  5292. .nav {
  5293. padding-top: 10px; padding-bottom: 10px; padding-left: 15px; font-size: .70em;
  5294. margin-top: 10px; margin-left: 0px; color: #000000;
  5295. background-color: #ccccff; width: 20%; margin-left: 20px; margin-top: 20px; }
  5296. .title {
  5297. font-family: arial; font-size: 26px; color: #ffffff;
  5298. background-color: #999999; width: 100%;
  5299. margin-left: 0px; margin-right: 0px;
  5300. padding-top: 10px; padding-bottom: 10px;}
  5301. .hidden {
  5302. position: absolute; visibility: hidden; z-index: 200; left: 250px; top: 100px;
  5303. font-family: arial; overflow: hidden; width: 600;
  5304. padding: 20px; font-size: 10px; background-color: #999999;
  5305. layer-background-color:#FFFFFF; }
  5306. a,a:active { color: charcoal; font-weight: bold; }
  5307. a:visited { color: #666666; font-weight: bold; }
  5308. a:hover { color: cc3300; font-weight: bold; }
  5309. </style>
  5310. <script language="JavaScript" type="text/javascript">
  5311. <!--
  5312. // POP-UP CAPTIONS...
  5313. function lib_bwcheck(){ //Browsercheck (needed)
  5314. this.ver=navigator.appVersion
  5315. this.agent=navigator.userAgent
  5316. this.dom=document.getElementById?1:0
  5317. this.opera5=this.agent.indexOf("Opera 5")>-1
  5318. this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0;
  5319. this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
  5320. this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
  5321. this.ie=this.ie4||this.ie5||this.ie6
  5322. this.mac=this.agent.indexOf("Mac")>-1
  5323. this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0;
  5324. this.ns4=(document.layers && !this.dom)?1:0;
  5325. this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5)
  5326. return this
  5327. }
  5328. var bw = new lib_bwcheck()
  5329. //Makes crossbrowser object.
  5330. function makeObj(obj){
  5331. this.evnt=bw.dom? document.getElementById(obj):bw.ie4?document.all[obj]:bw.ns4?document.layers[obj]:0;
  5332. if(!this.evnt) return false
  5333. this.css=bw.dom||bw.ie4?this.evnt.style:bw.ns4?this.evnt:0;
  5334. this.wref=bw.dom||bw.ie4?this.evnt:bw.ns4?this.css.document:0;
  5335. this.writeIt=b_writeIt;
  5336. return this
  5337. }
  5338. // A unit of measure that will be added when setting the position of a layer.
  5339. //var px = bw.ns4||window.opera?"":"px";
  5340. function b_writeIt(text){
  5341. if (bw.ns4){this.wref.write(text);this.wref.close()}
  5342. else this.wref.innerHTML = text
  5343. }
  5344. //Shows the messages
  5345. var oDesc;
  5346. function popup(divid){
  5347. if(oDesc = new makeObj(divid)){
  5348. oDesc.css.visibility = "visible"
  5349. }
  5350. }
  5351. function popout(){ // Hides message
  5352. if(oDesc) oDesc.css.visibility = "hidden"
  5353. }
  5354. //-->
  5355. </script>
  5356. </head>
  5357. <body>
  5358. <div class=content>
  5359. <br><br>
  5360. <div class=title>'.$this->serviceName.'</div>
  5361. <div class=nav>
  5362. <p>View the <a href="'.$PHP_SELF.'?wsdl">WSDL</a> for the service.
  5363. Click on an operation name to view it&apos;s details.</p>
  5364. <ul>';
  5365. foreach($this->getOperations() as $op => $data){
  5366. $b .= "<li><a href='#' onclick=\"popout();popup('$op')\">$op</a></li>";
  5367. // create hidden div
  5368. $b .= "<div id='$op' class='hidden'>
  5369. <a href='#' onclick='popout()'><font color='#ffffff'>Close</font></a><br><br>";
  5370. foreach($data as $donnie => $marie){ // loop through opdata
  5371. if($donnie == 'input' || $donnie == 'output'){ // show input/output data
  5372. $b .= "<font color='white'>".ucfirst($donnie).':</font><br>';
  5373. foreach($marie as $captain => $tenille){ // loop through data
  5374. if($captain == 'parts'){ // loop thru parts
  5375. $b .= "&nbsp;&nbsp;$captain:<br>";
  5376. //if(is_array($tenille)){
  5377. foreach($tenille as $joanie => $chachi){
  5378. $b .= "&nbsp;&nbsp;&nbsp;&nbsp;$joanie: $chachi<br>";
  5379. }
  5380. //}
  5381. } else {
  5382. $b .= "&nbsp;&nbsp;$captain: $tenille<br>";
  5383. }
  5384. }
  5385. } else {
  5386. $b .= "<font color='white'>".ucfirst($donnie).":</font> $marie<br>";
  5387. }
  5388. }
  5389. $b .= '</div>';
  5390. }
  5391. $b .= '
  5392. <ul>
  5393. </div>
  5394. </div></body></html>';
  5395. return $b;
  5396. }
  5397.  
  5398. /**
  5399. * serialize the parsed wsdl
  5400. *
  5401. * @param mixed $debug whether to put debug=1 in endpoint URL
  5402. * @return string serialization of WSDL
  5403. * @access public
  5404. */
  5405. function serialize($debug = 0)
  5406. {
  5407. $xml = '<?xml version="1.0" encoding="ISO-8859-1"?>';
  5408. $xml .= "\n<definitions";
  5409. foreach($this->namespaces as $k => $v) {
  5410. $xml .= " xmlns:$k=\"$v\"";
  5411. }
  5412. // 10.9.02 - add poulter fix for wsdl and tns declarations
  5413. if (isset($this->namespaces['wsdl'])) {
  5414. $xml .= " xmlns=\"" . $this->namespaces['wsdl'] . "\"";
  5415. }
  5416. if (isset($this->namespaces['tns'])) {
  5417. $xml .= " targetNamespace=\"" . $this->namespaces['tns'] . "\"";
  5418. }
  5419. $xml .= '>';
  5420. // imports
  5421. if (sizeof($this->import) > 0) {
  5422. foreach($this->import as $ns => $list) {
  5423. foreach ($list as $ii) {
  5424. if ($ii['location'] != '') {
  5425. $xml .= '<import location="' . $ii['location'] . '" namespace="' . $ns . '" />';
  5426. } else {
  5427. $xml .= '<import namespace="' . $ns . '" />';
  5428. }
  5429. }
  5430. }
  5431. }
  5432. // types
  5433. if (count($this->schemas)>=1) {
  5434. $xml .= "\n<types>\n";
  5435. foreach ($this->schemas as $ns => $list) {
  5436. foreach ($list as $xs) {
  5437. $xml .= $xs->serializeSchema();
  5438. }
  5439. }
  5440. $xml .= '</types>';
  5441. }
  5442. // messages
  5443. if (count($this->messages) >= 1) {
  5444. foreach($this->messages as $msgName => $msgParts) {
  5445. $xml .= "\n<message name=\"" . $msgName . '">';
  5446. if(is_array($msgParts)){
  5447. foreach($msgParts as $partName => $partType) {
  5448. // print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'<br>';
  5449. if (strpos($partType, ':')) {
  5450. $typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType));
  5451. } elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) {
  5452. // print 'checking typemap: '.$this->XMLSchemaVersion.'<br>';
  5453. $typePrefix = 'xsd';
  5454. } else {
  5455. foreach($this->typemap as $ns => $types) {
  5456. if (isset($types[$partType])) {
  5457. $typePrefix = $this->getPrefixFromNamespace($ns);
  5458. }
  5459. }
  5460. if (!isset($typePrefix)) {
  5461. die("$partType has no namespace!");
  5462. }
  5463. }
  5464. $ns = $this->getNamespaceFromPrefix($typePrefix);
  5465. $localPart = $this->getLocalPart($partType);
  5466. $typeDef = $this->getTypeDef($localPart, $ns);
  5467. if ($typeDef['typeClass'] == 'element') {
  5468. $elementortype = 'element';
  5469. if (substr($localPart, -1) == '^') {
  5470. $localPart = substr($localPart, 0, -1);
  5471. }
  5472. } else {
  5473. $elementortype = 'type';
  5474. }
  5475. $xml .= "\n" . ' <part name="' . $partName . '" ' . $elementortype . '="' . $typePrefix . ':' . $localPart . '" />';
  5476. }
  5477. }
  5478. $xml .= '</message>';
  5479. }
  5480. }
  5481. // bindings & porttypes
  5482. if (count($this->bindings) >= 1) {
  5483. $binding_xml = '';
  5484. $portType_xml = '';
  5485. foreach($this->bindings as $bindingName => $attrs) {
  5486. $binding_xml .= "\n<binding name=\"" . $bindingName . '" type="tns:' . $attrs['portType'] . '">';
  5487. $binding_xml .= "\n" . ' <soap:binding style="' . $attrs['style'] . '" transport="' . $attrs['transport'] . '"/>';
  5488. $portType_xml .= "\n<portType name=\"" . $attrs['portType'] . '">';
  5489. foreach($attrs['operations'] as $opName => $opParts) {
  5490. $binding_xml .= "\n" . ' <operation name="' . $opName . '">';
  5491. $binding_xml .= "\n" . ' <soap:operation soapAction="' . $opParts['soapAction'] . '" style="'. $opParts['style'] . '"/>';
  5492. if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') {
  5493. $enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"';
  5494. } else {
  5495. $enc_style = '';
  5496. }
  5497. $binding_xml .= "\n" . ' <input><soap:body use="' . $opParts['input']['use'] . '" namespace="' . $opParts['input']['namespace'] . '"' . $enc_style . '/></input>';
  5498. if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') {
  5499. $enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"';
  5500. } else {
  5501. $enc_style = '';
  5502. }
  5503. $binding_xml .= "\n" . ' <output><soap:body use="' . $opParts['output']['use'] . '" namespace="' . $opParts['output']['namespace'] . '"' . $enc_style . '/></output>';
  5504. $binding_xml .= "\n" . ' </operation>';
  5505. $portType_xml .= "\n" . ' <operation name="' . $opParts['name'] . '"';
  5506. if (isset($opParts['parameterOrder'])) {
  5507. $portType_xml .= ' parameterOrder="' . $opParts['parameterOrder'] . '"';
  5508. }
  5509. $portType_xml .= '>';
  5510. if(isset($opParts['documentation']) && $opParts['documentation'] != '') {
  5511. $portType_xml .= "\n" . ' <documentation>' . htmlspecialchars($opParts['documentation']) . '</documentation>';
  5512. }
  5513. $portType_xml .= "\n" . ' <input message="tns:' . $opParts['input']['message'] . '"/>';
  5514. $portType_xml .= "\n" . ' <output message="tns:' . $opParts['output']['message'] . '"/>';
  5515. $portType_xml .= "\n" . ' </operation>';
  5516. }
  5517. $portType_xml .= "\n" . '</portType>';
  5518. $binding_xml .= "\n" . '</binding>';
  5519. }
  5520. $xml .= $portType_xml . $binding_xml;
  5521. }
  5522. // services
  5523. $xml .= "\n<service name=\"" . $this->serviceName . '">';
  5524. if (count($this->ports) >= 1) {
  5525. foreach($this->ports as $pName => $attrs) {
  5526. $xml .= "\n" . ' <port name="' . $pName . '" binding="tns:' . $attrs['binding'] . '">';
  5527. $xml .= "\n" . ' <soap:address location="' . $attrs['location'] . ($debug ? '?debug=1' : '') . '"/>';
  5528. $xml .= "\n" . ' </port>';
  5529. }
  5530. }
  5531. $xml .= "\n" . '</service>';
  5532. return $xml . "\n</definitions>";
  5533. }
  5534.  
  5535. /**
  5536. * determine whether a set of parameters are unwrapped
  5537. * when they are expect to be wrapped, Microsoft-style.
  5538. *
  5539. * @param string $type the type (element name) of the wrapper
  5540. * @param array $parameters the parameter values for the SOAP call
  5541. * @return boolean whether they parameters are unwrapped (and should be wrapped)
  5542. * @access private
  5543. */
  5544. function parametersMatchWrapped($type, &$parameters) {
  5545. $this->debug("in parametersMatchWrapped type=$type, parameters=");
  5546. $this->appendDebug($this->varDump($parameters));
  5547.  
  5548. // split type into namespace:unqualified-type
  5549. if (strpos($type, ':')) {
  5550. $uqType = substr($type, strrpos($type, ':') + 1);
  5551. $ns = substr($type, 0, strrpos($type, ':'));
  5552. $this->debug("in parametersMatchWrapped: got a prefixed type: $uqType, $ns");
  5553. if ($this->getNamespaceFromPrefix($ns)) {
  5554. $ns = $this->getNamespaceFromPrefix($ns);
  5555. $this->debug("in parametersMatchWrapped: expanded prefixed type: $uqType, $ns");
  5556. }
  5557. } else {
  5558. // TODO: should the type be compared to types in XSD, and the namespace
  5559. // set to XSD if the type matches?
  5560. $this->debug("in parametersMatchWrapped: No namespace for type $type");
  5561. $ns = '';
  5562. $uqType = $type;
  5563. }
  5564.  
  5565. // get the type information
  5566. if (!$typeDef = $this->getTypeDef($uqType, $ns)) {
  5567. $this->debug("in parametersMatchWrapped: $type ($uqType) is not a supported type.");
  5568. return false;
  5569. }
  5570. $this->debug("in parametersMatchWrapped: found typeDef=");
  5571. $this->appendDebug($this->varDump($typeDef));
  5572. if (substr($uqType, -1) == '^') {
  5573. $uqType = substr($uqType, 0, -1);
  5574. }
  5575. $phpType = $typeDef['phpType'];
  5576. $arrayType = (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '');
  5577. $this->debug("in parametersMatchWrapped: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: $arrayType");
  5578. // we expect a complexType or element of complexType
  5579. if ($phpType != 'struct') {
  5580. $this->debug("in parametersMatchWrapped: not a struct");
  5581. return false;
  5582. }
  5583.  
  5584. // see whether the parameter names match the elements
  5585. if (isset($typeDef['elements']) && is_array($typeDef['elements'])) {
  5586. $elements = 0;
  5587. $matches = 0;
  5588. foreach ($typeDef['elements'] as $name => $attrs) {
  5589. if (isset($parameters[$name])) {
  5590. $this->debug("in parametersMatchWrapped: have parameter named $name");
  5591. $matches++;
  5592. } else {
  5593. $this->debug("in parametersMatchWrapped: do not have parameter named $name");
  5594. }
  5595. $elements++;
  5596. }
  5597.  
  5598. $this->debug("in parametersMatchWrapped: $matches parameter names match $elements wrapped parameter names");
  5599. if ($matches == 0) {
  5600. return false;
  5601. }
  5602. return true;
  5603. }
  5604.  
  5605. // since there are no elements for the type, if the user passed no
  5606. // parameters, the parameters match wrapped.
  5607. $this->debug("in parametersMatchWrapped: no elements type $ns:$uqType");
  5608. return count($parameters) == 0;
  5609. }
  5610.  
  5611. /**
  5612. * serialize PHP values according to a WSDL message definition
  5613. * contrary to the method name, this is not limited to RPC
  5614. *
  5615. * TODO
  5616. * - multi-ref serialization
  5617. * - validate PHP values against type definitions, return errors if invalid
  5618. *
  5619. * @param string $operation operation name
  5620. * @param string $direction (input|output)
  5621. * @param mixed $parameters parameter value(s)
  5622. * @param string $bindingType (soap|soap12)
  5623. * @return mixed parameters serialized as XML or false on error (e.g. operation not found)
  5624. * @access public
  5625. */
  5626. function serializeRPCParameters($operation, $direction, $parameters, $bindingType = 'soap') {
  5627. $this->debug("in serializeRPCParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion, bindingType=$bindingType");
  5628. $this->appendDebug('parameters=' . $this->varDump($parameters));
  5629. if ($direction != 'input' && $direction != 'output') {
  5630. $this->debug('The value of the \$direction argument needs to be either "input" or "output"');
  5631. $this->setError('The value of the \$direction argument needs to be either "input" or "output"');
  5632. return false;
  5633. }
  5634. if (!$opData = $this->getOperationData($operation, $bindingType)) {
  5635. $this->debug('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType);
  5636. $this->setError('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType);
  5637. return false;
  5638. }
  5639. $this->debug('in serializeRPCParameters: opData:');
  5640. $this->appendDebug($this->varDump($opData));
  5641.  
  5642. // Get encoding style for output and set to current
  5643. $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
  5644. if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
  5645. $encodingStyle = $opData['output']['encodingStyle'];
  5646. $enc_style = $encodingStyle;
  5647. }
  5648.  
  5649. // set input params
  5650. $xml = '';
  5651. if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
  5652. $parts = &$opData[$direction]['parts'];
  5653. $part_count = sizeof($parts);
  5654. $style = $opData['style'];
  5655. $use = $opData[$direction]['use'];
  5656. $this->debug("have $part_count part(s) to serialize using $style/$use");
  5657. if (is_array($parameters)) {
  5658. $parametersArrayType = $this->isArraySimpleOrStruct($parameters);
  5659. $parameter_count = count($parameters);
  5660. $this->debug("have $parameter_count parameter(s) provided as $parametersArrayType to serialize");
  5661. // check for Microsoft-style wrapped parameters
  5662. if ($style == 'document' && $use == 'literal' && $part_count == 1 && isset($parts['parameters'])) {
  5663. $this->debug('check whether the caller has wrapped the parameters');
  5664. if ($direction == 'output' && $parametersArrayType == 'arraySimple' && $parameter_count == 1) {
  5665. // TODO: consider checking here for double-wrapping, when
  5666. // service function wraps, then NuSOAP wraps again
  5667. $this->debug("change simple array to associative with 'parameters' element");
  5668. $parameters['parameters'] = $parameters[0];
  5669. unset($parameters[0]);
  5670. }
  5671. if (($parametersArrayType == 'arrayStruct' || $parameter_count == 0) && !isset($parameters['parameters'])) {
  5672. $this->debug('check whether caller\'s parameters match the wrapped ones');
  5673. if ($this->parametersMatchWrapped($parts['parameters'], $parameters)) {
  5674. $this->debug('wrap the parameters for the caller');
  5675. $parameters = array('parameters' => $parameters);
  5676. $parameter_count = 1;
  5677. }
  5678. }
  5679. }
  5680. foreach ($parts as $name => $type) {
  5681. $this->debug("serializing part $name of type $type");
  5682. // Track encoding style
  5683. if (isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
  5684. $encodingStyle = $opData[$direction]['encodingStyle'];
  5685. $enc_style = $encodingStyle;
  5686. } else {
  5687. $enc_style = false;
  5688. }
  5689. // NOTE: add error handling here
  5690. // if serializeType returns false, then catch global error and fault
  5691. if ($parametersArrayType == 'arraySimple') {
  5692. $p = array_shift($parameters);
  5693. $this->debug('calling serializeType w/indexed param');
  5694. $xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
  5695. } elseif (isset($parameters[$name])) {
  5696. $this->debug('calling serializeType w/named param');
  5697. $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
  5698. } else {
  5699. // TODO: only send nillable
  5700. $this->debug('calling serializeType w/null param');
  5701. $xml .= $this->serializeType($name, $type, null, $use, $enc_style);
  5702. }
  5703. }
  5704. } else {
  5705. $this->debug('no parameters passed.');
  5706. }
  5707. }
  5708. $this->debug("serializeRPCParameters returning: $xml");
  5709. return $xml;
  5710. }
  5711. /**
  5712. * serialize a PHP value according to a WSDL message definition
  5713. *
  5714. * TODO
  5715. * - multi-ref serialization
  5716. * - validate PHP values against type definitions, return errors if invalid
  5717. *
  5718. * @param string $operation operation name
  5719. * @param string $direction (input|output)
  5720. * @param mixed $parameters parameter value(s)
  5721. * @return mixed parameters serialized as XML or false on error (e.g. operation not found)
  5722. * @access public
  5723. * @deprecated
  5724. */
  5725. function serializeParameters($operation, $direction, $parameters)
  5726. {
  5727. $this->debug("in serializeParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion");
  5728. $this->appendDebug('parameters=' . $this->varDump($parameters));
  5729. if ($direction != 'input' && $direction != 'output') {
  5730. $this->debug('The value of the \$direction argument needs to be either "input" or "output"');
  5731. $this->setError('The value of the \$direction argument needs to be either "input" or "output"');
  5732. return false;
  5733. }
  5734. if (!$opData = $this->getOperationData($operation)) {
  5735. $this->debug('Unable to retrieve WSDL data for operation: ' . $operation);
  5736. $this->setError('Unable to retrieve WSDL data for operation: ' . $operation);
  5737. return false;
  5738. }
  5739. $this->debug('opData:');
  5740. $this->appendDebug($this->varDump($opData));
  5741. // Get encoding style for output and set to current
  5742. $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
  5743. if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
  5744. $encodingStyle = $opData['output']['encodingStyle'];
  5745. $enc_style = $encodingStyle;
  5746. }
  5747. // set input params
  5748. $xml = '';
  5749. if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
  5750. $use = $opData[$direction]['use'];
  5751. $this->debug("use=$use");
  5752. $this->debug('got ' . count($opData[$direction]['parts']) . ' part(s)');
  5753. if (is_array($parameters)) {
  5754. $parametersArrayType = $this->isArraySimpleOrStruct($parameters);
  5755. $this->debug('have ' . $parametersArrayType . ' parameters');
  5756. foreach($opData[$direction]['parts'] as $name => $type) {
  5757. $this->debug('serializing part "'.$name.'" of type "'.$type.'"');
  5758. // Track encoding style
  5759. if(isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
  5760. $encodingStyle = $opData[$direction]['encodingStyle'];
  5761. $enc_style = $encodingStyle;
  5762. } else {
  5763. $enc_style = false;
  5764. }
  5765. // NOTE: add error handling here
  5766. // if serializeType returns false, then catch global error and fault
  5767. if ($parametersArrayType == 'arraySimple') {
  5768. $p = array_shift($parameters);
  5769. $this->debug('calling serializeType w/indexed param');
  5770. $xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
  5771. } elseif (isset($parameters[$name])) {
  5772. $this->debug('calling serializeType w/named param');
  5773. $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
  5774. } else {
  5775. // TODO: only send nillable
  5776. $this->debug('calling serializeType w/null param');
  5777. $xml .= $this->serializeType($name, $type, null, $use, $enc_style);
  5778. }
  5779. }
  5780. } else {
  5781. $this->debug('no parameters passed.');
  5782. }
  5783. }
  5784. $this->debug("serializeParameters returning: $xml");
  5785. return $xml;
  5786. }
  5787. /**
  5788. * serializes a PHP value according a given type definition
  5789. *
  5790. * @param string $name name of value (part or element)
  5791. * @param string $type XML schema type of value (type or element)
  5792. * @param mixed $value a native PHP value (parameter value)
  5793. * @param string $use use for part (encoded|literal)
  5794. * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
  5795. * @param boolean $unqualified a kludge for what should be XML namespace form handling
  5796. * @return string value serialized as an XML string
  5797. * @access private
  5798. */
  5799. function serializeType($name, $type, $value, $use='encoded', $encodingStyle=false, $unqualified=false)
  5800. {
  5801. $this->debug("in serializeType: name=$name, type=$type, use=$use, encodingStyle=$encodingStyle, unqualified=" . ($unqualified ? "unqualified" : "qualified"));
  5802. $this->appendDebug("value=" . $this->varDump($value));
  5803. if($use == 'encoded' && $encodingStyle) {
  5804. $encodingStyle = ' SOAP-ENV:encodingStyle="' . $encodingStyle . '"';
  5805. }
  5806.  
  5807. // if a soapval has been supplied, let its type override the WSDL
  5808. if (is_object($value) && get_class($value) == 'soapval') {
  5809. if ($value->type_ns) {
  5810. $type = $value->type_ns . ':' . $value->type;
  5811. $forceType = true;
  5812. $this->debug("in serializeType: soapval overrides type to $type");
  5813. } elseif ($value->type) {
  5814. $type = $value->type;
  5815. $forceType = true;
  5816. $this->debug("in serializeType: soapval overrides type to $type");
  5817. } else {
  5818. $forceType = false;
  5819. $this->debug("in serializeType: soapval does not override type");
  5820. }
  5821. $attrs = $value->attributes;
  5822. $value = $value->value;
  5823. $this->debug("in serializeType: soapval overrides value to $value");
  5824. if ($attrs) {
  5825. if (!is_array($value)) {
  5826. $value['!'] = $value;
  5827. }
  5828. foreach ($attrs as $n => $v) {
  5829. $value['!' . $n] = $v;
  5830. }
  5831. $this->debug("in serializeType: soapval provides attributes");
  5832. }
  5833. } else {
  5834. $forceType = false;
  5835. }
  5836.  
  5837. $xml = '';
  5838. if (strpos($type, ':')) {
  5839. $uqType = substr($type, strrpos($type, ':') + 1);
  5840. $ns = substr($type, 0, strrpos($type, ':'));
  5841. $this->debug("in serializeType: got a prefixed type: $uqType, $ns");
  5842. if ($this->getNamespaceFromPrefix($ns)) {
  5843. $ns = $this->getNamespaceFromPrefix($ns);
  5844. $this->debug("in serializeType: expanded prefixed type: $uqType, $ns");
  5845. }
  5846.  
  5847. if($ns == $this->XMLSchemaVersion || $ns == 'http://schemas.xmlsoap.org/soap/encoding/'){
  5848. $this->debug('in serializeType: type namespace indicates XML Schema or SOAP Encoding type');
  5849. if ($unqualified && $use == 'literal') {
  5850. $elementNS = " xmlns=\"\"";
  5851. } else {
  5852. $elementNS = '';
  5853. }
  5854. if (is_null($value)) {
  5855. if ($use == 'literal') {
  5856. // TODO: depends on minOccurs
  5857. $xml = "<$name$elementNS/>";
  5858. } else {
  5859. // TODO: depends on nillable, which should be checked before calling this method
  5860. $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>";
  5861. }
  5862. $this->debug("in serializeType: returning: $xml");
  5863. return $xml;
  5864. }
  5865. if ($uqType == 'Array') {
  5866. // JBoss/Axis does this sometimes
  5867. return $this->serialize_val($value, $name, false, false, false, false, $use);
  5868. }
  5869. if ($uqType == 'boolean') {
  5870. if ((is_string($value) && $value == 'false') || (! $value)) {
  5871. $value = 'false';
  5872. } else {
  5873. $value = 'true';
  5874. }
  5875. }
  5876. if ($uqType == 'string' && gettype($value) == 'string') {
  5877. $value = $this->expandEntities($value);
  5878. }
  5879. if (($uqType == 'long' || $uqType == 'unsignedLong') && gettype($value) == 'double') {
  5880. $value = sprintf("%.0lf", $value);
  5881. }
  5882. // it's a scalar
  5883. // TODO: what about null/nil values?
  5884. // check type isn't a custom type extending xmlschema namespace
  5885. if (!$this->getTypeDef($uqType, $ns)) {
  5886. if ($use == 'literal') {
  5887. if ($forceType) {
  5888. $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value</$name>";
  5889. } else {
  5890. $xml = "<$name$elementNS>$value</$name>";
  5891. }
  5892. } else {
  5893. $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value</$name>";
  5894. }
  5895. $this->debug("in serializeType: returning: $xml");
  5896. return $xml;
  5897. }
  5898. $this->debug('custom type extends XML Schema or SOAP Encoding namespace (yuck)');
  5899. } else if ($ns == 'http://xml.apache.org/xml-soap') {
  5900. $this->debug('in serializeType: appears to be Apache SOAP type');
  5901. if ($uqType == 'Map') {
  5902. $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap');
  5903. if (! $tt_prefix) {
  5904. $this->debug('in serializeType: Add namespace for Apache SOAP type');
  5905. $tt_prefix = 'ns' . rand(1000, 9999);
  5906. $this->namespaces[$tt_prefix] = 'http://xml.apache.org/xml-soap';
  5907. // force this to be added to usedNamespaces
  5908. $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap');
  5909. }
  5910. $contents = '';
  5911. foreach($value as $k => $v) {
  5912. $this->debug("serializing map element: key $k, value $v");
  5913. $contents .= '<item>';
  5914. $contents .= $this->serialize_val($k,'key',false,false,false,false,$use);
  5915. $contents .= $this->serialize_val($v,'value',false,false,false,false,$use);
  5916. $contents .= '</item>';
  5917. }
  5918. if ($use == 'literal') {
  5919. if ($forceType) {
  5920. $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\">$contents</$name>";
  5921. } else {
  5922. $xml = "<$name>$contents</$name>";
  5923. }
  5924. } else {
  5925. $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\"$encodingStyle>$contents</$name>";
  5926. }
  5927. $this->debug("in serializeType: returning: $xml");
  5928. return $xml;
  5929. }
  5930. $this->debug('in serializeType: Apache SOAP type, but only support Map');
  5931. }
  5932. } else {
  5933. // TODO: should the type be compared to types in XSD, and the namespace
  5934. // set to XSD if the type matches?
  5935. $this->debug("in serializeType: No namespace for type $type");
  5936. $ns = '';
  5937. $uqType = $type;
  5938. }
  5939. if(!$typeDef = $this->getTypeDef($uqType, $ns)){
  5940. $this->setError("$type ($uqType) is not a supported type.");
  5941. $this->debug("in serializeType: $type ($uqType) is not a supported type.");
  5942. return false;
  5943. } else {
  5944. $this->debug("in serializeType: found typeDef");
  5945. $this->appendDebug('typeDef=' . $this->varDump($typeDef));
  5946. if (substr($uqType, -1) == '^') {
  5947. $uqType = substr($uqType, 0, -1);
  5948. }
  5949. }
  5950. if (!isset($typeDef['phpType'])) {
  5951. $this->setError("$type ($uqType) has no phpType.");
  5952. $this->debug("in serializeType: $type ($uqType) has no phpType.");
  5953. return false;
  5954. }
  5955. $phpType = $typeDef['phpType'];
  5956. $this->debug("in serializeType: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: " . (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '') );
  5957. // if php type == struct, map value to the <all> element names
  5958. if ($phpType == 'struct') {
  5959. if (isset($typeDef['typeClass']) && $typeDef['typeClass'] == 'element') {
  5960. $elementName = $uqType;
  5961. if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
  5962. $elementNS = " xmlns=\"$ns\"";
  5963. } else {
  5964. $elementNS = " xmlns=\"\"";
  5965. }
  5966. } else {
  5967. $elementName = $name;
  5968. if ($unqualified) {
  5969. $elementNS = " xmlns=\"\"";
  5970. } else {
  5971. $elementNS = '';
  5972. }
  5973. }
  5974. if (is_null($value)) {
  5975. if ($use == 'literal') {
  5976. // TODO: depends on minOccurs and nillable
  5977. $xml = "<$elementName$elementNS/>";
  5978. } else {
  5979. $xml = "<$elementName$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>";
  5980. }
  5981. $this->debug("in serializeType: returning: $xml");
  5982. return $xml;
  5983. }
  5984. if (is_object($value)) {
  5985. $value = get_object_vars($value);
  5986. }
  5987. if (is_array($value)) {
  5988. $elementAttrs = $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType);
  5989. if ($use == 'literal') {
  5990. if ($forceType) {
  5991. $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">";
  5992. } else {
  5993. $xml = "<$elementName$elementNS$elementAttrs>";
  5994. }
  5995. } else {
  5996. $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>";
  5997. }
  5998.  
  5999. if (isset($typeDef['simpleContent']) && $typeDef['simpleContent'] == 'true') {
  6000. if (isset($value['!'])) {
  6001. $xml .= $value['!'];
  6002. $this->debug("in serializeType: serialized simpleContent for type $type");
  6003. } else {
  6004. $this->debug("in serializeType: no simpleContent to serialize for type $type");
  6005. }
  6006. } else {
  6007. // complexContent
  6008. $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle);
  6009. }
  6010. $xml .= "</$elementName>";
  6011. } else {
  6012. $this->debug("in serializeType: phpType is struct, but value is not an array");
  6013. $this->setError("phpType is struct, but value is not an array: see debug output for details");
  6014. $xml = '';
  6015. }
  6016. } elseif ($phpType == 'array') {
  6017. if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
  6018. $elementNS = " xmlns=\"$ns\"";
  6019. } else {
  6020. if ($unqualified) {
  6021. $elementNS = " xmlns=\"\"";
  6022. } else {
  6023. $elementNS = '';
  6024. }
  6025. }
  6026. if (is_null($value)) {
  6027. if ($use == 'literal') {
  6028. // TODO: depends on minOccurs
  6029. $xml = "<$name$elementNS/>";
  6030. } else {
  6031. $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" .
  6032. $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .
  6033. ":Array\" " .
  6034. $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .
  6035. ':arrayType="' .
  6036. $this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) .
  6037. ':' .
  6038. $this->getLocalPart($typeDef['arrayType'])."[0]\"/>";
  6039. }
  6040. $this->debug("in serializeType: returning: $xml");
  6041. return $xml;
  6042. }
  6043. if (isset($typeDef['multidimensional'])) {
  6044. $nv = array();
  6045. foreach($value as $v) {
  6046. $cols = ',' . sizeof($v);
  6047. $nv = array_merge($nv, $v);
  6048. }
  6049. $value = $nv;
  6050. } else {
  6051. $cols = '';
  6052. }
  6053. if (is_array($value) && sizeof($value) >= 1) {
  6054. $rows = sizeof($value);
  6055. $contents = '';
  6056. foreach($value as $k => $v) {
  6057. $this->debug("serializing array element: $k, $v of type: $typeDef[arrayType]");
  6058. //if (strpos($typeDef['arrayType'], ':') ) {
  6059. if (!in_array($typeDef['arrayType'],$this->typemap['http://www.w3.org/2001/XMLSchema'])) {
  6060. $contents .= $this->serializeType('item', $typeDef['arrayType'], $v, $use);
  6061. } else {
  6062. $contents .= $this->serialize_val($v, 'item', $typeDef['arrayType'], null, $this->XMLSchemaVersion, false, $use);
  6063. }
  6064. }
  6065. } else {
  6066. $rows = 0;
  6067. $contents = null;
  6068. }
  6069. // TODO: for now, an empty value will be serialized as a zero element
  6070. // array. Revisit this when coding the handling of null/nil values.
  6071. if ($use == 'literal') {
  6072. $xml = "<$name$elementNS>"
  6073. .$contents
  6074. ."</$name>";
  6075. } else {
  6076. $xml = "<$name$elementNS xsi:type=\"".$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/').':Array" '.
  6077. $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/')
  6078. .':arrayType="'
  6079. .$this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType']))
  6080. .":".$this->getLocalPart($typeDef['arrayType'])."[$rows$cols]\">"
  6081. .$contents
  6082. ."</$name>";
  6083. }
  6084. } elseif ($phpType == 'scalar') {
  6085. if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
  6086. $elementNS = " xmlns=\"$ns\"";
  6087. } else {
  6088. if ($unqualified) {
  6089. $elementNS = " xmlns=\"\"";
  6090. } else {
  6091. $elementNS = '';
  6092. }
  6093. }
  6094. if ($use == 'literal') {
  6095. if ($forceType) {
  6096. $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value</$name>";
  6097. } else {
  6098. $xml = "<$name$elementNS>$value</$name>";
  6099. }
  6100. } else {
  6101. $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value</$name>";
  6102. }
  6103. }
  6104. $this->debug("in serializeType: returning: $xml");
  6105. return $xml;
  6106. }
  6107. /**
  6108. * serializes the attributes for a complexType
  6109. *
  6110. * @param array $typeDef our internal representation of an XML schema type (or element)
  6111. * @param mixed $value a native PHP value (parameter value)
  6112. * @param string $ns the namespace of the type
  6113. * @param string $uqType the local part of the type
  6114. * @return string value serialized as an XML string
  6115. * @access private
  6116. */
  6117. function serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType) {
  6118. $this->debug("serializeComplexTypeAttributes for XML Schema type $ns:$uqType");
  6119. $xml = '';
  6120. if (isset($typeDef['extensionBase'])) {
  6121. $nsx = $this->getPrefix($typeDef['extensionBase']);
  6122. $uqTypex = $this->getLocalPart($typeDef['extensionBase']);
  6123. if ($this->getNamespaceFromPrefix($nsx)) {
  6124. $nsx = $this->getNamespaceFromPrefix($nsx);
  6125. }
  6126. if ($typeDefx = $this->getTypeDef($uqTypex, $nsx)) {
  6127. $this->debug("serialize attributes for extension base $nsx:$uqTypex");
  6128. $xml .= $this->serializeComplexTypeAttributes($typeDefx, $value, $nsx, $uqTypex);
  6129. } else {
  6130. $this->debug("extension base $nsx:$uqTypex is not a supported type");
  6131. }
  6132. }
  6133. if (isset($typeDef['attrs']) && is_array($typeDef['attrs'])) {
  6134. $this->debug("serialize attributes for XML Schema type $ns:$uqType");
  6135. if (is_array($value)) {
  6136. $xvalue = $value;
  6137. } elseif (is_object($value)) {
  6138. $xvalue = get_object_vars($value);
  6139. } else {
  6140. $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
  6141. $xvalue = array();
  6142. }
  6143. foreach ($typeDef['attrs'] as $aName => $attrs) {
  6144. if (isset($xvalue['!' . $aName])) {
  6145. $xname = '!' . $aName;
  6146. $this->debug("value provided for attribute $aName with key $xname");
  6147. } elseif (isset($xvalue[$aName])) {
  6148. $xname = $aName;
  6149. $this->debug("value provided for attribute $aName with key $xname");
  6150. } elseif (isset($attrs['default'])) {
  6151. $xname = '!' . $aName;
  6152. $xvalue[$xname] = $attrs['default'];
  6153. $this->debug('use default value of ' . $xvalue[$aName] . ' for attribute ' . $aName);
  6154. } else {
  6155. $xname = '';
  6156. $this->debug("no value provided for attribute $aName");
  6157. }
  6158. if ($xname) {
  6159. $xml .= " $aName=\"" . $this->expandEntities($xvalue[$xname]) . "\"";
  6160. }
  6161. }
  6162. } else {
  6163. $this->debug("no attributes to serialize for XML Schema type $ns:$uqType");
  6164. }
  6165. return $xml;
  6166. }
  6167.  
  6168. /**
  6169. * serializes the elements for a complexType
  6170. *
  6171. * @param array $typeDef our internal representation of an XML schema type (or element)
  6172. * @param mixed $value a native PHP value (parameter value)
  6173. * @param string $ns the namespace of the type
  6174. * @param string $uqType the local part of the type
  6175. * @param string $use use for part (encoded|literal)
  6176. * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
  6177. * @return string value serialized as an XML string
  6178. * @access private
  6179. */
  6180. function serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use='encoded', $encodingStyle=false) {
  6181. $this->debug("in serializeComplexTypeElements for XML Schema type $ns:$uqType");
  6182. $xml = '';
  6183. if (isset($typeDef['extensionBase'])) {
  6184. $nsx = $this->getPrefix($typeDef['extensionBase']);
  6185. $uqTypex = $this->getLocalPart($typeDef['extensionBase']);
  6186. if ($this->getNamespaceFromPrefix($nsx)) {
  6187. $nsx = $this->getNamespaceFromPrefix($nsx);
  6188. }
  6189. if ($typeDefx = $this->getTypeDef($uqTypex, $nsx)) {
  6190. $this->debug("serialize elements for extension base $nsx:$uqTypex");
  6191. $xml .= $this->serializeComplexTypeElements($typeDefx, $value, $nsx, $uqTypex, $use, $encodingStyle);
  6192. } else {
  6193. $this->debug("extension base $nsx:$uqTypex is not a supported type");
  6194. }
  6195. }
  6196. if (isset($typeDef['elements']) && is_array($typeDef['elements'])) {
  6197. $this->debug("in serializeComplexTypeElements, serialize elements for XML Schema type $ns:$uqType");
  6198. if (is_array($value)) {
  6199. $xvalue = $value;
  6200. } elseif (is_object($value)) {
  6201. $xvalue = get_object_vars($value);
  6202. } else {
  6203. $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
  6204. $xvalue = array();
  6205. }
  6206. // toggle whether all elements are present - ideally should validate against schema
  6207. if (count($typeDef['elements']) != count($xvalue)){
  6208. $optionals = true;
  6209. }
  6210. foreach ($typeDef['elements'] as $eName => $attrs) {
  6211. if (!isset($xvalue[$eName])) {
  6212. if (isset($attrs['default'])) {
  6213. $xvalue[$eName] = $attrs['default'];
  6214. $this->debug('use default value of ' . $xvalue[$eName] . ' for element ' . $eName);
  6215. }
  6216. }
  6217. // if user took advantage of a minOccurs=0, then only serialize named parameters
  6218. if (isset($optionals)
  6219. && (!isset($xvalue[$eName]))
  6220. && ( (!isset($attrs['nillable'])) || $attrs['nillable'] != 'true')
  6221. ){
  6222. if (isset($attrs['minOccurs']) && $attrs['minOccurs'] <> '0') {
  6223. $this->debug("apparent error: no value provided for element $eName with minOccurs=" . $attrs['minOccurs']);
  6224. }
  6225. // do nothing
  6226. $this->debug("no value provided for complexType element $eName and element is not nillable, so serialize nothing");
  6227. } else {
  6228. // get value
  6229. if (isset($xvalue[$eName])) {
  6230. $v = $xvalue[$eName];
  6231. } else {
  6232. $v = null;
  6233. }
  6234. if (isset($attrs['form'])) {
  6235. $unqualified = ($attrs['form'] == 'unqualified');
  6236. } else {
  6237. $unqualified = false;
  6238. }
  6239. if (isset($attrs['maxOccurs']) && ($attrs['maxOccurs'] == 'unbounded' || $attrs['maxOccurs'] > 1) && isset($v) && is_array($v) && $this->isArraySimpleOrStruct($v) == 'arraySimple') {
  6240. $vv = $v;
  6241. foreach ($vv as $k => $v) {
  6242. if (isset($attrs['type']) || isset($attrs['ref'])) {
  6243. // serialize schema-defined type
  6244. $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
  6245. } else {
  6246. // serialize generic type (can this ever really happen?)
  6247. $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
  6248. $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
  6249. }
  6250. }
  6251. } else {
  6252. if (is_null($v) && isset($attrs['minOccurs']) && $attrs['minOccurs'] == '0') {
  6253. // do nothing
  6254. } elseif (is_null($v) && isset($attrs['nillable']) && $attrs['nillable'] == 'true') {
  6255. // TODO: serialize a nil correctly, but for now serialize schema-defined type
  6256. $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
  6257. } elseif (isset($attrs['type']) || isset($attrs['ref'])) {
  6258. // serialize schema-defined type
  6259. $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
  6260. } else {
  6261. // serialize generic type (can this ever really happen?)
  6262. $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
  6263. $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
  6264. }
  6265. }
  6266. }
  6267. }
  6268. } else {
  6269. $this->debug("no elements to serialize for XML Schema type $ns:$uqType");
  6270. }
  6271. return $xml;
  6272. }
  6273.  
  6274. /**
  6275. * adds an XML Schema complex type to the WSDL types
  6276. *
  6277. * @param string $name
  6278. * @param string $typeClass (complexType|simpleType|attribute)
  6279. * @param string $phpType currently supported are array and struct (php assoc array)
  6280. * @param string $compositor (all|sequence|choice)
  6281. * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
  6282. * @param array $elements e.g. array ( name => array(name=>'',type=>'') )
  6283. * @param array $attrs e.g. array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'xsd:string[]'))
  6284. * @param string $arrayType as namespace:name (xsd:string)
  6285. * @see nusoap_xmlschema
  6286. * @access public
  6287. */
  6288. function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType='') {
  6289. if (count($elements) > 0) {
  6290. $eElements = array();
  6291. foreach($elements as $n => $e){
  6292. // expand each element
  6293. $ee = array();
  6294. foreach ($e as $k => $v) {
  6295. $k = strpos($k,':') ? $this->expandQname($k) : $k;
  6296. $v = strpos($v,':') ? $this->expandQname($v) : $v;
  6297. $ee[$k] = $v;
  6298. }
  6299. $eElements[$n] = $ee;
  6300. }
  6301. $elements = $eElements;
  6302. }
  6303. if (count($attrs) > 0) {
  6304. foreach($attrs as $n => $a){
  6305. // expand each attribute
  6306. foreach ($a as $k => $v) {
  6307. $k = strpos($k,':') ? $this->expandQname($k) : $k;
  6308. $v = strpos($v,':') ? $this->expandQname($v) : $v;
  6309. $aa[$k] = $v;
  6310. }
  6311. $eAttrs[$n] = $aa;
  6312. }
  6313. $attrs = $eAttrs;
  6314. }
  6315.  
  6316. $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
  6317. $arrayType = strpos($arrayType,':') ? $this->expandQname($arrayType) : $arrayType;
  6318.  
  6319. $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
  6320. $this->schemas[$typens][0]->addComplexType($name,$typeClass,$phpType,$compositor,$restrictionBase,$elements,$attrs,$arrayType);
  6321. }
  6322.  
  6323. /**
  6324. * adds an XML Schema simple type to the WSDL types
  6325. *
  6326. * @param string $name
  6327. * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
  6328. * @param string $typeClass (should always be simpleType)
  6329. * @param string $phpType (should always be scalar)
  6330. * @param array $enumeration array of values
  6331. * @see nusoap_xmlschema
  6332. * @access public
  6333. */
  6334. function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
  6335. $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
  6336.  
  6337. $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
  6338. $this->schemas[$typens][0]->addSimpleType($name, $restrictionBase, $typeClass, $phpType, $enumeration);
  6339. }
  6340.  
  6341. /**
  6342. * adds an element to the WSDL types
  6343. *
  6344. * @param array $attrs attributes that must include name and type
  6345. * @see nusoap_xmlschema
  6346. * @access public
  6347. */
  6348. function addElement($attrs) {
  6349. $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
  6350. $this->schemas[$typens][0]->addElement($attrs);
  6351. }
  6352.  
  6353. /**
  6354. * register an operation with the server
  6355. *
  6356. * @param string $name operation (method) name
  6357. * @param array $in assoc array of input values: key = param name, value = param type
  6358. * @param array $out assoc array of output values: key = param name, value = param type
  6359. * @param string $namespace optional The namespace for the operation
  6360. * @param string $soapaction optional The soapaction for the operation
  6361. * @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
  6362. * @param string $use (encoded|literal) optional The use for the parameters (cannot mix right now)
  6363. * @param string $documentation optional The description to include in the WSDL
  6364. * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
  6365. * @access public
  6366. */
  6367. function addOperation($name, $in = false, $out = false, $namespace = false, $soapaction = false, $style = 'rpc', $use = 'encoded', $documentation = '', $encodingStyle = ''){
  6368. if ($use == 'encoded' && $encodingStyle == '') {
  6369. $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
  6370. }
  6371.  
  6372. if ($style == 'document') {
  6373. $elements = array();
  6374. foreach ($in as $n => $t) {
  6375. $elements[$n] = array('name' => $n, 'type' => $t, 'form' => 'unqualified');
  6376. }
  6377. $this->addComplexType($name . 'RequestType', 'complexType', 'struct', 'all', '', $elements);
  6378. $this->addElement(array('name' => $name, 'type' => $name . 'RequestType'));
  6379. $in = array('parameters' => 'tns:' . $name . '^');
  6380.  
  6381. $elements = array();
  6382. foreach ($out as $n => $t) {
  6383. $elements[$n] = array('name' => $n, 'type' => $t, 'form' => 'unqualified');
  6384. }
  6385. $this->addComplexType($name . 'ResponseType', 'complexType', 'struct', 'all', '', $elements);
  6386. $this->addElement(array('name' => $name . 'Response', 'type' => $name . 'ResponseType', 'form' => 'qualified'));
  6387. $out = array('parameters' => 'tns:' . $name . 'Response' . '^');
  6388. }
  6389.  
  6390. // get binding
  6391. $this->bindings[ $this->serviceName . 'Binding' ]['operations'][$name] =
  6392. array(
  6393. 'name' => $name,
  6394. 'binding' => $this->serviceName . 'Binding',
  6395. 'endpoint' => $this->endpoint,
  6396. 'soapAction' => $soapaction,
  6397. 'style' => $style,
  6398. 'input' => array(
  6399. 'use' => $use,
  6400. 'namespace' => $namespace,
  6401. 'encodingStyle' => $encodingStyle,
  6402. 'message' => $name . 'Request',
  6403. 'parts' => $in),
  6404. 'output' => array(
  6405. 'use' => $use,
  6406. 'namespace' => $namespace,
  6407. 'encodingStyle' => $encodingStyle,
  6408. 'message' => $name . 'Response',
  6409. 'parts' => $out),
  6410. 'namespace' => $namespace,
  6411. 'transport' => 'http://schemas.xmlsoap.org/soap/http',
  6412. 'documentation' => $documentation);
  6413. // add portTypes
  6414. // add messages
  6415. if($in)
  6416. {
  6417. foreach($in as $pName => $pType)
  6418. {
  6419. if(strpos($pType,':')) {
  6420. $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
  6421. }
  6422. $this->messages[$name.'Request'][$pName] = $pType;
  6423. }
  6424. } else {
  6425. $this->messages[$name.'Request']= '0';
  6426. }
  6427. if($out)
  6428. {
  6429. foreach($out as $pName => $pType)
  6430. {
  6431. if(strpos($pType,':')) {
  6432. $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
  6433. }
  6434. $this->messages[$name.'Response'][$pName] = $pType;
  6435. }
  6436. } else {
  6437. $this->messages[$name.'Response']= '0';
  6438. }
  6439. return true;
  6440. }
  6441. }
  6442. ?><?php
  6443.  
  6444.  
  6445.  
  6446. /**
  6447. *
  6448. * nusoap_parser class parses SOAP XML messages into native PHP values
  6449. *
  6450. * @author Dietrich Ayala <dietrich@ganx4.com>
  6451. * @author Scott Nichol <snichol@users.sourceforge.net>
  6452. * @version $Id: fsource_nusoap__nusoap.php.html,v 1.2 2010/04/26 20:25:21 snichol Exp $
  6453. * @access public
  6454. */
  6455. class nusoap_parser extends nusoap_base {
  6456.  
  6457. var $xml = '';
  6458. var $xml_encoding = '';
  6459. var $method = '';
  6460. var $root_struct = '';
  6461. var $root_struct_name = '';
  6462. var $root_struct_namespace = '';
  6463. var $root_header = '';
  6464. var $document = ''; // incoming SOAP body (text)
  6465. // determines where in the message we are (envelope,header,body,method)
  6466. var $status = '';
  6467. var $position = 0;
  6468. var $depth = 0;
  6469. var $default_namespace = '';
  6470. var $namespaces = array();
  6471. var $message = array();
  6472. var $parent = '';
  6473. var $fault = false;
  6474. var $fault_code = '';
  6475. var $fault_str = '';
  6476. var $fault_detail = '';
  6477. var $depth_array = array();
  6478. var $debug_flag = true;
  6479. var $soapresponse = NULL; // parsed SOAP Body
  6480. var $soapheader = NULL; // parsed SOAP Header
  6481. var $responseHeaders = ''; // incoming SOAP headers (text)
  6482. var $body_position = 0;
  6483. // for multiref parsing:
  6484. // array of id => pos
  6485. var $ids = array();
  6486. // array of id => hrefs => pos
  6487. var $multirefs = array();
  6488. // toggle for auto-decoding element content
  6489. var $decode_utf8 = true;
  6490.  
  6491. /**
  6492. * constructor that actually does the parsing
  6493. *
  6494. * @param string $xml SOAP message
  6495. * @param string $encoding character encoding scheme of message
  6496. * @param string $method method for which XML is parsed (unused?)
  6497. * @param string $decode_utf8 whether to decode UTF-8 to ISO-8859-1
  6498. * @access public
  6499. */
  6500. function nusoap_parser($xml,$encoding='UTF-8',$method='',$decode_utf8=true){
  6501. parent::nusoap_base();
  6502. $this->xml = $xml;
  6503. $this->xml_encoding = $encoding;
  6504. $this->method = $method;
  6505. $this->decode_utf8 = $decode_utf8;
  6506.  
  6507. // Check whether content has been read.
  6508. if(!empty($xml)){
  6509. // Check XML encoding
  6510. $pos_xml = strpos($xml, '<?xml');
  6511. if ($pos_xml !== FALSE) {
  6512. $xml_decl = substr($xml, $pos_xml, strpos($xml, '?>', $pos_xml + 2) - $pos_xml + 1);
  6513. if (preg_match("/encoding=[\"']([^\"']*)[\"']/", $xml_decl, $res)) {
  6514. $xml_encoding = $res[1];
  6515. if (strtoupper($xml_encoding) != $encoding) {
  6516. $err = "Charset from HTTP Content-Type '" . $encoding . "' does not match encoding from XML declaration '" . $xml_encoding . "'";
  6517. $this->debug($err);
  6518. if ($encoding != 'ISO-8859-1' || strtoupper($xml_encoding) != 'UTF-8') {
  6519. $this->setError($err);
  6520. return;
  6521. }
  6522. // when HTTP says ISO-8859-1 (the default) and XML says UTF-8 (the typical), assume the other endpoint is just sloppy and proceed
  6523. } else {
  6524. $this->debug('Charset from HTTP Content-Type matches encoding from XML declaration');
  6525. }
  6526. } else {
  6527. $this->debug('No encoding specified in XML declaration');
  6528. }
  6529. } else {
  6530. $this->debug('No XML declaration');
  6531. }
  6532. $this->debug('Entering nusoap_parser(), length='.strlen($xml).', encoding='.$encoding);
  6533. // Create an XML parser - why not xml_parser_create_ns?
  6534. $this->parser = xml_parser_create($this->xml_encoding);
  6535. // Set the options for parsing the XML data.
  6536. //xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  6537. xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
  6538. xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->xml_encoding);
  6539. // Set the object for the parser.
  6540. xml_set_object($this->parser, $this);
  6541. // Set the element handlers for the parser.
  6542. xml_set_element_handler($this->parser, 'start_element','end_element');
  6543. xml_set_character_data_handler($this->parser,'character_data');
  6544.  
  6545. // Parse the XML file.
  6546. if(!xml_parse($this->parser,$xml,true)){
  6547. // Display an error message.
  6548. $err = sprintf('XML error parsing SOAP payload on line %d: %s',
  6549. xml_get_current_line_number($this->parser),
  6550. xml_error_string(xml_get_error_code($this->parser)));
  6551. $this->debug($err);
  6552. $this->debug("XML payload:\n" . $xml);
  6553. $this->setError($err);
  6554. } else {
  6555. $this->debug('in nusoap_parser ctor, message:');
  6556. $this->appendDebug($this->varDump($this->message));
  6557. $this->debug('parsed successfully, found root struct: '.$this->root_struct.' of name '.$this->root_struct_name);
  6558. // get final value
  6559. $this->soapresponse = $this->message[$this->root_struct]['result'];
  6560. // get header value
  6561. if($this->root_header != '' && isset($this->message[$this->root_header]['result'])){
  6562. $this->soapheader = $this->message[$this->root_header]['result'];
  6563. }
  6564. // resolve hrefs/ids
  6565. if(sizeof($this->multirefs) > 0){
  6566. foreach($this->multirefs as $id => $hrefs){
  6567. $this->debug('resolving multirefs for id: '.$id);
  6568. $idVal = $this->buildVal($this->ids[$id]);
  6569. if (is_array($idVal) && isset($idVal['!id'])) {
  6570. unset($idVal['!id']);
  6571. }
  6572. foreach($hrefs as $refPos => $ref){
  6573. $this->debug('resolving href at pos '.$refPos);
  6574. $this->multirefs[$id][$refPos] = $idVal;
  6575. }
  6576. }
  6577. }
  6578. }
  6579. xml_parser_free($this->parser);
  6580. } else {
  6581. $this->debug('xml was empty, didn\'t parse!');
  6582. $this->setError('xml was empty, didn\'t parse!');
  6583. }
  6584. }
  6585.  
  6586. /**
  6587. * start-element handler
  6588. *
  6589. * @param resource $parser XML parser object
  6590. * @param string $name element name
  6591. * @param array $attrs associative array of attributes
  6592. * @access private
  6593. */
  6594. function start_element($parser, $name, $attrs) {
  6595. // position in a total number of elements, starting from 0
  6596. // update class level pos
  6597. $pos = $this->position++;
  6598. // and set mine
  6599. $this->message[$pos] = array('pos' => $pos,'children'=>'','cdata'=>'');
  6600. // depth = how many levels removed from root?
  6601. // set mine as current global depth and increment global depth value
  6602. $this->message[$pos]['depth'] = $this->depth++;
  6603.  
  6604. // else add self as child to whoever the current parent is
  6605. if($pos != 0){
  6606. $this->message[$this->parent]['children'] .= '|'.$pos;
  6607. }
  6608. // set my parent
  6609. $this->message[$pos]['parent'] = $this->parent;
  6610. // set self as current parent
  6611. $this->parent = $pos;
  6612. // set self as current value for this depth
  6613. $this->depth_array[$this->depth] = $pos;
  6614. // get element prefix
  6615. if(strpos($name,':')){
  6616. // get ns prefix
  6617. $prefix = substr($name,0,strpos($name,':'));
  6618. // get unqualified name
  6619. $name = substr(strstr($name,':'),1);
  6620. }
  6621. // set status
  6622. if ($name == 'Envelope' && $this->status == '') {
  6623. $this->status = 'envelope';
  6624. } elseif ($name == 'Header' && $this->status == 'envelope') {
  6625. $this->root_header = $pos;
  6626. $this->status = 'header';
  6627. } elseif ($name == 'Body' && $this->status == 'envelope'){
  6628. $this->status = 'body';
  6629. $this->body_position = $pos;
  6630. // set method
  6631. } elseif($this->status == 'body' && $pos == ($this->body_position+1)) {
  6632. $this->status = 'method';
  6633. $this->root_struct_name = $name;
  6634. $this->root_struct = $pos;
  6635. $this->message[$pos]['type'] = 'struct';
  6636. $this->debug("found root struct $this->root_struct_name, pos $this->root_struct");
  6637. }
  6638. // set my status
  6639. $this->message[$pos]['status'] = $this->status;
  6640. // set name
  6641. $this->message[$pos]['name'] = htmlspecialchars($name);
  6642. // set attrs
  6643. $this->message[$pos]['attrs'] = $attrs;
  6644.  
  6645. // loop through atts, logging ns and type declarations
  6646. $attstr = '';
  6647. foreach($attrs as $key => $value){
  6648. $key_prefix = $this->getPrefix($key);
  6649. $key_localpart = $this->getLocalPart($key);
  6650. // if ns declarations, add to class level array of valid namespaces
  6651. if($key_prefix == 'xmlns'){
  6652. if(preg_match('/^http:\/\/www.w3.org\/[0-9]{4}\/XMLSchema$/',$value)){
  6653. $this->XMLSchemaVersion = $value;
  6654. $this->namespaces['xsd'] = $this->XMLSchemaVersion;
  6655. $this->namespaces['xsi'] = $this->XMLSchemaVersion.'-instance';
  6656. }
  6657. $this->namespaces[$key_localpart] = $value;
  6658. // set method namespace
  6659. if($name == $this->root_struct_name){
  6660. $this->methodNamespace = $value;
  6661. }
  6662. // if it's a type declaration, set type
  6663. } elseif($key_localpart == 'type'){
  6664. if (isset($this->message[$pos]['type']) && $this->message[$pos]['type'] == 'array') {
  6665. // do nothing: already processed arrayType
  6666. } else {
  6667. $value_prefix = $this->getPrefix($value);
  6668. $value_localpart = $this->getLocalPart($value);
  6669. $this->message[$pos]['type'] = $value_localpart;
  6670. $this->message[$pos]['typePrefix'] = $value_prefix;
  6671. if(isset($this->namespaces[$value_prefix])){
  6672. $this->message[$pos]['type_namespace'] = $this->namespaces[$value_prefix];
  6673. } else if(isset($attrs['xmlns:'.$value_prefix])) {
  6674. $this->message[$pos]['type_namespace'] = $attrs['xmlns:'.$value_prefix];
  6675. }
  6676. // should do something here with the namespace of specified type?
  6677. }
  6678. } elseif($key_localpart == 'arrayType'){
  6679. $this->message[$pos]['type'] = 'array';
  6680. /* do arrayType ereg here
  6681. [1] arrayTypeValue ::= atype asize
  6682. [2] atype ::= QName rank*
  6683. [3] rank ::= '[' (',')* ']'
  6684. [4] asize ::= '[' length~ ']'
  6685. [5] length ::= nextDimension* Digit+
  6686. [6] nextDimension ::= Digit+ ','
  6687. */
  6688. $expr = '/([A-Za-z0-9_]+):([A-Za-z]+[A-Za-z0-9_]+)\[([0-9]+),?([0-9]*)\]/';
  6689. if(preg_match($expr,$value,$regs)){
  6690. $this->message[$pos]['typePrefix'] = $regs[1];
  6691. $this->message[$pos]['arrayTypePrefix'] = $regs[1];
  6692. if (isset($this->namespaces[$regs[1]])) {
  6693. $this->message[$pos]['arrayTypeNamespace'] = $this->namespaces[$regs[1]];
  6694. } else if (isset($attrs['xmlns:'.$regs[1]])) {
  6695. $this->message[$pos]['arrayTypeNamespace'] = $attrs['xmlns:'.$regs[1]];
  6696. }
  6697. $this->message[$pos]['arrayType'] = $regs[2];
  6698. $this->message[$pos]['arraySize'] = $regs[3];
  6699. $this->message[$pos]['arrayCols'] = $regs[4];
  6700. }
  6701. // specifies nil value (or not)
  6702. } elseif ($key_localpart == 'nil'){
  6703. $this->message[$pos]['nil'] = ($value == 'true' || $value == '1');
  6704. // some other attribute
  6705. } elseif ($key != 'href' && $key != 'xmlns' && $key_localpart != 'encodingStyle' && $key_localpart != 'root') {
  6706. $this->message[$pos]['xattrs']['!' . $key] = $value;
  6707. }
  6708.  
  6709. if ($key == 'xmlns') {
  6710. $this->default_namespace = $value;
  6711. }
  6712. // log id
  6713. if($key == 'id'){
  6714. $this->ids[$value] = $pos;
  6715. }
  6716. // root
  6717. if($key_localpart == 'root' && $value == 1){
  6718. $this->status = 'method';
  6719. $this->root_struct_name = $name;
  6720. $this->root_struct = $pos;
  6721. $this->debug("found root struct $this->root_struct_name, pos $pos");
  6722. }
  6723. // for doclit
  6724. $attstr .= " $key=\"$value\"";
  6725. }
  6726. // get namespace - must be done after namespace atts are processed
  6727. if(isset($prefix)){
  6728. $this->message[$pos]['namespace'] = $this->namespaces[$prefix];
  6729. $this->default_namespace = $this->namespaces[$prefix];
  6730. } else {
  6731. $this->message[$pos]['namespace'] = $this->default_namespace;
  6732. }
  6733. if($this->status == 'header'){
  6734. if ($this->root_header != $pos) {
  6735. $this->responseHeaders .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>";
  6736. }
  6737. } elseif($this->root_struct_name != ''){
  6738. $this->document .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>";
  6739. }
  6740. }
  6741.  
  6742. /**
  6743. * end-element handler
  6744. *
  6745. * @param resource $parser XML parser object
  6746. * @param string $name element name
  6747. * @access private
  6748. */
  6749. function end_element($parser, $name) {
  6750. // position of current element is equal to the last value left in depth_array for my depth
  6751. $pos = $this->depth_array[$this->depth--];
  6752.  
  6753. // get element prefix
  6754. if(strpos($name,':')){
  6755. // get ns prefix
  6756. $prefix = substr($name,0,strpos($name,':'));
  6757. // get unqualified name
  6758. $name = substr(strstr($name,':'),1);
  6759. }
  6760. // build to native type
  6761. if(isset($this->body_position) && $pos > $this->body_position){
  6762. // deal w/ multirefs
  6763. if(isset($this->message[$pos]['attrs']['href'])){
  6764. // get id
  6765. $id = substr($this->message[$pos]['attrs']['href'],1);
  6766. // add placeholder to href array
  6767. $this->multirefs[$id][$pos] = 'placeholder';
  6768. // add set a reference to it as the result value
  6769. $this->message[$pos]['result'] =& $this->multirefs[$id][$pos];
  6770. // build complexType values
  6771. } elseif($this->message[$pos]['children'] != ''){
  6772. // if result has already been generated (struct/array)
  6773. if(!isset($this->message[$pos]['result'])){
  6774. $this->message[$pos]['result'] = $this->buildVal($pos);
  6775. }
  6776. // build complexType values of attributes and possibly simpleContent
  6777. } elseif (isset($this->message[$pos]['xattrs'])) {
  6778. if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) {
  6779. $this->message[$pos]['xattrs']['!'] = null;
  6780. } elseif (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') {
  6781. if (isset($this->message[$pos]['type'])) {
  6782. $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'] : '');
  6783. } else {
  6784. $parent = $this->message[$pos]['parent'];
  6785. if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
  6786. $this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
  6787. } else {
  6788. $this->message[$pos]['xattrs']['!'] = $this->message[$pos]['cdata'];
  6789. }
  6790. }
  6791. }
  6792. $this->message[$pos]['result'] = $this->message[$pos]['xattrs'];
  6793. // set value of simpleType (or nil complexType)
  6794. } else {
  6795. //$this->debug('adding data for scalar value '.$this->message[$pos]['name'].' of value '.$this->message[$pos]['cdata']);
  6796. if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) {
  6797. $this->message[$pos]['xattrs']['!'] = null;
  6798. } elseif (isset($this->message[$pos]['type'])) {
  6799. $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'] : '');
  6800. } else {
  6801. $parent = $this->message[$pos]['parent'];
  6802. if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
  6803. $this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
  6804. } else {
  6805. $this->message[$pos]['result'] = $this->message[$pos]['cdata'];
  6806. }
  6807. }
  6808.  
  6809. /* add value to parent's result, if parent is struct/array
  6810. $parent = $this->message[$pos]['parent'];
  6811. if($this->message[$parent]['type'] != 'map'){
  6812. if(strtolower($this->message[$parent]['type']) == 'array'){
  6813. $this->message[$parent]['result'][] = $this->message[$pos]['result'];
  6814. } else {
  6815. $this->message[$parent]['result'][$this->message[$pos]['name']] = $this->message[$pos]['result'];
  6816. }
  6817. }
  6818. */
  6819. }
  6820. }
  6821. // for doclit
  6822. if($this->status == 'header'){
  6823. if ($this->root_header != $pos) {
  6824. $this->responseHeaders .= "</" . (isset($prefix) ? $prefix . ':' : '') . "$name>";
  6825. }
  6826. } elseif($pos >= $this->root_struct){
  6827. $this->document .= "</" . (isset($prefix) ? $prefix . ':' : '') . "$name>";
  6828. }
  6829. // switch status
  6830. if ($pos == $this->root_struct){
  6831. $this->status = 'body';
  6832. $this->root_struct_namespace = $this->message[$pos]['namespace'];
  6833. } elseif ($pos == $this->root_header) {
  6834. $this->status = 'envelope';
  6835. } elseif ($name == 'Body' && $this->status == 'body') {
  6836. $this->status = 'envelope';
  6837. } elseif ($name == 'Header' && $this->status == 'header') { // will never happen
  6838. $this->status = 'envelope';
  6839. } elseif ($name == 'Envelope' && $this->status == 'envelope') {
  6840. $this->status = '';
  6841. }
  6842. // set parent back to my parent
  6843. $this->parent = $this->message[$pos]['parent'];
  6844. }
  6845.  
  6846. /**
  6847. * element content handler
  6848. *
  6849. * @param resource $parser XML parser object
  6850. * @param string $data element content
  6851. * @access private
  6852. */
  6853. function character_data($parser, $data){
  6854. $pos = $this->depth_array[$this->depth];
  6855. if ($this->xml_encoding=='UTF-8'){
  6856. // TODO: add an option to disable this for folks who want
  6857. // raw UTF-8 that, e.g., might not map to iso-8859-1
  6858. // TODO: this can also be handled with xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "ISO-8859-1");
  6859. if($this->decode_utf8){
  6860. $data = utf8_decode($data);
  6861. }
  6862. }
  6863. $this->message[$pos]['cdata'] .= $data;
  6864. // for doclit
  6865. if($this->status == 'header'){
  6866. $this->responseHeaders .= $data;
  6867. } else {
  6868. $this->document .= $data;
  6869. }
  6870. }
  6871.  
  6872. /**
  6873. * get the parsed message (SOAP Body)
  6874. *
  6875. * @return mixed
  6876. * @access public
  6877. * @deprecated use get_soapbody instead
  6878. */
  6879. function get_response(){
  6880. return $this->soapresponse;
  6881. }
  6882.  
  6883. /**
  6884. * get the parsed SOAP Body (NULL if there was none)
  6885. *
  6886. * @return mixed
  6887. * @access public
  6888. */
  6889. function get_soapbody(){
  6890. return $this->soapresponse;
  6891. }
  6892.  
  6893. /**
  6894. * get the parsed SOAP Header (NULL if there was none)
  6895. *
  6896. * @return mixed
  6897. * @access public
  6898. */
  6899. function get_soapheader(){
  6900. return $this->soapheader;
  6901. }
  6902.  
  6903. /**
  6904. * get the unparsed SOAP Header
  6905. *
  6906. * @return string XML or empty if no Header
  6907. * @access public
  6908. */
  6909. function getHeaders(){
  6910. return $this->responseHeaders;
  6911. }
  6912.  
  6913. /**
  6914. * decodes simple types into PHP variables
  6915. *
  6916. * @param string $value value to decode
  6917. * @param string $type XML type to decode
  6918. * @param string $typens XML type namespace to decode
  6919. * @return mixed PHP value
  6920. * @access private
  6921. */
  6922. function decodeSimple($value, $type, $typens) {
  6923. // TODO: use the namespace!
  6924. if ((!isset($type)) || $type == 'string' || $type == 'long' || $type == 'unsignedLong') {
  6925. return (string) $value;
  6926. }
  6927. if ($type == 'int' || $type == 'integer' || $type == 'short' || $type == 'byte') {
  6928. return (int) $value;
  6929. }
  6930. if ($type == 'float' || $type == 'double' || $type == 'decimal') {
  6931. return (double) $value;
  6932. }
  6933. if ($type == 'boolean') {
  6934. if (strtolower($value) == 'false' || strtolower($value) == 'f') {
  6935. return false;
  6936. }
  6937. return (boolean) $value;
  6938. }
  6939. if ($type == 'base64' || $type == 'base64Binary') {
  6940. $this->debug('Decode base64 value');
  6941. return base64_decode($value);
  6942. }
  6943. // obscure numeric types
  6944. if ($type == 'nonPositiveInteger' || $type == 'negativeInteger'
  6945. || $type == 'nonNegativeInteger' || $type == 'positiveInteger'
  6946. || $type == 'unsignedInt'
  6947. || $type == 'unsignedShort' || $type == 'unsignedByte') {
  6948. return (int) $value;
  6949. }
  6950. // bogus: parser treats array with no elements as a simple type
  6951. if ($type == 'array') {
  6952. return array();
  6953. }
  6954. // everything else
  6955. return (string) $value;
  6956. }
  6957.  
  6958. /**
  6959. * builds response structures for compound values (arrays/structs)
  6960. * and scalars
  6961. *
  6962. * @param integer $pos position in node tree
  6963. * @return mixed PHP value
  6964. * @access private
  6965. */
  6966. function buildVal($pos){
  6967. if(!isset($this->message[$pos]['type'])){
  6968. $this->message[$pos]['type'] = '';
  6969. }
  6970. $this->debug('in buildVal() for '.$this->message[$pos]['name']."(pos $pos) of type ".$this->message[$pos]['type']);
  6971. // if there are children...
  6972. if($this->message[$pos]['children'] != ''){
  6973. $this->debug('in buildVal, there are children');
  6974. $children = explode('|',$this->message[$pos]['children']);
  6975. array_shift($children); // knock off empty
  6976. // md array
  6977. if(isset($this->message[$pos]['arrayCols']) && $this->message[$pos]['arrayCols'] != ''){
  6978. $r=0; // rowcount
  6979. $c=0; // colcount
  6980. foreach($children as $child_pos){
  6981. $this->debug("in buildVal, got an MD array element: $r, $c");
  6982. $params[$r][] = $this->message[$child_pos]['result'];
  6983. $c++;
  6984. if($c == $this->message[$pos]['arrayCols']){
  6985. $c = 0;
  6986. $r++;
  6987. }
  6988. }
  6989. // array
  6990. } elseif($this->message[$pos]['type'] == 'array' || $this->message[$pos]['type'] == 'Array'){
  6991. $this->debug('in buildVal, adding array '.$this->message[$pos]['name']);
  6992. foreach($children as $child_pos){
  6993. $params[] = &$this->message[$child_pos]['result'];
  6994. }
  6995. // apache Map type: java hashtable
  6996. } elseif($this->message[$pos]['type'] == 'Map' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap'){
  6997. $this->debug('in buildVal, Java Map '.$this->message[$pos]['name']);
  6998. foreach($children as $child_pos){
  6999. $kv = explode("|",$this->message[$child_pos]['children']);
  7000. $params[$this->message[$kv[1]]['result']] = &$this->message[$kv[2]]['result'];
  7001. }
  7002. // generic compound type
  7003. //} elseif($this->message[$pos]['type'] == 'SOAPStruct' || $this->message[$pos]['type'] == 'struct') {
  7004. } else {
  7005. // Apache Vector type: treat as an array
  7006. $this->debug('in buildVal, adding Java Vector or generic compound type '.$this->message[$pos]['name']);
  7007. if ($this->message[$pos]['type'] == 'Vector' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap') {
  7008. $notstruct = 1;
  7009. } else {
  7010. $notstruct = 0;
  7011. }
  7012. //
  7013. foreach($children as $child_pos){
  7014. if($notstruct){
  7015. $params[] = &$this->message[$child_pos]['result'];
  7016. } else {
  7017. if (isset($params[$this->message[$child_pos]['name']])) {
  7018. // de-serialize repeated element name into an array
  7019. if ((!is_array($params[$this->message[$child_pos]['name']])) || (!isset($params[$this->message[$child_pos]['name']][0]))) {
  7020. $params[$this->message[$child_pos]['name']] = array($params[$this->message[$child_pos]['name']]);
  7021. }
  7022. $params[$this->message[$child_pos]['name']][] = &$this->message[$child_pos]['result'];
  7023. } else {
  7024. $params[$this->message[$child_pos]['name']] = &$this->message[$child_pos]['result'];
  7025. }
  7026. }
  7027. }
  7028. }
  7029. if (isset($this->message[$pos]['xattrs'])) {
  7030. $this->debug('in buildVal, handling attributes');
  7031. foreach ($this->message[$pos]['xattrs'] as $n => $v) {
  7032. $params[$n] = $v;
  7033. }
  7034. }
  7035. // handle simpleContent
  7036. if (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') {
  7037. $this->debug('in buildVal, handling simpleContent');
  7038. if (isset($this->message[$pos]['type'])) {
  7039. $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
  7040. } else {
  7041. $parent = $this->message[$pos]['parent'];
  7042. if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
  7043. $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
  7044. } else {
  7045. $params['!'] = $this->message[$pos]['cdata'];
  7046. }
  7047. }
  7048. }
  7049. $ret = is_array($params) ? $params : array();
  7050. $this->debug('in buildVal, return:');
  7051. $this->appendDebug($this->varDump($ret));
  7052. return $ret;
  7053. } else {
  7054. $this->debug('in buildVal, no children, building scalar');
  7055. $cdata = isset($this->message[$pos]['cdata']) ? $this->message[$pos]['cdata'] : '';
  7056. if (isset($this->message[$pos]['type'])) {
  7057. $ret = $this->decodeSimple($cdata, $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : '');
  7058. $this->debug("in buildVal, return: $ret");
  7059. return $ret;
  7060. }
  7061. $parent = $this->message[$pos]['parent'];
  7062. if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) {
  7063. $ret = $this->decodeSimple($cdata, $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : '');
  7064. $this->debug("in buildVal, return: $ret");
  7065. return $ret;
  7066. }
  7067. $ret = $this->message[$pos]['cdata'];
  7068. $this->debug("in buildVal, return: $ret");
  7069. return $ret;
  7070. }
  7071. }
  7072. }
  7073.  
  7074. /**
  7075. * Backward compatibility
  7076. */
  7077. class soap_parser extends nusoap_parser {
  7078. }
  7079.  
  7080. ?><?php
  7081.  
  7082.  
  7083.  
  7084. /**
  7085. *
  7086. * [nu]soapclient higher level class for easy usage.
  7087. *
  7088. * usage:
  7089. *
  7090. * // instantiate client with server info
  7091. * $soapclient = new nusoap_client( string path [ ,mixed wsdl] );
  7092. *
  7093. * // call method, get results
  7094. * echo $soapclient->call( string methodname [ ,array parameters] );
  7095. *
  7096. * // bye bye client
  7097. * unset($soapclient);
  7098. *
  7099. * @author Dietrich Ayala <dietrich@ganx4.com>
  7100. * @author Scott Nichol <snichol@users.sourceforge.net>
  7101. * @version $Id: fsource_nusoap__nusoap.php.html,v 1.2 2010/04/26 20:25:21 snichol Exp $
  7102. * @access public
  7103. */
  7104. class nusoap_client extends nusoap_base {
  7105.  
  7106. var $username = ''; // Username for HTTP authentication
  7107. var $password = ''; // Password for HTTP authentication
  7108. var $authtype = ''; // Type of HTTP authentication
  7109. var $certRequest = array(); // Certificate for HTTP SSL authentication
  7110. var $requestHeaders = false; // SOAP headers in request (text)
  7111. var $responseHeaders = ''; // SOAP headers from response (incomplete namespace resolution) (text)
  7112. var $responseHeader = NULL; // SOAP Header from response (parsed)
  7113. var $document = ''; // SOAP body response portion (incomplete namespace resolution) (text)
  7114. var $endpoint;
  7115. var $forceEndpoint = ''; // overrides WSDL endpoint
  7116. var $proxyhost = '';
  7117. var $proxyport = '';
  7118. var $proxyusername = '';
  7119. var $proxypassword = '';
  7120. var $portName = ''; // port name to use in WSDL
  7121. var $xml_encoding = ''; // character set encoding of incoming (response) messages
  7122. var $http_encoding = false;
  7123. var $timeout = 0; // HTTP connection timeout
  7124. var $response_timeout = 30; // HTTP response timeout
  7125. var $endpointType = ''; // soap|wsdl, empty for WSDL initialization error
  7126. var $persistentConnection = false;
  7127. var $defaultRpcParams = false; // This is no longer used
  7128. var $request = ''; // HTTP request
  7129. var $response = ''; // HTTP response
  7130. var $responseData = ''; // SOAP payload of response
  7131. var $cookies = array(); // Cookies from response or for request
  7132. var $decode_utf8 = true; // toggles whether the parser decodes element content w/ utf8_decode()
  7133. var $operations = array(); // WSDL operations, empty for WSDL initialization error
  7134. var $curl_options = array(); // User-specified cURL options
  7135. var $bindingType = ''; // WSDL operation binding type
  7136. var $use_curl = false; // whether to always try to use cURL
  7137.  
  7138. /*
  7139. * fault related variables
  7140. */
  7141. /**
  7142. * @var fault
  7143. * @access public
  7144. */
  7145. var $fault;
  7146. /**
  7147. * @var faultcode
  7148. * @access public
  7149. */
  7150. var $faultcode;
  7151. /**
  7152. * @var faultstring
  7153. * @access public
  7154. */
  7155. var $faultstring;
  7156. /**
  7157. * @var faultdetail
  7158. * @access public
  7159. */
  7160. var $faultdetail;
  7161.  
  7162. /**
  7163. * constructor
  7164. *
  7165. * @param mixed $endpoint SOAP server or WSDL URL (string), or wsdl instance (object)
  7166. * @param mixed $wsdl optional, set to 'wsdl' or true if using WSDL
  7167. * @param string $proxyhost optional
  7168. * @param string $proxyport optional
  7169. * @param string $proxyusername optional
  7170. * @param string $proxypassword optional
  7171. * @param integer $timeout set the connection timeout
  7172. * @param integer $response_timeout set the response timeout
  7173. * @param string $portName optional portName in WSDL document
  7174. * @access public
  7175. */
  7176. function nusoap_client($endpoint,$wsdl = false,$proxyhost = false,$proxyport = false,$proxyusername = false, $proxypassword = false, $timeout = 0, $response_timeout = 30, $portName = ''){
  7177. parent::nusoap_base();
  7178. $this->endpoint = $endpoint;
  7179. $this->proxyhost = $proxyhost;
  7180. $this->proxyport = $proxyport;
  7181. $this->proxyusername = $proxyusername;
  7182. $this->proxypassword = $proxypassword;
  7183. $this->timeout = $timeout;
  7184. $this->response_timeout = $response_timeout;
  7185. $this->portName = $portName;
  7186.  
  7187. $this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout");
  7188. $this->appendDebug('endpoint=' . $this->varDump($endpoint));
  7189.  
  7190. // make values
  7191. if($wsdl){
  7192. if (is_object($endpoint) && (get_class($endpoint) == 'wsdl')) {
  7193. $this->wsdl = $endpoint;
  7194. $this->endpoint = $this->wsdl->wsdl;
  7195. $this->wsdlFile = $this->endpoint;
  7196. $this->debug('existing wsdl instance created from ' . $this->endpoint);
  7197. $this->checkWSDL();
  7198. } else {
  7199. $this->wsdlFile = $this->endpoint;
  7200. $this->wsdl = null;
  7201. $this->debug('will use lazy evaluation of wsdl from ' . $this->endpoint);
  7202. }
  7203. $this->endpointType = 'wsdl';
  7204. } else {
  7205. $this->debug("instantiate SOAP with endpoint at $endpoint");
  7206. $this->endpointType = 'soap';
  7207. }
  7208. }
  7209.  
  7210. /**
  7211. * calls method, returns PHP native type
  7212. *
  7213. * @param string $operation SOAP server URL or path
  7214. * @param mixed $params An array, associative or simple, of the parameters
  7215. * for the method call, or a string that is the XML
  7216. * for the call. For rpc style, this call will
  7217. * wrap the XML in a tag named after the method, as
  7218. * well as the SOAP Envelope and Body. For document
  7219. * style, this will only wrap with the Envelope and Body.
  7220. * IMPORTANT: when using an array with document style,
  7221. * in which case there
  7222. * is really one parameter, the root of the fragment
  7223. * used in the call, which encloses what programmers
  7224. * normally think of parameters. A parameter array
  7225. * *must* include the wrapper.
  7226. * @param string $namespace optional method namespace (WSDL can override)
  7227. * @param string $soapAction optional SOAPAction value (WSDL can override)
  7228. * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers, or associative array
  7229. * @param boolean $rpcParams optional (no longer used)
  7230. * @param string $style optional (rpc|document) the style to use when serializing parameters (WSDL can override)
  7231. * @param string $use optional (encoded|literal) the use when serializing parameters (WSDL can override)
  7232. * @return mixed response from SOAP call, normally an associative array mirroring the structure of the XML response, false for certain fatal errors
  7233. * @access public
  7234. */
  7235. function call($operation,$params=array(),$namespace='http://tempuri.org',$soapAction='',$headers=false,$rpcParams=null,$style='rpc',$use='encoded'){
  7236. $this->operation = $operation;
  7237. $this->fault = false;
  7238. $this->setError('');
  7239. $this->request = '';
  7240. $this->response = '';
  7241. $this->responseData = '';
  7242. $this->faultstring = '';
  7243. $this->faultcode = '';
  7244. $this->opData = array();
  7245. $this->debug("call: operation=$operation, namespace=$namespace, soapAction=$soapAction, rpcParams=$rpcParams, style=$style, use=$use, endpointType=$this->endpointType");
  7246. $this->appendDebug('params=' . $this->varDump($params));
  7247. $this->appendDebug('headers=' . $this->varDump($headers));
  7248. if ($headers) {
  7249. $this->requestHeaders = $headers;
  7250. }
  7251. if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) {
  7252. $this->loadWSDL();
  7253. if ($this->getError())
  7254. return false;
  7255. }
  7256. // serialize parameters
  7257. if($this->endpointType == 'wsdl' && $opData = $this->getOperationData($operation)){
  7258. // use WSDL for operation
  7259. $this->opData = $opData;
  7260. $this->debug("found operation");
  7261. $this->appendDebug('opData=' . $this->varDump($opData));
  7262. if (isset($opData['soapAction'])) {
  7263. $soapAction = $opData['soapAction'];
  7264. }
  7265. if (! $this->forceEndpoint) {
  7266. $this->endpoint = $opData['endpoint'];
  7267. } else {
  7268. $this->endpoint = $this->forceEndpoint;
  7269. }
  7270. $namespace = isset($opData['input']['namespace']) ? $opData['input']['namespace'] : $namespace;
  7271. $style = $opData['style'];
  7272. $use = $opData['input']['use'];
  7273. // add ns to ns array
  7274. if($namespace != '' && !isset($this->wsdl->namespaces[$namespace])){
  7275. $nsPrefix = 'ns' . rand(1000, 9999);
  7276. $this->wsdl->namespaces[$nsPrefix] = $namespace;
  7277. }
  7278. $nsPrefix = $this->wsdl->getPrefixFromNamespace($namespace);
  7279. // serialize payload
  7280. if (is_string($params)) {
  7281. $this->debug("serializing param string for WSDL operation $operation");
  7282. $payload = $params;
  7283. } elseif (is_array($params)) {
  7284. $this->debug("serializing param array for WSDL operation $operation");
  7285. $payload = $this->wsdl->serializeRPCParameters($operation,'input',$params,$this->bindingType);
  7286. } else {
  7287. $this->debug('params must be array or string');
  7288. $this->setError('params must be array or string');
  7289. return false;
  7290. }
  7291. $usedNamespaces = $this->wsdl->usedNamespaces;
  7292. if (isset($opData['input']['encodingStyle'])) {
  7293. $encodingStyle = $opData['input']['encodingStyle'];
  7294. } else {
  7295. $encodingStyle = '';
  7296. }
  7297. $this->appendDebug($this->wsdl->getDebug());
  7298. $this->wsdl->clearDebug();
  7299. if ($errstr = $this->wsdl->getError()) {
  7300. $this->debug('got wsdl error: '.$errstr);
  7301. $this->setError('wsdl error: '.$errstr);
  7302. return false;
  7303. }
  7304. } elseif($this->endpointType == 'wsdl') {
  7305. // operation not in WSDL
  7306. $this->appendDebug($this->wsdl->getDebug());
  7307. $this->wsdl->clearDebug();
  7308. $this->setError('operation '.$operation.' not present in WSDL.');
  7309. $this->debug("operation '$operation' not present in WSDL.");
  7310. return false;
  7311. } else {
  7312. // no WSDL
  7313. //$this->namespaces['ns1'] = $namespace;
  7314. $nsPrefix = 'ns' . rand(1000, 9999);
  7315. // serialize
  7316. $payload = '';
  7317. if (is_string($params)) {
  7318. $this->debug("serializing param string for operation $operation");
  7319. $payload = $params;
  7320. } elseif (is_array($params)) {
  7321. $this->debug("serializing param array for operation $operation");
  7322. foreach($params as $k => $v){
  7323. $payload .= $this->serialize_val($v,$k,false,false,false,false,$use);
  7324. }
  7325. } else {
  7326. $this->debug('params must be array or string');
  7327. $this->setError('params must be array or string');
  7328. return false;
  7329. }
  7330. $usedNamespaces = array();
  7331. if ($use == 'encoded') {
  7332. $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
  7333. } else {
  7334. $encodingStyle = '';
  7335. }
  7336. }
  7337. // wrap RPC calls with method element
  7338. if ($style == 'rpc') {
  7339. if ($use == 'literal') {
  7340. $this->debug("wrapping RPC request with literal method element");
  7341. if ($namespace) {
  7342. // 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
  7343. $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" .
  7344. $payload .
  7345. "</$nsPrefix:$operation>";
  7346. } else {
  7347. $payload = "<$operation>" . $payload . "</$operation>";
  7348. }
  7349. } else {
  7350. $this->debug("wrapping RPC request with encoded method element");
  7351. if ($namespace) {
  7352. $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" .
  7353. $payload .
  7354. "</$nsPrefix:$operation>";
  7355. } else {
  7356. $payload = "<$operation>" .
  7357. $payload .
  7358. "</$operation>";
  7359. }
  7360. }
  7361. }
  7362. // serialize envelope
  7363. $soapmsg = $this->serializeEnvelope($payload,$this->requestHeaders,$usedNamespaces,$style,$use,$encodingStyle);
  7364. $this->debug("endpoint=$this->endpoint, soapAction=$soapAction, namespace=$namespace, style=$style, use=$use, encodingStyle=$encodingStyle");
  7365. $this->debug('SOAP message length=' . strlen($soapmsg) . ' contents (max 1000 bytes)=' . substr($soapmsg, 0, 1000));
  7366. // send
  7367. $return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout);
  7368. if($errstr = $this->getError()){
  7369. $this->debug('Error: '.$errstr);
  7370. return false;
  7371. } else {
  7372. $this->return = $return;
  7373. $this->debug('sent message successfully and got a(n) '.gettype($return));
  7374. $this->appendDebug('return=' . $this->varDump($return));
  7375. // fault?
  7376. if(is_array($return) && isset($return['faultcode'])){
  7377. $this->debug('got fault');
  7378. $this->setError($return['faultcode'].': '.$return['faultstring']);
  7379. $this->fault = true;
  7380. foreach($return as $k => $v){
  7381. $this->$k = $v;
  7382. $this->debug("$k = $v<br>");
  7383. }
  7384. return $return;
  7385. } elseif ($style == 'document') {
  7386. // NOTE: if the response is defined to have multiple parts (i.e. unwrapped),
  7387. // we are only going to return the first part here...sorry about that
  7388. return $return;
  7389. } else {
  7390. // array of return values
  7391. if(is_array($return)){
  7392. // multiple 'out' parameters, which we return wrapped up
  7393. // in the array
  7394. if(sizeof($return) > 1){
  7395. return $return;
  7396. }
  7397. // single 'out' parameter (normally the return value)
  7398. $return = array_shift($return);
  7399. $this->debug('return shifted value: ');
  7400. $this->appendDebug($this->varDump($return));
  7401. return $return;
  7402. // nothing returned (ie, echoVoid)
  7403. } else {
  7404. return "";
  7405. }
  7406. }
  7407. }
  7408. }
  7409.  
  7410. /**
  7411. * check WSDL passed as an instance or pulled from an endpoint
  7412. *
  7413. * @access private
  7414. */
  7415. function checkWSDL() {
  7416. $this->appendDebug($this->wsdl->getDebug());
  7417. $this->wsdl->clearDebug();
  7418. $this->debug('checkWSDL');
  7419. // catch errors
  7420. if ($errstr = $this->wsdl->getError()) {
  7421. $this->appendDebug($this->wsdl->getDebug());
  7422. $this->wsdl->clearDebug();
  7423. $this->debug('got wsdl error: '.$errstr);
  7424. $this->setError('wsdl error: '.$errstr);
  7425. } elseif ($this->operations = $this->wsdl->getOperations($this->portName, 'soap')) {
  7426. $this->appendDebug($this->wsdl->getDebug());
  7427. $this->wsdl->clearDebug();
  7428. $this->bindingType = 'soap';
  7429. $this->debug('got '.count($this->operations).' operations from wsdl '.$this->wsdlFile.' for binding type '.$this->bindingType);
  7430. } elseif ($this->operations = $this->wsdl->getOperations($this->portName, 'soap12')) {
  7431. $this->appendDebug($this->wsdl->getDebug());
  7432. $this->wsdl->clearDebug();
  7433. $this->bindingType = 'soap12';
  7434. $this->debug('got '.count($this->operations).' operations from wsdl '.$this->wsdlFile.' for binding type '.$this->bindingType);
  7435. $this->debug('**************** WARNING: SOAP 1.2 BINDING *****************');
  7436. } else {
  7437. $this->appendDebug($this->wsdl->getDebug());
  7438. $this->wsdl->clearDebug();
  7439. $this->debug('getOperations returned false');
  7440. $this->setError('no operations defined in the WSDL document!');
  7441. }
  7442. }
  7443.  
  7444. /**
  7445. * instantiate wsdl object and parse wsdl file
  7446. *
  7447. * @access public
  7448. */
  7449. function loadWSDL() {
  7450. $this->debug('instantiating wsdl class with doc: '.$this->wsdlFile);
  7451. $this->wsdl = new wsdl('',$this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword,$this->timeout,$this->response_timeout,$this->curl_options,$this->use_curl);
  7452. $this->wsdl->setCredentials($this->username, $this->password, $this->authtype, $this->certRequest);
  7453. $this->wsdl->fetchWSDL($this->wsdlFile);
  7454. $this->checkWSDL();
  7455. }
  7456.  
  7457. /**
  7458. * get available data pertaining to an operation
  7459. *
  7460. * @param string $operation operation name
  7461. * @return array array of data pertaining to the operation
  7462. * @access public
  7463. */
  7464. function getOperationData($operation){
  7465. if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) {
  7466. $this->loadWSDL();
  7467. if ($this->getError())
  7468. return false;
  7469. }
  7470. if(isset($this->operations[$operation])){
  7471. return $this->operations[$operation];
  7472. }
  7473. $this->debug("No data for operation: $operation");
  7474. }
  7475.  
  7476. /**
  7477. * send the SOAP message
  7478. *
  7479. * Note: if the operation has multiple return values
  7480. * the return value of this method will be an array
  7481. * of those values.
  7482. *
  7483. * @param string $msg a SOAPx4 soapmsg object
  7484. * @param string $soapaction SOAPAction value
  7485. * @param integer $timeout set connection timeout in seconds
  7486. * @param integer $response_timeout set response timeout in seconds
  7487. * @return mixed native PHP types.
  7488. * @access private
  7489. */
  7490. function send($msg, $soapaction = '', $timeout=0, $response_timeout=30) {
  7491. $this->checkCookies();
  7492. // detect transport
  7493. switch(true){
  7494. // http(s)
  7495. case preg_match('/^http/',$this->endpoint):
  7496. $this->debug('transporting via HTTP');
  7497. if($this->persistentConnection == true && is_object($this->persistentConnection)){
  7498. $http =& $this->persistentConnection;
  7499. } else {
  7500. $http = new soap_transport_http($this->endpoint, $this->curl_options, $this->use_curl);
  7501. if ($this->persistentConnection) {
  7502. $http->usePersistentConnection();
  7503. }
  7504. }
  7505. $http->setContentType($this->getHTTPContentType(), $this->getHTTPContentTypeCharset());
  7506. $http->setSOAPAction($soapaction);
  7507. if($this->proxyhost && $this->proxyport){
  7508. $http->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword);
  7509. }
  7510. if($this->authtype != '') {
  7511. $http->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest);
  7512. }
  7513. if($this->http_encoding != ''){
  7514. $http->setEncoding($this->http_encoding);
  7515. }
  7516. $this->debug('sending message, length='.strlen($msg));
  7517. if(preg_match('/^http:/',$this->endpoint)){
  7518. //if(strpos($this->endpoint,'http:')){
  7519. $this->responseData = $http->send($msg,$timeout,$response_timeout,$this->cookies);
  7520. } elseif(preg_match('/^https/',$this->endpoint)){
  7521. //} elseif(strpos($this->endpoint,'https:')){
  7522. //if(phpversion() == '4.3.0-dev'){
  7523. //$response = $http->send($msg,$timeout,$response_timeout);
  7524. //$this->request = $http->outgoing_payload;
  7525. //$this->response = $http->incoming_payload;
  7526. //} else
  7527. $this->responseData = $http->sendHTTPS($msg,$timeout,$response_timeout,$this->cookies);
  7528. } else {
  7529. $this->setError('no http/s in endpoint url');
  7530. }
  7531. $this->request = $http->outgoing_payload;
  7532. $this->response = $http->incoming_payload;
  7533. $this->appendDebug($http->getDebug());
  7534. $this->UpdateCookies($http->incoming_cookies);
  7535.  
  7536. // save transport object if using persistent connections
  7537. if ($this->persistentConnection) {
  7538. $http->clearDebug();
  7539. if (!is_object($this->persistentConnection)) {
  7540. $this->persistentConnection = $http;
  7541. }
  7542. }
  7543. if($err = $http->getError()){
  7544. $this->setError('HTTP Error: '.$err);
  7545. return false;
  7546. } elseif($this->getError()){
  7547. return false;
  7548. } else {
  7549. $this->debug('got response, length='. strlen($this->responseData).' type='.$http->incoming_headers['content-type']);
  7550. return $this->parseResponse($http->incoming_headers, $this->responseData);
  7551. }
  7552. break;
  7553. default:
  7554. $this->setError('no transport found, or selected transport is not yet supported!');
  7555. return false;
  7556. break;
  7557. }
  7558. }
  7559.  
  7560. /**
  7561. * processes SOAP message returned from server
  7562. *
  7563. * @param array $headers The HTTP headers
  7564. * @param string $data unprocessed response data from server
  7565. * @return mixed value of the message, decoded into a PHP type
  7566. * @access private
  7567. */
  7568. function parseResponse($headers, $data) {
  7569. $this->debug('Entering parseResponse() for data of length ' . strlen($data) . ' headers:');
  7570. $this->appendDebug($this->varDump($headers));
  7571. if (!isset($headers['content-type'])) {
  7572. $this->setError('Response not of type text/xml (no content-type header)');
  7573. return false;
  7574. }
  7575. if (!strstr($headers['content-type'], 'text/xml')) {
  7576. $this->setError('Response not of type text/xml: ' . $headers['content-type']);
  7577. return false;
  7578. }
  7579. if (strpos($headers['content-type'], '=')) {
  7580. $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1));
  7581. $this->debug('Got response encoding: ' . $enc);
  7582. if(preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)){
  7583. $this->xml_encoding = strtoupper($enc);
  7584. } else {
  7585. $this->xml_encoding = 'US-ASCII';
  7586. }
  7587. } else {
  7588. // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
  7589. $this->xml_encoding = 'ISO-8859-1';
  7590. }
  7591. $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating nusoap_parser');
  7592. $parser = new nusoap_parser($data,$this->xml_encoding,$this->operation,$this->decode_utf8);
  7593. // add parser debug data to our debug
  7594. $this->appendDebug($parser->getDebug());
  7595. // if parse errors
  7596. if($errstr = $parser->getError()){
  7597. $this->setError( $errstr);
  7598. // destroy the parser object
  7599. unset($parser);
  7600. return false;
  7601. } else {
  7602. // get SOAP headers
  7603. $this->responseHeaders = $parser->getHeaders();
  7604. // get SOAP headers
  7605. $this->responseHeader = $parser->get_soapheader();
  7606. // get decoded message
  7607. $return = $parser->get_soapbody();
  7608. // add document for doclit support
  7609. $this->document = $parser->document;
  7610. // destroy the parser object
  7611. unset($parser);
  7612. // return decode message
  7613. return $return;
  7614. }
  7615. }
  7616.  
  7617. /**
  7618. * sets user-specified cURL options
  7619. *
  7620. * @param mixed $option The cURL option (always integer?)
  7621. * @param mixed $value The cURL option value
  7622. * @access public
  7623. */
  7624. function setCurlOption($option, $value) {
  7625. $this->debug("setCurlOption option=$option, value=");
  7626. $this->appendDebug($this->varDump($value));
  7627. $this->curl_options[$option] = $value;
  7628. }
  7629.  
  7630. /**
  7631. * sets the SOAP endpoint, which can override WSDL
  7632. *
  7633. * @param string $endpoint The endpoint URL to use, or empty string or false to prevent override
  7634. * @access public
  7635. */
  7636. function setEndpoint($endpoint) {
  7637. $this->debug("setEndpoint(\"$endpoint\")");
  7638. $this->forceEndpoint = $endpoint;
  7639. }
  7640.  
  7641. /**
  7642. * set the SOAP headers
  7643. *
  7644. * @param mixed $headers String of XML with SOAP header content, or array of soapval objects for SOAP headers
  7645. * @access public
  7646. */
  7647. function setHeaders($headers){
  7648. $this->debug("setHeaders headers=");
  7649. $this->appendDebug($this->varDump($headers));
  7650. $this->requestHeaders = $headers;
  7651. }
  7652.  
  7653. /**
  7654. * get the SOAP response headers (namespace resolution incomplete)
  7655. *
  7656. * @return string
  7657. * @access public
  7658. */
  7659. function getHeaders(){
  7660. return $this->responseHeaders;
  7661. }
  7662.  
  7663. /**
  7664. * get the SOAP response Header (parsed)
  7665. *
  7666. * @return mixed
  7667. * @access public
  7668. */
  7669. function getHeader(){
  7670. return $this->responseHeader;
  7671. }
  7672.  
  7673. /**
  7674. * set proxy info here
  7675. *
  7676. * @param string $proxyhost
  7677. * @param string $proxyport
  7678. * @param string $proxyusername
  7679. * @param string $proxypassword
  7680. * @access public
  7681. */
  7682. function setHTTPProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') {
  7683. $this->proxyhost = $proxyhost;
  7684. $this->proxyport = $proxyport;
  7685. $this->proxyusername = $proxyusername;
  7686. $this->proxypassword = $proxypassword;
  7687. }
  7688.  
  7689. /**
  7690. * if authenticating, set user credentials here
  7691. *
  7692. * @param string $username
  7693. * @param string $password
  7694. * @param string $authtype (basic|digest|certificate|ntlm)
  7695. * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
  7696. * @access public
  7697. */
  7698. function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) {
  7699. $this->debug("setCredentials username=$username authtype=$authtype certRequest=");
  7700. $this->appendDebug($this->varDump($certRequest));
  7701. $this->username = $username;
  7702. $this->password = $password;
  7703. $this->authtype = $authtype;
  7704. $this->certRequest = $certRequest;
  7705. }
  7706. /**
  7707. * use HTTP encoding
  7708. *
  7709. * @param string $enc HTTP encoding
  7710. * @access public
  7711. */
  7712. function setHTTPEncoding($enc='gzip, deflate'){
  7713. $this->debug("setHTTPEncoding(\"$enc\")");
  7714. $this->http_encoding = $enc;
  7715. }
  7716. /**
  7717. * Set whether to try to use cURL connections if possible
  7718. *
  7719. * @param boolean $use Whether to try to use cURL
  7720. * @access public
  7721. */
  7722. function setUseCURL($use) {
  7723. $this->debug("setUseCURL($use)");
  7724. $this->use_curl = $use;
  7725. }
  7726.  
  7727. /**
  7728. * use HTTP persistent connections if possible
  7729. *
  7730. * @access public
  7731. */
  7732. function useHTTPPersistentConnection(){
  7733. $this->debug("useHTTPPersistentConnection");
  7734. $this->persistentConnection = true;
  7735. }
  7736. /**
  7737. * gets the default RPC parameter setting.
  7738. * If true, default is that call params are like RPC even for document style.
  7739. * Each call() can override this value.
  7740. *
  7741. * This is no longer used.
  7742. *
  7743. * @return boolean
  7744. * @access public
  7745. * @deprecated
  7746. */
  7747. function getDefaultRpcParams() {
  7748. return $this->defaultRpcParams;
  7749. }
  7750.  
  7751. /**
  7752. * sets the default RPC parameter setting.
  7753. * If true, default is that call params are like RPC even for document style
  7754. * Each call() can override this value.
  7755. *
  7756. * This is no longer used.
  7757. *
  7758. * @param boolean $rpcParams
  7759. * @access public
  7760. * @deprecated
  7761. */
  7762. function setDefaultRpcParams($rpcParams) {
  7763. $this->defaultRpcParams = $rpcParams;
  7764. }
  7765. /**
  7766. * dynamically creates an instance of a proxy class,
  7767. * allowing user to directly call methods from wsdl
  7768. *
  7769. * @return object soap_proxy object
  7770. * @access public
  7771. */
  7772. function getProxy() {
  7773. $r = rand();
  7774. $evalStr = $this->_getProxyClassCode($r);
  7775. //$this->debug("proxy class: $evalStr");
  7776. if ($this->getError()) {
  7777. $this->debug("Error from _getProxyClassCode, so return NULL");
  7778. return null;
  7779. }
  7780. // eval the class
  7781. eval($evalStr);
  7782. // instantiate proxy object
  7783. eval("\$proxy = new nusoap_proxy_$r('');");
  7784. // transfer current wsdl data to the proxy thereby avoiding parsing the wsdl twice
  7785. $proxy->endpointType = 'wsdl';
  7786. $proxy->wsdlFile = $this->wsdlFile;
  7787. $proxy->wsdl = $this->wsdl;
  7788. $proxy->operations = $this->operations;
  7789. $proxy->defaultRpcParams = $this->defaultRpcParams;
  7790. // transfer other state
  7791. $proxy->soap_defencoding = $this->soap_defencoding;
  7792. $proxy->username = $this->username;
  7793. $proxy->password = $this->password;
  7794. $proxy->authtype = $this->authtype;
  7795. $proxy->certRequest = $this->certRequest;
  7796. $proxy->requestHeaders = $this->requestHeaders;
  7797. $proxy->endpoint = $this->endpoint;
  7798. $proxy->forceEndpoint = $this->forceEndpoint;
  7799. $proxy->proxyhost = $this->proxyhost;
  7800. $proxy->proxyport = $this->proxyport;
  7801. $proxy->proxyusername = $this->proxyusername;
  7802. $proxy->proxypassword = $this->proxypassword;
  7803. $proxy->http_encoding = $this->http_encoding;
  7804. $proxy->timeout = $this->timeout;
  7805. $proxy->response_timeout = $this->response_timeout;
  7806. $proxy->persistentConnection = &$this->persistentConnection;
  7807. $proxy->decode_utf8 = $this->decode_utf8;
  7808. $proxy->curl_options = $this->curl_options;
  7809. $proxy->bindingType = $this->bindingType;
  7810. $proxy->use_curl = $this->use_curl;
  7811. return $proxy;
  7812. }
  7813.  
  7814. /**
  7815. * dynamically creates proxy class code
  7816. *
  7817. * @return string PHP/NuSOAP code for the proxy class
  7818. * @access private
  7819. */
  7820. function _getProxyClassCode($r) {
  7821. $this->debug("in getProxy endpointType=$this->endpointType");
  7822. $this->appendDebug("wsdl=" . $this->varDump($this->wsdl));
  7823. if ($this->endpointType != 'wsdl') {
  7824. $evalStr = 'A proxy can only be created for a WSDL client';
  7825. $this->setError($evalStr);
  7826. $evalStr = "echo \"$evalStr\";";
  7827. return $evalStr;
  7828. }
  7829. if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) {
  7830. $this->loadWSDL();
  7831. if ($this->getError()) {
  7832. return "echo \"" . $this->getError() . "\";";
  7833. }
  7834. }
  7835. $evalStr = '';
  7836. foreach ($this->operations as $operation => $opData) {
  7837. if ($operation != '') {
  7838. // create param string and param comment string
  7839. if (sizeof($opData['input']['parts']) > 0) {
  7840. $paramStr = '';
  7841. $paramArrayStr = '';
  7842. $paramCommentStr = '';
  7843. foreach ($opData['input']['parts'] as $name => $type) {
  7844. $paramStr .= "\$$name, ";
  7845. $paramArrayStr .= "'$name' => \$$name, ";
  7846. $paramCommentStr .= "$type \$$name, ";
  7847. }
  7848. $paramStr = substr($paramStr, 0, strlen($paramStr)-2);
  7849. $paramArrayStr = substr($paramArrayStr, 0, strlen($paramArrayStr)-2);
  7850. $paramCommentStr = substr($paramCommentStr, 0, strlen($paramCommentStr)-2);
  7851. } else {
  7852. $paramStr = '';
  7853. $paramArrayStr = '';
  7854. $paramCommentStr = 'void';
  7855. }
  7856. $opData['namespace'] = !isset($opData['namespace']) ? 'http://testuri.com' : $opData['namespace'];
  7857. $evalStr .= "// $paramCommentStr
  7858. function " . str_replace('.', '__', $operation) . "($paramStr) {
  7859. \$params = array($paramArrayStr);
  7860. return \$this->call('$operation', \$params, '".$opData['namespace']."', '".(isset($opData['soapAction']) ? $opData['soapAction'] : '')."');
  7861. }
  7862. ";
  7863. unset($paramStr);
  7864. unset($paramCommentStr);
  7865. }
  7866. }
  7867. $evalStr = 'class nusoap_proxy_'.$r.' extends nusoap_client {
  7868. '.$evalStr.'
  7869. }';
  7870. return $evalStr;
  7871. }
  7872.  
  7873. /**
  7874. * dynamically creates proxy class code
  7875. *
  7876. * @return string PHP/NuSOAP code for the proxy class
  7877. * @access public
  7878. */
  7879. function getProxyClassCode() {
  7880. $r = rand();
  7881. return $this->_getProxyClassCode($r);
  7882. }
  7883.  
  7884. /**
  7885. * gets the HTTP body for the current request.
  7886. *
  7887. * @param string $soapmsg The SOAP payload
  7888. * @return string The HTTP body, which includes the SOAP payload
  7889. * @access private
  7890. */
  7891. function getHTTPBody($soapmsg) {
  7892. return $soapmsg;
  7893. }
  7894. /**
  7895. * gets the HTTP content type for the current request.
  7896. *
  7897. * Note: getHTTPBody must be called before this.
  7898. *
  7899. * @return string the HTTP content type for the current request.
  7900. * @access private
  7901. */
  7902. function getHTTPContentType() {
  7903. return 'text/xml';
  7904. }
  7905. /**
  7906. * gets the HTTP content type charset for the current request.
  7907. * returns false for non-text content types.
  7908. *
  7909. * Note: getHTTPBody must be called before this.
  7910. *
  7911. * @return string the HTTP content type charset for the current request.
  7912. * @access private
  7913. */
  7914. function getHTTPContentTypeCharset() {
  7915. return $this->soap_defencoding;
  7916. }
  7917.  
  7918. /*
  7919. * whether or not parser should decode utf8 element content
  7920. *
  7921. * @return always returns true
  7922. * @access public
  7923. */
  7924. function decodeUTF8($bool){
  7925. $this->decode_utf8 = $bool;
  7926. return true;
  7927. }
  7928.  
  7929. /**
  7930. * adds a new Cookie into $this->cookies array
  7931. *
  7932. * @param string $name Cookie Name
  7933. * @param string $value Cookie Value
  7934. * @return boolean if cookie-set was successful returns true, else false
  7935. * @access public
  7936. */
  7937. function setCookie($name, $value) {
  7938. if (strlen($name) == 0) {
  7939. return false;
  7940. }
  7941. $this->cookies[] = array('name' => $name, 'value' => $value);
  7942. return true;
  7943. }
  7944.  
  7945. /**
  7946. * gets all Cookies
  7947. *
  7948. * @return array with all internal cookies
  7949. * @access public
  7950. */
  7951. function getCookies() {
  7952. return $this->cookies;
  7953. }
  7954.  
  7955. /**
  7956. * checks all Cookies and delete those which are expired
  7957. *
  7958. * @return boolean always return true
  7959. * @access private
  7960. */
  7961. function checkCookies() {
  7962. if (sizeof($this->cookies) == 0) {
  7963. return true;
  7964. }
  7965. $this->debug('checkCookie: check ' . sizeof($this->cookies) . ' cookies');
  7966. $curr_cookies = $this->cookies;
  7967. $this->cookies = array();
  7968. foreach ($curr_cookies as $cookie) {
  7969. if (! is_array($cookie)) {
  7970. $this->debug('Remove cookie that is not an array');
  7971. continue;
  7972. }
  7973. if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) {
  7974. if (strtotime($cookie['expires']) > time()) {
  7975. $this->cookies[] = $cookie;
  7976. } else {
  7977. $this->debug('Remove expired cookie ' . $cookie['name']);
  7978. }
  7979. } else {
  7980. $this->cookies[] = $cookie;
  7981. }
  7982. }
  7983. $this->debug('checkCookie: '.sizeof($this->cookies).' cookies left in array');
  7984. return true;
  7985. }
  7986.  
  7987. /**
  7988. * updates the current cookies with a new set
  7989. *
  7990. * @param array $cookies new cookies with which to update current ones
  7991. * @return boolean always return true
  7992. * @access private
  7993. */
  7994. function UpdateCookies($cookies) {
  7995. if (sizeof($this->cookies) == 0) {
  7996. // no existing cookies: take whatever is new
  7997. if (sizeof($cookies) > 0) {
  7998. $this->debug('Setting new cookie(s)');
  7999. $this->cookies = $cookies;
  8000. }
  8001. return true;
  8002. }
  8003. if (sizeof($cookies) == 0) {
  8004. // no new cookies: keep what we've got
  8005. return true;
  8006. }
  8007. // merge
  8008. foreach ($cookies as $newCookie) {
  8009. if (!is_array($newCookie)) {
  8010. continue;
  8011. }
  8012. if ((!isset($newCookie['name'])) || (!isset($newCookie['value']))) {
  8013. continue;
  8014. }
  8015. $newName = $newCookie['name'];
  8016.  
  8017. $found = false;
  8018. for ($i = 0; $i < count($this->cookies); $i++) {
  8019. $cookie = $this->cookies[$i];
  8020. if (!is_array($cookie)) {
  8021. continue;
  8022. }
  8023. if (!isset($cookie['name'])) {
  8024. continue;
  8025. }
  8026. if ($newName != $cookie['name']) {
  8027. continue;
  8028. }
  8029. $newDomain = isset($newCookie['domain']) ? $newCookie['domain'] : 'NODOMAIN';
  8030. $domain = isset($cookie['domain']) ? $cookie['domain'] : 'NODOMAIN';
  8031. if ($newDomain != $domain) {
  8032. continue;
  8033. }
  8034. $newPath = isset($newCookie['path']) ? $newCookie['path'] : 'NOPATH';
  8035. $path = isset($cookie['path']) ? $cookie['path'] : 'NOPATH';
  8036. if ($newPath != $path) {
  8037. continue;
  8038. }
  8039. $this->cookies[$i] = $newCookie;
  8040. $found = true;
  8041. $this->debug('Update cookie ' . $newName . '=' . $newCookie['value']);
  8042. break;
  8043. }
  8044. if (! $found) {
  8045. $this->debug('Add cookie ' . $newName . '=' . $newCookie['value']);
  8046. $this->cookies[] = $newCookie;
  8047. }
  8048. }
  8049. return true;
  8050. }
  8051. }
  8052.  
  8053. if (!extension_loaded('soap')) {
  8054. /**
  8055. * For backwards compatiblity, define soapclient unless the PHP SOAP extension is loaded.
  8056. */
  8057. class soapclient extends nusoap_client {
  8058. }
  8059. }
  8060. ?>

Documentation generated on Mon, 26 Apr 2010 16:17:01 -0400 by phpDocumentor 1.3.0RC3