summaryrefslogtreecommitdiff
path: root/framework/Web/Services/TSoapService.php
blob: 259fa5f87a4f15ffb0a69533e7fca573b419c7d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
<?php
/**
 * TSoapService and TSoapServer class file
 *
 * @author Knut Urdalen <knut.urdalen@gmail.com>
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @link http://www.pradosoft.com/
 * @copyright Copyright &copy; 2005-2008 PradoSoft
 * @license http://www.pradosoft.com/license/
 * @version $Id$
 * @package System.Web.Services
 */

/**
 * TSoapService class
 *
 * TSoapService processes SOAP requests for a PRADO application.
 * TSoapService requires PHP SOAP extension to be loaded.
 *
 * TSoapService manages a set of SOAP providers. Each SOAP provider
 * is a class that implements a set of SOAP methods which are exposed
 * to SOAP clients for remote invocation. TSoapService generates WSDL
 * automatically for the SOAP providers by default.
 *
 * To use TSoapService, configure it in the application specification like following:
 * <code>
 *   <services>
 *     <service id="soap" class="System.Web.Services.TSoapService">
 *       <soap id="stockquote" provider="MyStockQuote" />
 *     </service>
 *   </services>
 * </code>
 *
 * The above example specifies a single SOAP provider named "stockquote"
 * whose class is "MyStockQuote". A SOAP client can then obtain the WSDL for
 * this provider via the following URL:
 * <code>
 *   http://hostname/path/to/index.php?soap=stockquote.wsdl
 * </code>
 *
 * The WSDL for the provider class "MyStockQuote" is generated based on special
 * comment tags in the class. In particular, if a class method's comment
 * contains the keyword "@soapmethod", it is considered to be a SOAP method
 * and will be exposed to SOAP clients. For example,
 * <code>
 *   class MyStockQuote {
 *      / **
 *       * @param string $symbol the stock symbol
 *       * @return float the stock price
 *       * @soapmethod
 *       * /
 *      public function getQuote($symbol) {...}
 *   }
 * </code>
 *
 * With the above SOAP provider, a typical SOAP client may call the method "getQuote"
 * remotely like the following:
 * <code>
 *   $client=new SoapClient("http://hostname/path/to/index.php?soap=stockquote.wsdl");
 *   echo $client->getQuote("ibm");
 * </code>
 *
 * Each <soap> element in the application specification actually configures
 * the properties of a SOAP server which defaults to {@link TSoapServer}.
 * Therefore, any writable property of {@link TSoapServer} may appear as an attribute
 * in the <soap> element. For example, the "provider" attribute refers to
 * the {@link TSoapServer::setProvider Provider} property of {@link TSoapServer}.
 * The following configuration specifies that the SOAP server is persistent within
 * the user session (that means a MyStockQuote object will be stored in session)
 * <code>
 *   <services>
 *     <service id="soap" class="System.Web.Services.TSoapService">
 *       <soap id="stockquote" provider="MyStockQuote" SessionPersistent="true" />
 *     </service>
 *   </services>
 * </code>
 *
 * You may also use your own SOAP server class by specifying the "class" attribute of <soap>.
 *
 * @author Knut Urdalen <knut.urdalen@gmail.com>
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @package System.Web.Services
 * @since 3.1
 */
class TSoapService extends TService
{
	const DEFAULT_SOAP_SERVER='TSoapServer';
	const CONFIG_FILE_EXT='.xml';
	private $_servers=array();
	private $_configFile=null;
	private $_wsdlRequest=false;
	private $_serverID=null;

	/**
	 * Constructor.
	 * Sets default service ID to 'soap'.
	 */
	public function __construct()
	{
		$this->setID('soap');
	}

	/**
	 * Initializes this module.
	 * This method is required by the IModule interface.
	 * @param TXmlElement configuration for this module, can be null
	 * @throws TConfigurationException if {@link getConfigFile ConfigFile} is invalid.
	 */
	public function init($config)
	{
		if($this->_configFile!==null)
		{
 			if(is_file($this->_configFile))
 			{
				$dom=new TXmlDocument;
				$dom->loadFromFile($this->_configFile);
				$this->loadConfig($dom);
			}
			else
				throw new TConfigurationException('soapservice_configfile_invalid',$this->_configFile);
		}
		$this->loadConfig($config);

		$this->resolveRequest();
	}

