]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/nusoap/class.wsdl.php
Release 6.1.4
[Github/sugarcrm.git] / include / nusoap / class.wsdl.php
1 <?php
2
3 /*
4
5 Modification information for LGPL compliance
6
7 r57813 - 2010-08-19 10:34:44 -0700 (Thu, 19 Aug 2010) - kjing - Author: John Mertic <jmertic@sugarcrm.com>
8     Bug 39085 - When loading the opposite search panel via ajax on the ListViews, call the index action instead of the ListView action to avoid touching pre-MVC code by accident.
9
10 r56990 - 2010-06-16 13:05:36 -0700 (Wed, 16 Jun 2010) - kjing - snapshot "Mango" svn branch to a new one for GitHub sync
11
12 r56989 - 2010-06-16 13:01:33 -0700 (Wed, 16 Jun 2010) - kjing - defunt "Mango" svn dev branch before github cutover
13
14 r55980 - 2010-04-19 13:31:28 -0700 (Mon, 19 Apr 2010) - kjing - create Mango (6.1) based on windex
15
16 r51719 - 2009-10-22 10:18:00 -0700 (Thu, 22 Oct 2009) - mitani - Converted to Build 3  tags and updated the build system 
17
18 r51634 - 2009-10-19 13:32:22 -0700 (Mon, 19 Oct 2009) - mitani - Windex is the branch for Sugar Sales 1.0 development
19
20 r51443 - 2009-10-12 13:34:36 -0700 (Mon, 12 Oct 2009) - jmertic - Bug 33332 - Made application PHP 5.3 compliant with E_DEPRECATED warnings on by:
21 - Changing all ereg function to either preg or simple string based ones
22 - No more references to magic quotes.
23 - Change all the session_unregister() functions to just unset() the correct session variable instead.
24
25 r50375 - 2009-08-24 18:07:43 -0700 (Mon, 24 Aug 2009) - dwong - branch kobe2 from tokyo r50372
26
27 r42807 - 2008-12-29 11:16:59 -0800 (Mon, 29 Dec 2008) - dwong - Branch from trunk/sugarcrm r42806 to branches/tokyo/sugarcrm
28
29 r13782 - 2006-06-06 10:58:55 -0700 (Tue, 06 Jun 2006) - majed - changes entry point code
30
31 r11115 - 2006-01-17 14:54:45 -0800 (Tue, 17 Jan 2006) - majed - add entry point validation
32
33 r8846 - 2005-10-31 11:01:12 -0800 (Mon, 31 Oct 2005) - majed - new version of nusoap
34
35 r7905 - 2005-09-21 19:12:57 -0700 (Wed, 21 Sep 2005) - majed - restores old nusoap pre & with a few fixes
36
37 r7861 - 2005-09-20 15:40:25 -0700 (Tue, 20 Sep 2005) - majed - & fix for 3.5.1
38
39 r5462 - 2005-05-25 13:50:11 -0700 (Wed, 25 May 2005) - majed - upgraded nusoap to .6.9
40
41 r573 - 2004-09-04 13:03:32 -0700 (Sat, 04 Sep 2004) - sugarclint - undoing copyrights added in inadvertantly.  --clint
42
43 r546 - 2004-09-03 11:49:38 -0700 (Fri, 03 Sep 2004) - sugarmsi - removed echo count
44
45 r354 - 2004-08-02 23:00:37 -0700 (Mon, 02 Aug 2004) - sugarjacob - Adding Soap
46
47
48 */
49
50
51 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
52
53
54
55
56 /**
57 * parses a WSDL file, allows access to it's data, other utility methods.
58 * also builds WSDL structures programmatically.
59
60 * @author   Dietrich Ayala <dietrich@ganx4.com>
61 * @author   Scott Nichol <snichol@users.sourceforge.net>
62
63 * @access public 
64 */
65 class wsdl extends nusoap_base {
66         // URL or filename of the root of this WSDL
67     var $wsdl; 
68     // define internal arrays of bindings, ports, operations, messages, etc.
69     var $schemas = array();
70     var $currentSchema;
71     var $message = array();
72     var $complexTypes = array();
73     var $messages = array();
74     var $currentMessage;
75     var $currentOperation;
76     var $portTypes = array();
77     var $currentPortType;
78     var $bindings = array();
79     var $currentBinding;
80     var $ports = array();
81     var $currentPort;
82     var $opData = array();
83     var $status = '';
84     var $documentation = false;
85     var $endpoint = ''; 
86     // array of wsdl docs to import
87     var $import = array(); 
88     // parser vars
89     var $parser;
90     var $position = 0;
91     var $depth = 0;
92     var $depth_array = array();
93         // for getting wsdl
94         var $proxyhost = '';
95     var $proxyport = '';
96         var $proxyusername = '';
97         var $proxypassword = '';
98         var $timeout = 0;
99         var $response_timeout = 30;
100         var $curl_options = array();    // User-specified cURL options
101         var $use_curl = false;                  // whether to always try to use cURL
102         // for HTTP authentication
103         var $username = '';                             // Username for HTTP authentication
104         var $password = '';                             // Password for HTTP authentication
105         var $authtype = '';                             // Type of HTTP authentication
106         var $certRequest = array();             // Certificate for HTTP SSL authentication
107
108     /**
109      * constructor
110      * 
111      * @param string $wsdl WSDL document URL
112          * @param string $proxyhost
113          * @param string $proxyport
114          * @param string $proxyusername
115          * @param string $proxypassword
116          * @param integer $timeout set the connection timeout
117          * @param integer $response_timeout set the response timeout
118          * @param array $curl_options user-specified cURL options
119          * @param boolean $use_curl try to use cURL
120      * @access public 
121      */
122     function wsdl($wsdl = '',$proxyhost=false,$proxyport=false,$proxyusername=false,$proxypassword=false,$timeout=0,$response_timeout=30,$curl_options=null,$use_curl=false){
123                 parent::nusoap_base();
124                 $this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout");
125         $this->proxyhost = $proxyhost;
126         $this->proxyport = $proxyport;
127                 $this->proxyusername = $proxyusername;
128                 $this->proxypassword = $proxypassword;
129                 $this->timeout = $timeout;
130                 $this->response_timeout = $response_timeout;
131                 if (is_array($curl_options))
132                         $this->curl_options = $curl_options;
133                 $this->use_curl = $use_curl;
134                 $this->fetchWSDL($wsdl);
135     }
136
137         /**
138          * fetches the WSDL document and parses it
139          *
140          * @access public
141          */
142         function fetchWSDL($wsdl) {
143                 $this->debug("parse and process WSDL path=$wsdl");
144                 $this->wsdl = $wsdl;
145         // parse wsdl file
146         if ($this->wsdl != "") {
147             $this->parseWSDL($this->wsdl);
148         }
149         // imports
150         // TODO: handle imports more properly, grabbing them in-line and nesting them
151         $imported_urls = array();
152         $imported = 1;
153         while ($imported > 0) {
154                 $imported = 0;
155                 // Schema imports
156                 foreach ($this->schemas as $ns => $list) {
157                         foreach ($list as $xs) {
158                                         $wsdlparts = parse_url($this->wsdl);    // this is bogusly simple!
159                             foreach ($xs->imports as $ns2 => $list2) {
160                                 for ($ii = 0; $ii < count($list2); $ii++) {
161                                         if (! $list2[$ii]['loaded']) {
162                                                 $this->schemas[$ns]->imports[$ns2][$ii]['loaded'] = true;
163                                                 $url = $list2[$ii]['location'];
164                                                                 if ($url != '') {
165                                                                         $urlparts = parse_url($url);
166                                                                         if (!isset($urlparts['host'])) {
167                                                                                 $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' .$wsdlparts['port'] : '') .
168                                                                                                 substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
169                                                                         }
170                                                                         if (! in_array($url, $imported_urls)) {
171                                                                 $this->parseWSDL($url);
172                                                                 $imported++;
173                                                                 $imported_urls[] = $url;
174                                                         }
175                                                                 } else {
176                                                                         $this->debug("Unexpected scenario: empty URL for unloaded import");
177                                                                 }
178                                                         }
179                                                 }
180                             } 
181                         }
182                 }
183                 // WSDL imports
184                         $wsdlparts = parse_url($this->wsdl);    // this is bogusly simple!
185             foreach ($this->import as $ns => $list) {
186                 for ($ii = 0; $ii < count($list); $ii++) {
187                         if (! $list[$ii]['loaded']) {
188                                 $this->import[$ns][$ii]['loaded'] = true;
189                                 $url = $list[$ii]['location'];
190                                                 if ($url != '') {
191                                                         $urlparts = parse_url($url);
192                                                         if (!isset($urlparts['host'])) {
193                                                                 $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') .
194                                                                                 substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path'];
195                                                         }
196                                                         if (! in_array($url, $imported_urls)) {
197                                                 $this->parseWSDL($url);
198                                                 $imported++;
199                                                 $imported_urls[] = $url;
200                                         }
201                                                 } else {
202                                                         $this->debug("Unexpected scenario: empty URL for unloaded import");
203                                                 }
204                                         }
205                                 }
206             } 
207                 }
208         // add new data to operation data
209         foreach($this->bindings as $binding => $bindingData) {
210             if (isset($bindingData['operations']) && is_array($bindingData['operations'])) {
211                 foreach($bindingData['operations'] as $operation => $data) {
212                     $this->debug('post-parse data gathering for ' . $operation);
213                     $this->bindings[$binding]['operations'][$operation]['input'] = 
214                                                 isset($this->bindings[$binding]['operations'][$operation]['input']) ? 
215                                                 array_merge($this->bindings[$binding]['operations'][$operation]['input'], $this->portTypes[ $bindingData['portType'] ][$operation]['input']) :
216                                                 $this->portTypes[ $bindingData['portType'] ][$operation]['input'];
217                     $this->bindings[$binding]['operations'][$operation]['output'] = 
218                                                 isset($this->bindings[$binding]['operations'][$operation]['output']) ?
219                                                 array_merge($this->bindings[$binding]['operations'][$operation]['output'], $this->portTypes[ $bindingData['portType'] ][$operation]['output']) :
220                                                 $this->portTypes[ $bindingData['portType'] ][$operation]['output'];
221                     if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ])){
222                                                 $this->bindings[$binding]['operations'][$operation]['input']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ];
223                                         }
224                                         if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ])){
225                                 $this->bindings[$binding]['operations'][$operation]['output']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ];
226                     }
227                     // Set operation style if necessary, but do not override one already provided
228                                         if (isset($bindingData['style']) && !isset($this->bindings[$binding]['operations'][$operation]['style'])) {
229                         $this->bindings[$binding]['operations'][$operation]['style'] = $bindingData['style'];
230                     }
231                     $this->bindings[$binding]['operations'][$operation]['transport'] = isset($bindingData['transport']) ? $bindingData['transport'] : '';
232                     $this->bindings[$binding]['operations'][$operation]['documentation'] = isset($this->portTypes[ $bindingData['portType'] ][$operation]['documentation']) ? $this->portTypes[ $bindingData['portType'] ][$operation]['documentation'] : '';
233                     $this->bindings[$binding]['operations'][$operation]['endpoint'] = isset($bindingData['endpoint']) ? $bindingData['endpoint'] : '';
234                 } 
235             } 
236         }
237         }
238
239     /**
240      * parses the wsdl document
241      * 
242      * @param string $wsdl path or URL
243      * @access private 
244      */
245     function parseWSDL($wsdl = '') {
246                 $this->debug("parse WSDL at path=$wsdl");
247
248         if ($wsdl == '') {
249             $this->debug('no wsdl passed to parseWSDL()!!');
250             $this->setError('no wsdl passed to parseWSDL()!!');
251             return false;
252         }
253         
254         // parse $wsdl for url format
255         $wsdl_props = parse_url($wsdl);
256
257         if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'http' || $wsdl_props['scheme'] == 'https')) {
258             $this->debug('getting WSDL http(s) URL ' . $wsdl);
259                 // get wsdl
260                 $tr = new soap_transport_http($wsdl, $this->curl_options, $this->use_curl);
261                         $tr->request_method = 'GET';
262                         $tr->useSOAPAction = false;
263                         if($this->proxyhost && $this->proxyport){
264                                 $tr->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword);
265                         }
266                         if ($this->authtype != '') {
267                                 $tr->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest);
268                         }
269                         $tr->setEncoding('gzip, deflate');
270                         $wsdl_string = $tr->send('', $this->timeout, $this->response_timeout);
271                         //$this->debug("WSDL request\n" . $tr->outgoing_payload);
272                         //$this->debug("WSDL response\n" . $tr->incoming_payload);
273                         $this->appendDebug($tr->getDebug());
274                         // catch errors
275                         if($err = $tr->getError() ){
276                                 $errstr = 'Getting ' . $wsdl . ' - HTTP ERROR: '.$err;
277                                 $this->debug($errstr);
278                     $this->setError($errstr);
279                                 unset($tr);
280                     return false;
281                         }
282                         unset($tr);
283                         $this->debug("got WSDL URL");
284         } else {
285             // $wsdl is not http(s), so treat it as a file URL or plain file path
286                 if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'file') && isset($wsdl_props['path'])) {
287                         $path = isset($wsdl_props['host']) ? ($wsdl_props['host'] . ':' . $wsdl_props['path']) : $wsdl_props['path'];
288                 } else {
289                         $path = $wsdl;
290                 }
291             $this->debug('getting WSDL file ' . $path);
292             if ($fp = @fopen($path, 'r')) {
293                 $wsdl_string = '';
294                 while ($data = fread($fp, 32768)) {
295                     $wsdl_string .= $data;
296                 } 
297                 fclose($fp);
298             } else {
299                 $errstr = "Bad path to WSDL file $path";
300                 $this->debug($errstr);
301                 $this->setError($errstr);
302                 return false;
303             } 
304         }
305         $this->debug('Parse WSDL');
306         // end new code added
307         // Create an XML parser.
308         $this->parser = xml_parser_create(); 
309         // Set the options for parsing the XML data.
310         // xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
311         xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); 
312         // Set the object for the parser.
313         xml_set_object($this->parser, $this); 
314         // Set the element handlers for the parser.
315         xml_set_element_handler($this->parser, 'start_element', 'end_element');
316         xml_set_character_data_handler($this->parser, 'character_data');
317         // Parse the XML file.
318         if (!xml_parse($this->parser, $wsdl_string, true)) {
319             // Display an error message.
320             $errstr = sprintf(
321                                 'XML error parsing WSDL from %s on line %d: %s',
322                                 $wsdl,
323                 xml_get_current_line_number($this->parser),
324                 xml_error_string(xml_get_error_code($this->parser))
325                 );
326             $this->debug($errstr);
327                         $this->debug("XML payload:\n" . $wsdl_string);
328             $this->setError($errstr);
329             return false;
330         } 
331                 // free the parser
332         xml_parser_free($this->parser);
333         $this->debug('Parsing WSDL done');
334                 // catch wsdl parse errors
335                 if($this->getError()){
336                         return false;
337                 }
338         return true;
339     } 
340
341     /**
342      * start-element handler
343      * 
344      * @param string $parser XML parser object
345      * @param string $name element name
346      * @param string $attrs associative array of attributes
347      * @access private 
348      */
349     function start_element($parser, $name, $attrs)
350     {
351         if ($this->status == 'schema') {
352             $this->currentSchema->schemaStartElement($parser, $name, $attrs);
353             $this->appendDebug($this->currentSchema->getDebug());
354             $this->currentSchema->clearDebug();
355         } elseif (preg_match('/schema$/', $name)) {
356                 $this->debug('Parsing WSDL schema');
357             // $this->debug("startElement for $name ($attrs[name]). status = $this->status (".$this->getLocalPart($name).")");
358             $this->status = 'schema';
359             $this->currentSchema = new nusoap_xmlschema('', '', $this->namespaces);
360             $this->currentSchema->schemaStartElement($parser, $name, $attrs);
361             $this->appendDebug($this->currentSchema->getDebug());
362             $this->currentSchema->clearDebug();
363         } else {
364             // position in the total number of elements, starting from 0
365             $pos = $this->position++;
366             $depth = $this->depth++; 
367             // set self as current value for this depth
368             $this->depth_array[$depth] = $pos;
369             $this->message[$pos] = array('cdata' => ''); 
370             // process attributes
371             if (count($attrs) > 0) {
372                                 // register namespace declarations
373                 foreach($attrs as $k => $v) {
374                     if (preg_match('/^xmlns/',$k)) {
375                         if ($ns_prefix = substr(strrchr($k, ':'), 1)) {
376                             $this->namespaces[$ns_prefix] = $v;
377                         } else {
378                             $this->namespaces['ns' . (count($this->namespaces) + 1)] = $v;
379                         } 
380                         if ($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema') {
381                             $this->XMLSchemaVersion = $v;
382                             $this->namespaces['xsi'] = $v . '-instance';
383                         } 
384                     }
385                 }
386                 // expand each attribute prefix to its namespace
387                 foreach($attrs as $k => $v) {
388                     $k = strpos($k, ':') ? $this->expandQname($k) : $k;
389                     if ($k != 'location' && $k != 'soapAction' && $k != 'namespace') {
390                         $v = strpos($v, ':') ? $this->expandQname($v) : $v;
391                     } 
392                     $eAttrs[$k] = $v;
393                 } 
394                 $attrs = $eAttrs;
395             } else {
396                 $attrs = array();
397             } 
398             // get element prefix, namespace and name
399             if (preg_match('/:/', $name)) {
400                 // get ns prefix
401                 $prefix = substr($name, 0, strpos($name, ':')); 
402                 // get ns
403                 $namespace = isset($this->namespaces[$prefix]) ? $this->namespaces[$prefix] : ''; 
404                 // get unqualified name
405                 $name = substr(strstr($name, ':'), 1);
406             } 
407                         // process attributes, expanding any prefixes to namespaces
408             // find status, register data
409             switch ($this->status) {
410                 case 'message':
411                     if ($name == 'part') {
412                                     if (isset($attrs['type'])) {
413                                     $this->debug("msg " . $this->currentMessage . ": found part (with type) $attrs[name]: " . implode(',', $attrs));
414                                     $this->messages[$this->currentMessage][$attrs['name']] = $attrs['type'];
415                                 } 
416                                     if (isset($attrs['element'])) {
417                                     $this->debug("msg " . $this->currentMessage . ": found part (with element) $attrs[name]: " . implode(',', $attrs));
418                                         $this->messages[$this->currentMessage][$attrs['name']] = $attrs['element'] . '^';
419                                     } 
420                                 } 
421                                 break;
422                             case 'portType':
423                                 switch ($name) {
424                                     case 'operation':
425                                         $this->currentPortOperation = $attrs['name'];
426                                         $this->debug("portType $this->currentPortType operation: $this->currentPortOperation");
427                                         if (isset($attrs['parameterOrder'])) {
428                                                 $this->portTypes[$this->currentPortType][$attrs['name']]['parameterOrder'] = $attrs['parameterOrder'];
429                                                 } 
430                                                 break;
431                                             case 'documentation':
432                                                 $this->documentation = true;
433                                                 break; 
434                                             // merge input/output data
435                                             default:
436                                                 $m = isset($attrs['message']) ? $this->getLocalPart($attrs['message']) : '';
437                                                 $this->portTypes[$this->currentPortType][$this->currentPortOperation][$name]['message'] = $m;
438                                                 break;
439                                         } 
440                                 break;
441                                 case 'binding':
442                                     switch ($name) {
443                                         case 'binding': 
444                                             // get ns prefix
445                                             if (isset($attrs['style'])) {
446                                             $this->bindings[$this->currentBinding]['prefix'] = $prefix;
447                                                 } 
448                                                 $this->bindings[$this->currentBinding] = array_merge($this->bindings[$this->currentBinding], $attrs);
449                                                 break;
450                                                 case 'header':
451                                                     $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs;
452                                                     break;
453                                                 case 'operation':
454                                                     if (isset($attrs['soapAction'])) {
455                                                         $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['soapAction'] = $attrs['soapAction'];
456                                                     } 
457                                                     if (isset($attrs['style'])) {
458                                                         $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['style'] = $attrs['style'];
459                                                     } 
460                                                     if (isset($attrs['name'])) {
461                                                         $this->currentOperation = $attrs['name'];
462                                                         $this->debug("current binding operation: $this->currentOperation");
463                                                         $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['name'] = $attrs['name'];
464                                                         $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['binding'] = $this->currentBinding;
465                                                         $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['endpoint'] = isset($this->bindings[$this->currentBinding]['endpoint']) ? $this->bindings[$this->currentBinding]['endpoint'] : '';
466                                                     } 
467                                                     break;
468                                                 case 'input':
469                                                     $this->opStatus = 'input';
470                                                     break;
471                                                 case 'output':
472                                                     $this->opStatus = 'output';
473                                                     break;
474                                                 case 'body':
475                                                     if (isset($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus])) {
476                                                         $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = array_merge($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus], $attrs);
477                                                     } else {
478                                                         $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = $attrs;
479                                                     } 
480                                                     break;
481                                         } 
482                                         break;
483                                 case 'service':
484                                         switch ($name) {
485                                             case 'port':
486                                                 $this->currentPort = $attrs['name'];
487                                                 $this->debug('current port: ' . $this->currentPort);
488                                                 $this->ports[$this->currentPort]['binding'] = $this->getLocalPart($attrs['binding']);
489                                         
490                                                 break;
491                                             case 'address':
492                                                 $this->ports[$this->currentPort]['location'] = $attrs['location'];
493                                                 $this->ports[$this->currentPort]['bindingType'] = $namespace;
494                                                 $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['bindingType'] = $namespace;
495                                                 $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['endpoint'] = $attrs['location'];
496                                                 break;
497                                         } 
498                                         break;
499                         } 
500                 // set status
501                 switch ($name) {
502                         case 'import':
503                             if (isset($attrs['location'])) {
504                     $this->import[$attrs['namespace']][] = array('location' => $attrs['location'], 'loaded' => false);
505                     $this->debug('parsing import ' . $attrs['namespace']. ' - ' . $attrs['location'] . ' (' . count($this->import[$attrs['namespace']]).')');
506                                 } else {
507                     $this->import[$attrs['namespace']][] = array('location' => '', 'loaded' => true);
508                                         if (! $this->getPrefixFromNamespace($attrs['namespace'])) {
509                                                 $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace'];
510                                         }
511                     $this->debug('parsing import ' . $attrs['namespace']. ' - [no location] (' . count($this->import[$attrs['namespace']]).')');
512                                 }
513                                 break;
514                         //wait for schema
515                         //case 'types':
516                         //      $this->status = 'schema';
517                         //      break;
518                         case 'message':
519                                 $this->status = 'message';
520                                 $this->messages[$attrs['name']] = array();
521                                 $this->currentMessage = $attrs['name'];
522                                 break;
523                         case 'portType':
524                                 $this->status = 'portType';
525                                 $this->portTypes[$attrs['name']] = array();
526                                 $this->currentPortType = $attrs['name'];
527                                 break;
528                         case "binding":
529                                 if (isset($attrs['name'])) {
530                                 // get binding name
531                                         if (strpos($attrs['name'], ':')) {
532                                         $this->currentBinding = $this->getLocalPart($attrs['name']);
533                                         } else {
534                                         $this->currentBinding = $attrs['name'];
535                                         } 
536                                         $this->status = 'binding';
537                                         $this->bindings[$this->currentBinding]['portType'] = $this->getLocalPart($attrs['type']);
538                                         $this->debug("current binding: $this->currentBinding of portType: " . $attrs['type']);
539                                 } 
540                                 break;
541                         case 'service':
542                                 $this->serviceName = $attrs['name'];
543                                 $this->status = 'service';
544                                 $this->debug('current service: ' . $this->serviceName);
545                                 break;
546                         case 'definitions':
547                                 foreach ($attrs as $name => $value) {
548                                         $this->wsdl_info[$name] = $value;
549                                 } 
550                                 break;
551                         } 
552                 } 
553         } 
554
555         /**
556         * end-element handler
557         * 
558         * @param string $parser XML parser object
559         * @param string $name element name
560         * @access private 
561         */
562         function end_element($parser, $name){ 
563                 // unset schema status
564                 if (/*preg_match('/types$/', $name) ||*/ preg_match('/schema$/', $name)) {
565                         $this->status = "";
566             $this->appendDebug($this->currentSchema->getDebug());
567             $this->currentSchema->clearDebug();
568                         $this->schemas[$this->currentSchema->schemaTargetNamespace][] = $this->currentSchema;
569                 $this->debug('Parsing WSDL schema done');
570                 } 
571                 if ($this->status == 'schema') {
572                         $this->currentSchema->schemaEndElement($parser, $name);
573                 } else {
574                         // bring depth down a notch
575                         $this->depth--;
576                 } 
577                 // end documentation
578                 if ($this->documentation) {
579                         //TODO: track the node to which documentation should be assigned; it can be a part, message, etc.
580                         //$this->portTypes[$this->currentPortType][$this->currentPortOperation]['documentation'] = $this->documentation;
581                         $this->documentation = false;
582                 } 
583         } 
584
585         /**
586          * element content handler
587          * 
588          * @param string $parser XML parser object
589          * @param string $data element content
590          * @access private 
591          */
592         function character_data($parser, $data)
593         {
594                 $pos = isset($this->depth_array[$this->depth]) ? $this->depth_array[$this->depth] : 0;
595                 if (isset($this->message[$pos]['cdata'])) {
596                         $this->message[$pos]['cdata'] .= $data;
597                 } 
598                 if ($this->documentation) {
599                         $this->documentation .= $data;
600                 } 
601         } 
602
603         /**
604         * if authenticating, set user credentials here
605         *
606         * @param    string $username
607         * @param    string $password
608         * @param        string $authtype (basic|digest|certificate|ntlm)
609         * @param        array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs)
610         * @access   public
611         */
612         function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) {
613                 $this->debug("setCredentials username=$username authtype=$authtype certRequest=");
614                 $this->appendDebug($this->varDump($certRequest));
615                 $this->username = $username;
616                 $this->password = $password;
617                 $this->authtype = $authtype;
618                 $this->certRequest = $certRequest;
619         }
620         
621         function getBindingData($binding)
622         {
623                 if (is_array($this->bindings[$binding])) {
624                         return $this->bindings[$binding];
625                 } 
626         }
627         
628         /**
629          * returns an assoc array of operation names => operation data
630          * 
631          * @param string $portName WSDL port name
632          * @param string $bindingType eg: soap, smtp, dime (only soap and soap12 are currently supported)
633          * @return array 
634          * @access public 
635          */
636         function getOperations($portName = '', $bindingType = 'soap') {
637                 $ops = array();
638                 if ($bindingType == 'soap') {
639                         $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
640                 } elseif ($bindingType == 'soap12') {
641                         $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
642                 } else {
643                         $this->debug("getOperations bindingType $bindingType may not be supported");
644                 }
645                 $this->debug("getOperations for port '$portName' bindingType $bindingType");
646                 // loop thru ports
647                 foreach($this->ports as $port => $portData) {
648                         $this->debug("getOperations checking port $port bindingType " . $portData['bindingType']);
649                         if ($portName == '' || $port == $portName) {
650                                 // binding type of port matches parameter
651                                 if ($portData['bindingType'] == $bindingType) {
652                                         $this->debug("getOperations found port $port bindingType $bindingType");
653                                         //$this->debug("port data: " . $this->varDump($portData));
654                                         //$this->debug("bindings: " . $this->varDump($this->bindings[ $portData['binding'] ]));
655                                         // merge bindings
656                                         if (isset($this->bindings[ $portData['binding'] ]['operations'])) {
657                                                 $ops = array_merge ($ops, $this->bindings[ $portData['binding'] ]['operations']);
658                                         }
659                                 }
660                         }
661                 }
662                 if (count($ops) == 0) {
663                         $this->debug("getOperations found no operations for port '$portName' bindingType $bindingType");
664                 }
665                 return $ops;
666         } 
667         
668         /**
669          * returns an associative array of data necessary for calling an operation
670          * 
671          * @param string $operation name of operation
672          * @param string $bindingType type of binding eg: soap, soap12
673          * @return array 
674          * @access public 
675          */
676         function getOperationData($operation, $bindingType = 'soap')
677         {
678                 if ($bindingType == 'soap') {
679                         $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
680                 } elseif ($bindingType == 'soap12') {
681                         $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
682                 }
683                 // loop thru ports
684                 foreach($this->ports as $port => $portData) {
685                         // binding type of port matches parameter
686                         if ($portData['bindingType'] == $bindingType) {
687                                 // get binding
688                                 //foreach($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
689                                 foreach(array_keys($this->bindings[ $portData['binding'] ]['operations']) as $bOperation) {
690                                         // note that we could/should also check the namespace here
691                                         if ($operation == $bOperation) {
692                                                 $opData = $this->bindings[ $portData['binding'] ]['operations'][$operation];
693                                             return $opData;
694                                         } 
695                                 } 
696                         }
697                 } 
698         }
699         
700         /**
701          * returns an associative array of data necessary for calling an operation
702          * 
703          * @param string $soapAction soapAction for operation
704          * @param string $bindingType type of binding eg: soap, soap12
705          * @return array 
706          * @access public 
707          */
708         function getOperationDataForSoapAction($soapAction, $bindingType = 'soap') {
709                 if ($bindingType == 'soap') {
710                         $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/';
711                 } elseif ($bindingType == 'soap12') {
712                         $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/';
713                 }
714                 // loop thru ports
715                 foreach($this->ports as $port => $portData) {
716                         // binding type of port matches parameter
717                         if ($portData['bindingType'] == $bindingType) {
718                                 // loop through operations for the binding
719                                 foreach ($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) {
720                                         if ($opData['soapAction'] == $soapAction) {
721                                             return $opData;
722                                         } 
723                                 } 
724                         }
725                 } 
726         }
727         
728         /**
729     * returns an array of information about a given type
730     * returns false if no type exists by the given name
731     *
732         *        typeDef = array(
733         *        'elements' => array(), // refs to elements array
734         *       'restrictionBase' => '',
735         *       'phpType' => '',
736         *       'order' => '(sequence|all)',
737         *       'attrs' => array() // refs to attributes array
738         *       )
739     *
740     * @param string $type the type
741     * @param string $ns namespace (not prefix) of the type
742     * @return mixed
743     * @access public
744     * @see nusoap_xmlschema
745     */
746         function getTypeDef($type, $ns) {
747                 $this->debug("in getTypeDef: type=$type, ns=$ns");
748                 if ((! $ns) && isset($this->namespaces['tns'])) {
749                         $ns = $this->namespaces['tns'];
750                         $this->debug("in getTypeDef: type namespace forced to $ns");
751                 }
752                 if (!isset($this->schemas[$ns])) {
753                         foreach ($this->schemas as $ns0 => $schema0) {
754                                 if (strcasecmp($ns, $ns0) == 0) {
755                                         $this->debug("in getTypeDef: replacing schema namespace $ns with $ns0");
756                                         $ns = $ns0;
757                                         break;
758                                 }
759                         }
760                 }
761                 if (isset($this->schemas[$ns])) {
762                         $this->debug("in getTypeDef: have schema for namespace $ns");
763                         for ($i = 0; $i < count($this->schemas[$ns]); $i++) {
764                                 $xs = &$this->schemas[$ns][$i];
765                                 $t = $xs->getTypeDef($type);
766                                 $this->appendDebug($xs->getDebug());
767                                 $xs->clearDebug();
768                                 if ($t) {
769                                         $this->debug("in getTypeDef: found type $type");
770                                         if (!isset($t['phpType'])) {
771                                                 // get info for type to tack onto the element
772                                                 $uqType = substr($t['type'], strrpos($t['type'], ':') + 1);
773                                                 $ns = substr($t['type'], 0, strrpos($t['type'], ':'));
774                                                 $etype = $this->getTypeDef($uqType, $ns);
775                                                 if ($etype) {
776                                                         $this->debug("found type for [element] $type:");
777                                                         $this->debug($this->varDump($etype));
778                                                         if (isset($etype['phpType'])) {
779                                                                 $t['phpType'] = $etype['phpType'];
780                                                         }
781                                                         if (isset($etype['elements'])) {
782                                                                 $t['elements'] = $etype['elements'];
783                                                         }
784                                                         if (isset($etype['attrs'])) {
785                                                                 $t['attrs'] = $etype['attrs'];
786                                                         }
787                                                 } else {
788                                                         $this->debug("did not find type for [element] $type");
789                                                 }
790                                         }
791                                         return $t;
792                                 }
793                         }
794                         $this->debug("in getTypeDef: did not find type $type");
795                 } else {
796                         $this->debug("in getTypeDef: do not have schema for namespace $ns");
797                 }
798                 return false;
799         }
800
801     /**
802     * prints html description of services
803     *
804     * @access private
805     */
806     function webDescription(){
807         global $HTTP_SERVER_VARS;
808
809                 if (isset($_SERVER)) {
810                         $PHP_SELF = $_SERVER['PHP_SELF'];
811                 } elseif (isset($HTTP_SERVER_VARS)) {
812                         $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
813                 } else {
814                         $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available");
815                 }
816
817                 $b = '
818                 <html><head><title>NuSOAP: '.$this->serviceName.'</title>
819                 <style type="text/css">
820                     body    { font-family: arial; color: #000000; background-color: #ffffff; margin: 0px 0px 0px 0px; }
821                     p       { font-family: arial; color: #000000; margin-top: 0px; margin-bottom: 12px; }
822                     pre { background-color: silver; padding: 5px; font-family: Courier New; font-size: x-small; color: #000000;}
823                     ul      { margin-top: 10px; margin-left: 20px; }
824                     li      { list-style-type: none; margin-top: 10px; color: #000000; }
825                     .content{
826                         margin-left: 0px; padding-bottom: 2em; }
827                     .nav {
828                         padding-top: 10px; padding-bottom: 10px; padding-left: 15px; font-size: .70em;
829                         margin-top: 10px; margin-left: 0px; color: #000000;
830                         background-color: #ccccff; width: 20%; margin-left: 20px; margin-top: 20px; }
831                     .title {
832                         font-family: arial; font-size: 26px; color: #ffffff;
833                         background-color: #999999; width: 100%;
834                         margin-left: 0px; margin-right: 0px;
835                         padding-top: 10px; padding-bottom: 10px;}
836                     .hidden {
837                         position: absolute; visibility: hidden; z-index: 200; left: 250px; top: 100px;
838                         font-family: arial; overflow: hidden; width: 600;
839                         padding: 20px; font-size: 10px; background-color: #999999;
840                         layer-background-color:#FFFFFF; }
841                     a,a:active  { color: charcoal; font-weight: bold; }
842                     a:visited   { color: #666666; font-weight: bold; }
843                     a:hover     { color: cc3300; font-weight: bold; }
844                 </style>
845                 <script language="JavaScript" type="text/javascript">
846                 <!--
847                 // POP-UP CAPTIONS...
848                 function lib_bwcheck(){ //Browsercheck (needed)
849                     this.ver=navigator.appVersion
850                     this.agent=navigator.userAgent
851                     this.dom=document.getElementById?1:0
852                     this.opera5=this.agent.indexOf("Opera 5")>-1
853                     this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0;
854                     this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
855                     this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
856                     this.ie=this.ie4||this.ie5||this.ie6
857                     this.mac=this.agent.indexOf("Mac")>-1
858                     this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0;
859                     this.ns4=(document.layers && !this.dom)?1:0;
860                     this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5)
861                     return this
862                 }
863                 var bw = new lib_bwcheck()
864                 //Makes crossbrowser object.
865                 function makeObj(obj){
866                     this.evnt=bw.dom? document.getElementById(obj):bw.ie4?document.all[obj]:bw.ns4?document.layers[obj]:0;
867                     if(!this.evnt) return false
868                     this.css=bw.dom||bw.ie4?this.evnt.style:bw.ns4?this.evnt:0;
869                     this.wref=bw.dom||bw.ie4?this.evnt:bw.ns4?this.css.document:0;
870                     this.writeIt=b_writeIt;
871                     return this
872                 }
873                 // A unit of measure that will be added when setting the position of a layer.
874                 //var px = bw.ns4||window.opera?"":"px";
875                 function b_writeIt(text){
876                     if (bw.ns4){this.wref.write(text);this.wref.close()}
877                     else this.wref.innerHTML = text
878                 }
879                 //Shows the messages
880                 var oDesc;
881                 function popup(divid){
882                     if(oDesc = new makeObj(divid)){
883                         oDesc.css.visibility = "visible"
884                     }
885                 }
886                 function popout(){ // Hides message
887                     if(oDesc) oDesc.css.visibility = "hidden"
888                 }
889                 //-->
890                 </script>
891                 </head>
892                 <body>
893                 <div class=content>
894                         <br><br>
895                         <div class=title>'.$this->serviceName.'</div>
896                         <div class=nav>
897                                 <p>View the <a href="'.$PHP_SELF.'?wsdl">WSDL</a> for the service.
898                                 Click on an operation name to view it&apos;s details.</p>
899                                 <ul>';
900                                 foreach($this->getOperations() as $op => $data){
901                                     $b .= "<li><a href='#' onclick=\"popout();popup('$op')\">$op</a></li>";
902                                     // create hidden div
903                                     $b .= "<div id='$op' class='hidden'>
904                                     <a href='#' onclick='popout()'><font color='#ffffff'>Close</font></a><br><br>";
905                                     foreach($data as $donnie => $marie){ // loop through opdata
906                                                 if($donnie == 'input' || $donnie == 'output'){ // show input/output data
907                                                     $b .= "<font color='white'>".ucfirst($donnie).':</font><br>';
908                                                     foreach($marie as $captain => $tenille){ // loop through data
909                                                                 if($captain == 'parts'){ // loop thru parts
910                                                                     $b .= "&nbsp;&nbsp;$captain:<br>";
911                                                         //if(is_array($tenille)){
912                                                                         foreach($tenille as $joanie => $chachi){
913                                                                                         $b .= "&nbsp;&nbsp;&nbsp;&nbsp;$joanie: $chachi<br>";
914                                                                         }
915                                                                 //}
916                                                                 } else {
917                                                                     $b .= "&nbsp;&nbsp;$captain: $tenille<br>";
918                                                                 }
919                                                     }
920                                                 } else {
921                                                     $b .= "<font color='white'>".ucfirst($donnie).":</font> $marie<br>";
922                                                 }
923                                     }
924                                         $b .= '</div>';
925                                 }
926                                 $b .= '
927                                 <ul>
928                         </div>
929                 </div></body></html>';
930                 return $b;
931     }
932
933         /**
934         * serialize the parsed wsdl
935         *
936         * @param mixed $debug whether to put debug=1 in endpoint URL
937         * @return string serialization of WSDL
938         * @access public 
939         */
940         function serialize($debug = 0)
941         {
942                 $xml = '<?xml version="1.0" encoding="ISO-8859-1"?>';
943                 $xml .= "\n<definitions";
944                 foreach($this->namespaces as $k => $v) {
945                         $xml .= " xmlns:$k=\"$v\"";
946                 } 
947                 // 10.9.02 - add poulter fix for wsdl and tns declarations
948                 if (isset($this->namespaces['wsdl'])) {
949                         $xml .= " xmlns=\"" . $this->namespaces['wsdl'] . "\"";
950                 } 
951                 if (isset($this->namespaces['tns'])) {
952                         $xml .= " targetNamespace=\"" . $this->namespaces['tns'] . "\"";
953                 } 
954                 $xml .= '>'; 
955                 // imports
956                 if (sizeof($this->import) > 0) {
957                         foreach($this->import as $ns => $list) {
958                                 foreach ($list as $ii) {
959                                         if ($ii['location'] != '') {
960                                                 $xml .= '<import location="' . $ii['location'] . '" namespace="' . $ns . '" />';
961                                         } else {
962                                                 $xml .= '<import namespace="' . $ns . '" />';
963                                         }
964                                 }
965                         } 
966                 } 
967                 // types
968                 if (count($this->schemas)>=1) {
969                         $xml .= "\n<types>\n";
970                         foreach ($this->schemas as $ns => $list) {
971                                 foreach ($list as $xs) {
972                                         $xml .= $xs->serializeSchema();
973                                 }
974                         }
975                         $xml .= '</types>';
976                 } 
977                 // messages
978                 if (count($this->messages) >= 1) {
979                         foreach($this->messages as $msgName => $msgParts) {
980                                 $xml .= "\n<message name=\"" . $msgName . '">';
981                                 if(is_array($msgParts)){
982                                         foreach($msgParts as $partName => $partType) {
983                                                 // print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'<br>';
984                                                 if (strpos($partType, ':')) {
985                                                     $typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType));
986                                                 } elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) {
987                                                     // print 'checking typemap: '.$this->XMLSchemaVersion.'<br>';
988                                                     $typePrefix = 'xsd';
989                                                 } else {
990                                                     foreach($this->typemap as $ns => $types) {
991                                                         if (isset($types[$partType])) {
992                                                             $typePrefix = $this->getPrefixFromNamespace($ns);
993                                                         } 
994                                                     } 
995                                                     if (!isset($typePrefix)) {
996                                                         die("$partType has no namespace!");
997                                                     } 
998                                                 }
999                                                 $ns = $this->getNamespaceFromPrefix($typePrefix);
1000                                                 $localPart = $this->getLocalPart($partType);
1001                                                 $typeDef = $this->getTypeDef($localPart, $ns);
1002                                                 if ($typeDef['typeClass'] == 'element') {
1003                                                         $elementortype = 'element';
1004                                                         if (substr($localPart, -1) == '^') {
1005                                                                 $localPart = substr($localPart, 0, -1);
1006                                                         }
1007                                                 } else {
1008                                                         $elementortype = 'type';
1009                                                 }
1010                                                 $xml .= "\n" . '  <part name="' . $partName . '" ' . $elementortype . '="' . $typePrefix . ':' . $localPart . '" />';
1011                                         }
1012                                 }
1013                                 $xml .= '</message>';
1014                         } 
1015                 } 
1016                 // bindings & porttypes
1017                 if (count($this->bindings) >= 1) {
1018                         $binding_xml = '';
1019                         $portType_xml = '';
1020                         foreach($this->bindings as $bindingName => $attrs) {
1021                                 $binding_xml .= "\n<binding name=\"" . $bindingName . '" type="tns:' . $attrs['portType'] . '">';
1022                                 $binding_xml .= "\n" . '  <soap:binding style="' . $attrs['style'] . '" transport="' . $attrs['transport'] . '"/>';
1023                                 $portType_xml .= "\n<portType name=\"" . $attrs['portType'] . '">';
1024                                 foreach($attrs['operations'] as $opName => $opParts) {
1025                                         $binding_xml .= "\n" . '  <operation name="' . $opName . '">';
1026                                         $binding_xml .= "\n" . '    <soap:operation soapAction="' . $opParts['soapAction'] . '" style="'. $opParts['style'] . '"/>';
1027                                         if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') {
1028                                                 $enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"';
1029                                         } else {
1030                                                 $enc_style = '';
1031                                         }
1032                                         $binding_xml .= "\n" . '    <input><soap:body use="' . $opParts['input']['use'] . '" namespace="' . $opParts['input']['namespace'] . '"' . $enc_style . '/></input>';
1033                                         if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') {
1034                                                 $enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"';
1035                                         } else {
1036                                                 $enc_style = '';
1037                                         }
1038                                         $binding_xml .= "\n" . '    <output><soap:body use="' . $opParts['output']['use'] . '" namespace="' . $opParts['output']['namespace'] . '"' . $enc_style . '/></output>';
1039                                         $binding_xml .= "\n" . '  </operation>';
1040                                         $portType_xml .= "\n" . '  <operation name="' . $opParts['name'] . '"';
1041                                         if (isset($opParts['parameterOrder'])) {
1042                                             $portType_xml .= ' parameterOrder="' . $opParts['parameterOrder'] . '"';
1043                                         } 
1044                                         $portType_xml .= '>';
1045                                         if(isset($opParts['documentation']) && $opParts['documentation'] != '') {
1046                                                 $portType_xml .= "\n" . '    <documentation>' . htmlspecialchars($opParts['documentation']) . '</documentation>';
1047                                         }
1048                                         $portType_xml .= "\n" . '    <input message="tns:' . $opParts['input']['message'] . '"/>';
1049                                         $portType_xml .= "\n" . '    <output message="tns:' . $opParts['output']['message'] . '"/>';
1050                                         $portType_xml .= "\n" . '  </operation>';
1051                                 } 
1052                                 $portType_xml .= "\n" . '</portType>';
1053                                 $binding_xml .= "\n" . '</binding>';
1054                         } 
1055                         $xml .= $portType_xml . $binding_xml;
1056                 } 
1057                 // services
1058                 $xml .= "\n<service name=\"" . $this->serviceName . '">';
1059                 if (count($this->ports) >= 1) {
1060                         foreach($this->ports as $pName => $attrs) {
1061                                 $xml .= "\n" . '  <port name="' . $pName . '" binding="tns:' . $attrs['binding'] . '">';
1062                                 $xml .= "\n" . '    <soap:address location="' . $attrs['location'] . ($debug ? '?debug=1' : '') . '"/>';
1063                                 $xml .= "\n" . '  </port>';
1064                         } 
1065                 } 
1066                 $xml .= "\n" . '</service>';
1067                 return $xml . "\n</definitions>";
1068         } 
1069
1070         /**
1071          * determine whether a set of parameters are unwrapped
1072          * when they are expect to be wrapped, Microsoft-style.
1073          *
1074          * @param string $type the type (element name) of the wrapper
1075          * @param array $parameters the parameter values for the SOAP call
1076          * @return boolean whether they parameters are unwrapped (and should be wrapped)
1077          * @access private
1078          */
1079         function parametersMatchWrapped($type, &$parameters) {
1080                 $this->debug("in parametersMatchWrapped type=$type, parameters=");
1081                 $this->appendDebug($this->varDump($parameters));
1082
1083                 // split type into namespace:unqualified-type
1084                 if (strpos($type, ':')) {
1085                         $uqType = substr($type, strrpos($type, ':') + 1);
1086                         $ns = substr($type, 0, strrpos($type, ':'));
1087                         $this->debug("in parametersMatchWrapped: got a prefixed type: $uqType, $ns");
1088                         if ($this->getNamespaceFromPrefix($ns)) {
1089                                 $ns = $this->getNamespaceFromPrefix($ns);
1090                                 $this->debug("in parametersMatchWrapped: expanded prefixed type: $uqType, $ns");
1091                         }
1092                 } else {
1093                         // TODO: should the type be compared to types in XSD, and the namespace
1094                         // set to XSD if the type matches?
1095                         $this->debug("in parametersMatchWrapped: No namespace for type $type");
1096                         $ns = '';
1097                         $uqType = $type;
1098                 }
1099
1100                 // get the type information
1101                 if (!$typeDef = $this->getTypeDef($uqType, $ns)) {
1102                         $this->debug("in parametersMatchWrapped: $type ($uqType) is not a supported type.");
1103                         return false;
1104                 }
1105                 $this->debug("in parametersMatchWrapped: found typeDef=");
1106                 $this->appendDebug($this->varDump($typeDef));
1107                 if (substr($uqType, -1) == '^') {
1108                         $uqType = substr($uqType, 0, -1);
1109                 }
1110                 $phpType = $typeDef['phpType'];
1111                 $arrayType = (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '');
1112                 $this->debug("in parametersMatchWrapped: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: $arrayType");
1113                 
1114                 // we expect a complexType or element of complexType
1115                 if ($phpType != 'struct') {
1116                         $this->debug("in parametersMatchWrapped: not a struct");
1117                         return false;
1118                 }
1119
1120                 // see whether the parameter names match the elements
1121                 if (isset($typeDef['elements']) && is_array($typeDef['elements'])) {
1122                         $elements = 0;
1123                         $matches = 0;
1124                         foreach ($typeDef['elements'] as $name => $attrs) {
1125                                 if (isset($parameters[$name])) {
1126                                         $this->debug("in parametersMatchWrapped: have parameter named $name");
1127                                         $matches++;
1128                                 } else {
1129                                         $this->debug("in parametersMatchWrapped: do not have parameter named $name");
1130                                 }
1131                                 $elements++;
1132                         }
1133
1134                         $this->debug("in parametersMatchWrapped: $matches parameter names match $elements wrapped parameter names");
1135                         if ($matches == 0) {
1136                                 return false;
1137                         }
1138                         return true;
1139                 }
1140
1141                 // since there are no elements for the type, if the user passed no
1142                 // parameters, the parameters match wrapped.
1143                 $this->debug("in parametersMatchWrapped: no elements type $ns:$uqType");
1144                 return count($parameters) == 0;
1145         }
1146
1147         /**
1148          * serialize PHP values according to a WSDL message definition
1149          * contrary to the method name, this is not limited to RPC
1150          *
1151          * TODO
1152          * - multi-ref serialization
1153          * - validate PHP values against type definitions, return errors if invalid
1154          * 
1155          * @param string $operation operation name
1156          * @param string $direction (input|output)
1157          * @param mixed $parameters parameter value(s)
1158          * @param string $bindingType (soap|soap12)
1159          * @return mixed parameters serialized as XML or false on error (e.g. operation not found)
1160          * @access public
1161          */
1162         function serializeRPCParameters($operation, $direction, $parameters, $bindingType = 'soap') {
1163                 $this->debug("in serializeRPCParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion, bindingType=$bindingType");
1164                 $this->appendDebug('parameters=' . $this->varDump($parameters));
1165                 
1166                 if ($direction != 'input' && $direction != 'output') {
1167                         $this->debug('The value of the \$direction argument needs to be either "input" or "output"');
1168                         $this->setError('The value of the \$direction argument needs to be either "input" or "output"');
1169                         return false;
1170                 } 
1171                 if (!$opData = $this->getOperationData($operation, $bindingType)) {
1172                         $this->debug('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType);
1173                         $this->setError('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType);
1174                         return false;
1175                 }
1176                 $this->debug('in serializeRPCParameters: opData:');
1177                 $this->appendDebug($this->varDump($opData));
1178
1179                 // Get encoding style for output and set to current
1180                 $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
1181                 if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
1182                         $encodingStyle = $opData['output']['encodingStyle'];
1183                         $enc_style = $encodingStyle;
1184                 }
1185
1186                 // set input params
1187                 $xml = '';
1188                 if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
1189                         $parts = &$opData[$direction]['parts'];
1190                         $part_count = sizeof($parts);
1191                         $style = $opData['style'];
1192                         $use = $opData[$direction]['use'];
1193                         $this->debug("have $part_count part(s) to serialize using $style/$use");
1194                         if (is_array($parameters)) {
1195                                 $parametersArrayType = $this->isArraySimpleOrStruct($parameters);
1196                                 $parameter_count = count($parameters);
1197                                 $this->debug("have $parameter_count parameter(s) provided as $parametersArrayType to serialize");
1198                                 // check for Microsoft-style wrapped parameters
1199                                 if ($style == 'document' && $use == 'literal' && $part_count == 1 && isset($parts['parameters'])) {
1200                                         $this->debug('check whether the caller has wrapped the parameters');
1201                                         if ($direction == 'output' && $parametersArrayType == 'arraySimple' && $parameter_count == 1) {
1202                                                 // TODO: consider checking here for double-wrapping, when
1203                                                 // service function wraps, then NuSOAP wraps again
1204                                                 $this->debug("change simple array to associative with 'parameters' element");
1205                                                 $parameters['parameters'] = $parameters[0];
1206                                                 unset($parameters[0]);
1207                                         }
1208                                         if (($parametersArrayType == 'arrayStruct' || $parameter_count == 0) && !isset($parameters['parameters'])) {
1209                                                 $this->debug('check whether caller\'s parameters match the wrapped ones');
1210                                                 if ($this->parametersMatchWrapped($parts['parameters'], $parameters)) {
1211                                                         $this->debug('wrap the parameters for the caller');
1212                                                         $parameters = array('parameters' => $parameters);
1213                                                         $parameter_count = 1;
1214                                                 }
1215                                         }
1216                                 }
1217                                 foreach ($parts as $name => $type) {
1218                                         $this->debug("serializing part $name of type $type");
1219                                         // Track encoding style
1220                                         if (isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
1221                                                 $encodingStyle = $opData[$direction]['encodingStyle'];                  
1222                                                 $enc_style = $encodingStyle;
1223                                         } else {
1224                                                 $enc_style = false;
1225                                         }
1226                                         // NOTE: add error handling here
1227                                         // if serializeType returns false, then catch global error and fault
1228                                         if ($parametersArrayType == 'arraySimple') {
1229                                                 $p = array_shift($parameters);
1230                                                 $this->debug('calling serializeType w/indexed param');
1231                                                 $xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
1232                                         } elseif (isset($parameters[$name])) {
1233                                                 $this->debug('calling serializeType w/named param');
1234                                                 $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
1235                                         } else {
1236                                                 // TODO: only send nillable
1237                                                 $this->debug('calling serializeType w/null param');
1238                                                 $xml .= $this->serializeType($name, $type, null, $use, $enc_style);
1239                                         }
1240                                 }
1241                         } else {
1242                                 $this->debug('no parameters passed.');
1243                         }
1244                 }
1245                 $this->debug("serializeRPCParameters returning: $xml");
1246                 return $xml;
1247         } 
1248         
1249         /**
1250          * serialize a PHP value according to a WSDL message definition
1251          * 
1252          * TODO
1253          * - multi-ref serialization
1254          * - validate PHP values against type definitions, return errors if invalid
1255          * 
1256          * @param string $operation operation name
1257          * @param string $direction (input|output)
1258          * @param mixed $parameters parameter value(s)
1259          * @return mixed parameters serialized as XML or false on error (e.g. operation not found)
1260          * @access public
1261          * @deprecated
1262          */
1263         function serializeParameters($operation, $direction, $parameters)
1264         {
1265                 $this->debug("in serializeParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion"); 
1266                 $this->appendDebug('parameters=' . $this->varDump($parameters));
1267                 
1268                 if ($direction != 'input' && $direction != 'output') {
1269                         $this->debug('The value of the \$direction argument needs to be either "input" or "output"');
1270                         $this->setError('The value of the \$direction argument needs to be either "input" or "output"');
1271                         return false;
1272                 } 
1273                 if (!$opData = $this->getOperationData($operation)) {
1274                         $this->debug('Unable to retrieve WSDL data for operation: ' . $operation);
1275                         $this->setError('Unable to retrieve WSDL data for operation: ' . $operation);
1276                         return false;
1277                 }
1278                 $this->debug('opData:');
1279                 $this->appendDebug($this->varDump($opData));
1280                 
1281                 // Get encoding style for output and set to current
1282                 $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
1283                 if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) {
1284                         $encodingStyle = $opData['output']['encodingStyle'];
1285                         $enc_style = $encodingStyle;
1286                 }
1287                 
1288                 // set input params
1289                 $xml = '';
1290                 if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) {
1291                         
1292                         $use = $opData[$direction]['use'];
1293                         $this->debug("use=$use");
1294                         $this->debug('got ' . count($opData[$direction]['parts']) . ' part(s)');
1295                         if (is_array($parameters)) {
1296                                 $parametersArrayType = $this->isArraySimpleOrStruct($parameters);
1297                                 $this->debug('have ' . $parametersArrayType . ' parameters');
1298                                 foreach($opData[$direction]['parts'] as $name => $type) {
1299                                         $this->debug('serializing part "'.$name.'" of type "'.$type.'"');
1300                                         // Track encoding style
1301                                         if(isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) {
1302                                                 $encodingStyle = $opData[$direction]['encodingStyle'];                  
1303                                                 $enc_style = $encodingStyle;
1304                                         } else {
1305                                                 $enc_style = false;
1306                                         }
1307                                         // NOTE: add error handling here
1308                                         // if serializeType returns false, then catch global error and fault
1309                                         if ($parametersArrayType == 'arraySimple') {
1310                                                 $p = array_shift($parameters);
1311                                                 $this->debug('calling serializeType w/indexed param');
1312                                                 $xml .= $this->serializeType($name, $type, $p, $use, $enc_style);
1313                                         } elseif (isset($parameters[$name])) {
1314                                                 $this->debug('calling serializeType w/named param');
1315                                                 $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style);
1316                                         } else {
1317                                                 // TODO: only send nillable
1318                                                 $this->debug('calling serializeType w/null param');
1319                                                 $xml .= $this->serializeType($name, $type, null, $use, $enc_style);
1320                                         }
1321                                 }
1322                         } else {
1323                                 $this->debug('no parameters passed.');
1324                         }
1325                 }
1326                 $this->debug("serializeParameters returning: $xml");
1327                 return $xml;
1328         } 
1329         
1330         /**
1331          * serializes a PHP value according a given type definition
1332          * 
1333          * @param string $name name of value (part or element)
1334          * @param string $type XML schema type of value (type or element)
1335          * @param mixed $value a native PHP value (parameter value)
1336          * @param string $use use for part (encoded|literal)
1337          * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
1338          * @param boolean $unqualified a kludge for what should be XML namespace form handling
1339          * @return string value serialized as an XML string
1340          * @access private
1341          */
1342         function serializeType($name, $type, $value, $use='encoded', $encodingStyle=false, $unqualified=false)
1343         {
1344                 $this->debug("in serializeType: name=$name, type=$type, use=$use, encodingStyle=$encodingStyle, unqualified=" . ($unqualified ? "unqualified" : "qualified"));
1345                 $this->appendDebug("value=" . $this->varDump($value));
1346                 if($use == 'encoded' && $encodingStyle) {
1347                         $encodingStyle = ' SOAP-ENV:encodingStyle="' . $encodingStyle . '"';
1348                 }
1349
1350                 // if a soapval has been supplied, let its type override the WSDL
1351         if (is_object($value) && get_class($value) == 'soapval') {
1352                 if ($value->type_ns) {
1353                         $type = $value->type_ns . ':' . $value->type;
1354                         $forceType = true;
1355                         $this->debug("in serializeType: soapval overrides type to $type");
1356                 } elseif ($value->type) {
1357                         $type = $value->type;
1358                         $forceType = true;
1359                         $this->debug("in serializeType: soapval overrides type to $type");
1360                 } else {
1361                         $forceType = false;
1362                         $this->debug("in serializeType: soapval does not override type");
1363                 }
1364                 $attrs = $value->attributes;
1365                 $value = $value->value;
1366                 $this->debug("in serializeType: soapval overrides value to $value");
1367                 if ($attrs) {
1368                         if (!is_array($value)) {
1369                                 $value['!'] = $value;
1370                         }
1371                         foreach ($attrs as $n => $v) {
1372                                 $value['!' . $n] = $v;
1373                         }
1374                         $this->debug("in serializeType: soapval provides attributes");
1375                     }
1376         } else {
1377                 $forceType = false;
1378         }
1379
1380                 $xml = '';
1381                 if (strpos($type, ':')) {
1382                         $uqType = substr($type, strrpos($type, ':') + 1);
1383                         $ns = substr($type, 0, strrpos($type, ':'));
1384                         $this->debug("in serializeType: got a prefixed type: $uqType, $ns");
1385                         if ($this->getNamespaceFromPrefix($ns)) {
1386                                 $ns = $this->getNamespaceFromPrefix($ns);
1387                                 $this->debug("in serializeType: expanded prefixed type: $uqType, $ns");
1388                         }
1389
1390                         if($ns == $this->XMLSchemaVersion || $ns == 'http://schemas.xmlsoap.org/soap/encoding/'){
1391                                 $this->debug('in serializeType: type namespace indicates XML Schema or SOAP Encoding type');
1392                                 if ($unqualified && $use == 'literal') {
1393                                         $elementNS = " xmlns=\"\"";
1394                                 } else {
1395                                         $elementNS = '';
1396                                 }
1397                                 if (is_null($value)) {
1398                                         if ($use == 'literal') {
1399                                                 // TODO: depends on minOccurs
1400                                                 $xml = "<$name$elementNS/>";
1401                                         } else {
1402                                                 // TODO: depends on nillable, which should be checked before calling this method
1403                                                 $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>";
1404                                         }
1405                                         $this->debug("in serializeType: returning: $xml");
1406                                         return $xml;
1407                                 }
1408                                 if ($uqType == 'Array') {
1409                                         // JBoss/Axis does this sometimes
1410                                         return $this->serialize_val($value, $name, false, false, false, false, $use);
1411                                 }
1412                         if ($uqType == 'boolean') {
1413                                 if ((is_string($value) && $value == 'false') || (! $value)) {
1414                                                 $value = 'false';
1415                                         } else {
1416                                                 $value = 'true';
1417                                         }
1418                                 } 
1419                                 if ($uqType == 'string' && gettype($value) == 'string') {
1420                                         $value = $this->expandEntities($value);
1421                                 }
1422                                 if (($uqType == 'long' || $uqType == 'unsignedLong') && gettype($value) == 'double') {
1423                                         $value = sprintf("%.0lf", $value);
1424                                 }
1425                                 // it's a scalar
1426                                 // TODO: what about null/nil values?
1427                                 // check type isn't a custom type extending xmlschema namespace
1428                                 if (!$this->getTypeDef($uqType, $ns)) {
1429                                         if ($use == 'literal') {
1430                                                 if ($forceType) {
1431                                                         $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value</$name>";
1432                                                 } else {
1433                                                         $xml = "<$name$elementNS>$value</$name>";
1434                                                 }
1435                                         } else {
1436                                                 $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value</$name>";
1437                                         }
1438                                         $this->debug("in serializeType: returning: $xml");
1439                                         return $xml;
1440                                 }
1441                                 $this->debug('custom type extends XML Schema or SOAP Encoding namespace (yuck)');
1442                         } else if ($ns == 'http://xml.apache.org/xml-soap') {
1443                                 $this->debug('in serializeType: appears to be Apache SOAP type');
1444                                 if ($uqType == 'Map') {
1445                                         $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap');
1446                                         if (! $tt_prefix) {
1447                                                 $this->debug('in serializeType: Add namespace for Apache SOAP type');
1448                                                 $tt_prefix = 'ns' . rand(1000, 9999);
1449                                                 $this->namespaces[$tt_prefix] = 'http://xml.apache.org/xml-soap';
1450                                                 // force this to be added to usedNamespaces
1451                                                 $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap');
1452                                         }
1453                                         $contents = '';
1454                                         foreach($value as $k => $v) {
1455                                                 $this->debug("serializing map element: key $k, value $v");
1456                                                 $contents .= '<item>';
1457                                                 $contents .= $this->serialize_val($k,'key',false,false,false,false,$use);
1458                                                 $contents .= $this->serialize_val($v,'value',false,false,false,false,$use);
1459                                                 $contents .= '</item>';
1460                                         }
1461                                         if ($use == 'literal') {
1462                                                 if ($forceType) {
1463                                                         $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\">$contents</$name>";
1464                                                 } else {
1465                                                         $xml = "<$name>$contents</$name>";
1466                                                 }
1467                                         } else {
1468                                                 $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\"$encodingStyle>$contents</$name>";
1469                                         }
1470                                         $this->debug("in serializeType: returning: $xml");
1471                                         return $xml;
1472                                 }
1473                                 $this->debug('in serializeType: Apache SOAP type, but only support Map');
1474                         }
1475                 } else {
1476                         // TODO: should the type be compared to types in XSD, and the namespace
1477                         // set to XSD if the type matches?
1478                         $this->debug("in serializeType: No namespace for type $type");
1479                         $ns = '';
1480                         $uqType = $type;
1481                 }
1482                 if(!$typeDef = $this->getTypeDef($uqType, $ns)){
1483                         $this->setError("$type ($uqType) is not a supported type.");
1484                         $this->debug("in serializeType: $type ($uqType) is not a supported type.");
1485                         return false;
1486                 } else {
1487                         $this->debug("in serializeType: found typeDef");
1488                         $this->appendDebug('typeDef=' . $this->varDump($typeDef));
1489                         if (substr($uqType, -1) == '^') {
1490                                 $uqType = substr($uqType, 0, -1);
1491                         }
1492                 }
1493                 if (!isset($typeDef['phpType'])) {
1494                         $this->setError("$type ($uqType) has no phpType.");
1495                         $this->debug("in serializeType: $type ($uqType) has no phpType.");
1496                         return false;
1497                 }
1498                 $phpType = $typeDef['phpType'];
1499                 $this->debug("in serializeType: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: " . (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '') ); 
1500                 // if php type == struct, map value to the <all> element names
1501                 if ($phpType == 'struct') {
1502                         if (isset($typeDef['typeClass']) && $typeDef['typeClass'] == 'element') {
1503                                 $elementName = $uqType;
1504                                 if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
1505                                         $elementNS = " xmlns=\"$ns\"";
1506                                 } else {
1507                                         $elementNS = " xmlns=\"\"";
1508                                 }
1509                         } else {
1510                                 $elementName = $name;
1511                                 if ($unqualified) {
1512                                         $elementNS = " xmlns=\"\"";
1513                                 } else {
1514                                         $elementNS = '';
1515                                 }
1516                         }
1517                         if (is_null($value)) {
1518                                 if ($use == 'literal') {
1519                                         // TODO: depends on minOccurs and nillable
1520                                         $xml = "<$elementName$elementNS/>";
1521                                 } else {
1522                                         $xml = "<$elementName$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>";
1523                                 }
1524                                 $this->debug("in serializeType: returning: $xml");
1525                                 return $xml;
1526                         }
1527                         if (is_object($value)) {
1528                                 $value = get_object_vars($value);
1529                         }
1530                         if (is_array($value)) {
1531                                 $elementAttrs = $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType);
1532                                 if ($use == 'literal') {
1533                                         if ($forceType) {
1534                                                 $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">";
1535                                         } else {
1536                                                 $xml = "<$elementName$elementNS$elementAttrs>";
1537                                         }
1538                                 } else {
1539                                         $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>";
1540                                 }
1541
1542                                 if (isset($typeDef['simpleContent']) && $typeDef['simpleContent'] == 'true') {
1543                                         if (isset($value['!'])) {
1544                                                 $xml .= $value['!'];
1545                                                 $this->debug("in serializeType: serialized simpleContent for type $type");
1546                                         } else {
1547                                                 $this->debug("in serializeType: no simpleContent to serialize for type $type");
1548                                         }
1549                                 } else {
1550                                         // complexContent
1551                                         $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle);
1552                                 }
1553                                 $xml .= "</$elementName>";
1554                         } else {
1555                                 $this->debug("in serializeType: phpType is struct, but value is not an array");
1556                                 $this->setError("phpType is struct, but value is not an array: see debug output for details");
1557                                 $xml = '';
1558                         }
1559                 } elseif ($phpType == 'array') {
1560                         if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
1561                                 $elementNS = " xmlns=\"$ns\"";
1562                         } else {
1563                                 if ($unqualified) {
1564                                         $elementNS = " xmlns=\"\"";
1565                                 } else {
1566                                         $elementNS = '';
1567                                 }
1568                         }
1569                         if (is_null($value)) {
1570                                 if ($use == 'literal') {
1571                                         // TODO: depends on minOccurs
1572                                         $xml = "<$name$elementNS/>";
1573                                 } else {
1574                                         $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" .
1575                                                 $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .
1576                                                 ":Array\" " .
1577                                                 $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .
1578                                                 ':arrayType="' .
1579                                                 $this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) .
1580                                                 ':' .
1581                                                 $this->getLocalPart($typeDef['arrayType'])."[0]\"/>";
1582                                 }
1583                                 $this->debug("in serializeType: returning: $xml");
1584                                 return $xml;
1585                         }
1586                         if (isset($typeDef['multidimensional'])) {
1587                                 $nv = array();
1588                                 foreach($value as $v) {
1589                                         $cols = ',' . sizeof($v);
1590                                         $nv = array_merge($nv, $v);
1591                                 } 
1592                                 $value = $nv;
1593                         } else {
1594                                 $cols = '';
1595                         } 
1596                         if (is_array($value) && sizeof($value) >= 1) {
1597                                 $rows = sizeof($value);
1598                                 $contents = '';
1599                                 foreach($value as $k => $v) {
1600                                         $this->debug("serializing array element: $k, $v of type: $typeDef[arrayType]");
1601                                         //if (strpos($typeDef['arrayType'], ':') ) {
1602                                         if (!in_array($typeDef['arrayType'],$this->typemap['http://www.w3.org/2001/XMLSchema'])) {
1603                                             $contents .= $this->serializeType('item', $typeDef['arrayType'], $v, $use);
1604                                         } else {
1605                                             $contents .= $this->serialize_val($v, 'item', $typeDef['arrayType'], null, $this->XMLSchemaVersion, false, $use);
1606                                         } 
1607                                 }
1608                         } else {
1609                                 $rows = 0;
1610                                 $contents = null;
1611                         }
1612                         // TODO: for now, an empty value will be serialized as a zero element
1613                         // array.  Revisit this when coding the handling of null/nil values.
1614                         if ($use == 'literal') {
1615                                 $xml = "<$name$elementNS>"
1616                                         .$contents
1617                                         ."</$name>";
1618                         } else {
1619                                 $xml = "<$name$elementNS xsi:type=\"".$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/').':Array" '.
1620                                         $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/')
1621                                         .':arrayType="'
1622                                         .$this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType']))
1623                                         .":".$this->getLocalPart($typeDef['arrayType'])."[$rows$cols]\">"
1624                                         .$contents
1625                                         ."</$name>";
1626                         }
1627                 } elseif ($phpType == 'scalar') {
1628                         if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) {
1629                                 $elementNS = " xmlns=\"$ns\"";
1630                         } else {
1631                                 if ($unqualified) {
1632                                         $elementNS = " xmlns=\"\"";
1633                                 } else {
1634                                         $elementNS = '';
1635                                 }
1636                         }
1637                         if ($use == 'literal') {
1638                                 if ($forceType) {
1639                                         $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value</$name>";
1640                                 } else {
1641                                         $xml = "<$name$elementNS>$value</$name>";
1642                                 }
1643                         } else {
1644                                 $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value</$name>";
1645                         }
1646                 }
1647                 $this->debug("in serializeType: returning: $xml");
1648                 return $xml;
1649         }
1650         
1651         /**
1652          * serializes the attributes for a complexType
1653          *
1654          * @param array $typeDef our internal representation of an XML schema type (or element)
1655          * @param mixed $value a native PHP value (parameter value)
1656          * @param string $ns the namespace of the type
1657          * @param string $uqType the local part of the type
1658          * @return string value serialized as an XML string
1659          * @access private
1660          */
1661         function serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType) {
1662                 $this->debug("serializeComplexTypeAttributes for XML Schema type $ns:$uqType");
1663                 $xml = '';
1664                 if (isset($typeDef['extensionBase'])) {
1665                         $nsx = $this->getPrefix($typeDef['extensionBase']);
1666                         $uqTypex = $this->getLocalPart($typeDef['extensionBase']);
1667                         if ($this->getNamespaceFromPrefix($nsx)) {
1668                                 $nsx = $this->getNamespaceFromPrefix($nsx);
1669                         }
1670                         if ($typeDefx = $this->getTypeDef($uqTypex, $nsx)) {
1671                                 $this->debug("serialize attributes for extension base $nsx:$uqTypex");
1672                                 $xml .= $this->serializeComplexTypeAttributes($typeDefx, $value, $nsx, $uqTypex);
1673                         } else {
1674                                 $this->debug("extension base $nsx:$uqTypex is not a supported type");
1675                         }
1676                 }
1677                 if (isset($typeDef['attrs']) && is_array($typeDef['attrs'])) {
1678                         $this->debug("serialize attributes for XML Schema type $ns:$uqType");
1679                         if (is_array($value)) {
1680                                 $xvalue = $value;
1681                         } elseif (is_object($value)) {
1682                                 $xvalue = get_object_vars($value);
1683                         } else {
1684                                 $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
1685                                 $xvalue = array();
1686                         }
1687                         foreach ($typeDef['attrs'] as $aName => $attrs) {
1688                                 if (isset($xvalue['!' . $aName])) {
1689                                         $xname = '!' . $aName;
1690                                         $this->debug("value provided for attribute $aName with key $xname");
1691                                 } elseif (isset($xvalue[$aName])) {
1692                                         $xname = $aName;
1693                                         $this->debug("value provided for attribute $aName with key $xname");
1694                                 } elseif (isset($attrs['default'])) {
1695                                         $xname = '!' . $aName;
1696                                         $xvalue[$xname] = $attrs['default'];
1697                                         $this->debug('use default value of ' . $xvalue[$aName] . ' for attribute ' . $aName);
1698                                 } else {
1699                                         $xname = '';
1700                                         $this->debug("no value provided for attribute $aName");
1701                                 }
1702                                 if ($xname) {
1703                                         $xml .=  " $aName=\"" . $this->expandEntities($xvalue[$xname]) . "\"";
1704                                 }
1705                         } 
1706                 } else {
1707                         $this->debug("no attributes to serialize for XML Schema type $ns:$uqType");
1708                 }
1709                 return $xml;
1710         }
1711
1712         /**
1713          * serializes the elements for a complexType
1714          *
1715          * @param array $typeDef our internal representation of an XML schema type (or element)
1716          * @param mixed $value a native PHP value (parameter value)
1717          * @param string $ns the namespace of the type
1718          * @param string $uqType the local part of the type
1719          * @param string $use use for part (encoded|literal)
1720          * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style)
1721          * @return string value serialized as an XML string
1722          * @access private
1723          */
1724         function serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use='encoded', $encodingStyle=false) {
1725                 $this->debug("in serializeComplexTypeElements for XML Schema type $ns:$uqType");
1726                 $xml = '';
1727                 if (isset($typeDef['extensionBase'])) {
1728                         $nsx = $this->getPrefix($typeDef['extensionBase']);
1729                         $uqTypex = $this->getLocalPart($typeDef['extensionBase']);
1730                         if ($this->getNamespaceFromPrefix($nsx)) {
1731                                 $nsx = $this->getNamespaceFromPrefix($nsx);
1732                         }
1733                         if ($typeDefx = $this->getTypeDef($uqTypex, $nsx)) {
1734                                 $this->debug("serialize elements for extension base $nsx:$uqTypex");
1735                                 $xml .= $this->serializeComplexTypeElements($typeDefx, $value, $nsx, $uqTypex, $use, $encodingStyle);
1736                         } else {
1737                                 $this->debug("extension base $nsx:$uqTypex is not a supported type");
1738                         }
1739                 }
1740                 if (isset($typeDef['elements']) && is_array($typeDef['elements'])) {
1741                         $this->debug("in serializeComplexTypeElements, serialize elements for XML Schema type $ns:$uqType");
1742                         if (is_array($value)) {
1743                                 $xvalue = $value;
1744                         } elseif (is_object($value)) {
1745                                 $xvalue = get_object_vars($value);
1746                         } else {
1747                                 $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType");
1748                                 $xvalue = array();
1749                         }
1750                         // toggle whether all elements are present - ideally should validate against schema
1751                         if (count($typeDef['elements']) != count($xvalue)){
1752                                 $optionals = true;
1753                         }
1754                         foreach ($typeDef['elements'] as $eName => $attrs) {
1755                                 if (!isset($xvalue[$eName])) {
1756                                         if (isset($attrs['default'])) {
1757                                                 $xvalue[$eName] = $attrs['default'];
1758                                                 $this->debug('use default value of ' . $xvalue[$eName] . ' for element ' . $eName);
1759                                         }
1760                                 }
1761                                 // if user took advantage of a minOccurs=0, then only serialize named parameters
1762                                 if (isset($optionals)
1763                                     && (!isset($xvalue[$eName])) 
1764                                         && ( (!isset($attrs['nillable'])) || $attrs['nillable'] != 'true')
1765                                         ){
1766                                         if (isset($attrs['minOccurs']) && $attrs['minOccurs'] <> '0') {
1767                                                 $this->debug("apparent error: no value provided for element $eName with minOccurs=" . $attrs['minOccurs']);
1768                                         }
1769                                         // do nothing
1770                                         $this->debug("no value provided for complexType element $eName and element is not nillable, so serialize nothing");
1771                                 } else {
1772                                         // get value
1773                                         if (isset($xvalue[$eName])) {
1774                                             $v = $xvalue[$eName];
1775                                         } else {
1776                                             $v = null;
1777                                         }
1778                                         if (isset($attrs['form'])) {
1779                                                 $unqualified = ($attrs['form'] == 'unqualified');
1780                                         } else {
1781                                                 $unqualified = false;
1782                                         }
1783                                         if (isset($attrs['maxOccurs']) && ($attrs['maxOccurs'] == 'unbounded' || $attrs['maxOccurs'] > 1) && isset($v) && is_array($v) && $this->isArraySimpleOrStruct($v) == 'arraySimple') {
1784                                                 $vv = $v;
1785                                                 foreach ($vv as $k => $v) {
1786                                                         if (isset($attrs['type']) || isset($attrs['ref'])) {
1787                                                                 // serialize schema-defined type
1788                                                             $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
1789                                                         } else {
1790                                                                 // serialize generic type (can this ever really happen?)
1791                                                             $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
1792                                                             $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
1793                                                         }
1794                                                 }
1795                                         } else {
1796                                                 if (is_null($v) && isset($attrs['minOccurs']) && $attrs['minOccurs'] == '0') {
1797                                                         // do nothing
1798                                                 } elseif (is_null($v) && isset($attrs['nillable']) && $attrs['nillable'] == 'true') {
1799                                                         // TODO: serialize a nil correctly, but for now serialize schema-defined type
1800                                                     $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
1801                                                 } elseif (isset($attrs['type']) || isset($attrs['ref'])) {
1802                                                         // serialize schema-defined type
1803                                                     $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified);
1804                                                 } else {
1805                                                         // serialize generic type (can this ever really happen?)
1806                                                     $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use");
1807                                                     $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use);
1808                                                 }
1809                                         }
1810                                 }
1811                         } 
1812                 } else {
1813                         $this->debug("no elements to serialize for XML Schema type $ns:$uqType");
1814                 }
1815                 return $xml;
1816         }
1817
1818         /**
1819         * adds an XML Schema complex type to the WSDL types
1820         *
1821         * @param string $name
1822         * @param string $typeClass (complexType|simpleType|attribute)
1823         * @param string $phpType currently supported are array and struct (php assoc array)
1824         * @param string $compositor (all|sequence|choice)
1825         * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
1826         * @param array $elements e.g. array ( name => array(name=>'',type=>'') )
1827         * @param array $attrs e.g. array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'xsd:string[]'))
1828         * @param string $arrayType as namespace:name (xsd:string)
1829         * @see nusoap_xmlschema
1830         * @access public
1831         */
1832         function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType='') {
1833                 if (count($elements) > 0) {
1834                         $eElements = array();
1835                 foreach($elements as $n => $e){
1836                     // expand each element
1837                     $ee = array();
1838                     foreach ($e as $k => $v) {
1839                             $k = strpos($k,':') ? $this->expandQname($k) : $k;
1840                             $v = strpos($v,':') ? $this->expandQname($v) : $v;
1841                             $ee[$k] = $v;
1842                         }
1843                         $eElements[$n] = $ee;
1844                 }
1845                 $elements = $eElements;
1846                 }
1847                 
1848                 if (count($attrs) > 0) {
1849                 foreach($attrs as $n => $a){
1850                     // expand each attribute
1851                     foreach ($a as $k => $v) {
1852                             $k = strpos($k,':') ? $this->expandQname($k) : $k;
1853                             $v = strpos($v,':') ? $this->expandQname($v) : $v;
1854                             $aa[$k] = $v;
1855                         }
1856                         $eAttrs[$n] = $aa;
1857                 }
1858                 $attrs = $eAttrs;
1859                 }
1860
1861                 $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
1862                 $arrayType = strpos($arrayType,':') ? $this->expandQname($arrayType) : $arrayType;
1863
1864                 $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
1865                 $this->schemas[$typens][0]->addComplexType($name,$typeClass,$phpType,$compositor,$restrictionBase,$elements,$attrs,$arrayType);
1866         }
1867
1868         /**
1869         * adds an XML Schema simple type to the WSDL types
1870         *
1871         * @param string $name
1872         * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array)
1873         * @param string $typeClass (should always be simpleType)
1874         * @param string $phpType (should always be scalar)
1875         * @param array $enumeration array of values
1876         * @see nusoap_xmlschema
1877         * @access public
1878         */
1879         function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) {
1880                 $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase;
1881
1882                 $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
1883                 $this->schemas[$typens][0]->addSimpleType($name, $restrictionBase, $typeClass, $phpType, $enumeration);
1884         }
1885
1886         /**
1887         * adds an element to the WSDL types
1888         *
1889         * @param array $attrs attributes that must include name and type
1890         * @see nusoap_xmlschema
1891         * @access public
1892         */
1893         function addElement($attrs) {
1894                 $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns'];
1895                 $this->schemas[$typens][0]->addElement($attrs);
1896         }
1897
1898         /**
1899         * register an operation with the server
1900         * 
1901         * @param string $name operation (method) name
1902         * @param array $in assoc array of input values: key = param name, value = param type
1903         * @param array $out assoc array of output values: key = param name, value = param type
1904         * @param string $namespace optional The namespace for the operation
1905         * @param string $soapaction optional The soapaction for the operation
1906         * @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
1907         * @param string $use (encoded|literal) optional The use for the parameters (cannot mix right now)
1908         * @param string $documentation optional The description to include in the WSDL
1909         * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded)
1910         * @access public 
1911         */
1912         function addOperation($name, $in = false, $out = false, $namespace = false, $soapaction = false, $style = 'rpc', $use = 'encoded', $documentation = '', $encodingStyle = ''){
1913                 if ($use == 'encoded' && $encodingStyle == '') {
1914                         $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/';
1915                 }
1916
1917                 if ($style == 'document') {
1918                         $elements = array();
1919                         foreach ($in as $n => $t) {
1920                                 $elements[$n] = array('name' => $n, 'type' => $t, 'form' => 'unqualified');
1921                         }
1922                         $this->addComplexType($name . 'RequestType', 'complexType', 'struct', 'all', '', $elements);
1923                         $this->addElement(array('name' => $name, 'type' => $name . 'RequestType'));
1924                         $in = array('parameters' => 'tns:' . $name . '^');
1925
1926                         $elements = array();
1927                         foreach ($out as $n => $t) {
1928                                 $elements[$n] = array('name' => $n, 'type' => $t, 'form' => 'unqualified');
1929                         }
1930                         $this->addComplexType($name . 'ResponseType', 'complexType', 'struct', 'all', '', $elements);
1931                         $this->addElement(array('name' => $name . 'Response', 'type' => $name . 'ResponseType', 'form' => 'qualified'));
1932                         $out = array('parameters' => 'tns:' . $name . 'Response' . '^');
1933                 }
1934
1935                 // get binding
1936                 $this->bindings[ $this->serviceName . 'Binding' ]['operations'][$name] =
1937                 array(
1938                 'name' => $name,
1939                 'binding' => $this->serviceName . 'Binding',
1940                 'endpoint' => $this->endpoint,
1941                 'soapAction' => $soapaction,
1942                 'style' => $style,
1943                 'input' => array(
1944                         'use' => $use,
1945                         'namespace' => $namespace,
1946                         'encodingStyle' => $encodingStyle,
1947                         'message' => $name . 'Request',
1948                         'parts' => $in),
1949                 'output' => array(
1950                         'use' => $use,
1951                         'namespace' => $namespace,
1952                         'encodingStyle' => $encodingStyle,
1953                         'message' => $name . 'Response',
1954                         'parts' => $out),
1955                 'namespace' => $namespace,
1956                 'transport' => 'http://schemas.xmlsoap.org/soap/http',
1957                 'documentation' => $documentation); 
1958                 // add portTypes
1959                 // add messages
1960                 if($in)
1961                 {
1962                         foreach($in as $pName => $pType)
1963                         {
1964                                 if(strpos($pType,':')) {
1965                                         $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
1966                                 }
1967                                 $this->messages[$name.'Request'][$pName] = $pType;
1968                         }
1969                 } else {
1970             $this->messages[$name.'Request']= '0';
1971         }
1972                 if($out)
1973                 {
1974                         foreach($out as $pName => $pType)
1975                         {
1976                                 if(strpos($pType,':')) {
1977                                         $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType);
1978                                 }
1979                                 $this->messages[$name.'Response'][$pName] = $pType;
1980                         }
1981                 } else {
1982             $this->messages[$name.'Response']= '0';
1983         }
1984                 return true;
1985         } 
1986 }
1987
1988 ?>