PageRenderTime 26ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/library/haquery/server/Lib.hx

https://code.google.com/p/haquery/
Haxe | 299 lines | 222 code | 44 blank | 33 comment | 39 complexity | a0be0d3c261f5a91c6c777fa916b339e MD5 | raw file
Possible License(s): BSD-3-Clause
  1. package haquery.server;
  2. import haxe.Stack;
  3. import php.Sys;
  4. import php.NativeArray;
  5. import php.Session;
  6. import php.FileSystem;
  7. import php.io.FileOutput;
  8. import php.io.Path;
  9. import php.firePHP.FirePHP;
  10. import haquery.server.HaqInternals;
  11. import haquery.server.HaqConfig;
  12. import haquery.server.HaqRoute;
  13. import haquery.server.HaqBootstrap;
  14. import haquery.server.HaqSystem;
  15. import haquery.server.db.HaqDb;
  16. import haquery.server.HaqProfiler;
  17. import haquery.server.Web;
  18. using haquery.StringTools;
  19. class Lib
  20. {
  21. public static var config = new HaqConfig();
  22. public static var profiler = new HaqProfiler();
  23. /**
  24. * Ajax?
  25. * false => rendering HTML;
  26. * true => calling server event handler.
  27. */
  28. public static var isPostback(default, null) : Bool;
  29. static var startTime : Float;
  30. public static function getParamsString()
  31. {
  32. var s = Web.getParamsString();
  33. var re = ~/route=[^&]*/g;
  34. s = re.replace(s, '');
  35. return haquery.StringTools.trim(s, '&');
  36. }
  37. static public function run() : Void
  38. {
  39. try
  40. {
  41. profiler.begin("HAQUERY");
  42. startTime = Date.now().getTime();
  43. haxe.Log.trace = Lib.trace;
  44. isPostback = php.Web.getParams().get('HAQUERY_POSTBACK') != null;
  45. var route = new HaqRoute(Web.getParams().get('route'));
  46. loadBootstraps(route.path);
  47. if (Lib.config.autoSessionStart)
  48. {
  49. Session.start();
  50. }
  51. if (config.autoDatabaseConnect && config.db!=null && config.db.type!=null && config.db.type!="")
  52. {
  53. HaqDb.connect(Lib.config.db);
  54. }
  55. if (route.routeType == HaqRouteType.file)
  56. {
  57. untyped __call__('require', route.path);
  58. }
  59. else
  60. {
  61. var system = new HaqSystem(route, isPostback);
  62. }
  63. profiler.end();
  64. profiler.traceResults();
  65. }
  66. catch (e:Dynamic)
  67. {
  68. haquery.server.Lib.traceException(e);
  69. }
  70. }
  71. static public function redirect(url:String) : Void
  72. {
  73. if (Lib.isPostback) HaqInternals.addAjaxResponse("haquery.client.Lib.redirect('" + StringTools.addcslashes(url) + "');");
  74. else php.Web.redirect(url);
  75. }
  76. static public function reload() : Void
  77. {
  78. if (Lib.isPostback) HaqInternals.addAjaxResponse("window.location.reload(true);");
  79. else redirect(php.Web.getURI());
  80. }
  81. #if debug
  82. static public function assert(e:Bool, errorMessage:String=null, ?pos : haxe.PosInfos) : Void
  83. {
  84. if (!e)
  85. {
  86. if (errorMessage == null) errorMessage = "ASSERT";
  87. throw errorMessage + " in " + pos.fileName + ' at line ' + pos.lineNumber;
  88. }
  89. }
  90. #else
  91. static public inline function assert(e:Bool, errorMessage:String=null, ?pos : haxe.PosInfos) : Void
  92. {
  93. }
  94. #end
  95. static function trace(v:Dynamic, ?pos : haxe.PosInfos) : Void
  96. {
  97. if (Lib.config.filterTracesByIP != '')
  98. {
  99. if (Lib.config.filterTracesByIP!=Web.getClientIP()) return;
  100. }
  101. var text = '';
  102. if (Type.getClassName(Type.getClass(v)) == 'String') text += v;
  103. else
  104. if (v!=null)
  105. {
  106. text += "DUMP\n";
  107. var dump = ''; untyped __php__("ob_start(); var_dump($v); $dump = ob_get_clean();");
  108. text += StringTools.stripTags(dump);
  109. }
  110. if (text != '')
  111. {
  112. var isHeadersSent : Bool = untyped __call__('headers_sent');
  113. if (!isHeadersSent)
  114. {
  115. try
  116. {
  117. if (text.startsWith('HAXE EXCEPTION'))
  118. {
  119. FirePHP.getInstance(true).error(text);
  120. }
  121. else if (text.startsWith('HAQUERY'))
  122. {
  123. FirePHP.getInstance(true).info(text);
  124. }
  125. else
  126. {
  127. text = pos.fileName + ":" + pos.lineNumber + " : " + text;
  128. FirePHP.getInstance(true).warn(text);
  129. }
  130. }
  131. catch (s:String)
  132. {
  133. text += "\n\nFirePHP exception: " + s;
  134. }
  135. }
  136. else
  137. {
  138. php.Lib.println("<script>if (console) console.debug(decodeURIComponent(\"" + StringTools.urlEncode("SERVER " + text) + "\"));</script>");
  139. }
  140. }
  141. if (!FileSystem.exists(HaqDefines.folders.temp))
  142. {
  143. FileSystem.createDirectory(HaqDefines.folders.temp);
  144. }
  145. var f : FileOutput = php.io.File.append(HaqDefines.folders.temp + "/haquery.log", false);
  146. if (f != null)
  147. {
  148. f.writeString(text != '' ? StringTools.format('%.3f', (Date.now().getTime() - startTime) / 1000.0) + " " + StringTools.replace(text, "\n", "\r\n\t") + "\r\n" : "\r\n");
  149. f.close();
  150. }
  151. }
  152. /**
  153. * Load bootstrap files from current folder to relativePath.
  154. */
  155. private static function loadBootstraps(relativePath:String) : Void
  156. {
  157. var folders = StringTools.trim(relativePath, '/').split('/');
  158. for (i in 1...folders.length + 1)
  159. {
  160. var className = folders.slice(0, i).join('.') + '.Bootstrap';
  161. var clas : Class<HaqBootstrap> = untyped Type.resolveClass(className);
  162. if (clas != null)
  163. {
  164. var b : HaqBootstrap = Type.createInstance(clas, []);
  165. b.init(config);
  166. }
  167. }
  168. }
  169. /**
  170. * Disk path to virtual path (url).
  171. */
  172. static public function path2url(path:String) : String
  173. {
  174. var realPath = FileSystem.fullPath('').replace("\\", '/') + '/' + path.trim('/\\');
  175. var rootPath:String = StringTools.replace(Web.getDocumentRoot(), "\\", '/');
  176. if (!StringTools.startsWith(realPath, rootPath))
  177. {
  178. throw "Can't resolve path '" + path + "' with realPath = '" + realPath + "' and rootPath = '" + rootPath + "'.";
  179. }
  180. var n = rootPath.length;
  181. var s = realPath.substr(n);
  182. return '/' + s.ltrim('/');
  183. }
  184. static function traceException(e:Dynamic) : Void
  185. {
  186. var text = "HAXE EXCEPTION: " + Std.string(e) + "\n"
  187. + "Stack trace:" + Stack.toString(Stack.exceptionStack()).replace('\n', '\n\t');
  188. var nativeStack : Array<Hash<Dynamic>> = php.Stack.nativeExceptionStack();
  189. assert(nativeStack != null);
  190. text += "\n\n";
  191. text += "NATIVE EXCEPTION: " + Std.string(e) + "\n";
  192. text += "Stack trace:\n";
  193. for (row in nativeStack)
  194. {
  195. text += "\t";
  196. if (row.exists('class')) text += row.get('class') + row.get('type');
  197. text += row.get('function');
  198. if (row.exists('file'))
  199. {
  200. text += " in " + row.get('file') + " at line " + row.get('line') + "\n";
  201. }
  202. else
  203. {
  204. text += "\n";
  205. }
  206. }
  207. trace(text);
  208. }
  209. static public function mail(email:String, fromEmail:String, subject:String, message:String) : Bool
  210. {
  211. var headers : String = "MIME-Version: 1.0\r\n";
  212. headers += "Content-Type: text/plain; charset=utf-8\r\n";
  213. headers += "Date: " + Date.now() + "\r\n";
  214. headers += "From: " + fromEmail + "\r\n";
  215. headers += "X-Mailer: My Send E-mail\r\n";
  216. return untyped __call__("mail", email, subject, message, headers);
  217. }
  218. ////////////////////////////////////////////////
  219. // official methods
  220. ////////////////////////////////////////////////
  221. /**
  222. Print the specified value on the default output.
  223. **/
  224. public static inline function print( v : Dynamic ) : Void { return php.Lib.print(v); }
  225. /**
  226. Print the specified value on the default output followed by a newline character.
  227. **/
  228. public static inline function println( v : Dynamic ) : Void { return php.Lib.println(v); }
  229. public static inline function dump(v : Dynamic) : Void { return php.Lib.dump(v); }
  230. /**
  231. Serialize using native PHP serialization. This will return a Binary string that can be
  232. stored for long term usage.
  233. **/
  234. public static inline function serialize( v : Dynamic ) : String { return php.Lib.serialize(v); }
  235. /**
  236. Unserialize a string using native PHP serialization. See [serialize].
  237. **/
  238. public static inline function unserialize( s : String ) : Dynamic { return php.Lib.unserialize(s); }
  239. public static inline function extensionLoaded(name : String) { return php.Lib.extensionLoaded(name); }
  240. public static inline function isCli() : Bool { return php.Lib.isCli(); }
  241. public static inline function printFile(file : String) { return php.Lib.printFile(file); }
  242. public static inline function toPhpArray(a : Array<Dynamic>) : NativeArray { return php.Lib.toPhpArray(a); }
  243. public static inline function toHaxeArray(a : NativeArray) : Array<Dynamic> { return php.Lib.toHaxeArray(a); }
  244. public static inline function hashOfAssociativeArray<T>(arr : NativeArray) : Hash<T> { return php.Lib.hashOfAssociativeArray(arr); }
  245. public static inline function associativeArrayOfHash(hash : Hash<Dynamic>) : NativeArray { return php.Lib.associativeArrayOfHash(hash); }
  246. /**
  247. For neko compatibility only.
  248. **/
  249. public static inline function rethrow( e : Dynamic ) { return php.Lib.rethrow(e); }
  250. public static inline function getClasses() { return php.Lib.getClasses(); }
  251. /**
  252. * Loads types defined in the specified directory.
  253. */
  254. public static inline function loadLib(pathToLib : String) : Void { return php.Lib.loadLib(pathToLib); }
  255. }