summaryrefslogtreecommitdiff
path: root/framework/Web/TUrlMapping.php
blob: 929a873e09afd2489595e5a184119d365773474d (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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
<?php
/**
 * TUrlMapping, TUrlMappingPattern and TUrlMappingPatternSecureConnection class file.
 *
 * @author Wei Zhuo <weizhuo[at]gamil[dot]com>
 * @link http://www.pradosoft.com/
 * @copyright Copyright &copy; 2005-2013 PradoSoft
 * @license http://www.pradosoft.com/license/
 * @version $Id: TUrlMapping.php 3290 2013-05-06 08:32:15Z ctrlaltca $
 * @package System.Web
 */

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

/**
 * TUrlMapping Class
 *
 * The TUrlMapping module allows PRADO to construct and recognize URLs
 * based on specific patterns.
 *
 * TUrlMapping consists of a list of URL patterns which are used to match
 * against the currently requested URL. The first matching pattern will then
 * be used to decompose the URL into request parameters (accessible through
 * <code>$this->Request['paramname']</code>).
 *
 * The patterns can also be used to construct customized URLs. In this case,
 * the parameters in an applied pattern will be replaced with the corresponding
 * GET variable values.
 *
 * Since it is derived from {@link TUrlManager}, it should be configured globally
 * in the application configuration like the following,
 * <code>
 *  <module id="request" class="THttpRequest" UrlManager="friendly-url" />
 *  <module id="friendly-url" class="System.Web.TUrlMapping" EnableCustomUrl="true">
 *    <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>
 * </code>
 *
 * In the above, each <tt>&lt;url&gt;</tt> element specifies a URL pattern represented
 * as a {@link TUrlMappingPattern} internally. You may create your own pattern classes
 * by extending {@link TUrlMappingPattern} and specifying the <tt>&lt;class&gt;</tt> attribute
 * in the element.
 *
 * The patterns can be also be specified in an external file using the {@link setConfigFile ConfigFile} 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.
 *
 * Only the PATH_INFO part of the URL is used to match the available patterns. The matching
 * is strict in the sense that the whole pattern must match the whole PATH_INFO of the URL.
 *
 * From PRADO v3.1.1, TUrlMapping also provides support for constructing URLs according to
 * the specified pattern. You may enable this functionality by setting {@link setEnableCustomUrl EnableCustomUrl} to true.
 * When you call THttpRequest::constructUrl() (or via TPageService::constructUrl()),
 * TUrlMapping will examine the available URL mapping patterns using their {@link TUrlMappingPattern::getServiceParameter ServiceParameter}
 * and {@link TUrlMappingPattern::getPattern Pattern} properties. A pattern is applied if its
 * {@link TUrlMappingPattern::getServiceParameter ServiceParameter} matches the service parameter passed
 * to constructUrl() and every parameter in the {@link getPattern Pattern} is found
 * in the GET variables.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @version $Id: TUrlMapping.php 3290 2013-05-06 08:32:15Z ctrlaltca $
 * @package System.Web
 * @since 3.0.5
 */
class TUrlMapping extends TUrlManager
{
	/**
	 * @var TUrlMappingPattern[] list of patterns.
	 */
	protected $_patterns=array();
	/**
	 * @var TUrlMappingPattern matched pattern.
	 */
	private $_matched;
	/**
	 * @var string external configuration file
	 */
	private $_configFile=null;
	/**
	 * @var boolean whether to enable custom contructUrl
	 */
	private $_customUrl=false;
	/**
	 * @var array rules for constructing URLs
	 */
	protected $_constructRules=array();

	private $_urlPrefix='';

	private $_defaultMappingClass='TUrlMappingPattern';

	/**
	 * Initializes this module.
	 * This method is required by the IModule interface.
	 * @param mixed configuration for this module, can be null
	 * @throws TConfigurationException if module is configured in the global scope.
	 */
	public function init($config)
	{
		parent::init($config);
		if($this->getRequest()->getRequestResolved())
			throw new TConfigurationException('urlmapping_global_required');
		if($this->_configFile!==null)
			$this->loadConfigFile();
		$this->loadUrlMappings($config);
		if($this->_urlPrefix==='')
		{
			$request=$this->getRequest();
			if($request->getUrlFormat()===THttpRequestUrlFormat::HiddenPath)
			{
				$this->_urlPrefix=dirname($request->getApplicationUrl());
			} else {
				$this->_urlPrefix=$request->getApplicationUrl();
			}
		}
		$this->_urlPrefix=rtrim($this->_urlPrefix,'/');
	}

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

	/**
	 * Returns a value indicating whether to enable custom constructUrl.
	 * If true, constructUrl() will make use of the URL mapping rules to
	 * construct valid URLs.
	 * @return boolean whether to enable custom constructUrl. Defaults to false.
	 * @since 3.1.1
	 */
	public function getEnableCustomUrl()
	{
		return $this->_customUrl;
	}

	/**
	 * Sets a value indicating whether to enable custom constructUrl.
	 * If true, constructUrl() will make use of the URL mapping rules to
	 * construct valid URLs.
	 * @param boolean whether to enable custom constructUrl.
	 * @since 3.1.1
	 */
	public function setEnableCustomUrl($value)
	{
		$this->_customUrl=TPropertyValue::ensureBoolean($value);
	}

	/**
	 * @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)
	 * @since 3.1.1
	 */
	public function getUrlPrefix()
	{
		return $this->_urlPrefix;
	}

	/**
	 * @param string the part that will be prefixed to the constructed URLs. This is used by constructUrl() when EnableCustomUrl is set true.
	 * @see getUrlPrefix
	 * @since 3.1.1
	 */
	public function setUrlPrefix($value)
	{
		$this->_urlPrefix=$value;
	}

	/**
	 * @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,$this->getApplication()->getConfigurationFileExt()))===null)
			throw new TConfigurationException('urlmapping_configfile_invalid',$value);
	}

	/**
	 * @return string the default class of URL mapping patterns. Defaults to TUrlMappingPattern.
	 * @since 3.1.1
	 */
	public function getDefaultMappingClass()
	{
		return $this->_defaultMappingClass;
	}

	/**
	 * Sets the default class of URL mapping patterns.
	 * When a URL matching pattern does not specify "class" attribute, it will default to the class
	 * 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.)
	 * @param string the default class of URL mapping patterns.
	 * @since 3.1.1
	 */
	public function setDefaultMappingClass($value)
	{
		$this->_defaultMappingClass=$value;
	}

	/**
	 * Load and configure each url mapping pattern.
	 * @param mixed configuration node
	 * @throws TConfigurationException if specific pattern class is invalid
	 */
	protected function loadUrlMappings($config)
	{
		$defaultClass = $this->getDefaultMappingClass();

		if(is_array($config))
		{
			if(isset($config['urls']) && is_array($config['urls']))
			{
				foreach($config['urls'] as $url)
				{
					$class=null;
					if(!isset($url['class']))
						$class=$defaultClass;
					$properties = isset($url['properties'])?$url['properties']:array();
					$this->buildUrlMapping($class,$properties,$url);
				}
			}
		}
		else
		{
			foreach($config->getElementsByTagName('url') as $url)
			{
				$properties=$url->getAttributes();
				if(($class=$properties->remove('class'))===null)
					$class=$defaultClass;
				$this->buildUrlMapping($class,$properties,$url);
			}
		}
	}

	private function buildUrlMapping($class, $properties, $url)
	{
		$pattern=Prado::createComponent($class,$this);
		if(!($pattern instanceof TUrlMappingPattern))
			throw new TConfigurationException('urlmapping_urlmappingpattern_required');
		foreach($properties as $name=>$value)
			$pattern->setSubproperty($name,$value);

		if($url instanceof TXmlElement) {
			$text = $url -> getValue();
			if($text) {
				$text = preg_replace('/(\s+)/S', '', $text);
				if(($regExp = $pattern->getRegularExpression()) !== '')
				trigger_error(sPrintF('%s.RegularExpression property value "%s" for ServiceID="%s" and ServiceParameter="%s" was replaced by node value "%s"',
				get_class($pattern),
				$regExp,
				$pattern->getServiceID(),
				$pattern->getServiceParameter(),
				$text),
				E_USER_NOTICE);
				$pattern->setRegularExpression($text);
			}
		}

		$this->_patterns[]=$pattern;
		$pattern->init($url);

		$key=$pattern->getServiceID().':'.$pattern->getServiceParameter();
		$this->_constructRules[$key][]=$pattern;
	}

	/**
	 * 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()
	{
		$request=$this->getRequest();
		foreach($this->_patterns as $pattern)
		{
			$matches=$pattern->getPatternMatches($request);
			if(count($matches)>0)
			{
				$this->_matched=$pattern;
				$params=array();
				foreach($matches as $key=>$value)
				{
					if(is_string($key))
						$params[$key]=$value;
				}
				if (!$pattern->getIsWildCardPattern())
					$params[$pattern->getServiceID()]=$pattern->getServiceParameter();
				return $params;
			}
		}
		return parent::parseUrl();
	}

	/**
	 * Constructs a URL that can be recognized by PRADO.
	 *
	 * This method provides the actual implementation used by {@link THttpRequest::constructUrl}.
	 * Override this method if you want to provide your own way of URL formatting.
	 * If you do so, you may also need to override {@link parseUrl} so that the URL can be properly parsed.
	 *
	 * The URL is constructed as the following format:
	 * /entryscript.php?serviceID=serviceParameter&get1=value1&...
	 * If {@link THttpRequest::setUrlFormat THttpRequest.UrlFormat} is 'Path',
	 * the following format is used instead:
	 * /entryscript.php/serviceID/serviceParameter/get1,value1/get2,value2...
	 * If {@link THttpRequest::setUrlFormat THttpRequest.UrlFormat} is 'HiddenPath',
	 * the following format is used instead:
	 * /serviceID/serviceParameter/get1,value1/get2,value2...
	 * @param string service ID
	 * @param string service parameter
	 * @param array GET parameters, null if not provided
	 * @param boolean whether to encode the ampersand in URL
	 * @param boolean whether to encode the GET parameters (their names and values)
	 * @return string URL
	 * @see parseUrl
	 * @since 3.1.1
	 */
	public function constructUrl($serviceID,$serviceParam,$getItems,$encodeAmpersand,$encodeGetItems)
	{
		if($this->_customUrl)
		{
			if(!(is_array($getItems) || ($getItems instanceof Traversable)))
				$getItems=array();
			$key=$serviceID.':'.$serviceParam;
			$wildCardKey = ($pos=strrpos($serviceParam,'.'))!==false ?
				$serviceID.':'.substr($serviceParam,0,$pos).'.*' : $serviceID.':*';
			if(isset($this->_constructRules[$key]))
			{
				foreach($this->_constructRules[$key] as $rule)
				{
					if($rule->supportCustomUrl($getItems))
						return $rule->constructUrl($getItems,$encodeAmpersand,$encodeGetItems);
				}
			}
			elseif(isset($this->_constructRules[$wildCardKey]))
			{
				foreach($this->_constructRules[$wildCardKey] as $rule)
				{
					if($rule->supportCustomUrl($getItems))
					{
						$getItems['*']= $pos ? substr($serviceParam,$pos+1) : $serviceParam;
						return $rule->constructUrl($getItems,$encodeAmpersand,$encodeGetItems);
					}
				}
			}
		}
		return parent::constructUrl($serviceID,$serviceParam,$getItems,$encodeAmpersand,$encodeGetItems);
	}

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

/**
 * TUrlMappingPattern class.
 *
 * TUrlMappingPattern represents a pattern used to parse and construct URLs.
 * If the currently requested URL matches the pattern, it will alter
 * the THttpRequest parameters. If a constructUrl() call matches the pattern
 * parameters, the pattern will generate a valid URL. In both case, only the PATH_INFO
 * part of a URL is parsed/constructed using the pattern.
 *
 * To specify the pattern, set the {@link setPattern Pattern} property.
 * {@link setPattern Pattern} takes a string expression with
 * parameter names enclosed between a left brace '{' and a right brace '}'.
 * The patterns 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.
 *
 * For more complicated patterns, one may specify the pattern using a regular expression
 * by {@link setRegularExpression RegularExpression}. For example, the above pattern
 * is equivalent to the following regular expression-based 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.
 * If you intended to use the <tt>RegularExpression</tt> property or
 * regular expressions in CDATA sections, notice that you need to escape the slash,
 * if you are using the slash as regular expressions delimiter.
 *
 * Thus, only an url that matches the pattern will be valid. For example,
 * a URL <tt>http://example.com/index.php/articles/2006/07/21</tt> will match the above pattern,
 * while <tt>http://example.com/index.php/articles/2006/07/hello</tt> will not
 * since the "day" parameter pattern is not satisfied.
 *
 * The parameter values are available through the <tt>THttpRequest</tt> instance (e.g.
 * <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.
 *
 * Since 3.1.4 you can also use simplyfied wildcard patterns to match multiple
 * ServiceParameters with a single rule. The pattern must contain the placeholder
 * {*} for the ServiceParameter. For example
 *
 * <url ServiceParameter="adminpages.*" pattern="admin/{*}" />
 *
 * This rule will match an URL like <tt>http://example.com/index.php/admin/edituser</tt>
 * and resolve it to the page Application.pages.admin.edituser. The wildcard matching
 * is non-recursive. That means you have to add a rule for every subdirectory you
 * want to access pages in:
 *
 * <url ServiceParameter="adminpages.users.*" pattern="useradmin/{*}" />
 *
 * It is still possible to define an explicit rule for a page in the wildcard path.
 * This rule has to preceed the wildcard rule.
 *
 * You can also use parameters with wildcard patterns. The parameters are then
 * available with every matching page:
 *
 * <url ServiceParameter="adminpages.*" pattern="admin/{*}/{id}" parameters.id="\d+" />
 *
 * To enable automatic parameter encoding in a path format from wildcard patterns you can set
 * {@setUrlFormat UrlFormat} to 'Path':
 *
 * <url ServiceParameter="adminpages.*" pattern="admin/{*}" UrlFormat="Path" />
 *
 * This will create and parse URLs of the form
 * <tt>.../index.php/admin/listuser/param1/value1/param2/value2</tt>.
 *
 * Use {@setUrlParamSeparator} to define another separator character between parameter
 * name and value. Parameter/value pairs are always separated by a '/'.
 *
 * <url ServiceParameter="adminpages.*" pattern="admin/{*}" UrlFormat="Path" UrlParamSeparator="-" />
 *
 * <tt>.../index.php/admin/listuser/param1-value1/param2-value2</tt>.
 *
 * Since 3.2.2 you can also add a list of "constants" parameters that can be used just
 * like the original "parameters" parameters, except that the supplied value will be treated
 * as a simple string constant instead of a regular expression. For example
 * 
 * <url ServiceParameter="MyPage" pattern="/mypage/mypath/list/detail/{pageidx}" parameters.pageidx="\d+" constants.listtype="detailed"/>
 * <url ServiceParameter="MyPage" pattern="/mypage/mypath/list/summary/{pageidx}" parameters.pageidx="\d+" constants.listtype="summarized"/>
 *
 * These rules, when matched by the actual request, will make the application see a "lisstype" parameter present
 * (even through not supplied in the request) and equal to "detailed" or "summarized", depending on the friendly url matched.
 * The constants is practically a table-based validation and translation of specified, fixed-set parameter values.
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @version $Id: TUrlMapping.php 3290 2013-05-06 08:32:15Z ctrlaltca $
 * @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 TAttributeCollection parameter regular expressions.
	 */
	private $_parameters;
	/**
	 * @var TAttributeCollection of constant parameters.
	 */
	protected $_constants;
	/**
	 * @var string regular expression pattern.
	 */
	private $_regexp='';

	private $_customUrl=true;

	private $_manager;

	private $_caseSensitive=true;

	private $_isWildCardPattern=false;

	private $_urlFormat=THttpRequestUrlFormat::Get;

	private $_separator='/';

	/**
	 * @var TUrlMappingPatternSecureConnection
	 * @since 3.2
	 */
	private $_secureConnection = TUrlMappingPatternSecureConnection::Automatic;

	/**
	 * Constructor.
	 * @param TUrlManager the URL manager instance
	 */
	public function __construct(TUrlManager $manager)
	{
		$this->_manager=$manager;
	}

	/**
	 * @return TUrlManager the URL manager instance
	 */
	public function getManager()
	{
		return $this->_manager;
	}

	/**
	 * Initializes the pattern.
	 * @param TXmlElement configuration for this module.
	 * @throws TConfigurationException if service parameter is not specified
	 */
	public function init($config)
	{
		if($this->_serviceParameter===null)
			throw new TConfigurationException('urlmappingpattern_serviceparameter_required', $this->getPattern());
		if(strpos($this->_serviceParameter,'*')!==false)
				$this->_isWildCardPattern=true;
	}

	/**
	 * Substitute 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();
		if ($this->_parameters)
		{
			foreach($this->_parameters as $key=>$value)
			{
				$params[]='{'.$key.'}';
				$values[]='(?P<'.$key.'>'.$value.')';
			}
		}
		if ($this->getIsWildCardPattern())
		{
				$params[]='{*}';
				// service parameter must not contain '=' and '/'
				$values[]='(?P<'.$this->getServiceID().'>[^=/]+)';
		}
		$params[]='/';
		$values[]='\\/';
		$regexp=str_replace($params,$values,trim($this->getPattern(),'/').'/');
		if ($this->_urlFormat===THttpRequestUrlFormat::Get)
				$regexp='/^'.$regexp.'$/u';
		else
				$regexp='/^'.$regexp.'(?P<urlparams>.*)$/u';

		if(!$this->getCaseSensitive())
			$regexp.='i';
		return $regexp;
	}

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

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

	/**
	 * @return boolean whether the {@link getPattern Pattern} should be treated as case sensititve. Defaults to true.
	 */
	public function getCaseSensitive()
	{
		return $this->_caseSensitive;
	}

	/**
	 * @param boolean whether the {@link getPattern Pattern} should be treated as case sensititve.
	 */
	public function setCaseSensitive($value)
	{
		$this->_caseSensitive=TPropertyValue::ensureBoolean($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. Defaults to ''.
	 */
	public function getPattern()
	{
		return $this->_pattern;
	}

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

	/**
	 * @return TAttributeCollection parameter key value pairs.
	 */
	public function getParameters()
	{
		if (!$this->_parameters)
		{
			$this->_parameters=new TAttributeCollection;
			$this->_parameters->setCaseSensitive(true);
		}
		return $this->_parameters;
	}

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

	/**
	 * @return TAttributeCollection constanst parameter key value pairs.
	 * @since 3.2.2
	 */
	public function getConstants()
	{
		if (!$this->_constants)
		{
			$this->_constants = new TAttributeCollection;
			$this->_constants->setCaseSensitive(true);
		}
		return $this->_constants;
	}

	/**
	 * Uses URL pattern (or full regular expression if available) to
	 * match the given url path.
	 * @param THttpRequest the request module
	 * @return array matched parameters, empty if no matches.
	 */
	public function getPatternMatches($request)
	{
		$matches=array();
		if(($pattern=$this->getRegularExpression())!=='')
			preg_match($pattern,$request->getPathInfo(),$matches);
		else
			preg_match($this->getParameterizedPattern(),trim($request->getPathInfo(),'/').'/',$matches);

		if($this->getIsWildCardPattern() && isset($matches[$this->_serviceID]))
			$matches[$this->_serviceID]=str_replace('*',$matches[$this->_serviceID],$this->_serviceParameter);

		if (isset($matches['urlparams']))
		{
			$params=explode('/',$matches['urlparams']);
			if ($this->_separator==='/')
			{
				while($key=array_shift($params))
					$matches[$key]=($value=array_shift($params)) ? $value : '';
			}
			else
			{
				array_pop($params);
				foreach($params as $param)
				{
					list($key,$value)=explode($this->_separator,$param,2);
					$matches[$key]=$value;
				}
			}
			unset($matches['urlparams']);
		}

		if(count($matches) > 0 && $this->_constants)
		{
			foreach($this->_constants->toArray() as $key=>$value)
				$matches[$key] = $value;
		}

		return $matches;
	}

	/**
	 * Returns a value indicating whether to use this pattern to construct URL.
	 * @return boolean whether to enable custom constructUrl. Defaults to true.
	 * @since 3.1.1
	 */
	public function getEnableCustomUrl()
	{
		return $this->_customUrl;
	}

	/**
	 * Sets a value indicating whether to enable custom constructUrl using this pattern
	 * @param boolean whether to enable custom constructUrl.
	 */
	public function setEnableCustomUrl($value)
	{
		$this->_customUrl=TPropertyValue::ensureBoolean($value);
	}

	/**
	 * @return boolean whether this pattern is a wildcard pattern
	 * @since 3.1.4
	 */
	public function getIsWildCardPattern() {
		return $this->_isWildCardPattern;
	}

	/**
	 * @return THttpRequestUrlFormat the format of URLs. Defaults to THttpRequestUrlFormat::Get.
	 */
	public function getUrlFormat()
	{
		return $this->_urlFormat;
	}

	/**
	 * Sets the format of URLs constructed and interpreted by this pattern.
	 * A Get URL format is like index.php?name1=value1&name2=value2
	 * while a Path URL format is like index.php/name1/value1/name2/value.
	 * The separating character between name and value can be configured with
	 * {@link setUrlParamSeparator} and defaults to '/'.
	 * Changing the UrlFormat will affect {@link constructUrl} and how GET variables
	 * are parsed.
	 * @param THttpRequestUrlFormat the format of URLs.
	 * @since 3.1.4
	 */
	public function setUrlFormat($value)
	{
		$this->_urlFormat=TPropertyValue::ensureEnum($value,'THttpRequestUrlFormat');
	}

	/**
	 * @return string separator used to separate GET variable name and value when URL format is Path. Defaults to slash '/'.
	 */
	public function getUrlParamSeparator()
	{
		return $this->_separator;
	}

	/**
	 * @param string separator used to separate GET variable name and value when URL format is Path.
	 * @throws TInvalidDataValueException if the separator is not a single character
	 */
	public function setUrlParamSeparator($value)
	{
		if(strlen($value)===1)
			$this->_separator=$value;
		else
			throw new TInvalidDataValueException('httprequest_separator_invalid');
	}

	/**
	 * @return TUrlMappingPatternSecureConnection the SecureConnection behavior. Defaults to {@link TUrlMappingPatternSecureConnection::Automatic Automatic}
	 * @since 3.2
	 */
	public function getSecureConnection()
	{
		return $this->_secureConnection;
	}

	/**
	 * @param TUrlMappingPatternSecureConnection the SecureConnection behavior.
	 * @since 3.2
	 */
	public function setSecureConnection($value)
	{
		$this->_secureConnection = TPropertyValue::ensureEnum($value, 'TUrlMappingPatternSecureConnection');
	}

	/**
	 * @param array list of GET items to be put in the constructed URL
	 * @return boolean whether this pattern IS the one for constructing the URL with the specified GET items.
	 * @since 3.1.1
	 */
	public function supportCustomUrl($getItems)
	{
		if(!$this->_customUrl || $this->getPattern()===null)
			return false;
		if ($this->_parameters)
		{
			foreach($this->_parameters as $key=>$value)
			{
				if(!isset($getItems[$key]))
					return false;
			}
		}

		if ($this->_constants)
		{
			foreach($this->_constants->toArray() as $key=>$value)
			{
				if (!isset($getItems[$key]))
					return false;
				if ($getItems[$key]!=$value)
					return false;
			}
		}
		return true;
	}

	/**
	 * Constructs a URL using this pattern.
	 * @param array list of GET variables
	 * @param boolean whether the ampersand should be encoded in the constructed URL
	 * @param boolean whether the GET variables should be encoded in the constructed URL
	 * @return string the constructed URL
	 * @since 3.1.1
	 */
	public function constructUrl($getItems,$encodeAmpersand,$encodeGetItems)
	{
		if ($this->_constants)
		{
			foreach($this->_constants->toArray() as $key=>$value)
			{
				unset($getItems[$key]);
			}
		}

		$extra=array();
		$replace=array();
		// for the GET variables matching the pattern, put them in the URL path
		foreach($getItems as $key=>$value)
		{
			if(($this->_parameters && $this->_parameters->contains($key)) || ($key==='*' && $this->getIsWildCardPattern()))
				$replace['{'.$key.'}']=$encodeGetItems ? rawurlencode($value) : $value;
			else
				$extra[$key]=$value;
		}

		$url=$this->_manager->getUrlPrefix().'/'.ltrim(strtr($this->getPattern(),$replace),'/');

		// for the rest of the GET variables, put them in the query string
		if(count($extra)>0)
		{
			if ($this->_urlFormat===THttpRequestUrlFormat::Path && $this->getIsWildCardPattern()) {
				foreach ($extra as $name=>$value)
					$url.='/'.$name.$this->_separator.($encodeGetItems?rawurlencode($value):$value);
				return $url;
			}

			$url2='';
			$amp=$encodeAmpersand?'&amp;':'&';
			if($encodeGetItems)
			{
				foreach($extra as $name=>$value)
				{
					if(is_array($value))
					{
						$name=rawurlencode($name.'[]');
						foreach($value as $v)
							$url2.=$amp.$name.'='.rawurlencode($v);
					}
					else
						$url2.=$amp.rawurlencode($name).'='.rawurlencode($value);
				}
			}
			else
			{
				foreach($extra as $name=>$value)
				{
					if(is_array($value))
					{
						foreach($value as $v)
							$url2.=$amp.$name.'[]='.$v;
					}
					else
						$url2.=$amp.$name.'='.$value;
				}
			}
			$url=$url.'?'.substr($url2,strlen($amp));
		}
		return $this -> applySecureConnectionPrefix($url);
	}

	/**
	 * Apply behavior of {@link SecureConnection} property by conditionaly prefixing
	 * URL with {@link THttpRequest::getBaseUrl()}
	 *
	 * @param string $url
	 * @return string
	 * @since 3.2
	 */
	protected function applySecureConnectionPrefix($url)
	{
		static $request;
		if($request === null) $request = Prado::getApplication() -> getRequest();

		static $isSecureConnection;
		if($isSecureConnection === null) $isSecureConnection = $request -> getIsSecureConnection();

		switch($this -> getSecureConnection())
		{
			case TUrlMappingPatternSecureConnection::EnableIfNotSecure:
				if($isSecureConnection) return $url;
				return $request -> getBaseUrl(true) . $url;
			break;
			case TUrlMappingPatternSecureConnection::DisableIfSecure:
				if(!$isSecureConnection) return $url;
				return $request -> getBaseUrl(false) . $url;
			break;
			case TUrlMappingPatternSecureConnection::Enable:
				return $request -> getBaseUrl(true) . $url;
			break;
			case TUrlMappingPatternSecureConnection::Disable:
				return $request -> getBaseUrl(false) . $url;
			break;
			case TUrlMappingPatternSecureConnection::Automatic:
			default:
				return $url;
			break;
		}
	}
}

/**
 * TUrlMappingPatternSecureConnection class
 *
 * TUrlMappingPatternSecureConnection defines the enumerable type for the possible SecureConnection
 * URL prefix behavior that can be used by {@link TUrlMappingPattern::constructUrl()}.
 *
 * @author Yves Berkholz <godzilla80[at]gmx[dot]net>
 * @version $Id: TUrlMapping.php 3290 2013-05-06 08:32:15Z ctrlaltca $
 * @package System.Web
 * @since 3.2
 */
class TUrlMappingPatternSecureConnection extends TEnumerable
{
	/**
	 * Keep current SecureConnection status
	 * means no prefixing
	 */
	const Automatic = 'Automatic';

	/**
	 * Force use secured connection
	 * always prefixing with https://example.com/path/to/app
	 */
	const Enable = 'Enable';

	/**
	 * Force use unsecured connection
	 * always prefixing with http://example.com/path/to/app
	 */
	const Disable = 'Disable';

	/**
	 * Force use secured connection, if in unsecured mode
	 * prefixing with https://example.com/path/to/app
	 */
	const EnableIfNotSecure = 'EnableIfNotSecure';

	/**
	 * Force use unsecured connection, if in secured mode
	 * prefixing with https://example.com/path/to/app
	 */
	const DisableIfSecure = 'DisableIfSecure';
}