Subversion-Projekte lars-tiefland.prado

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/**
3
 * TUrlMapping and TUrlMappingPattern class file.
4
 *
5
 * @author Wei Zhuo <weizhuo[at]gamil[dot]com>
6
 * @link http://www.pradosoft.com/
7
 * @copyright Copyright &copy; 2005-2008 PradoSoft
8
 * @license http://www.pradosoft.com/license/
9
 * @version $Id: TUrlMapping.php 2584 2008-12-04 17:05:12Z haertl.mike $
10
 * @package System.Web
11
 */
12
 
13
Prado::using('System.Web.TUrlManager');
14
Prado::using('System.Collections.TAttributeCollection');
15
 
16
/**
17
 * TUrlMapping Class
18
 *
19
 * The TUrlMapping module allows PRADO to construct and recognize URLs
20
 * based on specific patterns.
21
 *
22
 * TUrlMapping consists of a list of URL patterns which are used to match
23
 * against the currently requested URL. The first matching pattern will then
24
 * be used to decompose the URL into request parameters (accessible through
25
 * <code>$this->Request['paramname']</code>).
26
 *
27
 * The patterns can also be used to construct customized URLs. In this case,
28
 * the parameters in an applied pattern will be replaced with the corresponding
29
 * GET variable values.
30
 *
31
 * Since it is derived from {@link TUrlManager}, it should be configured globally
32
 * in the application configuration like the following,
33
 * <code>
34
 *  <module id="request" class="THttpRequest" UrlManager="friendly-url" />
35
 *  <module id="friendly-url" class="System.Web.TUrlMapping" EnableCustomUrl="true">
36
 *    <url ServiceParameter="Posts.ViewPost" pattern="post/{id}/" parameters.id="\d+" />
37
 *    <url ServiceParameter="Posts.ListPost" pattern="archive/{time}/" parameters.time="\d{6}" />
38
 *    <url ServiceParameter="Posts.ListPost" pattern="category/{cat}/" parameters.cat="\d+" />
39
 *  </module>
40
 * </code>
41
 *
42
 * In the above, each <tt>&lt;url&gt;</tt> element specifies a URL pattern represented
43
 * as a {@link TUrlMappingPattern} internally. You may create your own pattern classes
44
 * by extending {@link TUrlMappingPattern} and specifying the <tt>&lt;class&gt;</tt> attribute
45
 * in the element.
46
 *
47
 * The patterns can be also be specified in an external file using the {@link setConfigFile ConfigFile} property.
48
 *
49
 * The URL mapping are evaluated in order, only the first mapping that matches
50
 * the URL will be used. Cascaded mapping can be achieved by placing the URL mappings
51
 * in particular order. For example, placing the most specific mappings first.
52
 *
53
 * Only the PATH_INFO part of the URL is used to match the available patterns. The matching
54
 * is strict in the sense that the whole pattern must match the whole PATH_INFO of the URL.
55
 *
56
 * From PRADO v3.1.1, TUrlMapping also provides support for constructing URLs according to
57
 * the specified pattern. You may enable this functionality by setting {@link setEnableCustomUrl EnableCustomUrl} to true.
58
 * When you call THttpRequest::constructUrl() (or via TPageService::constructUrl()),
59
 * TUrlMapping will examine the available URL mapping patterns using their {@link TUrlMappingPattern::getServiceParameter ServiceParameter}
60
 * and {@link TUrlMappingPattern::getPattern Pattern} properties. A pattern is applied if its
61
 * {@link TUrlMappingPattern::getServiceParameter ServiceParameter} matches the service parameter passed
62
 * to constructUrl() and every parameter in the {@link getPattern Pattern} is found
63
 * in the GET variables.
64
 *
65
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
66
 * @version $Id: TUrlMapping.php 2584 2008-12-04 17:05:12Z haertl.mike $
67
 * @package System.Web
68
 * @since 3.0.5
69
 */
