summaryrefslogtreecommitdiff
path: root/framework/Web/Services/TPageService.php
blob: 43f5a3fd04ee6cfb570747368a780e8e1a7cb0bf (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
<?php
/**
 * TPageService class file.
 *
 * @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
 */

/**
 * Include classes to be used by page service
 */
Prado::using('System.Web.UI.TPage');
Prado::using('System.Web.UI.TTemplateManager');
Prado::using('System.Web.UI.TThemeManager');

/**
 * TPageService class.
 *
 * TPageService implements the service for serving user page requests.
 *
 * Pages that are available to client users are stored under a directory specified by
 * {@link setBasePath BasePath}. The directory may contain subdirectories.
 * Pages serving for a similar goal are usually placed under the same directory.
 * A directory may contain a configuration file <b>config.xml</b> whose content
 * is similar to that of application configuration file.
 *
 * A page is requested via page path, which is a dot-connected directory names
 * appended by the page name. Assume '<BasePath>/Users/Admin' is the directory
 * containing the page 'Update'. Then the page can be requested via 'Users.Admin.Update'.
 * By default, the {@link setBasePath BasePath} of the page service is the "pages"
 * directory under the application base path. You may change this default
 * by setting {@link setBasePath BasePath} with a different path you prefer.
 *
 * Page name refers to the file name (without extension) of the page template.
 * In order to differentiate from the common control template files, the extension
 * name of the page template files must be '.page'. If there is a PHP file with
 * the same page name under the same directory as the template file, that file
 * will be considered as the page class file and the file name is the page class name.
 * If such a file is not found, the page class is assumed as {@link TPage}.
 *
 * Modules can be configured and loaded in page directory configurations.
 * Configuration of a module in a subdirectory will overwrite its parent
 * directory's configuration, if both configurations refer to the same module.
 *
 * By default, TPageService will automatically load two modules:
 * - {@link TTemplateManager} : manages page and control templates
 * - {@link TThemeManager} : manages themes used in a Prado application
 *
 * In page directory configurations, static authorization rules can also be specified,
 * which governs who and which roles can access particular pages.
 * Refer to {@link TAuthorizationRule} for more details about authorization rules.
 * Page authorization rules can be configured within an <authorization> tag in
 * each page directory configuration as follows,
 * <authorization>
 *   <deny pages="Update" users="?" />
 *   <allow pages="Admin" roles="administrator" />
 *   <deny pages="Admin" users="*" />
 * </authorization>
 * where the 'pages' attribute may be filled with a sequence of comma-separated
 * page IDs. If 'pages' attribute does not appear in a rule, the rule will be
 * applied to all pages in this directory and all subdirectories (recursively).
 * Application of authorization rules are in a bottom-up fashion, starting from
 * the directory containing the requested page up to all parent directories.
 * The first matching rule will be used. The last rule always allows all users
 * accessing to any resources.
 *
 * The TPageService replicates the {@link TPage} events through {@link IPageEvents}.
 * When the TPage is run, the TPageService events attach to all the corresponding TPage 
 * events.  This allows modules to handle page events.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Carl G. Mathisen <carlgmathisen@gmail.com>
 * @author Brad Anderson <javalizard@gmail.com>
 * @version $Id$
 * @package System.Web.Services
 * @since 3.0
 */
class TPageService extends TService implements IPageEvents
{
	/**
	 * Configuration file name
	 */
	const CONFIG_FILE_XML='config.xml';
	/**
	 * Configuration file name
	 */
	const CONFIG_FILE_PHP='config.php';
	/**
	 * Default base path
	 */
	const DEFAULT_BASEPATH='pages';
	/**
	 * Prefix of ID used for storing parsed configuration in cache
	 */
	const CONFIG_CACHE_PREFIX='prado:pageservice:';
	/**
	 * Page template file extension
	 */
	const PAGE_FILE_EXT='.page';
	/**
	 * @var string root path of pages
	 */
	private $_basePath=null;
	/**
	 * @var string base path class in namespace format
	 */
	private $_basePageClass='TPage';
	/**
	 * @var string clientscript manager class in namespace format
	 * @since 3.1.7
	 */
	private $_clientScriptManagerClass='System.Web.UI.TClientScriptManager';
	/**
	 * @var string default page
	 */
	private $_defaultPage='Home';
	/**
	 * @var string requested page (path)
	 */
	private $_pagePath=null;
	/**
	 * @var TPage the requested page
	 */
	private $_page=null;
	/**
	 * @var array list of initial page property values
	 */
	private $_properties=array();
	/**
	 * @var boolean whether service is initialized
	 */
	private $_initialized=false;
	/**
	 * @var TThemeManager theme manager
	 */
	private $_themeManager=null;
	/**
	 * @var TTemplateManager template manager
	 */
	private $_templateManager=null;
	/**
	 * @var TPage is set when traversing the event onNoPage
	 */
	private $_foundpage = false;
	/**
	 * @var boolean if the onNoPage event is specifically blocked
	 */
	private $_blockOnNoPage = false;
	
	/**
	 * Initializes the service.
	 * This method is required by IService interface and is invoked by application.
	 * @param TXmlElement service configuration
	 */
	public function init($config)
	{
		Prado::trace("Initializing TPageService",'System.Web.Services.TPageService');

		$pageConfig=$this->loadPageConfig($config);

		$this->initPageContext($pageConfig);

		$this->_initialized=true;
	}

	/**
	 * Initializes page context.
	 * Page context includes path alias settings, namespace usages,
	 * parameter initialization, module loadings, page initial properties
	 * and authorization rules.
	 * @param TPageConfiguration
	 */
	protected function initPageContext($pageConfig)
	{
		$application=$this->getApplication();
		foreach($pageConfig->getApplicationConfigurations() as $appConfig)
			$application->applyConfiguration($appConfig);

		$this->applyConfiguration($pageConfig);
	}

	/**
	 * Applies a page configuration.
	 * @param TPageConfiguration the configuration
	 */
	protected function applyConfiguration($config)
	{
		// initial page properties (to be set when page runs)
		$this->_properties=array_merge($this->_properties, $config->getProperties());
		$this->getApplication()->getAuthorizationRules()->mergeWith($config->getRules());
		$pagePath=$this->getRequestedPagePath();
		// external configurations
		foreach($config->getExternalConfigurations() as $filePath=>$params)
		{
			list($configPagePath,$condition)=$params;
			if($condition!==true)
				$condition=$this->evaluateExpression($condition);
			if($condition)
			{
				if(($path=Prado::getPathOfNamespace($filePath,Prado::getApplication()->getConfigurationFileExt()))===null || !is_file($path))
					throw new TConfigurationException('pageservice_includefile_invalid',$filePath);
				$c=new TPageConfiguration($pagePath);
				$c->loadFromFile($path,$configPagePath);
				$this->applyConfiguration($c);
			}
		}

	}

	/**
	 * Determines the requested page path.
	 * @return string page path requested
	 */
	protected function determineRequestedPagePath()
	{
		$pagePath=$this->getRequest()->getServiceParameter();
		if(empty($pagePath))
			$pagePath=$this->getDefaultPage();
		return $pagePath;
	}

	/**
	 * Collects configuration for a page.
	 * @param TXmlElement additional configuration specified in the application configuration
	 * @return TPageConfiguration
	 */
	protected function loadPageConfig($config)
	{
		$application=$this->getApplication();
		$pagePath=$this->getRequestedPagePath();
		if(($cache=$application->getCache())===null)
		{
			$pageConfig=new TPageConfiguration($pagePath);
			if($config!==null)
			{
				if($application->getConfigurationType()==TApplication::CONFIG_TYPE_PHP)
					$pageConfig->loadPageConfigurationFromPhp($config,$application->getBasePath(),'');
				else
					$pageConfig->loadPageConfigurationFromXml($config,$application->getBasePath(),'');
			}
			$pageConfig->loadFromFiles($this->getBasePath());
		}
		else
		{
			$configCached=true;
			$currentTimestamp=array();
			$arr=$cache->get(self::CONFIG_CACHE_PREFIX.$this->getID().$pagePath);
			if(is_array($arr))
			{
				list($pageConfig,$timestamps)=$arr;
				if($application->getMode()!==TApplicationMode::Performance)
				{
					foreach($timestamps as $fileName=>$timestamp)
					{
						if($fileName===0) // application config file
						{
							$appConfigFile=$application->getConfigurationFile();
							$currentTimestamp[0]=$appConfigFile===null?0:@filemtime($appConfigFile);
							if($currentTimestamp[0]>$timestamp || ($timestamp>0 && !$currentTimestamp[0]))
								$configCached=false;
						}
						else
						{
							$currentTimestamp[$fileName]=@filemtime($fileName);
							if($currentTimestamp[$fileName]>$timestamp || ($timestamp>0 && !$currentTimestamp[$fileName]))
								$configCached=false;
						}
					}
				}
			}
			else
			{
				$configCached=false;
				$paths=explode('.',$pagePath);
				$configPath=$this->getBasePath();
				$fileName = $this->getApplication()->getConfigurationType()==TApplication::CONFIG_TYPE_PHP
					? self::CONFIG_FILE_PHP
					: self::CONFIG_FILE_XML;
				foreach($paths as $path)
				{
					$configFile=$configPath.DIRECTORY_SEPARATOR.$fileName;
					$currentTimestamp[$configFile]=@filemtime($configFile);
					$configPath.=DIRECTORY_SEPARATOR.$path;
				}
				$appConfigFile=$application->getConfigurationFile();
				$currentTimestamp[0]=$appConfigFile===null?0:@filemtime($appConfigFile);
			}
			if(!$configCached)
			{
				$pageConfig=new TPageConfiguration($pagePath);
				if($config!==null)
				{
					if($application->getConfigurationType()==TApplication::CONFIG_TYPE_PHP)
						$pageConfig->loadPageConfigurationFromPhp($config,$application->getBasePath(),'');
					else
						$pageConfig->loadPageConfigurationFromXml($config,$application->getBasePath(),'');
				}
				$pageConfig->loadFromFiles($this->getBasePath());
				$cache->set(self::CONFIG_CACHE_PREFIX.$this->getID().$pagePath,array($pageConfig,$currentTimestamp));
			}
		}
		return $pageConfig;
	}

	/**
	 * @return TTemplateManager template manager
	 */
	public function getTemplateManager()
	{
		if(!$this->_templateManager)
		{
			$this->_templateManager=new TTemplateManager;
			$this->_templateManager->init(null);
		}
		return $this->_templateManager;
	}

	/**
	 * @param TTemplateManager template manager
	 */
	public function setTemplateManager(TTemplateManager $value)
	{
		$this->_templateManager=$value;
	}

	/**
	 * @return TThemeManager theme manager
	 */
	public function getThemeManager()
	{
		if(!$this->_themeManager)
		{
			$this->_themeManager=new TThemeManager;
			$this->_themeManager->init(null);
		}
		return $this->_themeManager;
	}

	/**
	 * @param TThemeManager theme manager
	 */
	public function setThemeManager(TThemeManager $value)
	{
		$this->_themeManager=$value;
	}

	/**
	 * @return string the requested page path
	 */
	public function getRequestedPagePath()
	{
		if($this->_pagePath===null)
		{
			$this->_pagePath=strtr($this->determineRequestedPagePath(),'/\\','..');
			if(empty($this->_pagePath))
				throw new THttpException(404,'pageservice_page_required');
		}
		return $this->_pagePath;
	}

	/**
	 * @return TPage the requested page
	 */
	public function getRequestedPage()
	{
		return $this->_page;
	}

	/**
	 * @return string default page path to be served if no explicit page is request. Defaults to 'Home'.
	 */
	public function getDefaultPage()
	{
		return $this->_defaultPage;
	}

	/**
	 * @param string default page path to be served if no explicit page is request
	 * @throws TInvalidOperationException if the page service is initialized
	 */
	public function setDefaultPage($value)
	{
		if($this->_initialized)
			throw new TInvalidOperationException('pageservice_defaultpage_unchangeable');
		else
			$this->_defaultPage=$value;
	}

	/**
	 * @return string the URL for the default page
	 */
	public function getDefaultPageUrl()
	{
		return $this->constructUrl($this->getDefaultPage());
	}
	
	/**
	 *	This event is triggered when a 404 in the normal page tree hierarchy is not found
	 */
	public function onNoPage($sender, $param) {
	}
	
	
	/**
	 * @return TPage This is used by the other modules to provide their pages.  If they find one on an onNoPage event this is where it goes
	 */
	public function getFoundPage() { return $this->_foundpage; }
	
	/**
	 * This is set when a module finds a suitable page, this is set with that found page
	 * @param TPage the page to display
	 */
	public function setFoundPage($v) { $this->_foundpage = $v; }
	
	/**
	 * @return TPage This is used by the other modules to provide their pages.  If they find one on an onNoPage event this is where it goes
	 */
	public function getBlockOnNoPageEvent() { return $this->_blockOnNoPage; }
	
	/**
	 * This is set when a module finds a suitable page, this is set with that found page
	 * @param TPage the page to display
	 */
	public function setBlockOnNoPageEvent($v) { $this->_blockOnNoPage = TPropertyValue::ensureBoolean($v); }

	/**
	 * @return string the root directory for storing pages. Defaults to the 'pages' directory under the application base path.
	 */
	public function getBasePath()
	{
		if($this->_basePath===null)
		{
			$basePath=$this->getApplication()->getBasePath().DIRECTORY_SEPARATOR.self::DEFAULT_BASEPATH;
			if(($this->_basePath=realpath($basePath))===false || !is_dir($this->_basePath))
				throw new TConfigurationException('pageservice_basepath_invalid',$basePath);
		}
		return $this->_basePath;
	}

	/**
	 * @param string root directory (in namespace form) storing pages
	 * @throws TInvalidOperationException if the service is initialized already or basepath is invalid
	 */
	public function setBasePath($value)
	{
		if($this->_initialized)
			throw new TInvalidOperationException('pageservice_basepath_unchangeable');
		else if(($path=Prado::getPathOfNamespace($value))===null || !is_dir($path))
			throw new TConfigurationException('pageservice_basepath_invalid',$value);
		$this->_basePath=realpath($path);
	}

	/**
	 * Sets the base page class name (in namespace format).
	 * If a page only has a template file without page class file,
	 * this base page class will be instantiated.
	 * @param string class name
	 */
	public function setBasePageClass($value)
	{
		$this->_basePageClass=$value;
	}

	/**
	 * @return string base page class name in namespace format. Defaults to 'TPage'.
	 */
	public function getBasePageClass()
	{
		return $this->_basePageClass;
	}

	/**
	 * Sets the clientscript manager class (in namespace format).
	 * @param string class name
	 * @since 3.1.7
	 */
	public function setClientScriptManagerClass($value)
	{
		$this->_clientScriptManagerClass=$value;
	}

	/**
	 * @return string clientscript manager class in namespace format. Defaults to 'System.Web.UI.TClientScriptManager'.
	 * @since 3.1.7
	 */
	public function getClientScriptManagerClass()
	{
		return $this->_clientScriptManagerClass;
	}

	/**
	 * Runs the service.
	 * This will create the requested page, initializes it with the property values
	 * specified in the configuration, and executes the page.
	 */
	public function run()
	{
		Prado::trace("Running page service",'System.Web.Services.TPageService');
		$this->_page=$this->createPage($this->getRequestedPagePath());
		$this->runPage($this->_page,$this->_properties);
	}

	/**
	 * Creates a page instance based on requested page path.
	 * @param string requested page path
	 * @return TPage the requested page instance
	 * @throws THttpException if requested page path is invalid
	 * @throws TConfigurationException if the page class cannot be found
	 */
	protected function createPage($pagePath, $doError = null)
	{
		$path=$this->getBasePath().DIRECTORY_SEPARATOR.strtr($pagePath,'.',DIRECTORY_SEPARATOR);
		$hasTemplateFile=is_file($path.self::PAGE_FILE_EXT);
		$hasClassFile=is_file($path.Prado::CLASS_FILE_EXT);

		if(!$hasTemplateFile && !$hasClassFile && ($doError || $doError === null)) {
			if(!$this->BlockOnNoPageEvent)
				$this->raiseEvent('onNoPage', $this, $pagePath);
			if(!$this->FoundPage)
				throw new THttpException(404,'pageservice_page_unknown',$pagePath);
			return $this->FoundPage;
		}

		if($hasClassFile)
		{
			$className=basename($path);
			if(!class_exists($className,false))
				include_once($path.Prado::CLASS_FILE_EXT);
		}
		else
		{
			$className=$this->getBasePageClass();
			Prado::using($className);
			if(($pos=strrpos($className,'.'))!==false)
				$className=substr($className,$pos+1);
		}

 		if(!class_exists($className,false) || ($className!=='TPage' && !is_subclass_of($className,'TPage')))
			throw new THttpException(404,'pageservice_page_unknown',$pagePath);

		$page=new $className;
		$page->setPagePath($pagePath);

		if($hasTemplateFile)
			$page->setTemplate($this->getTemplateManager()->getTemplateByFileName($path.self::PAGE_FILE_EXT));

		return $page;
	}

	/**
	 * Executes a page.
	 * @param TPage the page instance to be run
	 * @param array list of initial page properties
	 */
	protected function runPage($page,$properties)
	{
		foreach($properties as $name=>$value)
			$page->setSubProperty($name,$value);
		
		$page->OnDataBinding[] = array($this, 'OnDataBinding');
		$page->OnPreInit[] = array($this, 'OnPreInit');
		$page->OnInit[] = array($this, 'OnInit');
		$page->OnInitComplete[] = array($this, 'OnInitComplete');
		$page->OnPreLoad[] = array($this, 'OnPreLoad');
		$page->OnLoad[] = array($this, 'OnLoad');
		$page->OnLoadComplete[] = array($this, 'OnLoadComplete');
		$page->OnPreRender[] = array($this, 'OnPreRender');
		$page->OnPreRenderComplete[] = array($this, 'OnPreRenderComplete');
		$page->OnSaveStateComplete[] = array($this, 'OnSaveStateComplete');
		$page->OnUnload[] = array($this, 'OnUnload');
		
		$page->run($this->getResponse()->createHtmlWriter());
	}

	/**
	 * Constructs a URL with specified page path and GET parameters.
	 * @param string page path
	 * @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($pagePath,$getParams=null,$encodeAmpersand=true,$encodeGetItems=true)
	{
		return $this->getRequest()->constructUrl($this->getID(),$pagePath,$getParams,$encodeAmpersand,$encodeGetItems);
	}
	
	
	/**
	 * Raises 'OnDataBinding' event. (inherited from TControl)
	 */
	public function onDataBinding($param) {
		Prado::trace("onDataBinding",'System.Web.Services.TPageService');
		$this->raiseEvent('OnDataBinding',$this,$param);
	}
	/**
	 * This method is invoked when the control enters 'OnInit' stage. (inherited from TControl)
	 */
	public function onInit($param) {
		Prado::trace("onInit",'System.Web.Services.TPageService');
		$this->raiseEvent('OnInit',$this,$param);
	}
	/**
	 * Raises OnInitComplete event.
	 */
	public function onInitComplete($param) {
		Prado::trace("onInitComplete",'System.Web.Services.TPageService');
		$this->raiseEvent('OnInitComplete',$this,$param);
	}
	/**
	 * This method is invoked when the control enters 'OnLoad' stage. (inherited from TControl)
	 */
	public function onLoad($param) {
		Prado::trace("OnLoad",'System.Web.Services.TPageService');
		$this->raiseEvent('OnLoad',$this,$param);
	}
	/**
	 * Raises OnLoadComplete event.
	 */
	public function onLoadComplete($param) {
		Prado::trace("OnLoadComplete",'System.Web.Services.TPageService');
		$this->raiseEvent('OnLoadComplete',$this,$param);
	}
	/**
	 * Raises OnPreInit event.
	 */
	public function onPreInit($param) {
		Prado::trace("OnPreInit",'System.Web.Services.TPageService');
		$this->raiseEvent('OnPreInit',$this,$param);
	}
	/**
	 * Raises OnPreLoad event.
	 */
	public function onPreLoad($param) {
		Prado::trace("OnPreLoad",'System.Web.Services.TPageService');
		$this->raiseEvent('OnPreLoad',$this,$param);
	}
	/**
	 * This method is invoked when the control enters 'OnPreRender' stage. (inherited from TControl)
	 */
	public function onPreRender($param) {
		Prado::trace("OnPreRender",'System.Web.Services.TPageService');
		$this->raiseEvent('OnPreRender',$this,$param);
	}
	/**
	 * Raises OnPreRenderComplete event.
	 */
	public function onPreRenderComplete($param) {
		Prado::trace("OnPreRenderComplete",'System.Web.Services.TPageService');
		$this->raiseEvent('OnPreRenderComplete',$this,$param);
	}
	/**
	 * Raises OnSaveStateComplete event.
	 */
	public function onSaveStateComplete($param) {
		Prado::trace("OnSaveStateComplete",'System.Web.Services.TPageService');
		$this->raiseEvent('OnSaveStateComplete',$this,$param);
	}
	/**
	 * This method is invoked when the control enters 'OnUnload' stage. (inherited from TControl)
	 */
	public function onUnload($param) {
		Prado::trace("OnUnload",'System.Web.Services.TPageService');
		$this->raiseEvent('OnUnload',$this,$param);
	}
	
	
}


/**
 * TPageConfiguration class
 *
 * TPageConfiguration represents the configuration for a page.
 * The page is specified by a dot-connected path.
 * Configurations along this path are merged together to be provided for the page.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @version $Id$
 * @package System.Web.Services
 * @since 3.0
 */
class TPageConfiguration extends TComponent
{
	/**
	 * @var array list of application configurations
	 */
	private $_appConfigs=array();
	/**
	 * @var array list of page initial property values
	 */
	private $_properties=array();
	/**
	 * @var TAuthorizationRuleCollection list of authorization rules
	 */
	private $_rules=array();
	/**
	 * @var array list of included configurations
	 */
	private $_includes=array();
	/**
	 * @var string the currently request page in the format of Path.To.PageName
	 */
	private $_pagePath='';

	/**
	 * Constructor.
	 * @param string the currently request page in the format of Path.To.PageName
	 */
	public function __construct($pagePath)
	{
		$this->_pagePath=$pagePath;
	}

	/**
	 * @return array list of external configuration files. Each element is like $filePath=>$condition
	 */
	public function getExternalConfigurations()
	{
		return $this->_includes;
	}

	/**
	 * Returns list of page initial property values.
	 * Each array element represents a single property with the key
	 * being the property name and the value the initial property value.
	 * @return array list of page initial property values
	 */
	public function getProperties()
	{
		return $this->_properties;
	}

	/**
	 * Returns list of authorization rules.
	 * The authorization rules are aggregated (bottom-up) from configuration files
	 * along the path to the specified page.
	 * @return TAuthorizationRuleCollection collection of authorization rules
	 */
	public function getRules()
	{
		return $this->_rules;
	}

	/**
	 * @return array list of application configurations specified along page path
	 */
	public function getApplicationConfigurations()
	{
		return $this->_appConfigs;
	}

	/**
	 * Loads configuration for a page specified in a path format.
	 * @param string root path for pages
	 */
	public function loadFromFiles($basePath)
	{
		$paths=explode('.',$this->_pagePath);
		$page=array_pop($paths);
		$path=$basePath;
		$configPagePath='';
		$fileName = Prado::getApplication()->getConfigurationType()==TApplication::CONFIG_TYPE_PHP
			? TPageService::CONFIG_FILE_PHP
			: TPageService::CONFIG_FILE_XML;
		foreach($paths as $p)
		{
			$this->loadFromFile($path.DIRECTORY_SEPARATOR.$fileName,$configPagePath);
			$path.=DIRECTORY_SEPARATOR.$p;
			if($configPagePath==='')
				$configPagePath=$p;
			else
				$configPagePath.='.'.$p;
		}
		$this->loadFromFile($path.DIRECTORY_SEPARATOR.$fileName,$configPagePath);
		$this->_rules=new TAuthorizationRuleCollection($this->_rules);
	}

	/**
	 * Loads a specific config file.
	 * @param string config file name
	 * @param string the page path that the config file is associated with. The page path doesn't include the page name.
	 */
	public function loadFromFile($fname,$configPagePath)
	{
		Prado::trace("Loading page configuration file $fname",'System.Web.Services.TPageService');
		if(empty($fname) || !is_file($fname))
			return;
		
		if(Prado::getApplication()->getConfigurationType()==TApplication::CONFIG_TYPE_PHP)
		{
			$fcontent = include $fname;
			$this->loadFromPhp($fcontent,dirname($fname),$configPagePath);
		}
		else
		{	
			$dom=new TXmlDocument;
			if($dom->loadFromFile($fname))
				$this->loadFromXml($dom,dirname($fname),$configPagePath);
			else
				throw new TConfigurationException('pageserviceconf_file_invalid',$fname);
		}
	}

	public function loadFromPhp($config,$configPath,$configPagePath)
	{
		$this->loadApplicationConfigurationFromPhp($config,$configPath);
		$this->loadPageConfigurationFromPhp($config,$configPath,$configPagePath);
	}

	/**
	 * Loads a page configuration.
	 * The configuration includes information for both application
	 * and page service.
	 * @param TXmlElement config xml element
	 * @param string the directory containing this configuration
	 * @param string the page path that the config XML is associated with. The page path doesn't include the page name.
	 */
	public function loadFromXml($dom,$configPath,$configPagePath)
	{
		$this->loadApplicationConfigurationFromXml($dom,$configPath);
		$this->loadPageConfigurationFromXml($dom,$configPath,$configPagePath);
	}
	
	public function loadApplicationConfigurationFromPhp($config,$configPath)
	{
		$appConfig=new TApplicationConfiguration;
		$appConfig->loadFromPhp($config,$configPath);
		$this->_appConfigs[]=$appConfig;
	}

	/**
	 * Loads the configuration specific for application part
	 * @param TXmlElement config xml element
	 * @param string base path corresponding to this xml element
	 */
	public function loadApplicationConfigurationFromXml($dom,$configPath)
	{
		$appConfig=new TApplicationConfiguration;
		$appConfig->loadFromXml($dom,$configPath);
		$this->_appConfigs[]=$appConfig;
	}

	public function loadPageConfigurationFromPhp($config, $configPath, $configPagePath)
	{
		// authorization
		if(isset($config['authorization']) && is_array($config['authorization']))
		{
			$rules = array();
			foreach($config['authorization'] as $authorization)
			{
				$patterns=isset($authorization['pages'])?$authorization['pages']:'';
				$ruleApplies=false;
				if(empty($patterns) || trim($patterns)==='*') // null or empty string
					$ruleApplies=true;
				else
				{
					foreach(explode(',',$patterns) as $pattern)
					{
						if(($pattern=trim($pattern))!=='')
						{
							// we know $configPagePath and $this->_pagePath
							if($configPagePath!=='')  // prepend the pattern with ConfigPagePath
								$pattern=$configPagePath.'.'.$pattern;
							if(strcasecmp($pattern,$this->_pagePath)===0)
							{
								$ruleApplies=true;
								break;
							}
							if($pattern[strlen($pattern)-1]==='*') // try wildcard matching
							{
								if(strncasecmp($this->_pagePath,$pattern,strlen($pattern)-1)===0)
								{
									$ruleApplies=true;
									break;
								}
							}
						}
					}
				}
				if($ruleApplies)
				{
					$action = isset($authorization['action'])?$authorization['action']:'';
					$users = isset($authorization['users'])?$authorization['users']:'';
					$roles = isset($authorization['roles'])?$authorization['roles']:'';
					$verb = isset($authorization['verb'])?$authorization['verb']:'';
					$ips = isset($authorization['ips'])?$authorization['ips']:'';
					$rules[]=new TAuthorizationRule($action,$users,$roles,$verb,$ips);
				}
			}
			$this->_rules=array_merge($rules,$this->_rules);
		}
		// pages
		if(isset($config['pages']) && is_array($config['pages']))
		{
			if(isset($config['pages']['properties']))
			{
				$this->_properties = array_merge($this->_properties, $config['pages']['properties']);
				unset($config['pages']['properties']);
			}
			foreach($config['pages'] as $id => $page)
			{
				$properties = array();
				if(isset($page['properties']))
				{
					$properties=$page['properties'];
					unset($page['properties']);	
				}
				$matching=false;
				$id=($configPagePath==='')?$id:$configPagePath.'.'.$id;
				if(strcasecmp($id,$this->_pagePath)===0)
					$matching=true;
				else if($id[strlen($id)-1]==='*') // try wildcard matching
					$matching=strncasecmp($this->_pagePath,$id,strlen($id)-1)===0;
				if($matching)
					$this->_properties=array_merge($this->_properties,$properties);
			}
		}
		
		// external configurations
		if(isset($config['includes']) && is_array($config['includes']))
		{
			foreach($config['includes'] as $include)
			{
				$when = isset($include['when'])?true:false;
				if(!isset($include['file']))
					throw new TConfigurationException('pageserviceconf_includefile_required');
				$filePath = $include['file'];
				if(isset($this->_includes[$filePath]))
					$this->_includes[$filePath]=array($configPagePath,'('.$this->_includes[$filePath][1].') || ('.$when.')');
				else
					$this->_includes[$filePath]=array($configPagePath,$when);
			}
		}
	}

	/**
	 * Loads the configuration specific for page service.
	 * @param TXmlElement config xml element
	 * @param string base path corresponding to this xml element
	 * @param string the page path that the config XML is associated with. The page path doesn't include the page name.
	 */
	public function loadPageConfigurationFromXml($dom,$configPath,$configPagePath)
	{
		// authorization
		if(($authorizationNode=$dom->getElementByTagName('authorization'))!==null)
		{
			$rules=array();
			foreach($authorizationNode->getElements() as $node)
			{
				$patterns=$node->getAttribute('pages');
				$ruleApplies=false;
				if(empty($patterns) || trim($patterns)==='*') // null or empty string
					$ruleApplies=true;
				else
				{
					foreach(explode(',',$patterns) as $pattern)
					{
						if(($pattern=trim($pattern))!=='')
						{
							// we know $configPagePath and $this->_pagePath
							if($configPagePath!=='')  // prepend the pattern with ConfigPagePath
								$pattern=$configPagePath.'.'.$pattern;
							if(strcasecmp($pattern,$this->_pagePath)===0)
							{
								$ruleApplies=true;
								break;
							}
							if($pattern[strlen($pattern)-1]==='*') // try wildcard matching
							{
								if(strncasecmp($this->_pagePath,$pattern,strlen($pattern)-1)===0)
								{
									$ruleApplies=true;
									break;
								}
							}
						}
					}
				}
				if($ruleApplies)
					$rules[]=new TAuthorizationRule($node->getTagName(),$node->getAttribute('users'),$node->getAttribute('roles'),$node->getAttribute('verb'),$node->getAttribute('ips'));
			}
			$this->_rules=array_merge($rules,$this->_rules);
		}

		// pages
		if(($pagesNode=$dom->getElementByTagName('pages'))!==null)
		{
			$this->_properties=array_merge($this->_properties,$pagesNode->getAttributes()->toArray());
			// at the page folder
			foreach($pagesNode->getElementsByTagName('page') as $node)
			{
				$properties=$node->getAttributes();
				$id=$properties->remove('id');
				if(empty($id))
					throw new TConfigurationException('pageserviceconf_page_invalid',$configPath);
				$matching=false;
				$id=($configPagePath==='')?$id:$configPagePath.'.'.$id;
				if(strcasecmp($id,$this->_pagePath)===0)
					$matching=true;
				else if($id[strlen($id)-1]==='*') // try wildcard matching
					$matching=strncasecmp($this->_pagePath,$id,strlen($id)-1)===0;
				if($matching)
					$this->_properties=array_merge($this->_properties,$properties->toArray());
			}
		}

		// external configurations
		foreach($dom->getElementsByTagName('include') as $node)
		{
			if(($when=$node->getAttribute('when'))===null)
				$when=true;
			if(($filePath=$node->getAttribute('file'))===null)
				throw new TConfigurationException('pageserviceconf_includefile_required');
			if(isset($this->_includes[$filePath]))
				$this->_includes[$filePath]=array($configPagePath,'('.$this->_includes[$filePath][1].') || ('.$when.')');
			else
				$this->_includes[$filePath]=array($configPagePath,$when);
		}
	}
}