summaryrefslogtreecommitdiff
path: root/framework/Web/TUrlMapping.php
blob: 33f013403c65dae1a056840a19e5fe618b8ab6fc (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
<?php
/**
 * TUrlMapping and TUrlMappingPattern class file.
 *
 * @author Wei Zhuo <weizhuo[at]gamil[dot]com>
 * @link http://www.pradosoft.com/
 * @copyright Copyright &copy; 2006 PradoSoft
 * @license http://www.pradosoft.com/license/
 * @version $Id$
 * @package System.Web
 */

Prado::using('System.Web.TUrlManager');

/**
 * TUrlMapping Class
 *
 * The TUrlMapping module allows aributary URL path to be mapped to a
 * particular service and page class. This module must be configured
 * before a service is initialized, thus this module should be configured
 * globally in the <tt>application.xml</tt> file and before any services.
 * <code>
 *  <module id="friendly-url" class="System.Web.TUrlMapping">
 *    <url ServiceParameter="Posts.ViewPost" pattern="post/{id}/?" parameters.id="\d+" />
 *    <url ServiceParameter="Posts.ListPost" pattern="archive/{time}/?" parameters.time="\d{6}" />
 *    <url ServiceParameter="Posts.ListPost" pattern="category/{cat}/?" parameters.cat="\d+" />
 *  </module>
 *  <module id="request" class="THttpRequest" UrlManager="friendly-url" />
 * </code>
 *
 * See {@link TUrlMappingPattern} for details regarding the mapping patterns.
 * Similar to other modules, the <tt>&lt;url /&gt;</tt> configuration class
 * can be customised using the <tt>class</tt> property.
 *
 * The URL mapping are evaluated in order, only the first mapping that matches
 * the URL will be used. Cascaded mapping can be achieved by placing the URL mappings
 * in particular order. For example, placing the most specific mappings first.
 *
 * The mapping can be load from an external file by specifying a configuration
 * file using the {@link setConfigFile ConfigFile} property.
 *
 * Since TUrlMapping is a URL manager extending from {@link TUrlManager},
 * you may override {@link TUrlManager::constructUrl} to support your pattern-based
 * URL scheme.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @version $Id$
 * @package System.Web
 * @since 3.0.5
 */
class TUrlMapping extends TUrlManager
{
	/**
	 * File extension of external configuration file
	 */
	const CONFIG_FILE_EXT='.xml';
	/**
	 * @var string default pattern class.
	 */
	private $_defaultPatternClass='TUrlMappingPattern';
	/**
	 * @var TUrlMappingPattern[] list of patterns.
	 */
	private $_patterns=array();
	/**
	 * @var TUrlMappingPattern matched pattern.
	 */
	private $_matched;
	/**
	 * @var string external configuration file
	 */
	private $_configFile=null;

	/**
	 * Initializes this module.
	 * This method is required by the IModule interface.
	 * @param TXmlElement configuration for this module, can be null
	 * @throws TConfigurationException if module is configured in the global scope.
	 */
	public function init($xml)
	{
		parent::init($xml);
		if($this->getRequest()->getRequestResolved())
			throw new TConfigurationException('urlpath_dispatch_module_must_be_global');
		if($this->_configFile!==null)
			$this->loadConfigFile();
		$this->loadUrlMappings($xml);
	}

	/**
	 * Initialize the module from configuration file.
	 * @throws TConfigurationException if {@link getConfigFile ConfigFile} is invalid.
	 */
	protected function loadConfigFile()
	{
		if(is_file($this->_configFile))
 		{
			$dom=new TXmlDocument;
			$dom->loadFromFile($this->_configFile);
			$this->loadUrlMappings($dom);
		}
		else
			throw new TConfigurationException(
				'urlpath_dispatch_configfile_invalid',$this->_configFile);
	}

	/**
	 * @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('urlpath_configfile_invalid',$value);
	}

	/**
	 * Load and configure each url mapping pattern.
	 * @param TXmlElement configuration node
	 * @throws TConfigurationException if specific pattern class is invalid
	 */
	protected function loadUrlMappings($xml)
	{
		foreach($xml->getElementsByTagName('url') as $url)
		{
			$properties=$url->getAttributes();
			$class=$properties->remove('class');
			if($class===null)
				$class = $this->_defaultPatternClass;
			$pattern = Prado::createComponent($class);
			if(!($pattern instanceof TUrlMappingPattern))
				throw new TConfigurationException('urlpath_dispatch_invalid_pattern_class');
			foreach($properties as $name=>$value)
				$pattern->setSubproperty($name,$value);
			$this->_patterns[] = $pattern;
			$pattern->init($url);
		}
	}

	/**
	 * Parses the request URL and returns an array of input parameters.
	 * This method overrides the parent implementation.
	 * The input parameters do not include GET and POST variables.
	 * This method uses the request URL path to find the first matching pattern. If found
	 * the matched pattern parameters are used to return as the input parameters.
	 * @return array list of input parameters
	 */
	public function parseUrl()
	{
		$url = $this->getRequest()->getUrl();
		foreach($this->_patterns as $pattern)
		{
			$matches = $pattern->getPatternMatches($url);
			if(count($matches) > 0)
			{
				$this->_matched=$pattern;
				$this->changeServiceParameters($pattern);
				$params=array();
				foreach($matches as $key=>$value)
					if(is_string($key))
						$params[$key]=$value;
				return $params;
			}
		}
		return parent::parseUrl();
	}

	/**
	 * @return TUrlMappingPattern the matched pattern, null if not found.
	 */
	public function getMatchingPattern()
	{
		return $this->_matched;
	}

	/**
	 * @param TUrlMappingPattern change the Request service ID and page class.
	 */
	protected function changeServiceParameters($pattern)
	{
		$request = $this->getRequest();
		$id = $pattern->getServiceID();
		$param = $pattern->getServiceParameter();
		$request->setServiceID($id);
		$request->setServiceParameter($param);
		$request->add($id,$param);
	}
}

/**
 * URL Mapping Pattern Class
 *
 * Describes an URL mapping pattern, if a given URL matches the pattern, the
 * TUrlMapping class will alter the THttpRequest parameters. The
 * url matching is done using patterns and regular expressions.
 *
 * The {@link setPattern Pattern} property takes an string expression with
 * parameter names enclosed between a left brace '{' and a right brace '}'.
 * The pattens for each parameter can be set using {@link getParameters Parameters}
 * attribute collection. For example
 * <code>
 * <url ... pattern="articles/{year}/{month}/{day}"
 *          parameters.year="\d{4}" parameters.month="\d{2}" parameters.day="\d+" />
 * </code>
 *
 * In the above example, the pattern contains 3 parameters named "year",
 * "month" and "day". The pattern for these parameters are, respectively,
 * "\d{4}" (4 digits), "\d{2}" (2 digits) and "\d+" (1 or more digits).
 * Essentially, the <tt>Parameters</tt> attribute name and values are used
 * as substrings in replacing the placeholders in the <tt>Pattern</tt> string
 * to form a complete regular expression string. A full regular expression
 * may be expressed using the <tt>RegularExpression</tt> attribute or
 * as the body content of the &lt;module&gt; tag. The above pattern is equivalent
 * to the following regular expression pattern.
 * <code>
 * /articles\/(?P<year>\d{4})\/(?P<month>\d{2})\/(?P<day>\d+)/u
 * </code>
 * The above regular expression used the "named group" feature available in PHP.
 * Notice that you need to escape the slash in regular expressions.
 *
 * In the TUrlMappingPattern class, the pattern is matched against the
 * <b>path</b> property of the url only.
 *
 * Thus, only an url that matches the pattern will be valid. For example,
 * an url "<tt>http://example.com/articles/2006/07/21</tt>" will matches and is valid.
 * However, "<tt>http://example.com/articles/2006/07/hello</tt>" is not
 * valid since the "day" parameter pattern is not satisfied.
 *
 * The parameter values are available through the standard <tt>Request</tt>
 * object. For example, <tt>$this->Request['year']</tt>.
 *
 * The {@link setServiceParameter ServiceParameter} and {@link setServiceID ServiceID}
 * (the default ID is 'page') set the service parameter and service id respectively.
 * The service parameter for the TPageService is the Page class name, other service
 * may use the service parameter differently.
 *
 * For more complicated mappings, the body of the <tt>&lt;url&gt;</tt>
 * can be used to specify the mapping pattern.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @version $Id$
 * @package System.Web
 * @since 3.0.5
 */
class TUrlMappingPattern extends TComponent
{
	/**
	 * @var string service parameter such as Page class name.
	 */
	private $_serviceParameter;
	/**
	 * @var string service ID, default is 'page'.
	 */
	private $_serviceID='page';
	/**
	 * @var string url pattern to match.
	 */
	private $_pattern;
	/**
	 * @var TMap parameter regular expressions.
	 */
	private $_parameters;
	/**
	 * @var string regular expression pattern.
	 */
	private $_regexp;
	/**
	 * @var boolean case sensitive matching, default is true
	 */
	private $_caseSensitive=true;

	public function __construct()
	{
		$this->_parameters = Prado::createComponent('System.Collections.TAttributeCollection');
	}

	/**
	 * Initialize the pattern, uses the body content as pattern is available.
	 * @param TXmlElement configuration for this module.
	 * @throws TConfigurationException if page class is not specified.
	 */
	public function init($config)
	{
		$body = trim($config->getValue());
		if(strlen($body)>0)
			$this->setRegularExpression($body);
		if(is_null($this->_serviceParameter))
		{
			throw new TConfigurationException(
				'dispatcher_url_service_parameter_missing', $this->getPattern());
		}
	}

	/**
	 * Subsitutue the parameter key value pairs as named groupings
	 * in the regular expression matching pattern.
	 * @return string regular expression pattern with parameter subsitution
	 */
	protected function getParameterizedPattern()
	{
		$params= array();
		$values = array();
		foreach($this->parameters as $key => $value)
		{
			$params[] = '{'.$key.'}';
			$values[] = '(?P<'.$key.'>'.$value.')';
		}
		$params[] = '/';
		$values[] = '\\/';
		$regexp = str_replace($params,$values,$this->getPattern());
		$modifiers = $this->getModifiers();
		return '/'.$regexp.'/'.$modifiers;
	}

	/**
	 * @return string full regular expression mapping pattern
	 */
	public function getRegularExpression()
	{
		return $this->_regexp;
	}

	/**
	 * @param string full regular expression mapping patern.
	 */
	public function setRegularExpression($value)
	{
		$this->_regexp=$value;
	}

	/**
	 * @param string service parameter, such as page class name.
	 */
	public function setServiceParameter($value)
	{
		$this->_serviceParameter=$value;
	}

	/**
	 * @return string service parameter, such as page class name.
	 */
	public function getServiceParameter()
	{
		return $this->_serviceParameter;
	}

	/**
	 * @param string service id to handle.
	 */
	public function setServiceID($value)
	{
		$this->_serviceID=$value;
	}

	/**
	 * @return string service id.
	 */
	public function getServiceID()
	{
		return $this->_serviceID;
	}

	/**
	 * @return string url pattern to match.
	 */
	public function getPattern()
	{
		return $this->_pattern;
	}

	/**
	 * @param string url pattern to match.
	 */
	public function setPattern($value)
	{
		$this->_pattern = $value;
	}

	/**
	 * @param boolean case sensitive pattern matching, default is true.
	 */
	public function setCaseSensitive($value)
	{
		$this->_caseSensitive=TPropertyValue::ensureBoolean($value);
	}

	/**
	 * @return boolean case sensitive pattern matching, default is true.
	 */
	public function getCaseSensitive()
	{
		return $this->_caseSensitive;
	}

	/**
	 * @return TAttributeCollection parameter key value pairs.
	 */
	public function getParameters()
	{
		return $this->_parameters;
	}

	/**
	 * @param TAttributeCollection new parameter key value pairs.
	 */
	public function setParameters($value)
	{
		$this->_parameters=$value;
	}

	/**
	 * Uses URL pattern (or full regular expression if available) to
	 * match the given url path.
	 * @param TUri url to match against
	 * @return array matched parameters, empty if no matches.
	 */
	public function getPatternMatches($url)
	{
		$path = $url->getPath();
		$matches=array();
		$pattern = $this->getRegularExpression();
		if($pattern === null)
			$pattern = $this->getParameterizedPattern();
		preg_match($pattern, $path, $matches);
		return $matches;
	}

	/**
	 * @return string regular expression matching modifiers.
	 */
	protected function getModifiers()
	{
		$modifiers = 'u';
		if(!$this->getCaseSensitive())
			$modifiers .= 'i';
		return $modifiers;
	}
}

?>