70
class TUrlMapping extends TUrlManager
71
{
72
	/**
73
	 * File extension of external configuration file
74
	 */
75
	const CONFIG_FILE_EXT='.xml';
76
	/**
77
	 * @var TUrlMappingPattern[] list of patterns.
78
	 */
79
	protected $_patterns=array();
80
	/**
81
	 * @var TUrlMappingPattern matched pattern.
82
	 */
83
	private $_matched;
84
	/**
85
	 * @var string external configuration file
86
	 */
87
	private $_configFile=null;
88
	/**
89
	 * @var boolean whether to enable custom contructUrl
90
	 */
91
	private $_customUrl=false;
92
	/**
93
	 * @var array rules for constructing URLs
94
	 */
95
	protected $_constructRules=array();
96
 
97
	private $_urlPrefix='';
98
 
99
	private $_defaultMappingClass='TUrlMappingPattern';
100
 
101
	/**
102
	 * Initializes this module.
103
	 * This method is required by the IModule interface.
104
	 * @param TXmlElement configuration for this module, can be null
105
	 * @throws TConfigurationException if module is configured in the global scope.
106
	 */
107
	public function init($xml)
108
	{
109
		parent::init($xml);
110
		if($this->getRequest()->getRequestResolved())
111
			throw new TConfigurationException('urlmapping_global_required');
112
		if($this->_configFile!==null)
113
			$this->loadConfigFile();
114
		$this->loadUrlMappings($xml);
115
		if($this->_urlPrefix==='')
116
			$this->_urlPrefix=$this->getRequest()->getApplicationUrl();
117
		$this->_urlPrefix=rtrim($this->_urlPrefix,'/');
118
	}
119
 
120
	/**
121
	 * Initialize the module from configuration file.
122
	 * @throws TConfigurationException if {@link getConfigFile ConfigFile} is invalid.
123
	 */
124
	protected function loadConfigFile()
125
	{
126
		if(is_file($this->_configFile))
127
 		{
128
			$dom=new TXmlDocument;
129
			$dom->loadFromFile($this->_configFile);
130
			$this->loadUrlMappings($dom);
131
		}
132
		else
133
			throw new TConfigurationException('urlmapping_configfile_inexistent',$this->_configFile);
134
	}
135
 
136
	/**
137
	 * Returns a value indicating whether to enable custom constructUrl.
138
	 * If true, constructUrl() will make use of the URL mapping rules to
139
	 * construct valid URLs.
140
	 * @return boolean whether to enable custom constructUrl. Defaults to false.
141
	 * @since 3.1.1
142
	 */
143
	public function getEnableCustomUrl()
144
	{
145
		return $this->_customUrl;
146
	}
147
 
148
	/**
149
	 * Sets a value indicating whether to enable custom constructUrl.
150
	 * If true, constructUrl() will make use of the URL mapping rules to
151
	 * construct valid URLs.
152
	 * @param boolean whether to enable custom constructUrl.
153
	 * @since 3.1.1
154
	 */
155
	public function setEnableCustomUrl($value)
156
	{
157
		$this->_customUrl=TPropertyValue::ensureBoolean($value);
158
	}
159
 
160
	/**
161
	 * @return string the part that will be prefixed to the constructed URLs. Defaults to the requested script path (e.g. /path/to/index.php for a URL http://hostname/path/to/index.php)
162
	 * @since 3.1.1
163
	 */
164
	public function getUrlPrefix()
165
	{
166
		return $this->_urlPrefix;
167
	}
168
 
169
	/**
170
	 * @param string the part that will be prefixed to the constructed URLs. This is used by constructUrl() when EnableCustomUrl is set true.
171
	 * @see getUrlPrefix
172
	 * @since 3.1.1
173
	 */
174
	public function setUrlPrefix($value)
175
	{
176
		$this->_urlPrefix=$value;
177
	}
178
 
179
	/**
180
	 * @return string external configuration file. Defaults to null.
181
	 */
182
	public function getConfigFile()
183
	{
184
		return $this->_configFile;
185
	}
186
 
187
	/**
188
	 * @param string external configuration file in namespace format. The file
189
	 * must be suffixed with '.xml'.
190
	 * @throws TInvalidDataValueException if the file is invalid.
191
	 */
192
	public function setConfigFile($value)
193
	{
194
		if(($this->_configFile=Prado::getPathOfNamespace($value,self::CONFIG_FILE_EXT))===null)
195
			throw new TConfigurationException('urlmapping_configfile_invalid',$value);
196
	}
197
 
198
	/**
199
	 * @return string the default class of URL mapping patterns. Defaults to TUrlMappingPattern.
200
	 * @since 3.1.1
201
	 */
202
	public function getDefaultMappingClass()
203
	{
204
		return $this->_defaultMappingClass;
205
	}
206
 
207
	/**
208
	 * Sets the default class of URL mapping patterns.
209
	 * When a URL matching pattern does not specify "class" attribute, it will default to the class
210
	 * specified by this property. You may use either a class name or a namespace format of class (if the class needs to be included first.)
211
	 * @param string the default class of URL mapping patterns.
212
	 * @since 3.1.1
213
	 */
214
	public function setDefaultMappingClass($value)
215
	{
216
		$this->_defaultMappingClass=$value;
217
	}
218
 
219
	/**
220
	 * Load and configure each url mapping pattern.
221
	 * @param TXmlElement configuration node
222
	 * @throws TConfigurationException if specific pattern class is invalid
223
	 */
224
	protected function loadUrlMappings($xml)
225
	{
226
		foreach($xml->getElementsByTagName('url') as $url)
227
		{
228
			$properties=$url->getAttributes();
229
			if(($class=$properties->remove('class'))===null)
230
				$class=$this->getDefaultMappingClass();
231
			$pattern=Prado::createComponent($class,$this);
232
			if(!($pattern instanceof TUrlMappingPattern))
233
				throw new TConfigurationException('urlmapping_urlmappingpattern_required');
234
			foreach($properties as $name=>$value)
235
				$pattern->setSubproperty($name,$value);
236
			$this->_patterns[]=$pattern;
237
			$pattern->init($url);
238
 
239
			$key=$pattern->getServiceID().':'.$pattern->getServiceParameter();
240
			$this->_constructRules[$key][]=$pattern;
241
		}
242
	}
243
 
244
	/**
245
	 * Parses the request URL and returns an array of input parameters.
246
	 * This method overrides the parent implementation.
247
	 * The input parameters do not include GET and POST variables.
248
	 * This method uses the request URL path to find the first matching pattern. If found
249
	 * the matched pattern parameters are used to return as the input parameters.
250
	 * @return array list of input parameters
251
	 */
252
	public function parseUrl()
253
	{
254
		$request=$this->getRequest();
255
		foreach($this->_patterns as $pattern)
256
		{
257
			$matches=$pattern->getPatternMatches($request);
258
			if(count($matches)>0)
259
			{
260
				$this->_matched=$pattern;
261
				$params=array();
262
				foreach($matches as $key=>$value)
263
				{
264
					if(is_string($key))
265
						$params[$key]=$value;
266
				}
267
				if (!$pattern->getIsWildCardPattern())
268
					$params[$pattern->getServiceID()]=$pattern->getServiceParameter();
269
				return $params;
270
			}
271
		}
272
		return parent::parseUrl();
273
	}
274
 
275
	/**
276
	 * Constructs a URL that can be recognized by PRADO.
277
	 *
278
	 * This method provides the actual implementation used by {@link THttpRequest::constructUrl}.
279
	 * Override this method if you want to provide your own way of URL formatting.
280
	 * If you do so, you may also need to override {@link parseUrl} so that the URL can be properly parsed.
281
	 *
282
	 * The URL is constructed as the following format:
283
	 * /entryscript.php?serviceID=serviceParameter&get1=value1&...
284
	 * If {@link THttpRequest::setUrlFormat THttpRequest.UrlFormat} is 'Path',
285
	 * the following format is used instead:
286
	 * /entryscript.php/serviceID/serviceParameter/get1,value1/get2,value2...
287
	 * @param string service ID
288
	 * @param string service parameter
289
	 * @param array GET parameters, null if not provided
290
	 * @param boolean whether to encode the ampersand in URL
291
	 * @param boolean whether to encode the GET parameters (their names and values)
292
	 * @return string URL
293
	 * @see parseUrl
294
	 * @since 3.1.1
295
	 */
296
	public function constructUrl($serviceID,$serviceParam,$getItems,$encodeAmpersand,$encodeGetItems)
297
	{
298
		if($this->_customUrl)
299
		{
300
	 		if(!(is_array($getItems) || ($getItems instanceof Traversable)))
301
	 			$getItems=array();
302
			$key=$serviceID.':'.$serviceParam;
303
			$wildCardKey = ($pos=strrpos($serviceParam,'.'))!==false ?
304
				$serviceID.':'.substr($serviceParam,0,$pos).'.*' : $serviceID.':*';
305
			if(isset($this->_constructRules[$key]))
306
			{
307
				foreach($this->_constructRules[$key] as $rule)
308
				{
309
					if($rule->supportCustomUrl($getItems))
310
						return $rule->constructUrl($getItems,$encodeAmpersand,$encodeGetItems);
311
				}
312
			}
313
			elseif(isset($this->_constructRules[$wildCardKey]))
314
			{
315
				foreach($this->_constructRules[$wildCardKey] as $rule)
316
				{
317
					if($rule->supportCustomUrl($getItems))
318
					{
319
						$getItems['*']= $pos ? substr($serviceParam,$pos+1) : $serviceParam;
320
						return $rule->constructUrl($getItems,$encodeAmpersand,$encodeGetItems);
321
					}
322
				}
323
			}
324
		}
325
		return parent::constructUrl($serviceID,$serviceParam,$getItems,$encodeAmpersand,$encodeGetItems);
326
	}
327
 
328
	/**
329
	 * @return TUrlMappingPattern the matched pattern, null if not found.
330
	 */
331
	public function getMatchingPattern()
332
	{
333
		return $this->_matched;
334
	}
335
}
336
 
