summaryrefslogtreecommitdiff
path: root/framework/Web/UI/TPage.php
blob: 412d14b6c18c73b348b824ebad0bdf4796a0a1de (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
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
<?php
/**
 * TPage class file
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @link http://www.pradosoft.com/
 * @copyright Copyright &copy; 2005-2014 PradoSoft
 * @license http://www.pradosoft.com/license/
 * @package System.Web.UI
 */

Prado::using('System.Web.UI.WebControls.*');
Prado::using('System.Web.UI.TControl');
Prado::using('System.Web.UI.WebControls.TWebControl');
Prado::using('System.Web.UI.TCompositeControl');
Prado::using('System.Web.UI.TTemplateControl');
Prado::using('System.Web.UI.TForm');
Prado::using('System.Web.UI.TClientScriptManager');

/**
 * TPage class
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @package System.Web.UI
 * @since 3.0
 */
class TPage extends TTemplateControl
{
	/**
	 * system post fields
	 */
	const FIELD_POSTBACK_TARGET='PRADO_POSTBACK_TARGET';
	const FIELD_POSTBACK_PARAMETER='PRADO_POSTBACK_PARAMETER';
	const FIELD_LASTFOCUS='PRADO_LASTFOCUS';
	const FIELD_PAGESTATE='PRADO_PAGESTATE';
	const FIELD_CALLBACK_TARGET='PRADO_CALLBACK_TARGET';
	const FIELD_CALLBACK_PARAMETER='PRADO_CALLBACK_PARAMETER';

	/**
	 * @var array system post fields
	 */
	private static $_systemPostFields=array(
		'PRADO_POSTBACK_TARGET'=>true,
		'PRADO_POSTBACK_PARAMETER'=>true,
		'PRADO_LASTFOCUS'=>true,
		'PRADO_PAGESTATE'=>true,
		'PRADO_CALLBACK_TARGET'=>true,
		'PRADO_CALLBACK_PARAMETER'=>true
	);
	/**
	 * @var TForm form instance
	 */
	private $_form;
	/**
	 * @var THead head instance
	 */
	private $_head;
	/**
	 * @var array list of registered validators
	 */
	private $_validators=array();
	/**
	 * @var boolean if validation has been performed
	 */
	private $_validated=false;
	/**
	 * @var TTheme page theme
	 */
	private $_theme;
	/**
	 * @var string page title set when Head is not in page yet
	 */
	private $_title;
	/**
	 * @var TTheme page stylesheet theme
	 */
	private $_styleSheet;
	/**
	 * @var TClientScriptManager client script manager
	 */
	private $_clientScript;
	/**
	 * @var TMap data post back by user
	 */
	protected $_postData;
	/**
	 * @var TMap postback data that is not handled during first invocation of LoadPostData.
	 */
	protected $_restPostData;
	/**
	 * @var array list of controls whose data have been changed due to the postback
	 */
	protected $_controlsPostDataChanged=array();
	/**
	 * @var array list of controls that need to load post data in the current request
	 */
	protected $_controlsRequiringPostData=array();
	/**
	 * @var array list of controls that need to load post data in the next postback
	 */
	protected $_controlsRegisteredForPostData=array();
	/**
	 * @var TControl control that needs to raise postback event
	 */
	private $_postBackEventTarget;
	/**
	 * @var string postback event parameter
	 */
	private $_postBackEventParameter;
	/**
	 * @var boolean whether the form has been rendered
	 */
	protected $_formRendered=false;
	/**
	 * @var boolean whether the current rendering is within a form
	 */
	protected $_inFormRender=false;
	/**
	 * @var TControl|string the control or the ID of the element on the page to be focused when the page is sent back to user
	 */
	private $_focus;
	/**
	 * @var string page path to this page
	 */
	private $_pagePath='';
	/**
	 * @var boolean whether page state should be HMAC validated
	 */
	private $_enableStateValidation=true;
	/**
	 * @var boolean whether page state should be encrypted
	 */
	private $_enableStateEncryption=false;
	/**
	 * @var boolean whether page state should be compressed
	 * @since 3.1.6
	 */
	private $_enableStateCompression=true;
	/**
	 * @var string page state persister class name
	 */
	private $_statePersisterClass='System.Web.UI.TPageStatePersister';
	/**
	 * @var mixed page state persister
	 */
	private $_statePersister;
	/**
	 * @var TStack stack used to store currently active caching controls
	 */
	private $_cachingStack;
	/**
	 * @var string state string to be stored on the client side
	 */
	private $_clientState='';
	/**
	 * @var array post data loader IDs.
	 */
	protected $_postDataLoaders=array();
	/**
	 * @var boolean true if loading post data.
	 */
	protected $_isLoadingPostData=false;
	/**
	 * @var boolean whether client supports javascript
	 */
	private $_enableJavaScript=true;
	/**
	 * @var THtmlWriter current html render writer
	 */
	private $_writer;

	/**
	 * Constructor.
	 * Sets the page object to itself.
	 * Derived classes must call parent implementation.
	 */
	public function __construct()
	{
		$this->setPage($this);
	}

	/**
	 * Runs through the page lifecycles.
	 * @param THtmlTextWriter the HTML writer
	 */
	public function run($writer)
	{
		Prado::trace("Running page life cycles",'System.Web.UI.TPage');
		$this->_writer = $writer;

		$this->determinePostBackMode();

		if($this->getIsPostBack())
		{
			if($this->getIsCallback())
				$this->processCallbackRequest($writer);
			else
				$this->processPostBackRequest($writer);
		}
		else
			$this->processNormalRequest($writer);

		$this->_writer = null;
	}

	protected function processNormalRequest($writer)
	{
		Prado::trace("Page onPreInit()",'System.Web.UI.TPage');
		$this->onPreInit(null);

		Prado::trace("Page initRecursive()",'System.Web.UI.TPage');
		$this->initRecursive();

		Prado::trace("Page onInitComplete()",'System.Web.UI.TPage');
		$this->onInitComplete(null);

		Prado::trace("Page onPreLoad()",'System.Web.UI.TPage');
		$this->onPreLoad(null);
		Prado::trace("Page loadRecursive()",'System.Web.UI.TPage');
		$this->loadRecursive();
		Prado::trace("Page onLoadComplete()",'System.Web.UI.TPage');
		$this->onLoadComplete(null);

		Prado::trace("Page preRenderRecursive()",'System.Web.UI.TPage');
		$this->preRenderRecursive();
		Prado::trace("Page onPreRenderComplete()",'System.Web.UI.TPage');
		$this->onPreRenderComplete(null);

		Prado::trace("Page savePageState()",'System.Web.UI.TPage');
		$this->savePageState();
		Prado::trace("Page onSaveStateComplete()",'System.Web.UI.TPage');
		$this->onSaveStateComplete(null);

		Prado::trace("Page renderControl()",'System.Web.UI.TPage');
		$this->renderControl($writer);
		Prado::trace("Page unloadRecursive()",'System.Web.UI.TPage');
		$this->unloadRecursive();
	}

	protected function processPostBackRequest($writer)
	{
		Prado::trace("Page onPreInit()",'System.Web.UI.TPage');
		$this->onPreInit(null);

		Prado::trace("Page initRecursive()",'System.Web.UI.TPage');
		$this->initRecursive();

		Prado::trace("Page onInitComplete()",'System.Web.UI.TPage');
		$this->onInitComplete(null);

		$this->_restPostData=new TMap;
		Prado::trace("Page loadPageState()",'System.Web.UI.TPage');
		$this->loadPageState();
		Prado::trace("Page processPostData()",'System.Web.UI.TPage');
		$this->processPostData($this->_postData,true);
		Prado::trace("Page onPreLoad()",'System.Web.UI.TPage');
		$this->onPreLoad(null);
		Prado::trace("Page loadRecursive()",'System.Web.UI.TPage');
		$this->loadRecursive();
		Prado::trace("Page processPostData()",'System.Web.UI.TPage');
		$this->processPostData($this->_restPostData,false);
		Prado::trace("Page raiseChangedEvents()",'System.Web.UI.TPage');
		$this->raiseChangedEvents();
		Prado::trace("Page raisePostBackEvent()",'System.Web.UI.TPage');
		$this->raisePostBackEvent();
		Prado::trace("Page onLoadComplete()",'System.Web.UI.TPage');
		$this->onLoadComplete(null);

		Prado::trace("Page preRenderRecursive()",'System.Web.UI.TPage');
		$this->preRenderRecursive();
		Prado::trace("Page onPreRenderComplete()",'System.Web.UI.TPage');
		$this->onPreRenderComplete(null);

		Prado::trace("Page savePageState()",'System.Web.UI.TPage');
		$this->savePageState();
		Prado::trace("Page onSaveStateComplete()",'System.Web.UI.TPage');
		$this->onSaveStateComplete(null);

		Prado::trace("Page renderControl()",'System.Web.UI.TPage');
		$this->renderControl($writer);
		Prado::trace("Page unloadRecursive()",'System.Web.UI.TPage');
		$this->unloadRecursive();
	}

	protected static function decodeUTF8($data, $enc)
	{
		if(is_array($data))
		{
			foreach($data as $k=>$v)
				$data[$k]=self::decodeUTF8($v, $enc);
			return $data;
		} elseif(is_string($data)) {
			return iconv('UTF-8',$enc.'//IGNORE',$data);
		} else {
			return $data;
		}
	}

	/**
	 * Sets Adapter to TActivePageAdapter and calls apter to process the
	 * callback request.
	 */
	protected function processCallbackRequest($writer)
	{
		Prado::using('System.Web.UI.ActiveControls.TActivePageAdapter');

		$this->setAdapter(new TActivePageAdapter($this));

        $callbackEventParameter = $this->getRequest()->itemAt(TPage::FIELD_CALLBACK_PARAMETER);
        if(strlen($callbackEventParameter) > 0)
            $this->_postData[TPage::FIELD_CALLBACK_PARAMETER]=TJavaScript::jsonDecode((string)$callbackEventParameter);

        // Decode Callback postData from UTF-8 to current Charset
        if (($g=$this->getApplication()->getGlobalization(false))!==null &&
            strtoupper($enc=$g->getCharset())!='UTF-8')
                foreach ($this->_postData as $k=>$v)
                	$this->_postData[$k]=self::decodeUTF8($v, $enc);

		Prado::trace("Page onPreInit()",'System.Web.UI.TPage');
		$this->onPreInit(null);

		Prado::trace("Page initRecursive()",'System.Web.UI.TPage');
		$this->initRecursive();

		Prado::trace("Page onInitComplete()",'System.Web.UI.TPage');
		$this->onInitComplete(null);

		$this->_restPostData=new TMap;
		Prado::trace("Page loadPageState()",'System.Web.UI.TPage');
		$this->loadPageState();
		Prado::trace("Page processPostData()",'System.Web.UI.TPage');
		$this->processPostData($this->_postData,true);
		Prado::trace("Page onPreLoad()",'System.Web.UI.TPage');
		$this->onPreLoad(null);
		Prado::trace("Page loadRecursive()",'System.Web.UI.TPage');
		$this->loadRecursive();

		Prado::trace("Page processPostData()",'System.Web.UI.TPage');
		$this->processPostData($this->_restPostData,false);

		Prado::trace("Page raiseChangedEvents()",'System.Web.UI.TPage');
		$this->raiseChangedEvents();


		$this->getAdapter()->processCallbackEvent($writer);

/*
		Prado::trace("Page raisePostBackEvent()",'System.Web.UI.TPage');
		$this->raisePostBackEvent();
*/
		Prado::trace("Page onLoadComplete()",'System.Web.UI.TPage');
		$this->onLoadComplete(null);

		Prado::trace("Page preRenderRecursive()",'System.Web.UI.TPage');
		$this->preRenderRecursive();
		Prado::trace("Page onPreRenderComplete()",'System.Web.UI.TPage');
		$this->onPreRenderComplete(null);

		Prado::trace("Page savePageState()",'System.Web.UI.TPage');
		$this->savePageState();
		Prado::trace("Page onSaveStateComplete()",'System.Web.UI.TPage');
		$this->onSaveStateComplete(null);

/*
		Prado::trace("Page renderControl()",'System.Web.UI.TPage');
		$this->renderControl($writer);
*/
		$this->getAdapter()->renderCallbackResponse($writer);

		Prado::trace("Page unloadRecursive()",'System.Web.UI.TPage');
		$this->unloadRecursive();
	}

	/**
	 * Gets the callback client script handler that allows javascript functions
	 * to be executed during the callback response.
	 * @return TCallbackClientScript interface to client-side javascript code.
	 */
	public function getCallbackClient()
	{
		if($this->getAdapter() !== null)
			return $this->getAdapter()->getCallbackClientHandler();
		else
			return new TCallbackClientScript();
	}

	/**
	 * Set a new callback client handler.
	 * @param TCallbackClientScript new callback client script handler.
	 */
	public function setCallbackClient($client)
	{
		$this->getAdapter()->setCallbackClientHandler($client);
	}

	/**
	 * @return TControl the control responsible for the current callback event,
	 * null if nonexistent
	 */
	public function getCallbackEventTarget()
	{
		return $this->getAdapter()->getCallbackEventTarget();
	}

	/**
	 * Registers a control to raise callback event in the current request.
	 * @param TControl control registered to raise callback event.
	 */
	public function setCallbackEventTarget(TControl $control)
	{
		$this->getAdapter()->setCallbackEventTarget($control);
	}

	/**
	 * Callback parameter is decoded assuming JSON encoding.
	 * @return string callback event parameter
	 */
	public function getCallbackEventParameter()
	{
		return $this->getAdapter()->getCallbackEventParameter();
	}

	/**
	 * @param mixed callback event parameter
	 */
	public function setCallbackEventParameter($value)
	{
		$this->getAdapter()->setCallbackEventParameter($value);
	}

	/**
	 * Register post data loaders for Callback to collect post data.
	 * This method should only be called by framework developers.
	 * @param TControl control that requires post data.
	 * @see TControl::preRenderRecursive();
	 */
	public function registerPostDataLoader($control)
	{
		$id=is_string($control)?$control:$control->getUniqueID();
		$this->_postDataLoaders[$id] = true;
	}

	/**
	 * Get a list of IDs of controls that are enabled and require post data.
	 * @return array list of IDs implementing IPostBackDataHandler
	 */
	public function getPostDataLoaders()
	{
		return array_keys($this->_postDataLoaders);
	}

	/**
	 * @return TForm the form on the page
	 */
	public function getForm()
	{
		return $this->_form;
	}

	/**
	 * Registers a TForm instance to the page.
	 * Note, a page can contain at most one TForm instance.
	 * @param TForm the form on the page
	 * @throws TInvalidOperationException if this method is invoked twice or more.
	 */
	public function setForm(TForm $form)
	{
		if($this->_form===null)
			$this->_form=$form;
		else
			throw new TInvalidOperationException('page_form_duplicated');
	}

	/**
	 * Returns a list of registered validators.
	 * If validation group is specified, only the validators in that group will be returned.
	 * @param string validation group
	 * @return TList registered validators in the requested group. If the group is null, all validators will be returned.
	 */
	public function getValidators($validationGroup=null)
	{
		if(!$this->_validators)
			$this->_validators=new TList;
		if(empty($validationGroup) === true)
			return $this->_validators;
		else
		{
			$list=new TList;
			foreach($this->_validators as $validator)
				if($validator->getValidationGroup()===$validationGroup)
					$list->add($validator);
			return $list;
		}
	}

	/**
	 * Performs input validation.
	 * This method will invoke the registered validators to perform the actual validation.
	 * If validation group is specified, only the validators in that group will be invoked.
	 * @param string validation group. If null, all validators will perform validation.
	 */
	public function validate($validationGroup=null)
	{
		Prado::trace("Page validate()",'System.Web.UI.TPage');
		$this->_validated=true;
		if($this->_validators && $this->_validators->getCount())
		{
			if($validationGroup===null)
			{
				foreach($this->_validators as $validator)
					$validator->validate();
			}
			else
			{
				foreach($this->_validators as $validator)
				{
					if($validator->getValidationGroup()===$validationGroup)
						$validator->validate();
				}
			}
		}
	}

	/**
	 * Returns whether user input is valid or not.
	 * This method must be invoked after {@link validate} is called.
	 * @return boolean whether the user input is valid or not.
	 * @throws TInvalidOperationException if {@link validate} is not invoked yet.
	 */
	public function getIsValid()
	{
		if($this->_validated)
		{
			if($this->_validators && $this->_validators->getCount())
			{
				foreach($this->_validators as $validator)
					if(!$validator->getIsValid())
						return false;
			}
			return true;
		}
		else
			throw new TInvalidOperationException('page_isvalid_unknown');
	}

	/**
	 * @return TTheme the theme used for the page. Defaults to null.
	 */
	public function getTheme()
	{
		if(is_string($this->_theme))
			$this->_theme=$this->getService()->getThemeManager()->getTheme($this->_theme);
		return $this->_theme;
	}

	/**
	 * Sets the theme to be used for the page.
	 * @param string|TTheme the theme name or the theme object to be used for the page.
	 */
	public function setTheme($value)
	{
		$this->_theme=empty($value)?null:$value;
	}


	/**
	 * @return TTheme the stylesheet theme used for the page. Defaults to null.
	 */
	public function getStyleSheetTheme()
	{
		if(is_string($this->_styleSheet))
			$this->_styleSheet=$this->getService()->getThemeManager()->getTheme($this->_styleSheet);
		return $this->_styleSheet;
	}

	/**
	 * Sets the stylesheet theme to be used for the page.
	 * @param string|TTheme the stylesheet theme name or the stylesheet theme object to be used for the page.
	 */
	public function setStyleSheetTheme($value)
	{
		$this->_styleSheet=empty($value)?null:$value;
	}

	/**
	 * Applies a skin in the current theme to a control.
	 * This method should only be used by framework developers.
	 * @param TControl a control to be applied skin with
	 */
	public function applyControlSkin($control)
	{
		if(($theme=$this->getTheme())!==null)
			$theme->applySkin($control);
	}

	/**
	 * Applies a stylesheet skin in the current theme to a control.
	 * This method should only be used by framework developers.
	 * @param TControl a control to be applied stylesheet skin with
	 */
	public function applyControlStyleSheet($control)
	{
		if(($theme=$this->getStyleSheetTheme())!==null)
			$theme->applySkin($control);
	}

	/**
	 * @return TClientScriptManager client script manager
	 */
	public function getClientScript()
	{
		if(!$this->_clientScript) {
			$className = $classPath = $this->getService()->getClientScriptManagerClass();
			Prado::using($className);
			if(($pos=strrpos($className,'.'))!==false)
				$className=substr($className,$pos+1);

 			if(!class_exists($className,false) || ($className!=='TClientScriptManager' && !is_subclass_of($className,'TClientScriptManager')))
				throw new THttpException(404,'page_csmanagerclass_invalid',$classPath);

			$this->_clientScript=new $className($this);
		}
		return $this->_clientScript;
	}

	/**
	 * Raises OnPreInit event.
	 * This method is invoked right before {@link onInit OnInit} stage.
	 * You may override this method to provide additional initialization that
	 * should be done before {@link onInit OnInit} (e.g. setting {@link setTheme Theme} or
	 * {@link setStyleSheetTheme StyleSheetTheme}).
	 * Remember to call the parent implementation to ensure OnPreInit event is raised.
	 * @param mixed event parameter
	 */
	public function onPreInit($param)
	{
		$this->raiseEvent('OnPreInit',$this,$param);
	}

	/**
	 * Raises OnInitComplete event.
	 * This method is invoked right after {@link onInit OnInit} stage and before {@link onLoad OnLoad} stage.
	 * You may override this method to provide additional initialization that
	 * should be done after {@link onInit OnInit}.
	 * Remember to call the parent implementation to ensure OnInitComplete event is raised.
	 * @param mixed event parameter
	 */
	public function onInitComplete($param)
	{
		$this->raiseEvent('OnInitComplete',$this,$param);
	}

	/**
	 * Raises OnPreLoad event.
	 * This method is invoked right before {@link onLoad OnLoad} stage.
	 * You may override this method to provide additional page loading logic that
	 * should be done before {@link onLoad OnLoad}.
	 * Remember to call the parent implementation to ensure OnPreLoad event is raised.
	 * @param mixed event parameter
	 */
	public function onPreLoad($param)
	{
		$this->raiseEvent('OnPreLoad',$this,$param);
	}

	/**
	 * Raises OnLoadComplete event.
	 * This method is invoked right after {@link onLoad OnLoad} stage.
	 * You may override this method to provide additional page loading logic that
	 * should be done after {@link onLoad OnLoad}.
	 * Remember to call the parent implementation to ensure OnLoadComplete event is raised.
	 * @param mixed event parameter
	 */
	public function onLoadComplete($param)
	{
		$this->raiseEvent('OnLoadComplete',$this,$param);
	}

	/**
	 * Raises OnPreRenderComplete event.
	 * This method is invoked right after {@link onPreRender OnPreRender} stage.
	 * You may override this method to provide additional preparation for page rendering
	 * that should be done after {@link onPreRender OnPreRender}.
	 * Remember to call the parent implementation to ensure OnPreRenderComplete event is raised.
	 * @param mixed event parameter
	 */
	public function onPreRenderComplete($param)
	{
		$this->raiseEvent('OnPreRenderComplete',$this,$param);
		$cs=$this->getClientScript();
		$theme=$this->getTheme();
		if($theme instanceof ITheme)
		{
			foreach($theme->getStyleSheetFiles() as $url)
				$cs->registerStyleSheetFile($url,$url,$this->getCssMediaType($url));
			foreach($theme->getJavaScriptFiles() as $url)
				$cs->registerHeadScriptFile($url,$url);
		}
		$styleSheet=$this->getStyleSheetTheme();
		if($styleSheet instanceof ITheme)
		{
			foreach($styleSheet->getStyleSheetFiles() as $url)
				$cs->registerStyleSheetFile($url,$url,$this->getCssMediaType($url));
			foreach($styleSheet->getJavaScriptFiles() as $url)
				$cs->registerHeadScriptFile($url,$url);
		}

		if($cs->getRequiresHead() && $this->getHead()===null)
			throw new TConfigurationException('page_head_required');
	}

	/**
	 * Determines the media type of the CSS file.
	 * The media type is determined according to the following file name pattern:
	 *        xxx.media-type.extension
	 * For example, 'mystyle.print.css' means its media type is 'print'.
	 * @param string CSS URL
	 * @return string media type of the CSS file
	 */
	private function getCssMediaType($url)
	{
		$segs=explode('.',basename($url));
		if(isset($segs[2]))
			return $segs[count($segs)-2];
		else
			return '';
	}

	/**
	 * Raises OnSaveStateComplete event.
	 * This method is invoked right after {@link onSaveState OnSaveState} stage.
	 * You may override this method to provide additional logic after page state is saved.
	 * Remember to call the parent implementation to ensure OnSaveStateComplete event is raised.
	 * @param mixed event parameter
	 */
	public function onSaveStateComplete($param)
	{
		$this->raiseEvent('OnSaveStateComplete',$this,$param);
	}

	/**
	 * Determines whether the current page request is a postback.
	 * Call {@link getIsPostBack} to get the result.
	 */
	private function determinePostBackMode()
	{
		$postData=$this->getRequest();
		if($postData->contains(self::FIELD_PAGESTATE) || $postData->contains(self::FIELD_POSTBACK_TARGET))
			$this->_postData=$postData;
	}

	/**
	 * @return boolean whether the current page request is a postback
	 */
	public function getIsPostBack()
	{
		return $this->_postData!==null;
	}

	/**
	 * @return boolean whether this is a callback request
	 */
	public function getIsCallback()
	{
		return $this->getIsPostBack() && $this->getRequest()->contains(self::FIELD_CALLBACK_TARGET);
	}

	/**
	 * This method is invoked when control state is to be saved.
	 * You can override this method to do last step state saving.
	 * Parent implementation must be invoked.
	 */
	public function saveState()
	{
		parent::saveState();
		$this->setViewState('ControlsRequiringPostBack',$this->_controlsRegisteredForPostData,array());
	}

	/**
	 * This method is invoked right after the control has loaded its state.
	 * You can override this method to initialize data from the control state.
	 * Parent implementation must be invoked.
	 */
	public function loadState()
	{
		parent::loadState();
		$this->_controlsRequiringPostData=$this->getViewState('ControlsRequiringPostBack',array());
	}

	/**
	 * Loads page state from persistent storage.
	 */
	protected function loadPageState()
	{
		Prado::trace("Loading state",'System.Web.UI.TPage');
		$state=$this->getStatePersister()->load();
		$this->loadStateRecursive($state,$this->getEnableViewState());
	}

	/**
	 * Saves page state from persistent storage.
	 */
	protected function savePageState()
	{
		Prado::trace("Saving state",'System.Web.UI.TPage');
		$state=&$this->saveStateRecursive($this->getEnableViewState());
		$this->getStatePersister()->save($state);
	}

	/**
	 * @param string the field name
	 * @return boolean whether the specified field is a system field in postback data
	 */
	protected function isSystemPostField($field)
	{
		return isset(self::$_systemPostFields[$field]);
	}

	/**
	 * Registers a control for loading post data in the next postback.
	 * This method needs to be invoked if the control to load post data
	 * may not have a post variable in some cases. For example, a checkbox,
	 * if not checked, will not have a post value.
	 * @param TControl control registered for loading post data
	 */
	public function registerRequiresPostData($control)
	{
		$id=is_string($control)?$control:$control->getUniqueID();
		$this->_controlsRegisteredForPostData[$id]=true;
		$this->registerPostDataLoader($id);
		$params=func_get_args();
		foreach($this->getCachingStack() as $item)
			$item->registerAction('Page','registerRequiresPostData',array($id));
	}

	/**
	 * @return TControl the control responsible for the current postback event, null if nonexistent
	 */
	public function getPostBackEventTarget()
	{
		if($this->_postBackEventTarget===null && $this->_postData!==null)
		{
			$eventTarget=$this->_postData->itemAt(self::FIELD_POSTBACK_TARGET);
			if(!empty($eventTarget))
				$this->_postBackEventTarget=$this->findControl($eventTarget);
		}
		return $this->_postBackEventTarget;
	}

	/**
	 * Registers a control to raise postback event in the current request.
	 * @param TControl control registered to raise postback event.
	 */
	public function setPostBackEventTarget(TControl $control)
	{
		$this->_postBackEventTarget=$control;
	}

	/**
	 * @return string postback event parameter
	 */
	public function getPostBackEventParameter()
	{
		if($this->_postBackEventParameter===null && $this->_postData!==null)
		{
			if(($this->_postBackEventParameter=$this->_postData->itemAt(self::FIELD_POSTBACK_PARAMETER))===null)
				$this->_postBackEventParameter='';
		}
		return $this->_postBackEventParameter;
	}

	/**
	 * @param string postback event parameter
	 */
	public function setPostBackEventParameter($value)
	{
		$this->_postBackEventParameter=$value;
	}

	/**
	 * Processes post data.
	 * @param TMap post data to be processed
	 * @param boolean whether this method is invoked before {@link onLoad OnLoad}.
	 */
	protected function processPostData($postData,$beforeLoad)
	{
		$this->_isLoadingPostData=true;
		if($beforeLoad)
			$this->_restPostData=new TMap;
		foreach($postData as $key=>$value)
		{
			if($this->isSystemPostField($key))
				continue;
			else if($control=$this->findControl($key))
			{
				if($control instanceof IPostBackDataHandler)
				{
					if($control->loadPostData($key,$postData))
						$this->_controlsPostDataChanged[]=$control;
				}
				else if($control instanceof IPostBackEventHandler &&
					empty($this->_postData[self::FIELD_POSTBACK_TARGET]))
				{
					$this->_postData->add(self::FIELD_POSTBACK_TARGET,$key);  // not calling setPostBackEventTarget() because the control may be removed later
				}
				unset($this->_controlsRequiringPostData[$key]);
			}
			else if($beforeLoad)
				$this->_restPostData->add($key,$value);
		}

		foreach($this->_controlsRequiringPostData as $key=>$value)
		{
			if($control=$this->findControl($key))
			{
				if($control instanceof IPostBackDataHandler)
				{
					if($control->loadPostData($key,$this->_postData))
						$this->_controlsPostDataChanged[]=$control;
				}
				else
					throw new TInvalidDataValueException('page_postbackcontrol_invalid',$key);
				unset($this->_controlsRequiringPostData[$key]);
			}
		}
		$this->_isLoadingPostData=false;
	}

	/**
	 * @return boolean true if loading post data.
	 */
	public function getIsLoadingPostData()
	{
		return $this->_isLoadingPostData;
	}

	/**
	 * Raises OnPostDataChangedEvent for controls whose data have been changed due to the postback.
	 */
	protected function raiseChangedEvents()
	{
		foreach($this->_controlsPostDataChanged as $control)
			$control->raisePostDataChangedEvent();
	}

	/**
	 * Raises PostBack event.
	 */
	protected function raisePostBackEvent()
	{
		if(($postBackHandler=$this->getPostBackEventTarget())===null)
			$this->validate();
		else if($postBackHandler instanceof IPostBackEventHandler)
			$postBackHandler->raisePostBackEvent($this->getPostBackEventParameter());
	}

	/**
	 * @return boolean Whether form rendering is in progress
	 */
	public function getInFormRender()
	{
		return $this->_inFormRender;
	}

	/**
	 * Ensures the control is rendered within a form.
	 * @param TControl the control to be rendered
	 * @throws TConfigurationException if the control is outside of the form
	 */
	public function ensureRenderInForm($control)
	{
		if(!$this->getIsCallback() && !$this->_inFormRender)
			throw new TConfigurationException('page_control_outofform',get_class($control), $control ? $control->getUniqueID() : null);
	}

	/**
	 * @internal This method is invoked by TForm at the beginning of its rendering
	 */
	public function beginFormRender($writer)
	{
		if($this->_formRendered)
			throw new TConfigurationException('page_form_duplicated');
		$this->_formRendered=true;
		$this->getClientScript()->registerHiddenField(self::FIELD_PAGESTATE,$this->getClientState());
		$this->_inFormRender=true;
	}

	/**
	 * @internal This method is invoked by TForm  at the end of its rendering
	 */
	public function endFormRender($writer)
	{
		if($this->_focus)
		{
			if(($this->_focus instanceof TControl) && $this->_focus->getVisible(true))
				$focus=$this->_focus->getClientID();
			else
				$focus=$this->_focus;
			$this->getClientScript()->registerFocusControl($focus);
		}
		else if($this->_postData && ($lastFocus=$this->_postData->itemAt(self::FIELD_LASTFOCUS))!==null)
			$this->getClientScript()->registerFocusControl($lastFocus);
		$this->_inFormRender=false;
	}

	/**
	 * Sets input focus on a control after the page is rendered to users.
	 * @param TControl|string control to receive focus, or the ID of the element on the page to receive focus
	 */
	public function setFocus($value)
	{
		$this->_focus=$value;
	}

	/**
	 * @return boolean whether client supports javascript. Defaults to true.
	 */
	public function getClientSupportsJavaScript()
	{
		return $this->_enableJavaScript;
	}

	/**
	 * @param boolean whether client supports javascript. If false, javascript will not be generated for controls.
	 */
	public function setClientSupportsJavaScript($value)
	{
		$this->_enableJavaScript=TPropertyValue::ensureBoolean($value);
	}

	/**
	 * @return THead page head, null if not available
	 */
	public function getHead()
	{
		return $this->_head;
	}

	/**
	 * @param THead page head
	 * @throws TInvalidOperationException if a head already exists
	 */
	public function setHead(THead $value)
	{
		if($this->_head)
			throw new TInvalidOperationException('page_head_duplicated');
		$this->_head=$value;
		if($this->_title!==null)
		{
			$this->_head->setTitle($this->_title);
			$this->_title=null;
		}
	}

	/**
	 * @return string page title.
	 */
	public function getTitle()
	{
		if($this->_head)
			return $this->_head->getTitle();
		else
			return $this->_title===null ? '' : $this->_title;
	}

	/**
	 * Sets the page title.
	 * Note, a {@link THead} control needs to place on the page
	 * in order that this title be rendered.
	 * @param string page title. This will override the title set in {@link getHead Head}.
	 */
	public function setTitle($value)
	{
		if($this->_head)
			$this->_head->setTitle($value);
		else
			$this->_title=$value;
	}

	/**
	 * Returns the state to be stored on the client side.
	 * This method should only be used by framework and control developers.
	 * @return string the state to be stored on the client side
	 */
	public function getClientState()
	{
		return $this->_clientState;
	}

	/**
	 * Sets the state to be stored on the client side.
	 * This method should only be used by framework and control developers.
	 * @param string the state to be stored on the client side
	 */
	public function setClientState($state)
	{
		$this->_clientState=$state;
	}

	/**
	 * @return string the state postback from client side
	 */
	public function getRequestClientState()
	{
		return $this->getRequest()->itemAt(self::FIELD_PAGESTATE);
	}

	/**
	 * @return string class name of the page state persister. Defaults to TPageStatePersister.
	 */
	public function getStatePersisterClass()
	{
		return $this->_statePersisterClass;
	}

	/**
	 * @param string class name of the page state persister.
	 */
	public function setStatePersisterClass($value)
	{
		$this->_statePersisterClass=$value;
	}

	/**
	 * @return IPageStatePersister page state persister
	 */
	public function getStatePersister()
	{
		if($this->_statePersister===null)
		{
			$this->_statePersister=Prado::createComponent($this->_statePersisterClass);
			if(!($this->_statePersister instanceof IPageStatePersister))
				throw new TInvalidDataTypeException('page_statepersister_invalid');
			$this->_statePersister->setPage($this);
		}
		return $this->_statePersister;
	}

	/**
	 * @return boolean whether page state should be HMAC validated. Defaults to true.
	 */
	public function getEnableStateValidation()
	{
		return $this->_enableStateValidation;
	}

	/**
	 * @param boolean whether page state should be HMAC validated.
	 */
	public function setEnableStateValidation($value)
	{
		$this->_enableStateValidation=TPropertyValue::ensureBoolean($value);
	}

	/**
	 * @return boolean whether page state should be encrypted. Defaults to false.
	 */
	public function getEnableStateEncryption()
	{
		return $this->_enableStateEncryption;
	}

	/**
	 * @param boolean whether page state should be encrypted.
	 */
	public function setEnableStateEncryption($value)
	{
		$this->_enableStateEncryption=TPropertyValue::ensureBoolean($value);
	}

	/**
	 * @return boolean whether page state should be compressed. Defaults to true.
	 * @since 3.1.6
	 */
	public function getEnableStateCompression()
	{
		return $this->_enableStateCompression;
	}

	/**
	 * @param boolean whether page state should be compressed.
	 * @since 3.1.6
	 */
	public function setEnableStateCompression($value)
	{
		$this->_enableStateCompression=TPropertyValue::ensureBoolean($value);
	}

	/**
	 * @return string the requested page path for this page
	 */
	public function getPagePath()
	{
		return $this->_pagePath;
	}

	/**
	 * @param string the requested page path for this page
	 */
	public function setPagePath($value)
	{
		$this->_pagePath=$value;
	}

	/**
	 * Registers an action associated with the content being cached.
	 * The registered action will be replayed if the content stored
	 * in the cache is served to end-users.
	 * @param string context of the action method. This is a property-path
	 * referring to the context object (e.g. Page, Page.ClientScript).
	 * @param string method name of the context object
	 * @param array list of parameters to be passed to the action method
	 */
	public function registerCachingAction($context,$funcName,$funcParams)
	{
		if($this->_cachingStack)
		{
			foreach($this->_cachingStack as $cache)
				$cache->registerAction($context,$funcName,$funcParams);
		}
	}

	/**
	 * @return TStack stack of {@link TOutputCache} objects
	 */
	public function getCachingStack()
	{
		if(!$this->_cachingStack)
			$this->_cachingStack=new TStack;
		return $this->_cachingStack;
	}

	/**
	 * Flushes output
	 */
	public function flushWriter()
	{
		if ($this->_writer)
			$this->Response->write($this->_writer->flush());
	}
}

/**
 * IPageStatePersister interface.
 *
 * IPageStatePersister interface is required for all page state persister
 * classes.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @package System.Web.UI
 * @since 3.1
 */
interface IPageStatePersister
{
	/**
	 * @param TPage the page that this persister works for
	 */
	public function getPage();
	/**
	 * @param TPage the page that this persister works for
	 */
	public function setPage(TPage $page);
	/**
	 * Saves state to persistent storage.
	 * @param mixed state to be stored
	 */
	public function save($state);
	/**
	 * Loads page state from persistent storage
	 * @return mixed the restored state
	 */
	public function load();
}


/**
 * TPageStateFormatter class.
 *
 * TPageStateFormatter is a utility class to transform the page state
 * into and from a string that can be properly saved in persistent storage.
 *
 * Depending on the {@link TPage::getEnableStateValidation() EnableStateValidation}
 * and {@link TPage::getEnableStateEncryption() EnableStateEncryption},
 * TPageStateFormatter may do HMAC validation and encryption to prevent
 * the state data from being tampered or viewed.
 * The private keys and hashing/encryption methods are determined by
 * {@link TApplication::getSecurityManager() SecurityManager}.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @version $Revision: $  $Date: $
 * @package System.Web.UI
 * @since 3.1
 */
class TPageStateFormatter
{
	/**
	 * @param TPage
	 * @param mixed state data
	 * @return string serialized data
	 */
	public static function serialize($page,$data)
	{
		$sm=$page->getApplication()->getSecurityManager();
		if($page->getEnableStateValidation())
			$str=$sm->hashData(Prado::serialize($data));
		else
			$str=Prado::serialize($data);
		if($page->getEnableStateCompression() && extension_loaded('zlib'))
			$str=gzcompress($str);
		if($page->getEnableStateEncryption())
			$str=$sm->encrypt($str);
		return base64_encode($str);
	}

	/**
	 * @param TPage
	 * @param string serialized data
	 * @return mixed unserialized state data, null if data is corrupted
	 */
	public static function unserialize($page,$data)
	{
		$str=base64_decode($data);
		if($str==='')
			return null;
		if($str!==false)
		{
			$sm=$page->getApplication()->getSecurityManager();
			if($page->getEnableStateEncryption())
				$str=$sm->decrypt($str);
			if($page->getEnableStateCompression() && extension_loaded('zlib'))
				$str=@gzuncompress($str);
			if($page->getEnableStateValidation())
			{
				if(($str=$sm->validateData($str))!==false)
					return Prado::unserialize($str);
			}
			else
				return Prado::unserialize($str);
		}
		return null;
	}
}