	/**
	 * Resolves the request parameter.
	 * It identifies the server ID and whether the request is for WSDL.
	 * @throws THttpException if the server ID cannot be found
	 * @see getServerID
	 * @see getIsWsdlRequest
	 */
	protected function resolveRequest()
	{
		$serverID=$this->getRequest()->getServiceParameter();
		if(($pos=strrpos($serverID,'.wsdl'))===strlen($serverID)-5)
		{
			$serverID=substr($serverID,0,$pos);
			$this->_wsdlRequest=true;
		}
		else
			$this->_wsdlRequest=false;
		$this->_serverID=$serverID;
		if(!isset($this->_servers[$serverID]))
			throw new THttpException(400,'soapservice_request_invalid',$serverID);
	}

	/**
	 * Loads configuration from an XML element
	 * @param mixed configuration node
	 * @throws TConfigurationException if soap server id is not specified or duplicated
	 */
	private function loadConfig($config)
	{	
		if($this->getApplication()->getConfigurationType()==TApplication::CONFIG_TYPE_PHP)
		{
			if(is_array($config))
			{
				foreach($config as $id => $server)
				{
					$properties = isset($server['properties'])?$server['properties']:array();
					if(isset($this->_servers[$id]))
						throw new TConfigurationException('soapservice_serverid_duplicated',$id);
					$this->_servers[$id]=$properties;
				}
			}
		}
		else
		{
			foreach($config->getElementsByTagName('soap') as $serverXML)
			{
				$properties=$serverXML->getAttributes();
				if(($id=$properties->remove('id'))===null)
					throw new TConfigurationException('soapservice_serverid_required');
				if(isset($this->_servers[$id]))
					throw new TConfigurationException('soapservice_serverid_duplicated',$id);
				$this->_servers[$id]=$properties;
			}
		}
	}

	/**
	 * @return string external configuration file. Defaults to null.
	 */
	public function getConfigFile()
	{
		return $this->_configFile;
	}

	/**
	 * @param string external configuration file in namespace format. The file
	 * must be suffixed with '.xml'.
	 * @throws TInvalidDataValueException if the file is invalid.
	 */
	public function setConfigFile($value)
	{
		if(($this->_configFile=Prado::getPathOfNamespace($value,self::CONFIG_FILE_EXT))===null)
			throw new TConfigurationException('soapservice_configfile_invalid',$value);
	}

	/**
	 * Constructs a URL with specified page path and GET parameters.
	 * @param string soap server ID
	 * @param array list of GET parameters, null if no GET parameters required
	 * @param boolean whether to encode the ampersand in URL, defaults to true.
	 * @param boolean whether to encode the GET parameters (their names and values), defaults to true.
	 * @return string URL for the page and GET parameters
	 */
	public function constructUrl($serverID,$getParams=null,$encodeAmpersand=true,$encodeGetItems=true)
	{
		return $this->getRequest()->constructUrl($this->getID(),$serverID,$getParams,$encodeAmpersand,$encodeGetItems);
	}

	/**
	 * @return boolean whether this is a request for WSDL
	 */
	public function getIsWsdlRequest()
	{
		return $this->_wsdlRequest;
	}

	/**
	 * @return string the SOAP server ID
	 */
	public function getServerID()
	{
		return $this->_serverID;
	}

	/**
	 * Creates the requested SOAP server.
	 * The SOAP server is initialized with the property values specified
	 * in the configuration.
	 * @return TSoapServer the SOAP server instance
	 */
	protected function createServer()
	{
		$properties=$this->_servers[$this->_serverID];
		if($this->getApplication()->getConfigurationType()==TApplication::CONFIG_TYPE_PHP || ($serverClass=$properties->remove('class'))===null)
			$serverClass=self::DEFAULT_SOAP_SERVER;
		Prado::using($serverClass);
		$className=($pos=strrpos($serverClass,'.'))!==false?substr($serverClass,$pos+1):$serverClass;
		if($className!==self::DEFAULT_SOAP_SERVER && !is_subclass_of($className,self::DEFAULT_SOAP_SERVER))
			throw new TConfigurationException('soapservice_server_invalid',$serverClass);
		$server=new $className;
		$server->setID($this->_serverID);
		foreach($properties as $name=>$value)
			$server->setSubproperty($name,$value);
		return $server;
	}

	/**
	 * Runs the service.
	 * If the service parameter ends with '.wsdl', it will serve a WSDL file for
	 * the specified soap server.
	 * Otherwise, it will handle the soap request using the specified server.
	 */
	public function run()
	{
		Prado::trace("Running SOAP service",'System.Web.Services.TSoapService');
		$server=$this->createServer();
		$this->getResponse()->setContentType('text/xml');
		$this->getResponse()->setCharset($server->getEncoding());
		if($this->getIsWsdlRequest())
		{
			// server WSDL file
			Prado::trace("Generating WSDL",'System.Web.Services.TSoapService');
			$this->getResponse()->write($server->getWsdl());
		}
		else
		{
			// provide SOAP service
			Prado::trace("Handling SOAP request",'System.Web.Services.TSoapService');
			$server->run();
		}
	}
}


