Web.hx 11 KB

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