Web.hx 13 KB

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