337
/**
338
 * TUrlMappingPattern class.
339
 *
340
 * TUrlMappingPattern represents a pattern used to parse and construct URLs.
341
 * If the currently requested URL matches the pattern, it will alter
342
 * the THttpRequest parameters. If a constructUrl() call matches the pattern
343
 * parameters, the pattern will generate a valid URL. In both case, only the PATH_INFO
344
 * part of a URL is parsed/constructed using the pattern.
345
 *
346
 * To specify the pattern, set the {@link setPattern Pattern} property.
347
 * {@link setPattern Pattern} takes a string expression with
348
 * parameter names enclosed between a left brace '{' and a right brace '}'.
349
 * The patterns for each parameter can be set using {@link getParameters Parameters}
350
 * attribute collection. For example
351
 * <code>
352
 * <url ... pattern="articles/{year}/{month}/{day}"
353
 *          parameters.year="\d{4}" parameters.month="\d{2}" parameters.day="\d+" />
354
 * </code>
355
 *
356
 * In the above example, the pattern contains 3 parameters named "year",
357
 * "month" and "day". The pattern for these parameters are, respectively,
358
 * "\d{4}" (4 digits), "\d{2}" (2 digits) and "\d+" (1 or more digits).
359
 * Essentially, the <tt>Parameters</tt> attribute name and values are used
360
 * as substrings in replacing the placeholders in the <tt>Pattern</tt> string
361
 * to form a complete regular expression string.
362
 *
363
 * For more complicated patterns, one may specify the pattern using a regular expression
364
 * by {@link setRegularExpression RegularExpression}. For example, the above pattern
365
 * is equivalent to the following regular expression-based pattern:
366
 * <code>
367
 * /^articles\/(?P<year>\d{4})\/(?P<month>\d{2})\/(?P<day>\d+)$/u
368
 * </code>
369
 * The above regular expression used the "named group" feature available in PHP.
370
 * Notice that you need to escape the slash in regular expressions.
371
 *
372
 * Thus, only an url that matches the pattern will be valid. For example,
373
 * a URL <tt>http://example.com/index.php/articles/2006/07/21</tt> will match the above pattern,
374
 * while <tt>http://example.com/index.php/articles/2006/07/hello</tt> will not
375
 * since the "day" parameter pattern is not satisfied.
376
 *
377
 * The parameter values are available through the <tt>THttpRequest</tt> instance (e.g.
378
 * <tt>$this->Request['year']</tt>).
379
 *
380
 * The {@link setServiceParameter ServiceParameter} and {@link setServiceID ServiceID}
381
 * (the default ID is 'page') set the service parameter and service id respectively.
382
 *
383
 * Since 3.1.4 you can also use simplyfied wildcard patterns to match multiple
384
 * ServiceParameters with a single rule. The pattern must contain the placeholder
385
 * {*} for the ServiceParameter. For example
386
 *
387
 * <url ServiceParameter="adminpages.*" pattern="admin/{*}" />
388
 *
389
 * This rule will match an URL like <tt>http://example.com/index.php/admin/edituser</tt>
390
 * and resolve it to the page Application.pages.admin.edituser. The wildcard matching
391
 * is non-recursive. That means you have to add a rule for every subdirectory you
392
 * want to access pages in:
393
 *
394
 * <url ServiceParameter="adminpages.users.*" pattern="useradmin/{*}" />
395
 *
396
 * It is still possible to define an explicit rule for a page in the wildcard path.
397
 * This rule has to preceed the wildcard rule.
398
 *
399
 * You can also use parameters with wildcard patterns. The parameters are then
400
 * available with every matching page:
401
 *
402
 * <url ServiceParameter="adminpages.*" pattern="admin/{*}/{id}" parameters.id="\d+" />
403
 *
404
 * To enable automatic parameter encoding in a path format fro wildcard patterns you can set
405
 * {@setUrlFormat UrlFormat} to 'Path':
406
 *
407
 * <url ServiceParameter="adminpages.*" pattern="admin/{*}" UrlFormat="Path" />
408
 *
409
 * This will create and parse URLs of the form
410
 * <tt>.../index.php/admin/listuser/param1/value1/param2/value2</tt>.
411
 *
412
 * Use {@setUrlParamSeparator} to define another separator character between parameter
413
 * name and value. Parameter/value pairs are always separated by a '/'.
414
 *
415
 * <url ServiceParameter="adminpages.*" pattern="admin/{*}" UrlFormat="Path" UrlParamSeparator="-" />
416
 *
417
 * <tt>.../index.php/admin/listuser/param1-value1/param2-value2</tt>.
418
 *
419
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
420
 * @version $Id: TUrlMapping.php 2584 2008-12-04 17:05:12Z haertl.mike $
421
 * @package System.Web
422
 * @since 3.0.5
423
 */
