BaseHandler.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. using BizCom;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Reflection;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Web;
  10. using Utils;
  11. namespace SiteCore.Handler
  12. {
  13. public class BaseHandler
  14. {
  15. public HttpContext con = null;
  16. public static readonly Regex mailReg = new Regex(@"^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$");
  17. public static readonly Regex mobileReg = new Regex(@"^(1)[0-9]{10}$");
  18. public static readonly Regex pwdReg = new Regex(@"^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,20}$");
  19. public static readonly Regex nnReg = new Regex(@"^[\u4E00-\u9FA5A-Za-z0-9_]+$");
  20. public static readonly Regex nameReg = new Regex(@"^([\u4e00-\u9fa5]+|([a-zA-Z]+\s?)+)$");
  21. public bool successFlag = false;
  22. public int labPtime = 15;
  23. public int ex_psize = 0;
  24. public DataTable ex_dtable = null;
  25. public BaseHandler()
  26. {
  27. CommonHelper.PageExpires();
  28. /*
  29. //上次请求的URL是否存在
  30. if (HttpContext.Current.Request.UrlReferrer != null)
  31. {
  32. string host = HttpContext.Current.Request.UrlReferrer.Host;
  33. if (host.IndexOf("csbq.cn") > 0)
  34. {
  35. }
  36. else
  37. {
  38. returnErrorMsg("服务器错误!");
  39. HttpContext.Current.Response.End();
  40. }
  41. }
  42. else
  43. {
  44. returnErrorMsg("服务器错误!");
  45. HttpContext.Current.Response.End();
  46. }*/
  47. }
  48. public static Dictionary<int, string> OpenCache = new Dictionary<int, string>();
  49. private static readonly List<int> userKeyList = new List<int>();
  50. private static readonly object usercache_Flag = 1;
  51. public static string GetCacheOpenId(int key)
  52. {
  53. if (!userKeyList.Contains(key) && !OpenCache.ContainsKey(key))
  54. {
  55. lock (usercache_Flag)
  56. {
  57. if (OpenCache.Count > 500)
  58. {
  59. OpenCache.Remove(userKeyList[userKeyList.Count - 1]);
  60. userKeyList.RemoveAt(userKeyList.Count - 1);
  61. }
  62. string value = SUser.GetOpenId(key);
  63. OpenCache.Add(key, value);
  64. userKeyList.Add(key);
  65. return value;
  66. }
  67. }
  68. else
  69. {
  70. return OpenCache[key];
  71. }
  72. }
  73. #region private
  74. public int getAppUserId()
  75. {
  76. if (UrlPostParmsCheck("uid"))
  77. {
  78. return getDecodeInt("uid");
  79. }
  80. return 0;
  81. }
  82. public void conWrite(string msg)
  83. {
  84. con.Response.Write(msg);
  85. }
  86. public void conSuccess(string msg)
  87. {
  88. con.Response.Write("{\"res\":1,\"msg\":\"" + msg + "\"}");
  89. }
  90. public void conSuccess(string msg, string ext)
  91. {
  92. con.Response.Write("{\"res\":1,\"ext\":[" + ext + "],\"msg\":\"" + msg + "\"}");
  93. }
  94. public void conSuccessData(string msg, string ext)
  95. {
  96. con.Response.Write("{\"res\":1,\"data\":" + ext + ",\"msg\":\"" + msg + "\"}");
  97. }
  98. public void conError(string msg)
  99. {
  100. con.Response.Write("{\"res\":0,\"msg\":\"" + msg + "\"}");
  101. }
  102. public void conLoginError(string msg)
  103. {
  104. con.Response.Write("{\"res\":9,\"msg\":\"" + msg + "\"}");
  105. }
  106. public void conGridJson(object total, string json)
  107. {
  108. con.Response.Write("{" + string.Format("\"res\":1,\"total\":{0},\"data\":{1}", total, json) + "}");
  109. }
  110. public int getDecodeInt(string p)
  111. {
  112. string id = GetPostString(p);
  113. if (id == "") return 0;
  114. return Convert.ToInt32(SecurityHelper.DecodingBase64(id));
  115. }
  116. public void ReturnJsonMsg(string sType, string sMsg)
  117. {
  118. string json = "\"type\":\"{0}\",\"result\":\"{1}\"";
  119. HttpContext.Current.Response.Write("{" + string.Format(json, sType, sMsg) + "}");
  120. }
  121. public void ReturnSuccess(string sContent)
  122. {
  123. string json = "\"type\":\"success\",\"result\":{0}";
  124. HttpContext.Current.Response.Write("{" + string.Format(json, sContent) + "}");
  125. }
  126. public void ReturnSuccess(string sContent, string con2)
  127. {
  128. string json = "\"type\":\"success\",\"result\":{0},\"result2\":{1}";
  129. HttpContext.Current.Response.Write("{" + string.Format(json, sContent) + "}");
  130. }
  131. //接口用的!!!
  132. public void ReturnSuccesss(string sContent)
  133. {
  134. string json = "\"code\":\"0\",\"result\":{0}";
  135. HttpContext.Current.Response.Write("{" + string.Format(json, sContent) + "}");
  136. }
  137. #endregion
  138. /// <summary>
  139. /// 解密
  140. /// </summary>
  141. /// <param name="pToDecrypt">要解密的以Base64</param>
  142. /// <param name="sKey">密钥,且必须为8位</param>
  143. /// <returns>已解密的字符串</returns>
  144. public static string DesDecryptAndroid(string pToDecrypt, string sKey)
  145. {
  146. //转义特殊字符
  147. pToDecrypt = pToDecrypt.Replace("-", "+");
  148. pToDecrypt = pToDecrypt.Replace("_", "/");
  149. pToDecrypt = pToDecrypt.Replace("~", "=");
  150. byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
  151. using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
  152. {
  153. des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
  154. des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
  155. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  156. using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
  157. {
  158. cs.Write(inputByteArray, 0, inputByteArray.Length);
  159. cs.FlushFinalBlock();
  160. cs.Close();
  161. }
  162. string str = Encoding.UTF8.GetString(ms.ToArray());
  163. ms.Close();
  164. return str;
  165. }
  166. }
  167. public static int ConvertDateTimeInt(System.DateTime time)
  168. {
  169. System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
  170. return (int)(time - startTime).TotalSeconds;
  171. }
  172. public DataStruct GetUCenterStruct()
  173. {
  174. DataStruct dStruct = new DataStruct();
  175. dStruct.CurrentPage = GetInt("pi") + 1;
  176. int ps = GetInt("ps");
  177. dStruct.PageSize = (ps == 0 ? 5 : ps);
  178. return dStruct;
  179. }
  180. public DataStruct GetStruct()
  181. {
  182. DataStruct dStruct = new DataStruct();
  183. dStruct.CurrentPage = GetInt("pageIndex") + 1;
  184. int ps = GetInt("pageSize");
  185. dStruct.PageSize = (ps == 0 ? 20 : ps);
  186. return dStruct;
  187. }
  188. public DataStruct GetPostStruct()
  189. {
  190. DataStruct dStruct = new DataStruct();
  191. if (ex_psize > 0) dStruct.isExport = true;
  192. dStruct.CurrentPage = GetPostInt("pageIndex") + 1;
  193. int ps = GetPostInt("pageSize");
  194. if (ex_psize > 0) dStruct.PageSize = ex_psize;
  195. else dStruct.PageSize = (ps == 0 ? 20 : ps);
  196. return dStruct;
  197. }
  198. public void writeGridJson(object total, string json)
  199. {
  200. con.Response.Write("{" + string.Format("\"total\":{0},\"data\":{1}", total, json) + "}");
  201. }
  202. public void writeGridDataTableJson(object total, DataTable dt)
  203. {
  204. if (ex_psize > 0) { ex_dtable = dt; return; }
  205. con.Response.Write("{" + string.Format("\"total\":{0},\"data\":{1}", total, Utils.Serialization.JsonString.DataTable2MiniAjaxJson(dt)) + "}");
  206. }
  207. public void writeGridDataViewJson(object total, DataView dv)
  208. {
  209. if (ex_psize > 0) { ex_dtable = dv.ToTable(); return; }
  210. con.Response.Write("{" + string.Format("\"total\":{0},\"data\":{1}", total, Utils.Serialization.JsonString.DataView2MiniAjaxJson(dv)) + "}");
  211. }
  212. private WebUser _currentUser = null;
  213. //获取用户数据
  214. public WebUser CurrentUser
  215. {
  216. get
  217. {
  218. if (_currentUser == null)
  219. _currentUser = WebUser.GetUser();
  220. return _currentUser;
  221. }
  222. }
  223. public string PKey
  224. {
  225. get
  226. {
  227. if (CurrentUser == null) return "";
  228. if (CurrentUser.User.State == 5) return "admin";
  229. return CurrentUser.UserPost.PostID.ToString();
  230. }
  231. }
  232. public void ReturnLoginMsg(string sMsg)
  233. {
  234. successFlag = true;
  235. CommonHelper.ReturnJsonMsg("login", sMsg);
  236. }
  237. public void ReturnUserMsg(string sMsg)
  238. {
  239. successFlag = true;
  240. CommonHelper.ReturnJsonMsg("user", sMsg);
  241. }
  242. public void returnErrorMsg(string msg)
  243. {
  244. successFlag = true;
  245. CommonHelper.ReturnJsonMsg("error", msg == "" ? "操作发生错误" : msg);
  246. }
  247. public void returnSuccessMsg(string msg)
  248. {
  249. successFlag = true;
  250. CommonHelper.ReturnJsonMsg("success", msg);
  251. }
  252. public void returnSuccess(string content)
  253. {
  254. successFlag = true;
  255. CommonHelper.ReturnSuccess(content);
  256. }
  257. public void ReturnError(string error, string msg)
  258. {
  259. successFlag = true;
  260. CommonHelper.ReturnJsonMsg(error, msg);
  261. }
  262. /// <summary>
  263. /// 检测URL参数是否存在
  264. /// </summary>
  265. /// <param name="parms"></param>
  266. /// <returns></returns>
  267. public static bool UrlParmsCheck(string parms)
  268. {
  269. return CommonHelper.UrlParmsCheck(parms);
  270. }
  271. public static bool UrlPostParmsCheck(string parms)
  272. {
  273. return CommonHelper.UrlPostParmsCheck(parms);
  274. }
  275. public static int GetInt(string param)
  276. {
  277. return CommonHelper.GetInt(param);
  278. }
  279. public static int GetPostInt(string param)
  280. {
  281. return CommonHelper.GetPostInt(param);
  282. }
  283. public static double GetDouble(string param)
  284. {
  285. string v = GetString(param);
  286. if (v == "") return 0;
  287. return Convert.ToDouble(v);
  288. }
  289. public static double GetPostDouble(string param)
  290. {
  291. string v = GetPostString(param);
  292. if (v == "") return 0;
  293. return Convert.ToDouble(v);
  294. }
  295. public static string GetString(string param)
  296. {
  297. string text = CommonHelper.GetString(param);
  298. text = cleanHtml(text);
  299. return text;
  300. }
  301. public static string GetPostString(string param)
  302. {
  303. string text = CommonHelper.GetPostString(param).Trim();
  304. text = cleanHtml(text);
  305. return text;
  306. }
  307. public static String cleanHtml(String htmlText)
  308. {
  309. if (htmlText == null)
  310. return null;
  311. htmlText = htmlText.Trim();
  312. if (htmlText.Length == 0)
  313. return htmlText;
  314. string[] regex = { "expression\\((.*?)\\)", "eval\\((.*?)\\)", "<script[^>]*?>[\\s\\S]*?</script>", "<style[^>]*?>[\\s\\S]*?</style>",
  315. "<!--.*?-->", "<script[^>]*?>", "<!--", "javascript:", "vbscript:","onload(.*?)=" };
  316. for (int i = 0; i < regex.Length; i++)
  317. {
  318. htmlText = Regex.Replace(htmlText, regex[i], "", RegexOptions.IgnoreCase);
  319. }
  320. htmlText = htmlText.Replace("--", "- -").Replace("'", "'").Replace("/*", "/ *");//.Replace("(", "(").Replace(")", ")");
  321. return htmlText;
  322. }
  323. public static int GetDecodeInt(string param)
  324. {
  325. return GetDecodeInt(param, false);
  326. }
  327. public static int GetDecodeInt(string param, bool isPost)
  328. {
  329. string value = null;
  330. if (isPost) value = GetPostString(param);
  331. else value = GetString(param);
  332. if (value.Length < 1) return 0;
  333. return CommonHelper.DecodeInt(value);
  334. }
  335. public static string GetDecodeString(string param)
  336. {
  337. return GetDecodeString(param, false);
  338. }
  339. public static string GetDecodeString(string param, bool isPost)
  340. {
  341. string value = null;
  342. if (isPost) value = GetPostString(param);
  343. else value = GetString(param);
  344. if (value.Length < 1) return "";
  345. return CommonHelper.DecodeString(value);
  346. }
  347. public static IList<int> GetDecodeList(string param)
  348. {
  349. string value = GetString(param);
  350. if (value.Length < 1) return null;
  351. return CommonHelper.DecodeList(value);
  352. }
  353. public string GetDoubleString(object value)
  354. {
  355. if (string.IsNullOrEmpty(value.ToString())) return "";
  356. string db = Convert.ToDouble(value).ToString("F2");
  357. return db.Replace(".00", "");
  358. }
  359. public string GetDoubleString(object value, int num)
  360. {
  361. if (string.IsNullOrEmpty(value.ToString())) return "";
  362. return Convert.ToDouble(value).ToString("N" + num);
  363. }
  364. public string GetShengText(object v)
  365. {
  366. if (v.ToString() == "") return "";
  367. string str = v.ToString();
  368. if (str.Length > 90) return str.Substring(0, 90) + "...";
  369. else return str;
  370. }
  371. public object GetReflectionObject(string className)
  372. {
  373. if (string.IsNullOrEmpty(className)) return null;
  374. string tmpName = "BizCom." + className;
  375. return Assembly.Load("BizCom").CreateInstance(tmpName);
  376. }
  377. /**
  378. * 根据当前系统时间加随机序列来生成订单号
  379. * @return 订单号
  380. */
  381. public static string GenerateOutTradeNo(string tag)
  382. {
  383. var ran = new Random();
  384. return string.Format("{0}{1}{2}", tag, GenerateTimeStamp(), ran.Next(999));
  385. }
  386. /**
  387. * 生成时间戳,标准北京时间,时区为东八区,自1970年1月1日 0点0分0秒以来的秒数
  388. * @return 时间戳
  389. */
  390. public static string GenerateTimeStamp()
  391. {
  392. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  393. return Convert.ToInt64(ts.TotalSeconds).ToString();
  394. }
  395. /**
  396. * 生成随机串,随机串包含字母或数字
  397. * @return 随机串
  398. */
  399. public static string GenerateNonceStr()
  400. {
  401. return Guid.NewGuid().ToString().Replace("-", "");
  402. }
  403. protected string GetDateWhere(string field, string start, string end)
  404. {
  405. if (start != "" || end != "")
  406. {
  407. if (start != "" && end != "")
  408. return string.Format(" (DATEDIFF(d,'{0}',{2})>=0 and DATEDIFF(d,'{1}',{2})<=0 )", start, end, field);
  409. else if (start != "")
  410. return string.Format(" {1}>='{0}'", start, field);
  411. else
  412. return string.Format(" dateDiff(d,{1},'{0}')=0 ", end, field);
  413. }
  414. return "";
  415. }
  416. protected string GetDateMinuteWhere(string field, string start, string end)
  417. {
  418. if (start != "" || end != "")
  419. {
  420. if (start != "" && end != "")
  421. return string.Format(" (DATEDIFF(n,'{0}',{2})>=0 and DATEDIFF(n,'{1}',{2})<=0 )", start, end, field);
  422. else if (start != "")
  423. return string.Format(" {1}>='{0}'", start, field);
  424. else
  425. return string.Format(" dateDiff(d,{1},'{0}')=0 ", end, field);
  426. }
  427. return "";
  428. }
  429. public virtual bool IsReusable
  430. {
  431. get
  432. {
  433. return false;
  434. }
  435. }
  436. }
  437. }