Web.hx 13 KB

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