Web.hx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 function getParamsString() : String {
  186. if(untyped __call__("isset", __var__("_SERVER", "QUERY_STRING")))
  187. return untyped __var__("_SERVER", "QUERY_STRING");
  188. else
  189. return "";
  190. }
  191. /**
  192. Returns all the POST data. POST Data is always parsed as
  193. being application/x-www-form-urlencoded and is stored into
  194. the getParams hashtable. POST Data is maximimized to 256K
  195. unless the content type is multipart/form-data. In that
  196. case, you will have to use [getMultipart] or [parseMultipart]
  197. methods.
  198. **/
  199. public static function getPostData() {
  200. var h = untyped __call__("fopen", "php://input", "r");
  201. var bsize = 8192;
  202. var max = 32;
  203. var data : String = null;
  204. var counter = 0;
  205. while (!untyped __call__("feof", h) && counter < max) {
  206. data += untyped __call__("fread", h, bsize);
  207. counter++;
  208. }
  209. untyped __call__("fclose", h);
  210. return data;
  211. }
  212. /**
  213. Returns an hashtable of all Cookies sent by the client.
  214. Modifying the hashtable will not modify the cookie, use setCookie instead.
  215. **/
  216. public static function getCookies() {
  217. return Lib.hashOfAssociativeArray(untyped __php__("$_COOKIE"));
  218. }
  219. /**
  220. Set a Cookie value in the HTTP headers. Same remark as setHeader.
  221. **/
  222. public static function setCookie( key : String, value : String, ?expire: Date, ?domain: String, ?path: String, ?secure: Bool ) {
  223. var t = expire == null ? 0 : Std.int(expire.getTime()/1000.0);
  224. if(path == null) path = '/';
  225. if(domain == null) domain = '';
  226. if(secure == null) secure = false;
  227. untyped __call__("setcookie", key, value, t, path, domain, secure);
  228. }
  229. static function addPair( name, value ) : String {
  230. if( value == null ) return "";
  231. return "; " + name + value;
  232. }
  233. /**
  234. Returns an object with the authorization sent by the client (Basic scheme only).
  235. **/
  236. public static function getAuthorization() : { user : String, pass : String } {
  237. if(!untyped __php__("isset($_SERVER['PHP_AUTH_USER'])"))
  238. return null;
  239. return untyped {user: __php__("$_SERVER['PHP_AUTH_USER']"), pass: __php__("$_SERVER['PHP_AUTH_PW']")};
  240. }
  241. /**
  242. Get the current script directory in the local filesystem.
  243. **/
  244. public static inline function getCwd() : String {
  245. return untyped __php__('dirname($_SERVER["SCRIPT_FILENAME"])') + "/";
  246. }
  247. /**
  248. Get the multipart parameters as an hashtable. The data
  249. cannot exceed the maximum size specified.
  250. **/
  251. public static function getMultipart( maxSize : Int ) : Hash<String> {
  252. var h = new Hash();
  253. var buf : StringBuf = null;
  254. var curname = null;
  255. parseMultipart(function(p,_) {
  256. if( curname != null )
  257. h.set(curname,buf.toString());
  258. curname = p;
  259. buf = new StringBuf();
  260. maxSize -= p.length;
  261. if( maxSize < 0 )
  262. throw "Maximum size reached";
  263. }, function(str,pos,len) {
  264. maxSize -= len;
  265. if( maxSize < 0 )
  266. throw "Maximum size reached";
  267. buf.addSub(str.toString(),pos,len);
  268. });
  269. if( curname != null )
  270. h.set(curname,buf.toString());
  271. return h;
  272. }
  273. /**
  274. Parse the multipart data. Call [onPart] when a new part is found
  275. with the part name and the filename if present
  276. and [onData] when some part data is readed. You can this way
  277. directly save the data on hard drive in the case of a file upload.
  278. **/
  279. public static function parseMultipart( onPart : String -> String -> Void, onData : Bytes -> Int -> Int -> Void ) : Void {
  280. var a : NativeArray = untyped __var__("_POST");
  281. if(untyped __call__("get_magic_quotes_gpc"))
  282. untyped __php__("reset($a); while(list($k, $v) = each($a)) $a[$k] = stripslashes((string)$v)");
  283. var post = Lib.hashOfAssociativeArray(a);
  284. for (key in post.keys())
  285. {
  286. onPart(key, "");
  287. var v = post.get(key);
  288. onData(Bytes.ofString(v), 0, untyped __call__("strlen", v));
  289. }
  290. if(!untyped __call__("isset", __php__("$_FILES"))) return;
  291. var parts : Array<String> = untyped __call__("new _hx_array",__call__("array_keys", __php__("$_FILES")));
  292. for(part in parts) {
  293. var info : Dynamic = untyped __php__("$_FILES[$part]");
  294. var tmp : String = untyped info['tmp_name'];
  295. var file : String = untyped info['name'];
  296. var err : Int = untyped info['error'];
  297. if(err > 0) {
  298. switch(err) {
  299. case 1: throw "The uploaded file exceeds the max size of " + untyped __call__('ini_get', 'upload_max_filesize');
  300. 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') + ")";
  301. case 3: throw "The uploaded file was only partially uploaded";
  302. case 4: continue; // No file was uploaded
  303. case 6: throw "Missing a temporary folder";
  304. case 7: throw "Failed to write file to disk";
  305. case 8: throw "File upload stopped by extension";
  306. }
  307. }
  308. onPart(part, file);
  309. if ("" != file)
  310. {
  311. var h = untyped __call__("fopen", tmp, "r");
  312. var bsize = 8192;
  313. while (!untyped __call__("feof", h)) {
  314. var buf : String = untyped __call__("fread", h, bsize);
  315. var size : Int = untyped __call__("strlen", buf);
  316. onData(Bytes.ofString(buf), 0, size);
  317. }
  318. untyped __call__("fclose", h);
  319. }
  320. }
  321. }
  322. /**
  323. Flush the data sent to the client. By default on Apache, outgoing data is buffered so
  324. this can be useful for displaying some long operation progress.
  325. **/
  326. public static inline function flush() : Void {
  327. untyped __call__("flush");
  328. }
  329. /**
  330. Get the HTTP method used by the client.
  331. **/
  332. public static function getMethod() : String {
  333. if(untyped __php__("isset($_SERVER['REQUEST_METHOD'])"))
  334. return untyped __php__("$_SERVER['REQUEST_METHOD']");
  335. else
  336. return null;
  337. }
  338. public static var isModNeko(default,null) : Bool;
  339. static function __init__() {
  340. isModNeko = !php.Lib.isCli();
  341. }
  342. }