Web.hx 12 KB

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