/
Env.java
6952 lines (5627 loc) · 166 KB
/
Env.java
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
/*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.env;
import com.caucho.java.WorkDir;
import com.caucho.quercus.*;
import com.caucho.quercus.expr.Expr;
import com.caucho.quercus.lib.ErrorModule;
import com.caucho.quercus.lib.VariableModule;
import com.caucho.quercus.lib.OptionsModule;
import com.caucho.quercus.lib.file.FileModule;
import com.caucho.quercus.lib.file.PhpStderr;
import com.caucho.quercus.lib.file.PhpStdin;
import com.caucho.quercus.lib.file.PhpStdout;
import com.caucho.quercus.lib.regexp.RegexpState;
import com.caucho.quercus.lib.string.StringModule;
import com.caucho.quercus.lib.string.StringUtility;
import com.caucho.quercus.module.ModuleContext;
import com.caucho.quercus.module.ModuleStartupListener;
import com.caucho.quercus.module.IniDefinition;
import com.caucho.quercus.page.QuercusPage;
import com.caucho.quercus.program.*;
import com.caucho.quercus.function.AbstractFunction;
import com.caucho.quercus.resources.StreamContextResource;
import com.caucho.util.*;
import com.caucho.vfs.*;
import com.caucho.vfs.i18n.EncodingReader;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Represents the Quercus environment.
*/
public class Env {
private static final L10N L = new L10N(Env.class);
private static final Logger log = Logger.getLogger(Env.class.getName());
public static final int B_ERROR = 0;
public static final int B_WARNING = 1;
public static final int B_PARSE = 2;
public static final int B_NOTICE = 3;
public static final int B_CORE_ERROR = 4;
public static final int B_CORE_WARNING = 5;
public static final int B_COMPILE_ERROR = 6;
public static final int B_COMPILE_WARNING = 7;
public static final int B_USER_ERROR = 8;
public static final int B_USER_WARNING = 9;
public static final int B_USER_NOTICE = 10;
public static final int B_STRICT = 11;
public static final int B_RECOVERABLE_ERROR = 12;
public static final int B_DEPRECATED = 13;
public static final int B_USER_DEPRECATED = 14;
public static final int B_LAST = B_USER_DEPRECATED;
public static final int E_ERROR = 1 << B_ERROR;
public static final int E_WARNING = 1 << B_WARNING;
public static final int E_PARSE = 1 << B_PARSE;
public static final int E_NOTICE = 1 << B_NOTICE;
public static final int E_CORE_ERROR = 1 << B_CORE_ERROR;
public static final int E_CORE_WARNING = 1 << B_CORE_WARNING;
public static final int E_COMPILE_ERROR = 1 << B_COMPILE_ERROR;
public static final int E_COMPILE_WARNING = 1 << B_COMPILE_WARNING;
public static final int E_USER_ERROR = 1 << B_USER_ERROR;
public static final int E_USER_WARNING = 1 << B_USER_WARNING;
public static final int E_USER_NOTICE = 1 << B_USER_NOTICE;
public static final int E_ALL = 30719; // E_ERROR | E_WARNING | E_PARSE | E_NOTICE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE | E_RECOVERABLE_ERROR | E_DEPRECATED | E_USER_DEPRECATED
public static final int E_STRICT = 1 << B_STRICT;
public static final int E_RECOVERABLE_ERROR = 1 << B_RECOVERABLE_ERROR;
public static final int E_DEPRECATED = 1 << B_DEPRECATED;
public static final int E_USER_DEPRECATED = 1 << B_USER_DEPRECATED;
public static final int E_DEFAULT = 30711; // E_ALL & ~E_NOTICE
private static final int _SERVER = 1;
private static final int _GET = 2;
private static final int _POST = 3;
private static final int _COOKIE = 4;
private static final int _GLOBAL = 5;
private static final int _REQUEST = 6;
private static final int _SESSION = 7;
private static final int HTTP_GET_VARS = 8;
private static final int HTTP_POST_VARS = 9;
private static final int HTTP_COOKIE_VARS = 10;
private static final int PHP_SELF = 11;
private static final int _FILES = 12;
private static final int HTTP_POST_FILES = 13;
private static final int _ENV = 14;
private static final int HTTP_SERVER_VARS = 15;
private static final int HTTP_RAW_POST_DATA = 16;
private static final IntMap SPECIAL_VARS = new IntMap();
private static final StringValue PHP_SELF_STRING = new ConstStringValue("PHP_SELF");
private static final StringValue UTF8_STRING = new ConstStringValue("utf-8");
private static final StringValue S_GET = new ConstStringValue("_GET");
private static final StringValue S_POST = new ConstStringValue("_POST");
private static final StringValue S_SESSION = new ConstStringValue("_SESSION");
private static final StringValue S_SERVER = new ConstStringValue("_SERVER");
private static final StringValue S_COOKIE = new ConstStringValue("_COOKIE");
private static final StringValue S_FILES = new ConstStringValue("_FILES");
public static final Value[] EMPTY_VALUE = new Value[0];
private static ThreadLocal<Env> _threadEnv = new ThreadLocal<Env>();
private static final FreeList<AbstractFunction[]> _freeFunList = new FreeList<AbstractFunction[]>(256);
private static final FreeList<ClassDef[]> _freeClassDefList = new FreeList<ClassDef[]>(256);
private static final FreeList<QuercusClass[]> _freeClassList = new FreeList<QuercusClass[]>(256);
private static final FreeList<Value[]> _freeConstList = new FreeList<Value[]>(256);
private static final FreeList<QDate> _freeGmtDateList = new FreeList<QDate>(256);
private static final FreeList<QDate> _freeLocalDateList = new FreeList<QDate>(256);
private static final LruCache<String, StringValue> _internStringMap = new LruCache<String, StringValue>(4096);
protected final QuercusContext _quercus;
private QuercusPage _page;
private HashMap<String, Value> _scriptGlobalMap = new HashMap<String, Value>(16);
// Function map
public AbstractFunction[] _fun;
// anonymous functions created by create_function()
public HashMap<String, AbstractFunction> _anonymousFunMap;
// Class map
public ClassDef[] _classDef;
public QuercusClass[] _qClass;
// Constant map
public Value[] _const;
// Globals
private Map<StringValue, EnvVar> _globalMap = new HashMap<StringValue, EnvVar>();
private EnvVar[] _globalList;
// Statics
private Map<StringValue, Var> _staticMap = new HashMap<StringValue, Var>();
// Current env
private Map<StringValue, EnvVar> _map = _globalMap;
private HashMap<String, Value> _iniMap;
// specialMap is used for implicit resources like the mysql link
private HashMap<String, Object> _specialMap = new HashMap<String, Object>();
private HashSet<String> _initializedClassSet = new HashSet<String>();
// include_path ini
private int _iniCount = 1;
private ArrayList<EnvCleanup> _cleanupList;
private ArrayList<ObjectExtValue> _objCleanupList;
private ArrayList<Shutdown> _shutdownList;
private String _defaultIncludePath;
private String _includePath;
private int _includePathIniCount;
private ArrayList<String> _includePathList;
private HashMap<Path, ArrayList<Path>> _includePathMap;
// TODO: may require a LinkedHashMap for ordering?
private HashMap<Path, QuercusPage> _includeMap = new HashMap<Path, QuercusPage>();
private Value _this = NullThisValue.NULL;
private final boolean _isUnicodeSemantics;
private boolean _isAllowUrlInclude;
private boolean _isAllowUrlFopen;
private HashMap<StringValue, Path> _lookupCache = new HashMap<StringValue, Path>();
private HashMap<ConnectionEntry, ConnectionEntry> _connMap = new HashMap<ConnectionEntry, ConnectionEntry>();
private AbstractFunction _autoload;
private HashSet<String> _autoloadClasses = new HashSet<String>();
private ArrayList<Callable> _autoloadList;
private InternalAutoloadCallback _internalAutoload;
private Location _location;
private long _startTime;
private long _timeLimit = 600000L;
private long _endTime;
private Expr[] _callStack;
private Value[] _callThisStack;
private Value[][] _callArgStack;
private int _callStackTop;
private QuercusClass _callingClass;
private Value[] _functionArgs;
private LinkedList<FieldGetEntry> _fieldGetList = new LinkedList<FieldGetEntry>();
private LinkedList<FieldGetEntry> _fieldSetList = new LinkedList<FieldGetEntry>();
private LinkedList<FieldGetEntry> _issetList = new LinkedList<FieldGetEntry>();
private LinkedList<FieldGetEntry> _unsetList = new LinkedList<FieldGetEntry>();
public enum OVERLOADING_TYPES {
INVALID_FIRST, FIELDGET, FIELDSET, ISSET, UNSET, INVALID_LAST
};
private Path _selfPath;
private Path _selfDirectory;
private Path _pwd;
private Path _uploadPath;
private Path _tmpPath;
private ArrayList<Path> _removePaths;
private final boolean _isStrict;
private HttpServletRequest _request;
private HttpServletResponse _response;
private ArrayValue _postArray = new ArrayValueImpl();
private ArrayValue _files = new ArrayValueImpl();
private StringValue _inputData;
private SessionArrayValue _session;
private HttpSession _javaSession;
private ScriptContext _scriptContext;
private WriteStream _originalOut;
private OutputBuffer _outputBuffer;
private WriteStream _out;
private LocaleInfo _locale;
private Callable[] _prevErrorHandlers = new Callback[B_LAST + 1];
private Callable[] _errorHandlers = new Callback[B_LAST + 1];
private Callable _prevExceptionHandler;
private Callable _exceptionHandler;
private SessionCallback _sessionCallback;
private StreamContextResource _defaultStreamContext;
private int _objectId = 0;
private Logger _logger;
// hold special Quercus php import statements
private ImportMap _importMap;
private TimeZone _defaultTimeZone;
private QDate _localDate;
private QDate _gmtDate;
private Object _gzStream;
private Env _oldThreadEnv;
private boolean _isTimeout;
private long _firstMicroTime;
private long _firstNanoTime;
private RegexpState _freeRegexpState;
private Object _duplex;
private StringValue _variablesOrder;
private int[] _querySeparatorMap;
public static final int[] DEFAULT_QUERY_SEPARATOR_MAP;
private CharBuffer _cb = new CharBuffer();
private String[] _authRequest;
public Env(QuercusContext quercus,
QuercusPage page,
WriteStream out,
HttpServletRequest request,
HttpServletResponse response) {
_quercus = quercus;
_isStrict = quercus.isStrict();
_isUnicodeSemantics = quercus.isUnicodeSemantics();
_isAllowUrlInclude = quercus.isAllowUrlInclude();
_isAllowUrlFopen = quercus.isAllowUrlFopen();
_variablesOrder = _quercus.getIniValue("variables_order").toStringValue(this);
StringValue querySeparators = _quercus.getIniValue("arg_separator.input").toStringValue(this);
int len = querySeparators.length();
if (len == 0) {
_querySeparatorMap = DEFAULT_QUERY_SEPARATOR_MAP;
} else {
_querySeparatorMap = new int[128];
for (int i = 0; i < len; i++) {
char ch = querySeparators.charAt(i);
_querySeparatorMap[ch] = 1;
}
}
_page = page;
// TODO: grab initial from page
// _defState = new DefinitionState(quercus);
AbstractFunction[] defFuns = getDefaultFunctionMap();
_fun = _freeFunList.allocate();
if (_fun == null || _fun.length < defFuns.length) {
_fun = new AbstractFunction[defFuns.length];
}
System.arraycopy(defFuns, 0, _fun, 0, defFuns.length);
ClassDef[] defClasses = quercus.getClassDefMap();
_classDef = _freeClassDefList.allocate();
if (_classDef == null || _classDef.length < defClasses.length) {
_classDef = new ClassDef[defClasses.length];
} else {
// list should have been zeroed on call to free
}
_qClass = _freeClassList.allocate();
if (_qClass == null || _qClass.length < defClasses.length) {
_qClass = new QuercusClass[defClasses.length];
} else {
// list should have been zeroed on call to free
}
Value[] defConst = quercus.getConstantMap();
_const = _freeConstList.allocate();
if (_const == null || _const.length < defConst.length) {
_const = new Value[defConst.length];
} else {
// list should have been zeroed on call to free
}
System.arraycopy(defConst, 0, _const, 0, defConst.length);
_originalOut = out;
_out = out;
_request = request;
_response = response;
if (_page != null) {
pageInit(_page);
}
setPwd(_quercus.getPwd());
if (_page != null) {
setSelfPath(_page.getSelfPath(null));
// php/0b32
_includeMap.put(_selfPath, _page);
}
// TODO: delete internal Autoload Callback
_internalAutoload = new InternalAutoloadCallback("com/caucho/quercus/php/");
// Define the constant string PHP_VERSION
addConstant("PHP_VERSION", OptionsModule.phpversion(this, null), true);
// Define the constant string PHP_SAPI
addConstant("PHP_SAPI", new ConstStringValue(OptionsModule.php_sapi_name(this)), true);
addConstant("PEAR_EXTENSION_DIR", new ConstStringValue(getPwd() + "WEB-INF/lib/"), true);
addConstant("PHP_EXTENSION_DIR", new ConstStringValue(getPwd() + "WEB-INF/lib/"), true);
addConstant("PHP_LIBDIR", new ConstStringValue(getPwd() + "WEB-INF/lib/"), true);
addConstant("PHP_CONFIG_FILE_PATH", new ConstStringValue(getPwd() + "WEB-INF/"), true);
addConstant("PHP_CONFIG_FILE_SCAN_DIR", new ConstStringValue(getPwd() + "WEB-INF/"), true);
// c#0004403 - #27
if (request != null) {
String _authHeader = request.getHeader("authorization");
if (_authHeader != null) {
_authRequest = _authHeader.split(" ");
if (_authRequest[0].equals("Basic")) {
// BASIC auth
String[] _auth64 = Base64.decode(_authRequest[1]).split(":");
getGlobalVar("_SERVER").put(new ConstStringValue("PHP_AUTH_USER"), new ConstStringValue(_auth64[0]));
getGlobalVar("_SERVER").put(new ConstStringValue("PHP_AUTH_PW"), new ConstStringValue(_auth64[1]));
}
}
}
// STDIN, STDOUT, STDERR
// php://stdin, php://stdout, php://stderr
if (response == null) {
addConstant("STDOUT", wrapJava(new PhpStdout()), false);
addConstant("STDERR", wrapJava(new PhpStderr()), false);
addConstant("STDIN", wrapJava(new PhpStdin(this)), false);
}
}
public Env(QuercusContext quercus) {
this(quercus, null, null, null, null);
}
public static Env getCurrent() {
return _threadEnv.get();
}
public static Env getInstance() {
return getCurrent();
}
private void fillGet(ArrayValue array, boolean isMagicQuotes) {
String queryString = getQueryString();
if (queryString == null || queryString.length() == 0) {
return;
}
StringUtility.parseStr(this,
queryString,
array,
true,
getHttpInputEncoding(),
isMagicQuotes,
_querySeparatorMap);
/*
try {
String encoding = getHttpInputEncoding();
if (encoding == null)
encoding = "iso-8859-1";
_request.setCharacterEncoding(encoding);
} catch (Exception e) {
log.log(Level.FINE, e.toString(), e);
}
ArrayList<String> keys = new ArrayList<String>();
keys.addAll(_request.getParameterMap().keySet());
Collections.sort(keys);
for (String key : keys) {
String []value = _request.getParameterValues(key);
Post.addFormValue(this,
array,
key,
value,
isMagicQuotes);
}
*/
}
private void fillPost(ArrayValue array, ArrayValue postArray) {
for (Map.Entry<Value, Value> entry : postArray.entrySet()) {
Value key = entry.getKey();
Value value = entry.getValue();
Value existingValue = array.get(key);
if (existingValue.isArray() && value.isArray()) {
existingValue.toArrayValue(this).putAll(value.toArrayValue(this));
} else {
array.put(entry.getKey(), entry.getValue().copy());
}
}
}
private void fillCookies(ArrayValue array,
Cookie[] cookies,
boolean isMagicQuotes) {
for (int i = 0; cookies != null && i < cookies.length; i++) {
Cookie cookie = cookies[i];
String decodedValue = decodeValue(cookie.getValue());
Post.addFormValue(this,
array,
cookie.getName(),
new String[]{decodedValue},
isMagicQuotes);
}
}
protected void fillPost(ArrayValue postArray,
ArrayValue files,
HttpServletRequest request,
boolean isMagicQuotes) {
if (request != null && request.getMethod().equals("POST")) {
Post.fillPost(this,
postArray,
files,
request,
isMagicQuotes,
getIniBoolean("file_uploads"));
} else if (request != null && !request.getMethod().equals("GET")) {
InputStream is = null;
try {
is = request.getInputStream();
} catch (IOException e) {
warning(e);
}
StringValue bb = createBinaryBuilder();
bb.appendReadAll(is, Integer.MAX_VALUE);
setInputData(bb);
}
}
protected AbstractFunction[] getDefaultFunctionMap() {
return getQuercus().getFunctionMap();
}
/**
* Initialize the page, loading any functions and classes
*/
protected QuercusPage pageInit(QuercusPage page) {
if (page.getCompiledPage() != null) {
page = page.getCompiledPage();
}
page.init(this);
page.importDefinitions(this);
return page;
}
//
// script accessible methods
//
/**
* External calls to set a global value.
*/
public Value setScriptGlobal(String name, Object object) {
Value value;
if (object instanceof Value) {
value = (Value) object;
} else if (object == null) {
value = NullValue.NULL;
} else {
value = wrapJava(object);
}
_scriptGlobalMap.put(name, value);
return value;
}
//
// i18n
//
/**
* Returns true if unicode.semantics is on.
*/
public boolean isUnicodeSemantics() {
return _isUnicodeSemantics;
}
/**
* Returns the encoding used for scripts.
*/
public String getScriptEncoding() {
StringValue encoding = getIni("unicode.script_encoding");
if (encoding.length() == 0) {
encoding = getIni("unicode.fallback_encoding");
if (encoding.length() == 0) {
return getQuercus().getScriptEncoding();
}
}
return encoding.toString();
}
/**
* Returns the encoding used for runtime conversions, e.g. files
* XXX: ISO-8859-1 when unicode.semantics is OFF
*/
public String getRuntimeEncoding() {
if (!_isUnicodeSemantics) {
return "iso-8859-1";
}
StringValue encoding = getIni("unicode.runtime_encoding");
if (encoding.length() == 0) {
encoding = getIni("unicode.fallback_encoding");
if (encoding.length() == 0) {
encoding = UTF8_STRING;
}
}
return encoding.toString();
}
/**
* Sets the encoding used for runtime conversions.
*/
public Value setRuntimeEncoding(String encoding) {
return setIni("unicode.runtime_encoding", encoding);
}
/**
* Returns the encoding used for runtime conversions, e.g. files
*/
public EncodingReader getRuntimeEncodingFactory()
throws IOException {
return Encoding.getReadFactory(getRuntimeEncoding());
}
/**
* Returns the encoding used for input, i.e. post,
* null if unicode.semantics is off.
*/
public String getHttpInputEncoding() {
if (!_isUnicodeSemantics) {
return null;
}
StringValue encoding = getIni("unicode.http_input_encoding");
if (encoding.length() == 0) {
encoding = getIni("unicode.fallback_encoding");
if (encoding.length() == 0) {
encoding = UTF8_STRING;
}
}
return encoding.toString();
}
/**
* Returns the encoding used for output, null if unicode.semantics is off.
*/
public String getOutputEncoding() {
if (!_isUnicodeSemantics) {
return null;
}
String encoding = QuercusContext.INI_UNICODE_OUTPUT_ENCODING.getAsString(this);
if (encoding == null) {
encoding = QuercusContext.INI_UNICODE_FALLBACK_ENCODING.getAsString(this);
}
if (encoding == null) {
encoding = "utf-8";
}
return encoding;
}
/**
* Creates a binary builder.
*/
public StringValue createBinaryBuilder() {
if (_isUnicodeSemantics) {
return new BinaryBuilderValue();
} else {
return new StringBuilderValue();
}
}
/**
* Creates a binary builder for large things like files.
*/
public StringValue createLargeBinaryBuilder() {
if (_isUnicodeSemantics) {
return new BinaryBuilderValue();
} else {
return new LargeStringBuilderValue();
}
}
/**
* Creates a binary builder.
*/
public StringValue createBinaryBuilder(int length) {
if (_isUnicodeSemantics) {
return new BinaryBuilderValue(length);
} else {
return new StringBuilderValue(length);
}
}
/**
* Creates a binary builder.
*/
public StringValue createBinaryBuilder(byte[] buffer, int offset, int length) {
if (_isUnicodeSemantics) {
return new BinaryBuilderValue(buffer, offset, length);
} else {
return new StringBuilderValue(buffer, offset, length);
}
}
/**
* Creates a binary builder.
*/
public StringValue createBinaryBuilder(byte[] buffer) {
if (_isUnicodeSemantics) {
return new BinaryBuilderValue(buffer, 0, buffer.length);
} else {
return new StringBuilderValue(buffer, 0, buffer.length);
}
}
/**
* Creates a unicode builder.
*/
public StringValue createUnicodeBuilder() {
if (_isUnicodeSemantics) {
return new UnicodeBuilderValue();
} else {
return new StringBuilderValue();
}
}
public TimeZone getDefaultTimeZone() {
if (_defaultTimeZone != null) {
return _defaultTimeZone;
}
String timeZone = getIniString("date.timezone");
if (timeZone != null) {
return TimeZone.getTimeZone(timeZone);
} else {
return TimeZone.getDefault();
}
}
public QDate getGmtDate() {
if (_gmtDate == null) {
_gmtDate = _freeGmtDateList.allocate();
if (_gmtDate == null) {
_gmtDate = new QDate();
}
}
return _gmtDate;
}
public QDate getLocalDate() {
if (_localDate == null) {
_localDate = _freeLocalDateList.allocate();
if (_localDate == null) {
_localDate = QDate.createLocal();
}
}
return _localDate;
}
public QDate getDate() {
TimeZone zone = getDefaultTimeZone();
if (zone.getID().equals("GMT")) {
return getGmtDate();
} else if (zone.equals(TimeZone.getDefault())) {
return getLocalDate();
} else {
return new QDate(zone);
}
}
public void setDefaultTimeZone(String id) {
_defaultTimeZone = TimeZone.getTimeZone(id);
}
public void setDefaultTimeZone(TimeZone zone) {
_defaultTimeZone = zone;
}
/*
* Returns the ServletContext.
*/
public ServletContext getServletContext() {
return _quercus.getServletContext();
}
/*
* Sets the ScriptContext.
*/
public void setScriptContext(ScriptContext context) {
_scriptContext = context;
}
/*
* Returns the input (POST, PUT) data.
*/
public StringValue getInputData() {
return _inputData;
}
/*
* Sets the post data.
*/
public void setInputData(StringValue data) {
_inputData = data;
}
/**
* Returns true for strict mode.
*/
public final boolean isStrict() {
return _isStrict;
}
/*
* Returns true if allowed to include urls.
*/
public boolean isAllowUrlInclude() {
return _isAllowUrlInclude;
}
/*
* Returns true if allowed to fopen urls.
*/
public boolean isAllowUrlFopen() {
return _isAllowUrlFopen;
}
/**
* Returns the connection status
*/
public int getConnectionStatus() {
// always returns a valid value for now
return 0;
}
public void start() {
_oldThreadEnv = _threadEnv.get();
_startTime = _quercus.getCurrentTime();
_timeLimit = getIniLong("max_execution_time") * 1000;
if (_timeLimit > 0) {
_endTime = _startTime + _timeLimit;
} else {
_endTime = Long.MAX_VALUE / 2;
}
_threadEnv.set(this);
fillPost(_postArray,
_files,
_request,
getIniBoolean("magic_quotes_gpc"));
// quercus/1b06
String encoding = getOutputEncoding();
String type = getIniString("default_mimetype");
if ("".equals(type) || _response == null) {
} else if (encoding != null) {
_response.setContentType(type + "; charset=" + encoding);
} else {
_response.setContentType(type);
}
if (_out != null && encoding != null) {
try {
_out.setEncoding(encoding);
} catch (Exception e) {
log.log(Level.WARNING, e.toString(), e);
}
}
HashSet<ModuleStartupListener> listeners = _quercus.getModuleStartupListeners();
for (ModuleStartupListener listener : listeners) {
listener.startup(this);
}
_quercus.startEnv(this);
}
/**
* Returns the current time (may be cached).
*/
public long getCurrentTime() {
return getQuercus().getCurrentTime();
}
/**
* Returns the current time (not cached).
*/
public long getExactTime() {
return getQuercus().getExactTime();
}
/**
* add resource to the list of refrences that are
* cleaned up when finished with this environment.
*/
public void addCleanup(EnvCleanup envCleanup) {
if (_cleanupList == null) {
_cleanupList = new ArrayList<EnvCleanup>();
}
_cleanupList.add(envCleanup);
}
/**
* add an object with a destructor to the list of references that are
* cleaned up when finished with this environment.
*/
public void addObjectCleanup(ObjectExtValue objCleanup) {
if (_objCleanupList == null) {
_objCleanupList = new ArrayList<ObjectExtValue>();
}
_objCleanupList.add(objCleanup);
}
/**
* remove resource from the list of references that are
* cleaned up when finished with this environment.
*
* @param resource
*/
public void removeCleanup(EnvCleanup envCleanup) {
if (_cleanupList == null) {
return;
}
for (int i = _cleanupList.size() - 1; i >= 0; i--) {
EnvCleanup res = _cleanupList.get(i);
if (envCleanup.equals(res)) {
_cleanupList.remove(i);
break;
}
}
}
/**
* Returns the owning PHP engine.
*/
public QuercusContext getQuercus() {
return _quercus;
}
/**
* Returns the owning PHP engine.
*/
public ModuleContext getModuleContext() {
return _quercus.getModuleContext();
}
/**
* Returns the configured database.
*/
public DataSource getDatabase() {
return _quercus.getDatabase();
}
protected final DataSource findDatabase(String driver, String url)
throws Exception {
return _quercus.findDatabase(driver, url);
}
/**
* Returns a connection to the given database. If there is
* already a connection to this specific database, then
* return the connection from the pool. Otherwise, create
* a new connection and add it to the pool.
*/
public ConnectionEntry getConnection(String driver, String url,
String userName, String password,
boolean isReuse)
throws Exception {
// TODO: connections might not be reusable (see gallery2), because
// of case with two reuses and one closes because of CREATE or
// catalog
isReuse = false;
DataSource database = _quercus.getDatabase();
if (database != null) {
userName = null;
password = null;
} else {
database = findDatabase(driver, url);
if (database == null) {
return null;
}
}
ConnectionEntry entry = new ConnectionEntry(this);
entry.init(database, userName, password);
ConnectionEntry oldEntry = null;
if (isReuse) {
oldEntry = _connMap.get(entry);
}
if (oldEntry != null && oldEntry.isReusable()) {
return oldEntry;
}
entry.connect(isReuse);
if (isReuse) {
_connMap.put(entry, entry);