PageRenderTime 41ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/haxe/std/php/Web.hx

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