424
class TUrlMappingPattern extends TComponent
425
{
426
	/**
427
	 * @var string service parameter such as Page class name.
428
	 */
429
	private $_serviceParameter;
430
	/**
431
	 * @var string service ID, default is 'page'.
432
	 */
433
	private $_serviceID='page';
434
	/**
435
	 * @var string url pattern to match.
436
	 */
437
	private $_pattern;
438
	/**
439
	 * @var TMap parameter regular expressions.
440
	 */
441
	private $_parameters;
442
	/**
443
	 * @var string regular expression pattern.
444
	 */
445
	private $_regexp='';
446
 
447
	private $_customUrl=true;
448
 
449
	private $_manager;
450
 
451
	private $_caseSensitive=true;
452
 
453
	private $_isWildCardPattern=false;
454
 
455
	private $_urlFormat=THttpRequestUrlFormat::Get;
456
 
457
	private $_separator='/';
458
 
459
	/**
460
	 * Constructor.
461
	 * @param TUrlManager the URL manager instance
462
	 */
463
	public function __construct(TUrlManager $manager)
464
	{
465
		$this->_manager=$manager;
466
		$this->_parameters=new TAttributeCollection;
467
		$this->_parameters->setCaseSensitive(true);
468
	}
469
 
470
	/**
471
	 * @return TUrlManager the URL manager instance
472
	 */
473
	public function getManager()
474
	{
475
		return $this->_manager;
476
	}
477
 
478
	/**
479
	 * Initializes the pattern.
480
	 * @param TXmlElement configuration for this module.
481
	 * @throws TConfigurationException if service parameter is not specified
482
	 */
483
	public function init($config)
484
	{
485
		if($this->_serviceParameter===null)
486
			throw new TConfigurationException('urlmappingpattern_serviceparameter_required', $this->getPattern());
487
		if(strpos($this->_serviceParameter,'*')!==false)
488
		    $this->_isWildCardPattern=true;
489
	}
490
 
491
	/**
492
	 * Substitute the parameter key value pairs as named groupings
493
	 * in the regular expression matching pattern.
494
	 * @return string regular expression pattern with parameter subsitution
495
	 */
496
	protected function getParameterizedPattern()
497
	{
498
		$params=array();
499
		$values=array();
500
		foreach($this->_parameters as $key=>$value)
501
		{
502
			$params[]='{'.$key.'}';
503
			$values[]='(?P<'.$key.'>'.$value.')';
504
		}
505
		if ($this->getIsWildCardPattern()) {
506
		    $params[]='{*}';
507
		    // service parameter must not contain '=' and '/'
508
		    $values[]='(?P<'.$this->getServiceID().'>[^=/]+)';
509
		}
510
		$params[]='/';
511
		$values[]='\\/';
512
		$regexp=str_replace($params,$values,trim($this->getPattern(),'/').'/');
513
		if ($this->_urlFormat===THttpRequestUrlFormat::Get)
514
		    $regexp='/^'.$regexp.'$/u';
515
		else
516
		    $regexp='/^'.$regexp.'(?P<urlparams>.*)$/u';
517
 
518
		if(!$this->getCaseSensitive())
519
			$regexp.='i';
520
		return $regexp;
521
	}
522
 
523
	/**
524
	 * @return string full regular expression mapping pattern
525
	 */
526
	public function getRegularExpression()
527
	{
528
		return $this->_regexp;
529
	}
530
 
531
	/**
532
	 * @param string full regular expression mapping pattern.
533
	 */
534
	public function setRegularExpression($value)
535
	{
536
		$this->_regexp=$value;
537
	}
538
 
539
	/**
540
	 * @return boolean whether the {@link getPattern Pattern} should be treated as case sensititve. Defaults to true.
541
	 */
542
	public function getCaseSensitive()
543
	{
544
		return $this->_caseSensitive;
545
	}
546
 
547
	/**
548
	 * @param boolean whether the {@link getPattern Pattern} should be treated as case sensititve.
549
	 */
550
	public function setCaseSensitive($value)
551
	{
552
		$this->_caseSensitive=TPropertyValue::ensureBoolean($value);
553
	}
554
 
555
	/**
556
	 * @param string service parameter, such as page class name.
557
	 */
558
	public function setServiceParameter($value)
559
	{
560
		$this->_serviceParameter=$value;
561
	}
562
 
563
	/**
564
	 * @return string service parameter, such as page class name.
565
	 */
566
	public function getServiceParameter()
567
	{
568
		return $this->_serviceParameter;
569
	}
570
 
571
	/**
572
	 * @param string service id to handle.
573
	 */
574
	public function setServiceID($value)
575
	{
576
		$this->_serviceID=$value;
577
	}
578
 
579
	/**
580
	 * @return string service id.
581
	 */
582
	public function getServiceID()
583
	{
584
		return $this->_serviceID;
585
	}
586
 
587
	/**
588
	 * @return string url pattern to match. Defaults to ''.
589
	 */
590
	public function getPattern()
591
	{
592
		return $this->_pattern;
593
	}
594
 
595
	/**
596
	 * @param string url pattern to match.
597
	 */
598
	public function setPattern($value)
599
	{
600
		$this->_pattern = $value;
601
	}
602
 
603
	/**
604
	 * @return TAttributeCollection parameter key value pairs.
605
	 */
606
	public function getParameters()
607
	{
608
		return $this->_parameters;
609
	}
610
 
611
	/**
612
	 * @param TAttributeCollection new parameter key value pairs.
613
	 */
614
	public function setParameters($value)
615
	{
616
		$this->_parameters=$value;
617
	}
618
 
619
	/**
620
	 * Uses URL pattern (or full regular expression if available) to
621
	 * match the given url path.
622
	 * @param THttpRequest the request module
623
	 * @return array matched parameters, empty if no matches.
624
	 */
625
	public function getPatternMatches($request)
626
	{
627
		$matches=array();
628
		if(($pattern=$this->getRegularExpression())!=='')
629
			preg_match($pattern,$request->getPathInfo(),$matches);
630
		else
631
			preg_match($this->getParameterizedPattern(),trim($request->getPathInfo(),'/').'/',$matches);
632
 
633
		if (isset($matches['urlparams']))
634
		{
635
			$params=explode('/',$matches['urlparams']);
636
			if ($this->_separator==='/')
637
			{
638
				while($key=array_shift($params))
639
					$matches2[$key]=($value=array_shift($params)) ? $value : '';
640
			}
641
			else
642
			{
643
				array_pop($params);
644
				foreach($params as $param)
645
				{
646
					list($key,$value)=explode($this->_separator,$param,2);
647
					$matches[$key]=$value;
648
				}
649
			}
650
			unset($matches['urlparams']);
651
		}
652
 
653
		return $matches;
654
	}
655
 
656
	/**
657
	 * Returns a value indicating whether to use this pattern to construct URL.
658
	 * @return boolean whether to enable custom constructUrl. Defaults to true.
659
	 * @since 3.1.1
660
	 */
661
	public function getEnableCustomUrl()
662
	{
663
		return $this->_customUrl;
664
	}
665
 
666
	/**
667
	 * Sets a value indicating whether to enable custom constructUrl using this pattern
668
	 * @param boolean whether to enable custom constructUrl.
669
	 */
670
	public function setEnableCustomUrl($value)
671
	{
672
		$this->_customUrl=TPropertyValue::ensureBoolean($value);
673
	}
674
 
675
	/**
676
	 * @return boolean whether this pattern is a wildcard pattern
677
	 * @since 3.1.4
678
	 */
679
	public function getIsWildCardPattern() {
680
		return $this->_isWildCardPattern;
681
	}
682
 
683
	/**
684
	 * @return THttpRequestUrlFormat the format of URLs. Defaults to THttpRequestUrlFormat::Get.
685
	 */
686
	public function getUrlFormat()
687
	{
688
		return $this->_urlFormat;
689
	}
690
 
691
	/**
692
	 * Sets the format of URLs constructed and interpreted by this pattern.
693
	 * A Get URL format is like index.php?name1=value1&name2=value2
694
	 * while a Path URL format is like index.php/name1/value1/name2/value.
695
	 * The separating character between name and value can be configured with
696
	 * {@link setUrlParamSeparator} and defaults to '/'.
697
	 * Changing the UrlFormat will affect {@link constructUrl} and how GET variables
698
	 * are parsed.
699
	 * @param THttpRequestUrlFormat the format of URLs.
700
	 * @param since 3.1.4
701
	 */
702
	public function setUrlFormat($value)
703
	{
704
		$this->_urlFormat=TPropertyValue::ensureEnum($value,'THttpRequestUrlFormat');
705
	}
706
 
707
	/**
708
	 * @return string separator used to separate GET variable name and value when URL format is Path. Defaults to slash '/'.
709
	 */
710
	public function getUrlParamSeparator()
711
	{
712
		return $this->_separator;
713
	}
714
 
715
	/**
716
	 * @param string separator used to separate GET variable name and value when URL format is Path.
717
	 * @throws TInvalidDataValueException if the separator is not a single character
718
	 */
719
	public function setUrlParamSeparator($value)
720
	{
721
		if(strlen($value)===1)
722
			$this->_separator=$value;
723
		else
724
			throw new TInvalidDataValueException('httprequest_separator_invalid');
725
	}
726
 
727
	/**
728
	 * @param array list of GET items to be put in the constructed URL
729
	 * @return boolean whether this pattern IS the one for constructing the URL with the specified GET items.
730
	 * @since 3.1.1
731
	 */
732
	public function supportCustomUrl($getItems)
733
	{
734
		if(!$this->_customUrl || $this->getPattern()===null)
735
			return false;
736
		foreach($this->_parameters as $key=>$value)
737
		{
738
			if(!isset($getItems[$key]))
739
				return false;
740
		}
741
		return true;
742
	}
743
 
744
	/**
745
	 * Constructs a URL using this pattern.
746
	 * @param array list of GET variables
747
	 * @param boolean whether the ampersand should be encoded in the constructed URL
748
	 * @param boolean whether the GET variables should be encoded in the constructed URL
749
	 * @return string the constructed URL
750
	 * @since 3.1.1
751
	 */
752
	public function constructUrl($getItems,$encodeAmpersand,$encodeGetItems)
753
	{
754
		$extra=array();
755
		$replace=array();
756
		// for the GET variables matching the pattern, put them in the URL path
757
		foreach($getItems as $key=>$value)
758
		{
759
			if($this->_parameters->contains($key) || $key==='*' && $this->getIsWildCardPattern())
760
				$replace['{'.$key.'}']=$encodeGetItems ? rawurlencode($value) : $value;
761
			else
762
				$extra[$key]=$value;
763
		}
764
 
765
		$url=$this->_manager->getUrlPrefix().'/'.ltrim(strtr($this->getPattern(),$replace),'/');
766
 
767
		// for the rest of the GET variables, put them in the query string
768
		if(count($extra)>0)
769
		{
770
			if ($this->_urlFormat===THttpRequestUrlFormat::Path && $this->getIsWildCardPattern()) {
771
				foreach ($extra as $name=>$value)
772
					$url.='/'.$name.$this->_separator.($encodeGetItems?rawurlencode($value):$value);
773
				return $url;
774
			}
775
 
776
			$url2='';
777
			$amp=$encodeAmpersand?'&amp;':'&';
778
			if($encodeGetItems)
779
			{
780
				foreach($extra as $name=>$value)
781
				{
782
					if(is_array($value))
783
					{
784
						$name=rawurlencode($name.'[]');
785
						foreach($value as $v)
786
							$url2.=$amp.$name.'='.rawurlencode($v);
787
					}
788
					else
789
						$url2.=$amp.rawurlencode($name).'='.rawurlencode($value);
790
				}
791
			}
792
			else
793
			{
794
				foreach($extra as $name=>$value)
795
				{
796
					if(is_array($value))
797
					{
798
						foreach($value as $v)
799
							$url2.=$amp.$name.'[]='.$v;
800
					}
801
					else
802
						$url2.=$amp.$name.'='.$value;
803
				}
804
			}
805
			$url=$url.'?'.substr($url2,strlen($amp));
806
		}
807
		return $url;
808
	}
809
}
810