PageRenderTime 55ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/std/php/Web.hx

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