Web.hx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. /*
  2. * Copyright (C)2005-2016 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package php;
  23. import haxe.io.Bytes;
  24. import php.Syntax.*;
  25. import php.Global.*;
  26. import php.SuperGlobal.*;
  27. /**
  28. This class is used for accessing the local Web server and the current
  29. client request and informations.
  30. **/
  31. class Web {
  32. /**
  33. Returns the GET and POST parameters.
  34. **/
  35. public static function getParams() : Map<String,String> {
  36. #if force_std_separator
  37. var a : NativeArray = untyped __php__("$_POST");
  38. if(untyped __call__("get_magic_quotes_gpc"))
  39. untyped __php__("reset($a); while(list($k, $v) = each($a)) $a[$k] = stripslashes((string)$v)");
  40. var h = Lib.hashOfAssociativeArray(a);
  41. var params = getParamsString();
  42. if( params == "" )
  43. return h;
  44. for( p in ~/[;&]/g.split(params) ) {
  45. var a = p.split("=");
  46. var n = a.shift();
  47. h.set(StringTools.urlDecode(n),StringTools.urlDecode(a.join("=")));
  48. }
  49. return h;
  50. #else
  51. var a : NativeArray = untyped __php__("array_merge($_GET, $_POST)");
  52. if(untyped __call__("get_magic_quotes_gpc"))
  53. untyped __php__("reset($a); while(list($k, $v) = each($a)) $a[$k] = stripslashes((string)$v)");
  54. return Lib.hashOfAssociativeArray(a);
  55. #end
  56. }
  57. /**
  58. Returns an Array of Strings built using GET / POST values.
  59. If you have in your URL the parameters `a[]=foo;a[]=hello;a[5]=bar;a[3]=baz` then
  60. `php.Web.getParamValues("a")` will return `["foo","hello",null,"baz",null,"bar"]`.
  61. **/
  62. public static function getParamValues( param : String ) : Array<String> {
  63. var reg = new EReg("^"+param+"(\\[|%5B)([0-9]*?)(\\]|%5D)=(.*?)$", "");
  64. var res = new Array<String>();
  65. var explore = function(data:String){
  66. if (data == null || data.length == 0)
  67. return;
  68. for (part in data.split("&")){
  69. if (reg.match(part)){
  70. var idx = reg.matched(2);
  71. var val = StringTools.urlDecode(reg.matched(4));
  72. if (idx == "")
  73. res.push(val);
  74. else
  75. res[Std.parseInt(idx)] = val;
  76. }
  77. }
  78. }
  79. explore(StringTools.replace(getParamsString(), ";", "&"));
  80. explore(getPostData());
  81. if (res.length == 0) {
  82. var post:haxe.ds.StringMap<Dynamic> = Lib.hashOfAssociativeArray(untyped __php__("$_POST"));
  83. var data = post.get(param);
  84. var k = 0, v = "";
  85. if (untyped __call__("is_array", data)) {
  86. untyped __php__(" reset($data); while(list($k, $v) = each($data)) { ");
  87. res[k] = v;
  88. untyped __php__(" } ");
  89. }
  90. }
  91. if (res.length == 0)
  92. return null;
  93. return res;
  94. }
  95. /**
  96. Returns the local server host name.
  97. **/
  98. public static inline function getHostName() : String {
  99. return untyped __php__("$_SERVER['SERVER_NAME']");
  100. }
  101. /**
  102. Surprisingly returns the client IP address.
  103. **/
  104. public static inline function getClientIP() : String {
  105. return untyped __php__("$_SERVER['REMOTE_ADDR']");
  106. }
  107. /**
  108. Returns the original request URL (before any server internal redirections).
  109. **/
  110. public static function getURI() : String {
  111. var s : String = untyped __php__("$_SERVER['REQUEST_URI']");
  112. return s.split("?")[0];
  113. }
  114. /**
  115. Tell the client to redirect to the given url ("Location" header).
  116. **/
  117. public static function redirect( url : String ) {
  118. untyped __call__('header', "Location: " + url);
  119. }
  120. /**
  121. Set an output header value. If some data have been printed, the headers have
  122. already been sent so this will raise an exception.
  123. **/
  124. public static inline function setHeader( h : String, v : String ) {
  125. untyped __call__('header', h+": "+v);
  126. }
  127. /**
  128. Set the HTTP return code. Same remark as `php.Web.setHeader()`.
  129. See status code explanation here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  130. **/
  131. public static function setReturnCode( r : Int ) {
  132. var code : String;
  133. switch(r) {
  134. case 100: code = "100 Continue";
  135. case 101: code = "101 Switching Protocols";
  136. case 200: code = "200 OK";
  137. case 201: code = "201 Created";
  138. case 202: code = "202 Accepted";
  139. case 203: code = "203 Non-Authoritative Information";
  140. case 204: code = "204 No Content";
  141. case 205: code = "205 Reset Content";
  142. case 206: code = "206 Partial Content";
  143. case 300: code = "300 Multiple Choices";
  144. case 301: code = "301 Moved Permanently";
  145. case 302: code = "302 Found";
  146. case 303: code = "303 See Other";
  147. case 304: code = "304 Not Modified";
  148. case 305: code = "305 Use Proxy";
  149. case 307: code = "307 Temporary Redirect";
  150. case 400: code = "400 Bad Request";
  151. case 401: code = "401 Unauthorized";
  152. case 402: code = "402 Payment Required";
  153. case 403: code = "403 Forbidden";
  154. case 404: code = "404 Not Found";
  155. case 405: code = "405 Method Not Allowed";
  156. case 406: code = "406 Not Acceptable";
  157. case 407: code = "407 Proxy Authentication Required";
  158. case 408: code = "408 Request Timeout";
  159. case 409: code = "409 Conflict";
  160. case 410: code = "410 Gone";
  161. case 411: code = "411 Length Required";
  162. case 412: code = "412 Precondition Failed";
  163. case 413: code = "413 Request Entity Too Large";
  164. case 414: code = "414 Request-URI Too Long";
  165. case 415: code = "415 Unsupported Media Type";
  166. case 416: code = "416 Requested Range Not Satisfiable";
  167. case 417: code = "417 Expectation Failed";
  168. case 500: code = "500 Internal Server Error";
  169. case 501: code = "501 Not Implemented";
  170. case 502: code = "502 Bad Gateway";
  171. case 503: code = "503 Service Unavailable";
  172. case 504: code = "504 Gateway Timeout";
  173. case 505: code = "505 HTTP Version Not Supported";
  174. default: code = Std.string(r);
  175. }
  176. untyped __call__('header', "HTTP/1.1 " + code, true, r);
  177. }
  178. /**
  179. Retrieve a client header value sent with the request.
  180. **/
  181. public static function getClientHeader( k : String ) : String {
  182. return loadClientHeaders().get(k);
  183. }
  184. private static var _clientHeaders : Map<String,String>;
  185. /**
  186. Based on https://github.com/ralouphie/getallheaders
  187. **/
  188. static function loadClientHeaders():Map<String,String> {
  189. if(_clientHeaders != null) return _clientHeaders;
  190. _clientHeaders = new Map();
  191. if(function_exists('getallheaders')) {
  192. foreach(getallheaders(), function(key:String, value:Dynamic) {
  193. _clientHeaders.set(key, Std.string(value));
  194. });
  195. return _clientHeaders;
  196. }
  197. var copyServer = [
  198. 'CONTENT_TYPE' => 'Content-Type',
  199. 'CONTENT_LENGTH' => 'Content-Length',
  200. 'CONTENT_MD5' => 'Content-Md5'
  201. ];
  202. foreach(_SERVER, function(key:String, value:Dynamic) {
  203. if((substr(key, 0, 5):String) == 'HTTP_') {
  204. key = substr(key, 5);
  205. if(!copyServer.exists(key) || !isset(_SERVER[key])) {
  206. key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', key))));
  207. _clientHeaders[key] = Std.string(value);
  208. }
  209. } else if(isset(copyServer[key])) {
  210. _clientHeaders[copyServer[key]] = Std.string(value);
  211. }
  212. });
  213. if(!_clientHeaders.exists('Authorization')) {
  214. if(isset(_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
  215. _clientHeaders['Authorization'] = Std.string(_SERVER['REDIRECT_HTTP_AUTHORIZATION']);
  216. } else if(isset(_SERVER['PHP_AUTH_USER'])) {
  217. var basic_pass = isset(_SERVER['PHP_AUTH_PW']) ? Std.string(_SERVER['PHP_AUTH_PW']) : '';
  218. _clientHeaders['Authorization'] = 'Basic ' + base64_encode(_SERVER['PHP_AUTH_USER'] + ':' + basic_pass);
  219. } else if(isset(_SERVER['PHP_AUTH_DIGEST'])) {
  220. _clientHeaders['Authorization'] = Std.string(_SERVER['PHP_AUTH_DIGEST']);
  221. }
  222. }
  223. return _clientHeaders;
  224. }
  225. /**
  226. Retrieve all the client headers.
  227. **/
  228. public static function getClientHeaders():List<{value:String, header:String}> {
  229. var headers = loadClientHeaders();
  230. var result = new List();
  231. for(key in headers.keys()) {
  232. result.push({value:headers.get(key), header:key});
  233. }
  234. return result;
  235. }
  236. /**
  237. Returns all the GET parameters `String`
  238. **/
  239. public static function getParamsString() : String {
  240. if(untyped __call__("isset", __var__("_SERVER", "QUERY_STRING")))
  241. return untyped __var__("_SERVER", "QUERY_STRING");
  242. else
  243. return "";
  244. }
  245. /**
  246. Returns all the POST data. POST Data is always parsed as
  247. being application/x-www-form-urlencoded and is stored into
  248. the getParams hashtable. POST Data is maximimized to 256K
  249. unless the content type is multipart/form-data. In that
  250. case, you will have to use `php.Web.getMultipart()` or
  251. `php.Web.parseMultipart()` methods.
  252. **/
  253. public static function getPostData() {
  254. var h = untyped __call__("fopen", "php://input", "r");
  255. var bsize = 8192;
  256. var max = 32;
  257. var data : String = null;
  258. var counter = 0;
  259. while (!untyped __call__("feof", h) && counter < max) {
  260. data += untyped __call__("fread", h, bsize);
  261. counter++;
  262. }
  263. untyped __call__("fclose", h);
  264. return data;
  265. }
  266. /**
  267. Returns an hashtable of all Cookies sent by the client.
  268. Modifying the hashtable will not modify the cookie, use `php.Web.setCookie()`
  269. instead.
  270. **/
  271. public static function getCookies():Map<String,String> {
  272. return Lib.hashOfAssociativeArray(untyped __php__("$_COOKIE"));
  273. }
  274. /**
  275. Set a Cookie value in the HTTP headers. Same remark as `php.Web.setHeader()`.
  276. **/
  277. public static function setCookie( key : String, value : String, ?expire: Date, ?domain: String, ?path: String, ?secure: Bool, ?httpOnly: Bool ) {
  278. var t = expire == null ? 0 : Std.int(expire.getTime()/1000.0);
  279. if(path == null) path = '/';
  280. if(domain == null) domain = '';
  281. if(secure == null) secure = false;
  282. if(httpOnly == null) httpOnly = false;
  283. untyped __call__("setcookie", key, value, t, path, domain, secure, httpOnly);
  284. }
  285. /**
  286. Returns an object with the authorization sent by the client (Basic scheme only).
  287. **/
  288. public static function getAuthorization() : { user : String, pass : String } {
  289. if(!untyped __php__("isset($_SERVER['PHP_AUTH_USER'])"))
  290. return null;
  291. return untyped {user: __php__("$_SERVER['PHP_AUTH_USER']"), pass: __php__("$_SERVER['PHP_AUTH_PW']")};
  292. }
  293. /**
  294. Get the current script directory in the local filesystem.
  295. **/
  296. public static inline function getCwd() : String {
  297. return untyped __php__("dirname($_SERVER[\"SCRIPT_FILENAME\"])") + "/";
  298. }
  299. /**
  300. Get the multipart parameters as an hashtable. The data
  301. cannot exceed the maximum size specified.
  302. **/
  303. public static function getMultipart( maxSize : Int ) : Map<String,String> {
  304. var h = new haxe.ds.StringMap();
  305. var buf : StringBuf = null;
  306. var curname = null;
  307. parseMultipart(function(p,_) {
  308. if( curname != null )
  309. h.set(curname,buf.toString());
  310. curname = p;
  311. buf = new StringBuf();
  312. maxSize -= p.length;
  313. if( maxSize < 0 )
  314. throw "Maximum size reached";
  315. }, function(str,pos,len) {
  316. maxSize -= len;
  317. if( maxSize < 0 )
  318. throw "Maximum size reached";
  319. buf.addSub(str.toString(),pos,len);
  320. });
  321. if( curname != null )
  322. h.set(curname,buf.toString());
  323. return h;
  324. }
  325. /**
  326. Parse the multipart data. Call `onPart` when a new part is found
  327. with the part name and the filename if present
  328. and `onData` when some part data is readed. You can this way
  329. directly save the data on hard drive in the case of a file upload.
  330. **/
  331. public static function parseMultipart( onPart : String -> String -> Void, onData : Bytes -> Int -> Int -> Void ) : Void {
  332. var a : NativeArray = untyped __var__("_POST");
  333. if(untyped __call__("get_magic_quotes_gpc"))
  334. untyped __php__("reset($a); while(list($k, $v) = each($a)) $a[$k] = stripslashes((string)$v)");
  335. var post = Lib.hashOfAssociativeArray(a);
  336. for (key in post.keys())
  337. {
  338. onPart(key, "");
  339. var v = post.get(key);
  340. onData(Bytes.ofString(v), 0, untyped __call__("strlen", v));
  341. }
  342. if(!untyped __call__("isset", __php__("$_FILES"))) return;
  343. var parts : Array<String> = untyped __call__("new _hx_array",__call__("array_keys", __php__("$_FILES")));
  344. for(part in parts) {
  345. var info : Dynamic = untyped __php__("$_FILES[$part]");
  346. var tmp : String = untyped info['tmp_name'];
  347. var file : String = untyped info['name'];
  348. var err : Int = untyped info['error'];
  349. if(err > 0) {
  350. switch(err) {
  351. case 1: throw "The uploaded file exceeds the max size of " + untyped __call__('ini_get', 'upload_max_filesize');
  352. case 2: throw "The uploaded file exceeds the max file size directive specified in the HTML form (max is" + untyped __call__('ini_get', 'post_max_size') + ")";
  353. case 3: throw "The uploaded file was only partially uploaded";
  354. case 4: continue; // No file was uploaded
  355. case 6: throw "Missing a temporary folder";
  356. case 7: throw "Failed to write file to disk";
  357. case 8: throw "File upload stopped by extension";
  358. }
  359. }
  360. onPart(part, file);
  361. if ("" != file)
  362. {
  363. var h = untyped __call__("fopen", tmp, "r");
  364. var bsize = 8192;
  365. while (!untyped __call__("feof", h)) {
  366. var buf : String = untyped __call__("fread", h, bsize);
  367. var size : Int = untyped __call__("strlen", buf);
  368. onData(Bytes.ofString(buf), 0, size);
  369. }
  370. untyped __call__("fclose", h);
  371. }
  372. }
  373. }
  374. /**
  375. Flush the data sent to the client. By default on Apache, outgoing data is buffered so
  376. this can be useful for displaying some long operation progress.
  377. **/
  378. public static inline function flush() : Void {
  379. untyped __call__("flush");
  380. }
  381. /**
  382. Get the HTTP method used by the client.
  383. **/
  384. public static function getMethod() : String {
  385. if(untyped __php__("isset($_SERVER['REQUEST_METHOD'])"))
  386. return untyped __php__("$_SERVER['REQUEST_METHOD']");
  387. else
  388. return null;
  389. }
  390. public static var isModNeko(default,null) : Bool;
  391. static function __init__() {
  392. isModNeko = !php.Lib.isCli();
  393. }
  394. }