PageRenderTime 178ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 2ms

/include/nusoap/nusoap.php

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