/**
 * TSoapServer class.
 *
 * TSoapServer is a wrapper of the PHP SoapServer class.
 * It associates a SOAP provider class to the SoapServer object.
 * It also manages the URI for the SOAP service and WSDL.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @version $Id$
 * @package System.Web.Services
 * @since 3.1
 */
class TSoapServer extends TApplicationComponent
{
	const WSDL_CACHE_PREFIX='wsdl.';

	private $_id;
	private $_provider;

	private $_version='';
	private $_actor='';
	private $_encoding='';
	private $_uri='';
	private $_classMap;
	private $_persistent=false;
	private $_wsdlUri='';

	private $_requestedMethod;

	private $_server;

	/**
	 * @return string the ID of the SOAP server
	 */
	public function getID()
	{
		return $this->_id;
	}

	/**
	 * @param string the ID of the SOAP server
	 * @throws TInvalidDataValueException if the ID ends with '.wsdl'.
	 */
	public function setID($id)
	{
		if(strrpos($this->_id,'.wsdl')===strlen($this->_id)-5)
			throw new TInvalidDataValueException('soapserver_id_invalid',$id);
		$this->_id=$id;
	}

	/**
	 * Handles the SOAP request.
	 */
	public function run()
	{
		if(($provider=$this->getProvider())!==null)
		{
			Prado::using($provider);
			$providerClass=($pos=strrpos($provider,'.'))!==false?substr($provider,$pos+1):$provider;
			$this->guessMethodCallRequested($providerClass);
			$server=$this->createServer();
			$server->setClass($providerClass, $this);
			if($this->_persistent)
				$server->setPersistence(SOAP_PERSISTENCE_SESSION);
		}
		else
			$server=$this->createServer();
		try
		{
			$server->handle();
		}
		catch (Exception $e)
		{
			if($this->getApplication()->getMode()===TApplicationMode::Debug)
				$this->fault($e->getMessage(), $e->__toString());
			else
				$this->fault($e->getMessage());
		}
	}

	/**
	 * Generate a SOAP fault message.
	 * @param string message title
	 * @param mixed message details
	 * @param string message code, defalt is 'SERVER'.
	 * @param string actors
	 * @param string message name
	 */
	public function fault($title, $details='', $code='SERVER', $actor='', $name='')
	{
		Prado::trace('SOAP-Fault '.$code. ' '.$title.' : '.$details, 'System.Web.Services.TSoapService');
		$this->_server->fault($code, $title, $actor, $details, $name);
	}

	/**
	 * Guess the SOAP method request from the actual SOAP message
	 *
	 * @param string $class current handler class.
	 */
	protected function guessMethodCallRequested($class)
	{
		$namespace = $class.'wsdl';
		$message = file_get_contents("php://input");
		$matches= array();
		if(preg_match('/xmlns:([^=]+)="urn:'.$namespace.'"/', $message, $matches))
		{
			if(preg_match('/<'.$matches[1].':([a-zA-Z_]+[a-zA-Z0-9_]+)/', $message, $method))
			{
				$this->_requestedMethod = $method[1];
			}
		}
	}

	/**
	 * Soap method guessed from the SOAP message received.
	 * @return string soap method request, null if not found.
	 */
	public function getRequestedMethod()
	{
		return $this->_requestedMethod;
	}

	/**
	 * Creates the SoapServer instance.
	 * @return SoapServer
	 */
	protected function createServer()
	{
		if($this->_server===null)
		{
			if($this->getApplication()->getMode()===TApplicationMode::Debug)
				ini_set("soap.wsdl_cache_enabled",0);
			$this->_server = new SoapServer($this->getWsdlUri(),$this->getOptions());
		}
		return $this->_server;
	}

	/**
	 * @return array options for creating SoapServer instance
	 */
	protected function getOptions()
	{
		$options=array();
		if($this->_version==='1.1')
			$options['soap_version']=SOAP_1_1;
		else if($this->_version==='1.2')
			$options['soap_version']=SOAP_1_2;
		if(!empty($this->_actor))
			$options['actor']=$this->_actor;
		if(!empty($this->_encoding))
			$options['encoding']=$this->_encoding;
		if(!empty($this->_uri))
			$options['uri']=$this->_uri;
		if(is_string($this->_classMap))
		{
			foreach(preg_split('/\s*,\s*/', $this->_classMap) as $className)
				$options['classmap'][$className]=$className; //complex type uses the class name in the wsdl
		}
		return $options;
	}

