關閉
標題:include.cs 2020
內容:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web;
using System.Globalization;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Configuration;
using System.Net;
namespace utility
{
public class myinclude : System.Web.Services.WebService
{
public myinclude()
{
}
public string strip_tags(string html_data)
{
//去除 html tag
Regex regHtml = new System.Text.RegularExpressions.Regex("<[^>]*>");
string s = regHtml.Replace(html_data, "");
return s;
}
//大小寫
public string strtoupper(string input)
{
return input.ToUpper();
}
public long filemtime(string filename)
{
if (!is_file(filename))
{
return -1;
}
DateTime dt = File.GetLastWriteTime(filename);
return Convert.ToInt64(strtotime(dt.ToString("yyyy-MM-dd HH:mm:ss")));
}
public string strtolower(string input)
{
return input.ToLower();
}
public string addslashes(string value)
{
return value.Replace("'", "\'").Replace("\"", "\\\"");
}
public string stripslashes(string value)
{
return value.Replace("\\'", "'").Replace("\\\"", "\"");
}
//public void alert(string value)
//{
// value = jsAddSlashes(value);
// echo("<script language='javascript'>alert('" + value + "');</script>");
//}
public void echo(double value)
{
echo(value.ToString());
}
public void echo(long value)
{
echo(value.ToString());
}
public void echo(int value)
{
echo(value.ToString());
}
public void echo(string value)
{
//System.Web.HttpContext.Current.Response.Write(value);
HttpContext.Current.Response.Write(HttpUtility.HtmlEncode(value));
}
public void downloadHeader(string filename)
{
//HttpContext.Current.Response.Headers.Clear();
HttpContext.Current.Response.AppendHeader("ContentType", "application/octet-stream");
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
}
//取得使用者IP
public string ip()
{
string ip = "";
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
{
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] == null)
{
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"] != null)
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"].ToString();
}
else
{
if (System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
}
}
}
else
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
}
else if (System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
}
return ip;
}
//UnixTimeToDateTime
public DateTime UnixTimeToDateTime(string text)
{
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
// Add the number of seconds in UNIX timestamp to be converted.
dateTime = dateTime.AddSeconds(Convert.ToDouble(text));
return dateTime;
}
//仿php的date
public string time()
{
return strtotime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}
public string date()
{
return date("Y-m-d H:i:s", strtotime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
}
public string date(string format)
{
return date(format, strtotime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
}
public string date(string format, string unixtimestamp)
{
DateTime tmp = UnixTimeToDateTime(unixtimestamp);
tmp = tmp.AddHours(+8);
switch (format)
{
case "Y-m-d H:i:s":
return tmp.ToString("yyyy-MM-dd HH:mm:ss");
case "Y-m-d_H_i_s":
return tmp.ToString("yyyy-MM-dd_HH_mm_ss");
case "Y-m-d":
return tmp.ToString("yyyy-MM-dd");
case "H:i:s":
return tmp.ToString("HH:mm:ss");
case "Y-m-d H:i":
return tmp.ToString("yyyy-MM-dd HH:mm");
case "w":
//回傳week, sun =0 , sat = 6, mon=1.....
return Convert.ToInt16(tmp.DayOfWeek).ToString();
case "Y":
return tmp.ToString("yyyy");
case "m":
return tmp.ToString("MM");
case "d":
return tmp.ToString("dd");
case "H":
return tmp.ToString("HH");
case "i":
return tmp.ToString("mm");
case "s":
return tmp.ToString("ss");
}
return "";
}
//strtotime 轉換成 Unix time
public string strtotime(string value)
{
//create Timespan by subtracting the value provided from
//the Unix Epoch
TimeSpan span = (Convert.ToDateTime(value) - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
//return the total seconds (which is a UNIX timestamp)
return span.TotalSeconds.ToString();
}
public string strtotime(DateTime value)
{
//create Timespan by subtracting the value provided from
//the Unix Epoch
TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
//return the total seconds (which is a UNIX timestamp)
return span.TotalSeconds.ToString();
}
//javascript用的吐js資料
public string jsAddSlashes(string value)
{
value = value.Replace("\\", "\\\\");
value = value.Replace("\n", "\\n");
value = value.Replace("\r", "\\r");
value = value.Replace("\"", "\\\"");
value = value.Replace("&", "\\x26");
value = value.Replace("<", "\\x3C");
value = value.Replace(">", "\\x3E");
return value;
}
public string b2s(byte[] input)
{
return System.Text.Encoding.UTF8.GetString(input);
}
public byte[] s2b(string input)
{
return System.Text.Encoding.UTF8.GetBytes(input);
}
private byte[] ReadStream(Stream stream, int initialLength)
{
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
{
read += chunk;
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte == -1)
{
return buffer;
}
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
byte[] bytes = new byte[read];
Array.Copy(buffer, bytes, read);
return bytes;
}
public string base64_encode(byte[] data)
{
//base64編碼
return Convert.ToBase64String(data);
}
public byte[] base64_decode(string data)
{
//base64解碼
return Convert.FromBase64String(data);
}
public string htmlspecialchars(string input)
{
return HttpContext.Current.Server.HtmlEncode(input);
}
public string htmlspecialchars_decode(string input)
{
// WebUtility.HtmlDecode(input);
return HttpContext.Current.Server.HtmlDecode(input);
}
public Dictionary<string, object> getGET_POST(string inputs, string method)
{
/*
string GETS_STRING="mode,id";
Dictionary<string, object> get = x.getGET_POST(GETS_STRING, "GET");
string vv=x.print_r(get,0);
foreach (string a in get.Keys)
{
Response.Write(a+":"+get[a]+"<br>");
}
sample:
string GETS_STRING="mode,id";
Dictionary<string, object> get = x.getGET_POST(GETS_STRING, "GET");
string POSTS_STRING ="abc,b,s_a,s_b[],ddd";
Dictionary<string, object> post = x.getGET_POST(POSTS_STRING, "POST");
string q = x.print_r(get, 0);
string p = x.print_r(post, 0);
Response.Write("<pre>" + q + "<br>" + p + "</pre>");
Response.Write("aaaaaaa->" + post["s_a"]+"<br>");
Response.Write("aaaaaab->" + post["s_b[]"] + "<br>");
*
*/
method = method.ToUpper();
Dictionary<string, object> get_post = new Dictionary<string, object>();
switch (method)
{
case "GET":
foreach (string k in inputs.Split(','))
{
if (this.Context.Request.QueryString[k] != null)
{
get_post[k] = addslashes(this.Context.Request.QueryString[k]);
}
else
{
get_post[k] = "";
}
}
break;
case "POST":
foreach (string k in inputs.Split(','))
{
if (this.Context.Request.Form[k] != null)
{
if (this.Context.Request.Form[k].Length != 1)
{
//暫時先這樣,以後再修= =
get_post[k] = htmlspecialchars(addslashes(this.Context.Request.Form[k]));
}
else
{
get_post[k] = htmlspecialchars(addslashes(this.Context.Request.Form[k]));
}
}
else
{
get_post[k] = "";
}
}
break;
}
return get_post;
}
/*public int insertSQL(string table, Dictionary<string, string> datas)
{
string SQL = "";
string[] field=new string[datas.Keys.Count];
string[] data=new string[datas.Keys.Count];
int i=0;
foreach (string k in datas.Keys)
{
field[i]=k;
data[i]=addslashes(stripslashes(datas[k].ToString()));
i++;
}
SQL = string.Format(@"
INSERT INTO {0}({1})VALUES(N'{2}');",
table,
implode(",", field),
implode("',N'", data));
SqlCommand cmd = new SqlCommand(SQL, conn);
cmd.ExecuteNonQuery();
Dictionary<int, Dictionary<string, string>> ro = selectSQL("SELECT @@IDENTITY AS LastID");
int last_id=Convert.ToInt32(ro[0]["LastID"]);
return last_id;
}*/
/*public Dictionary<int, Dictionary<string, string>> SQLTOARRAY(SqlCommand cmd)
{
int i = 0;
SqlDataReader dr = cmd.ExecuteReader();
Dictionary<int, Dictionary<string, string>> datas = new Dictionary<int, Dictionary<string, string>>();
while (dr.Read())
{
Dictionary<string, string> data_list = new Dictionary<string, string>();
for (int j = 0; j < dr.FieldCount; j++)
{
data_list[dr.GetName(j)] = dr[dr.GetName(j)].ToString();
}
datas[i] = new Dictionary<string, string>(data_list);
i++;
}
dr.Close();
return datas;
}
*/
/*public long insertSQL(string table, Dictionary<string, string> datas, bool isNeedLastID = false)
{
string SQL = "";
string[] field = new string[datas.Keys.Count];
string[] data = new string[datas.Keys.Count];
string[] field_marks = new string[datas.Keys.Count];
string[] question_marks = new string[datas.Keys.Count];
int i = 0;
foreach (string k in datas.Keys)
{
field[i] = k;
data[i] = datas[k].ToString();
field_marks[i] = "@FIELD_" + i;
question_marks[i] = "@DATA_" + i;
i++;
}
SQL = string.Format(@"
INSERT INTO {0}({1})VALUES({2});",
"@TABLE",
implode(",", field_marks),
implode(",", question_marks));
//SQL = SafeSqlLiteral(SQL);
SqlCommand cmd = new SqlCommand(SQL, conn);
List<SqlParameter> param_now = new List<SqlParameter>();
param_now.Clear();
cmd.Parameters.AddWithValue("@TABLE", table);
i = 0;
foreach (string k in datas.Keys)
{
cmd.Parameters.AddWithValue(field_marks[i], k);
i++;
}
for (i = 0; i < data.Length; i++)
{
cmd.Parameters.AddWithValue(question_marks[i], data[i]);
}
cmd.ExecuteNonQuery();
if (isNeedLastID)
{
List<string> arr = new List<string>();
cmd = new SqlCommand("SELECT @@IDENTITY AS LastID", conn);
Dictionary<int, Dictionary<string, string>> ro = SQLTOARRAY(cmd);
int last_id = Convert.ToInt32(ro[0]["LastID"]);
return last_id;
}
else
{
return -1;
}
}
*/
/*public Dictionary<int, Dictionary<string, string>> selectSQL(string SQL)
{
//SqlConnection conn = new SqlConnection(connString);
//conn.Open();
SqlCommand cmd = new SqlCommand(SQL, conn);
SqlDataReader dr = cmd.ExecuteReader();
int i = 0;
Dictionary<int, Dictionary<string, string>> datas = new Dictionary<int, Dictionary<string, string>>();
while (dr.Read())
{
Dictionary<string, string> data_list = new Dictionary<string, string>();
//label_3wa.Text = dr["Codecnt"].ToString();
for (int j = 0; j < dr.FieldCount; j++)
{
data_list[dr.GetName(j)] = dr[dr.GetName(j)].ToString();
}
datas[i] = new Dictionary<string, string>(data_list);
i++;
}
dr.Close();
return datas;
}*/
/*public void updateSQL(string table, Dictionary<string, string> datas, string MasterKey, string MasterKeyValue)
{
string[] tmp = new string[datas.Keys.Count];
int i = 0;
foreach (string k in datas.Keys)
{
tmp[i] = k + "=N'" + datas[k] + "'"; //N for Nvachar...Orz
i++;
}
String SQL = @"UPDATE " + table + " SET " + implode(",", tmp) + " WHERE " + MasterKey + "=N'" + MasterKeyValue + "' ";
//file_put_contents("c:\\log.txt", SQL);
SqlCommand cmd = new SqlCommand(SQL, conn);
cmd.ExecuteNonQuery();
}*/
/*public void deleteSQL(string table, string MasterKey, string MasterKeyValue)
{
String SQL = @"DELETE FROM " + table + " WHERE " + MasterKey + "='" + MasterKeyValue + "' ";
SqlCommand cmd = new SqlCommand(SQL, conn);
cmd.ExecuteNonQuery();
}*/
/*public void execSQL(string SQL)
{
SqlCommand cmd = new SqlCommand(SQL, conn);
cmd.ExecuteNonQuery();
}*/
public string implode(string keyword, string[] arrays)
{
return string.Join(keyword, arrays);
}
public string implode(string keyword, Dictionary<int, string> arrays)
{
string[] tmp = new String[arrays.Keys.Count];
int i = 0;
foreach (int k in arrays.Keys)
{
tmp[i++] = arrays[k];
}
return string.Join(keyword, tmp);
}
public string implode(string keyword, Dictionary<string, string> arrays)
{
string[] tmp = new String[arrays.Keys.Count];
int i = 0;
foreach (string k in arrays.Keys)
{
tmp[i++] = arrays[k];
}
return string.Join(keyword, tmp);
}
public string implode(string keyword, ArrayList arrays)
{
string[] tmp = new String[arrays.Count];
for (int i = 0; i < arrays.Count; i++)
{
tmp[i] = arrays[i].ToString();
}
return string.Join(keyword, tmp);
}
public string[] explode(string keyword, string data)
{
return data.Split(new string[] { keyword }, StringSplitOptions.None);
}
public string[] explode(string keyword, object data)
{
return data.ToString().Split(new string[] { keyword }, StringSplitOptions.None);
}
public string[] explode(string[] keyword, string data)
{
return data.Split(keyword, StringSplitOptions.None);
}
public void exit()
{
System.Web.HttpContext.Current.Response.Flush(); //強制輸出緩衝區資料
System.Web.HttpContext.Current.Response.Clear(); //清除緩衝區的資料
System.Web.HttpContext.Current.Response.End(); //結束資料輸出
//System.Web.HttpContext.Current.Response.StatusCode = 200;
}
public string EscapeUnicode(string input)
{
StringBuilder sb = new StringBuilder(input.Length);
foreach (char ch in input)
{
if (ch <= 0x7f)
sb.Append(ch);
else
sb.AppendFormat(CultureInfo.InvariantCulture, "\\u{0:x4}", (int)ch);
}
return sb.ToString();
}
public string unEscapeUnicode(string input)
{
return Regex.Unescape(input);
}
public string json_encode(object input)
{
return EscapeUnicode(JsonConvert.SerializeObject(input, Formatting.None));
}
public string trim(string input)
{
return input.Trim();
}
public string md5(string str)
{
using (var cryptoMD5 = System.Security.Cryptography.MD5.Create())
{
//將字串編碼成 UTF8 位元組陣列
var bytes = Encoding.UTF8.GetBytes(str);
//取得雜湊值位元組陣列
var hash = cryptoMD5.ComputeHash(bytes);
//取得 MD5
var md5 = BitConverter.ToString(hash)
.Replace("-", String.Empty)
.ToUpper();
return md5;
}
}
public bool deltree(string target_dir)
{
//From : https://dotblogs.com.tw/grepu9/2013/03/20/98267
try
{
bool result = false;
string[] files = Directory.GetFiles(target_dir);
string[] dirs = Directory.GetDirectories(target_dir);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
foreach (string dir in dirs)
{
deltree(dir);
}
Directory.Delete(target_dir, false);
return result;
}
catch (Exception ex)
{
return false;
}
}
public JArray json_decode(string input)
{
input = trim(input);
if (input.Length != 0)
{
if (input.Substring(1, 1) != "[")
{
input = "[" + input + "]";
return (JArray)JsonConvert.DeserializeObject<JArray>(input);
}
else
{
return (JArray)JsonConvert.DeserializeObject<JArray>(input);
}
}
else
{
return null;
}
}
public string getSystemKey(string keyindex)
{
return ConfigurationManager.AppSettings[keyindex];
}
public string dirname(string path)
{
return Directory.GetParent(path).FullName;
}
public bool is_dir(string path)
{
return Directory.Exists(path);
}
public void mkdir(string path)
{
Directory.CreateDirectory(path);
}
public bool is_file(string filepath)
{
return File.Exists(filepath);
}
public string pwd()
{
return dirname(System.Web.HttpContext.Current.Request.PhysicalPath);
}
public bool is_number(string input)
{
int i = 0;
string s = input;
bool result = int.TryParse(s, out i);
return result;
}
public void echoBinary(byte[] value)
{
HttpContext.Current.Response.BinaryWrite(value);
}
public void file_put_contents(string filepath, string input)
{
file_put_contents(filepath, s2b(input), false);
}
public void file_put_contents(string filepath, byte[] input)
{
file_put_contents(filepath, input, false);
}
public void file_put_contents(string filepath, string input, bool isFileAppend)
{
file_put_contents(filepath, s2b(input), isFileAppend);
}
public void file_put_contents(string filepath, byte[] input, bool isFileAppend)
{
switch (isFileAppend)
{
case true:
{
FileStream myFile = null;
if (!is_file(filepath))
{
myFile = File.Open(@filepath, FileMode.Create);
}
else
{
myFile = File.Open(@filepath, FileMode.Append);
}
myFile.Seek(myFile.Length, SeekOrigin.Begin);
myFile.Write(input, 0, input.Length);
myFile.Dispose();
}
break;
case false:
{
FileStream myFile = File.Open(@filepath, FileMode.Create);
myFile.Write(input, 0, input.Length);
myFile.Dispose();
}
break;
}
}
if (url.ToLower().IndexOf("http:") > -1 || url.ToLower().IndexOf("https:") > -1 )
{
// URL
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
HttpWebRequest request = null;
HttpWebResponse response = null;
byte[] byteData = null;
request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 60000;
request.Proxy = null;
request.UserAgent = "user_agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36";
//request.Referer = getSystemKey("HTTP_REFERER");
response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
byteData = ReadStream(stream, 32765);
response.Close();
stream.Close();
return byteData;
}
else
{
/*System.IO.StreamReader sr = new System.IO.StreamReader(url);
string sContents = sr.ReadToEnd();
sr.Close();
return s2b(sContents);
*/
/*FileStream fs = new FileStream(url, FileMode.Open);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
return buffer;
*/
byte[] data;
using (StreamReader sr = new StreamReader(url))
{
using (MemoryStream ms = new MemoryStream())
{
sr.BaseStream.CopyTo(ms);
data = ms.ToArray();
ms.Close();
ms.Dispose();
}
sr.Close();
sr.Dispose();
};
return data;
}
}
}
}