	/**
	 * Returns the WSDL content of the SOAP server.
	 * If {@link getWsdlUri WsdlUri} is set, its content will be returned.
	 * If not, the {@link setProvider Provider} class will be investigated
	 * and the WSDL will be automatically genearted.
	 * @return string the WSDL content of the SOAP server
	 */
	public function getWsdl()
	{
		if($this->_wsdlUri==='')
		{
			$provider=$this->getProvider();
			$providerClass=($pos=strrpos($provider,'.'))!==false?substr($provider,$pos+1):$provider;
			Prado::using($provider);
			if($this->getApplication()->getMode()===TApplicationMode::Performance && ($cache=$this->getApplication()->getCache())!==null)
			{
				$wsdl=$cache->get(self::WSDL_CACHE_PREFIX.$providerClass);
				if(is_string($wsdl))
					return $wsdl;
				Prado::using('System.3rdParty.WsdlGen.WsdlGenerator');
				$wsdl=WsdlGenerator::generate($providerClass, $this->getUri(), $this->getEncoding());
				$cache->set(self::WSDL_CACHE_PREFIX.$providerClass,$wsdl);
				return $wsdl;
			}
			else
			{
				Prado::using('System.3rdParty.WsdlGen.WsdlGenerator');
				return WsdlGenerator::generate($providerClass, $this->getUri(), $this->getEncoding());
			}
		}
		else
			return file_get_contents($this->_wsdlUri);
	}

	/**
	 * @return string the URI for WSDL
	 */
	public function getWsdlUri()
	{
		if($this->_wsdlUri==='')
			return $this->getRequest()->getBaseUrl().$this->getService()->constructUrl($this->getID().'.wsdl',false);
		else
			return $this->_wsdlUri;
	}

	/**
	 * @param string the URI for WSDL
	 */
	public function setWsdlUri($value)
	{
		$this->_wsdlUri=$value;
	}

	/**
	 * @return string the URI for the SOAP service
	 */
	public function getUri()
	{
		if($this->_uri==='')
			return $this->getRequest()->getBaseUrl().$this->getService()->constructUrl($this->getID(),false);
		else
			return $this->_uri;
	}

	/**
	 * @param string the URI for the SOAP service
	 */
	public function setUri($uri)
	{
		$this->_uri=$uri;
	}

	/**
	 * @return string the SOAP provider class (in namespace format)
	 */
	public function getProvider()
	{
		return $this->_provider;
	}

	/**
	 * @param string the SOAP provider class (in namespace format)
	 */
	public function setProvider($provider)
	{
		$this->_provider=$provider;
	}

	/**
	 * @return string SOAP version, defaults to empty (meaning not set).
	 */
	public function getVersion()
	{
		return $this->_version;
	}

	/**
	 * @param string SOAP version, either '1.1' or '1.2'
	 * @throws TInvalidDataValueException if neither '1.1' nor '1.2'
	 */
	public function setVersion($value)
	{
		if($value==='1.1' || $value==='1.2' || $value==='')
			$this->_version=$value;
		else
			throw new TInvalidDataValueException('soapserver_version_invalid',$value);
	}

	/**
	 * @return string actor of the SOAP service
	 */
	public function getActor()
	{
		return $this->_actor;
	}

	/**
	 * @param string actor of the SOAP service
	 */
	public function setActor($value)
	{
		$this->_actor=$value;
	}

	/**
	 * @return string encoding of the SOAP service
	 */
	public function getEncoding()
	{
		return $this->_encoding;
	}

	/**
	 * @param string encoding of the SOAP service
	 */
	public function setEncoding($value)
	{
		$this->_encoding=$value;
	}

	/**
	 * @return boolean whether the SOAP service is persistent within session. Defaults to false.
	 */
	public function getSessionPersistent()
	{
		return $this->_persistent;
	}

	/**
	 * @param boolean whether the SOAP service is persistent within session.
	 */
	public function setSessionPersistent($value)
	{
		$this->_persistent=TPropertyValue::ensureBoolean($value);
	}

	/**
	 * @return string comma delimit list of complex type classes.
	 */
	public function getClassMaps()
	{
		return $this->_classMap;
	}

	/**
	 * @return string comma delimit list of class names
	 */
	public function setClassMaps($classes)
	{
		$this->_classMap = $classes;
	}
}

?>