本文整理汇总了C#中Connector.Disconnect方法的典型用法代码示例。如果您正苦于以下问题:C# Connector.Disconnect方法的具体用法?C# Connector.Disconnect怎么用?C# Connector.Disconnect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Connector
的用法示例。
在下文中一共展示了Connector.Disconnect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: pageArticle_View_Delete
public static void pageArticle_View_Delete(ref string pluginid, ref Connector conn, ref Misc.PageElements pageElements, ref HttpRequest request, ref HttpResponse response, ref bool permCreate, ref bool permDelete, ref bool permPublish, ref bool owner, ref StringBuilder content, ref ResultRow article)
{
string error = null;
string captcha = request.Form["captcha"];
if (request.Form["confirm"] != null && captcha != null)
{
if (!Common.Validation.validCaptcha(captcha))
error = "Incorrect captcha verification code!";
else
{
// Delete the article
conn.Query_Execute("DELETE FROM articles WHERE articleid='" + Utils.Escape(article["articleid"]) + "';" + insertEvent(RecentChanges_EventType.Deleted, HttpContext.Current.User.Identity.Name, article["articleid"], article["threadid"]));
// Check if any more articles exist and if a current article is set
ResultRow thread = conn.Query_Read("SELECT (SELECT articleid_current FROM articles_thread WHERE threadid='" + Utils.Escape(article["threadid"]) + "') AS current_article, (SELECT COUNT('') FROM articles WHERE threadid='" + Utils.Escape(article["threadid"]) + "') AS articles_remaining")[0];
StringBuilder finalQuery = new StringBuilder();
if (thread["current_article"].Length == 0)
{
// Set a new article
if (int.Parse(thread["articles_remaining"]) == 0)
// Delete the thread
finalQuery.Append("DELETE FROM articles_thread WHERE threadid='" + Utils.Escape(article["threadid"]) + "';");
else
// Set a new article
finalQuery.Append("UPDATE articles_thread SET articleid_current=(SELECT articleid FROM articles WHERE published='1' AND threadid='" + Utils.Escape(article["threadid"]) + "' ORDER BY articleid DESC LIMIT 1) WHERE threadid='" + Utils.Escape(article["threadid"]) + "';");
}
// Append tags cleanup query
finalQuery.Append(QUERY_TAGS_CLEANUP);
// Finish up
conn.Query_Execute(finalQuery.ToString());
conn.Disconnect();
response.Redirect(pageElements["URL"] + "/articles", true);
}
}
// Display form
if (error != null)
content.Append(
Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", HttpUtility.HtmlEncode(error))
);
content.Append(
Core.templates["articles"]["article_delete"]
);
}
示例2: pageAdmin
/// <summary>
/// Administration page, used for managing various core functions of the CMS as well as plugins.
/// </summary>
/// <param name="pluginid"></param>
/// <param name="conn"></param>
/// <param name="pageElements"></param>
/// <param name="request"></param>
/// <param name="response"></param>
private static void pageAdmin(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
{
// Attach CSS file
Misc.Plugins.addHeaderCSS(pageElements["URL"] + "/Content/CSS/AdminPanel.css", ref pageElements);
// Check user has admin access
#if BASIC_SITE_AUTH // We'll use BSA's authentication if available
Result authCheck = conn.Query_Read("SELECT g.access_admin FROM bsa_users AS u LEFT OUTER JOIN bsa_user_groups AS g ON g.groupid=u.groupid WHERE u.userid='" + Utils.Escape(HttpContext.Current.User.Identity.Name) + "'");
if (authCheck.Rows.Count != 1 || !authCheck[0]["access_admin"].Equals("1"))
return;
#else // No authentication available; we'll require the user to login using the token stored in the local directory
if (currentToken == null) generateAuthToken(pluginid, conn);
// Check the user has been authenticated
if (HttpContext.Current.Session["ADMIN_PANEL_AUTH"] == null || (string)HttpContext.Current.Session["ADMIN_PANEL_AUTH"] != currentToken)
{
// Check for postback
string error = null;
string captcha = request.Form["captcha"];
string token = request.Form["token"];
if (captcha != null && token != null)
{
if (!Common.Validation.validCaptcha(captcha))
error = "Incorrect captcha verification code!";
else if (token != currentToken)
error = "Incorrect token!";
else
{
// Redirect back to this page - for security
HttpContext.Current.Session["ADMIN_PANEL_AUTH"] = token;
conn.Disconnect();
response.Redirect(pageElements["URL"] + "/admin");
}
}
// Display form
pageElements["TITLE"] = "Admin - Token Authentication";
pageElements["CONTENT"] = Core.templates["admin_panel"]["token_login"]
.Replace("%ERROR%", error != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", HttpUtility.HtmlEncode(error)) : string.Empty);
return;
}
#endif
// Handle the request and build the content based on the selected page
string pageid = request.QueryString["1"];
if (pageid == null)
{
// Check if to delete warning messages
if (request.QueryString["wipe"] != null && Common.AntiCSRF.isValidTokenCookie(request, response))
conn.Query_Execute("DELETE FROM admin_alerts;");
// Build warning messages
StringBuilder alerts = new StringBuilder(Core.templates["admin_panel"]["alert_header"]);
Result alertData = conn.Query_Read("SELECT message, datetime FROM admin_alerts ORDER BY datetime DESC");
if (alertData.Rows.Count > 0)
foreach (ResultRow alert in alertData)
alerts.Append(
Core.templates["admin_panel"]["alert"]
.Replace("%DATETIME%", HttpUtility.HtmlEncode(alert["datetime"]))
.Replace("%MESSAGE%", alert["message"].Replace("<", "<").Replace(">", ">").Replace("\n", "<br />"))
);
else
alerts.Append("No alerts.");
// Set anti-csrf cookie
Common.AntiCSRF.setCookieToken(response);
// No page requested, display welcome message
#if ADMIN_PANEL
pageElements["ADMIN_CONTENT"] = Core.templates["admin_panel"]["welcome"].Replace("%ALERTS%", alerts.ToString());
#else
pageElements["ADMIN_CONTENT"] = Core.templates["admin_panel"]["welcome_warning"].Replace("%ALERTS%", alerts.ToString());
#endif
pageElements["ADMIN_TITLE"] = "Welcome!";
}
else
{
// Grab the classpath
Result page = conn.Query_Read("SELECT classpath, method FROM admin_panel_pages WHERE pageid='" + Utils.Escape(pageid) + "'");
if (page.Rows.Count != 1)
return;
// Set the admin URL
pageElements["ADMIN_URL"] = pageElements["URL"] + "/admin/" + pageid;
// Invoke the page handler
if (!Misc.Plugins.invokeMethod(page[0]["classpath"], page[0]["method"], new object[] { conn, pageElements, request, response }))
return;
else if (pageElements["ADMIN_CONTENT"] == null || pageElements["ADMIN_CONTENT"].Length == 0)
return;
}
// Build menu
StringBuilder menu = new StringBuilder();
menu.Append(
Core.templates["admin_panel"]["menu_item"]
.Replace("%URL%", pageElements["URL"] + "/admin")
.Replace("%ICON%", HttpUtility.UrlEncode("Content/Images/admin_panel/home.png"))
.Replace("%TEXT%", HttpUtility.HtmlEncode("Home"))
);
//.........这里部分代码省略.........
示例3: pageProfile_Upload
public static void pageProfile_Upload(string pluginid, ref ResultRow profileData, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
{
string error = null;
HttpPostedFile image = request.Files["profile_picture"];
if(image != null)
{
int maxSize = Core.settings[SETTINGS_KEY].getInt(SETTINGS_KEY_PICTURE_MAX_SIZE);
if (image.ContentLength > maxSize)
error = "Picture cannot exceed " + maxSize + " bytes (" + Misc.Plugins.getBytesString(maxSize) + ") !";
else if (image.ContentType != "image/gif" && image.ContentType != "image/jpeg" && image.ContentType != "image/png" && image.ContentType != "image/jpg")
error = "Invalid file format!";
else
{
// Compress the image
double maxWidth = Core.settings[SETTINGS_KEY].getDouble(SETTINGS_KEY_PICTURE_MAX_WIDTH);
double maxHeight = Core.settings[SETTINGS_KEY].getDouble(SETTINGS_KEY_PICTURE_MAX_HEIGHT);
Stream bStream = image.InputStream;
Image pp = Image.FromStream(bStream);
// Work-out the size of the new image
int width;
int height;
if (pp.Width > maxWidth)
{
width = (int)maxWidth;
height = (int)((maxWidth / (double)pp.Width) * pp.Height);
}
else
{
height = (int)maxHeight;
width = (int)((maxHeight / (double)pp.Height) * pp.Width);
}
Bitmap compressedImage = new Bitmap(width, height);
// Draw the uploaded image
Graphics g = Graphics.FromImage(compressedImage);
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.DrawImage(pp, 0, 0, width, height);
g.Dispose();
// Save the image as a byte-array
MemoryStream ms = new MemoryStream();
compressedImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] data = ms.ToArray();
ms.Dispose();
ms = null;
// Dispose image
compressedImage.Dispose();
compressedImage = null;
pp.Dispose();
pp = null;
bStream.Dispose();
bStream = null;
// Save the byte-array to the database
Dictionary<string, object> queryParams = new Dictionary<string, object>();
queryParams.Add("profile_picture", data);
queryParams.Add("profileid", profileData["profileid"]);
// Save the byte-array to the database
conn.Query_Execute_Parameters("UPDATE bsa_profiles SET [email protected]_picture WHERE [email protected]", queryParams);
// Redirect to profile
conn.Disconnect();
response.Redirect(pageElements["URL"] + "/profile?userid=" + profileData["userid"], true);
}
}
pageElements["PROFILE_CONTENT"] = Core.templates["bsa_profiles"]["profile_upload"]
.Replace("<USERID>", HttpUtility.HtmlEncode(profileData["userid"]))
.Replace("<ERROR>", error != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", HttpUtility.HtmlEncode(error)) : string.Empty);
pageElements.setFlag("PROFILE_UPLOAD");
}
示例4: pageLogin
/// <summary>
/// Used to authenticate existing users.
/// </summary>
/// <param name="pluginid"></param>
/// <param name="conn"></param>
/// <param name="pageElements"></param>
/// <param name="request"></param>
/// <param name="response"></param>
private static void pageLogin(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
{
const string incorrectUserPassword = "Incorrect username or password!";
string error = null;
string referral = request.Form["referral"];
// Check for login
if (request.Form["username"] != null && request.Form["password"] != null)
{
bool persist = request.Form["persist"] != null;
string username = request.Form["username"];
string password = request.Form["password"];
// Validate
if (!Common.Validation.validCaptcha(request.Form["captcha"]))
error = "Invalid captcha code!";
else if (username.Length < USERNAME_MIN || username.Length > USERNAME_MAX)
error = incorrectUserPassword;
else if (password.Length < PASSWORD_MIN || password.Length > PASSWORD_MAX)
error = incorrectUserPassword;
else
{
int maxLoginPeriod = int.Parse(Core.settings[SETTINGS_CATEGORY][SETTINGS_MAX_LOGIN_PERIOD]);
int maxLoginAttempts = int.Parse(Core.settings[SETTINGS_CATEGORY][SETTINGS_MAX_LOGIN_ATTEMPTS]);
// Check the IP has not tried to authenticate in the past
if (conn.Query_Count("SELECT COUNT('') FROM bsa_failed_logins WHERE ip='" + Utils.Escape(request.UserHostAddress) + "' AND datetime >= '" + Utils.Escape(DateTime.Now.AddMinutes(-maxLoginPeriod).ToString("yyyy-MM-dd HH:mm:ss")) + "'") >= maxLoginAttempts)
error = "You've exceeded the maximum login-attempts, try again in " + maxLoginPeriod + " minutes...";
else
{
// Set anti-injection flag
pageElements.setFlag(FLAG_PASSWORD_ACCESSED);
// Authenticate
Result res = conn.Query_Read("SELECT u.userid, u.password, g.access_login, COUNT(b.banid) AS active_bans FROM bsa_users AS u LEFT OUTER JOIN bsa_user_groups AS g ON g.groupid=u.groupid LEFT OUTER JOIN bsa_user_bans AS b ON (b.userid=u.userid AND ((b.unban_date IS NULL) OR (b.unban_date > NOW()) )) WHERE u.username='" + Utils.Escape(username) + "'");
if (res.Rows.Count != 1 || res[0]["password"] != generateHash(password, salt1, salt2))
{
// Incorrect login - log as an attempt
// -- Check if the user exists, if so we'll log it into the user_log table
res = conn.Query_Read("SELECT userid FROM bsa_users WHERE username LIKE '" + username.Replace("%", "") + "'");
conn.Query_Execute("INSERT INTO bsa_failed_logins (ip, attempted_username, datetime) VALUES('" + Utils.Escape(request.UserHostAddress) + "', '" + Utils.Escape(username) + "', NOW());");
// Log event
if(res.Rows.Count == 1)
logEvent(res[0]["userid"], LogEvents.Login_Incorrect, request.UserHostAddress + " - " + request.UserAgent, conn);
// Inform the user
error = incorrectUserPassword;
}
else if (!res[0]["access_login"].Equals("1"))
error = "Your account is not allowed to login; your account is either awaiting activation or you've been banned.";
else if (int.Parse(res[0]["active_bans"]) > 0)
{
Result currentBan = conn.Query_Read("SELECT reason, unban_date FROM bsa_user_bans WHERE userid='" + Utils.Escape(res[0]["userid"]) + "' ORDER BY unban_date DESC");
if (currentBan.Rows.Count == 0)
error = "You are currently banned.";
else
error = "Your account is currently banned until '" + (currentBan[0]["unban_date"].Length > 0 ? HttpUtility.HtmlEncode(currentBan[0]["unban_date"]) : "the end of time (permanent)") + "' for the reason '" + HttpUtility.HtmlEncode(currentBan[0]["reason"]) + "'!";
}
else
{
// Authenticate the user
FormsAuthentication.SetAuthCookie(res[0]["userid"], persist);
// Log the event
logEvent(res[0]["userid"], LogEvents.Login_Authenticated, request.UserHostAddress + " - " + request.UserAgent, conn);
// Check if a ref-url exists, if so redirect to it
conn.Disconnect();
if (referral != null && referral.Length > 0)
response.Redirect(referral);
else
response.Redirect(pageElements["URL"]);
}
}
}
}
// Display page
pageElements["TITLE"] = "Login";
pageElements["CONTENT"] = Core.templates["basic_site_auth"]["login"]
.Replace("%REFERRAL%", HttpUtility.HtmlEncode(referral != null ? referral : request.UrlReferrer != null ? request.UrlReferrer.AbsoluteUri : pageElements["URL"] + "/home"))
.Replace("%USERNAME%", request.Form["username"] ?? string.Empty)
.Replace("%PERSIST%", request.Form["persist"] != null ? "checked" : string.Empty)
.Replace("%ERROR%", error != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", error) : string.Empty);
// Add CSS file
Misc.Plugins.addHeaderCSS("/Content/CSS/BasicSiteAuth.css", ref pageElements);
}
示例5: pageEmailQueue
public static void pageEmailQueue(Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
{
// Check for e-mail deletion
string deleteEmailID = request.QueryString["delete"];
if (deleteEmailID != null)
{
conn.Query_Execute("DELETE FROM email_queue WHERE emailid='" + Utils.Escape(deleteEmailID) + "'");
conn.Disconnect();
response.Redirect(pageElements["ADMIN_URL"], true);
}
// Grab statistics about the number of e-mails pending
ResultRow queueStats = conn.Query_Read("SELECT (SELECT COUNT('') FROM email_queue) AS count, (SELECT COUNT(DISTINCT email) FROM email_queue) AS unique_count")[0];
// Generate a list of pending e-mails at the top of the queue
StringBuilder pending = new StringBuilder();
foreach (ResultRow email in conn.Query_Read("SELECT * FROM email_queue ORDER BY emailid ASC LIMIT 10"))
pending.Append(
Core.templates["admin_panel"]["emailqueue_item"]
.Replace("%EMAILID%", HttpUtility.HtmlEncode(email["emailid"]))
.Replace("%EMAIL%", HttpUtility.HtmlEncode(email["email"]))
.Replace("%SUBJECT%", HttpUtility.HtmlEncode(email["subject"]))
);
if (pending.Length == 0) pending.Append("No e-mails in the queue!");
// Display page
pageElements["ADMIN_CONTENT"] =
Core.templates["admin_panel"]["emailqueue"]
.Replace("%COUNT%", HttpUtility.HtmlEncode(queueStats["count"]))
.Replace("%UNIQUE_COUNT%", HttpUtility.HtmlEncode(queueStats["unique_count"]))
.Replace("%ERRORS%", HttpUtility.HtmlEncode(Core.emailQueue.mailErrors.ToString()))
.Replace("%THREAD_STATUS%", HttpUtility.HtmlEncode(Core.emailQueue.cyclerThread != null ? Core.emailQueue.cyclerThread.ThreadState.ToString() : "Not operational - critical failure or undefined mail settings."))
.Replace("%EMAILS%", pending.ToString())
;
pageElements["ADMIN_TITLE"] = "Core - E-mail Queue";
}
示例6: pageUserGroups
public static void pageUserGroups(Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
{
string error = null;
bool updatedSettings = false;
// Check for transfer of users
string transferGroupID = request.QueryString["transfer"];
if (transferGroupID != null)
{
// -- Transfer users to another group
// Grab the title of the origin group - this will also help to validate it exists too, else we'll 404
Result groupOrigin = conn.Query_Read("SELECT title FROM bsa_user_groups WHERE groupid='" + Utils.Escape(transferGroupID) + "'");
if (groupOrigin.Rows.Count != 1) return; // 404 - the group does not exist
string newTransferGroupID = request.QueryString["transfer_b"]; // The destination group ID
if (newTransferGroupID != null)
{
// Validate the group exists
if (conn.Query_Count("SELECT COUNT('') FROM bsa_user_groups WHERE groupid='" + Utils.Escape(newTransferGroupID) + "'") != 1)
error = "Destination group does not exist!";
else
{
// Transfer all the users http://memegenerator.net/instance/23587059
conn.Query_Execute("UPDATE bsa_users SET groupid='" + Utils.Escape(newTransferGroupID) + "' WHERE groupid='" + Utils.Escape(transferGroupID) + "'");
conn.Disconnect();
response.Redirect(pageElements["ADMIN_URL"]);
}
}
// Build a list of the current groups
StringBuilder currentGroups = new StringBuilder();
foreach (ResultRow group in conn.Query_Read("SELECT groupid, title FROM bsa_user_groups WHERE groupid != '" + Utils.Escape(transferGroupID) + "' ORDER BY title ASC"))
currentGroups.Append("<option value=\"").Append(group["groupid"]).Append("\">").Append(group["title"]).Append("</option>");
// Display form
pageElements["ADMIN_CONTENT"] =
Core.templates["basic_site_auth"]["admin_user_groupstransfer"]
.Replace("%GROUPID%", HttpUtility.HtmlEncode(transferGroupID))
.Replace("%TITLE%", HttpUtility.HtmlEncode(groupOrigin[0]["title"]))
.Replace("%GROUPS%", currentGroups.ToString())
.Replace("%ERROR%", error != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", HttpUtility.HtmlEncode(error)) : string.Empty)
;
}
else
{
// -- List all user groups
// Check for postback - delete a group
string delete = request.QueryString["delete"];
if (delete != null)
{
if (conn.Query_Count("SELECT COUNT('') FROM bsa_users WHERE groupid='" + Utils.Escape(delete) + "'") > 0)
error = "Cannot delete group - the group contains users, transfer them to another group first!";
else
{
conn.Query_Execute("DELETE FROM bsa_user_groups WHERE groupid='" + Utils.Escape(delete) + "'");
conn.Disconnect();
response.Redirect(pageElements["ADMIN_URL"], true);
}
}
// Check for postback - added group
string groupAddTitle = request.Form["group_add_title"];
if (groupAddTitle != null)
{
if (groupAddTitle.Length < Plugins.BasicSiteAuth.USER_GROUP_TITLE_MIN || groupAddTitle.Length > Plugins.BasicSiteAuth.USER_GROUP_TITLE_MAX)
error = "Group title must be between " + Plugins.BasicSiteAuth.USER_GROUP_TITLE_MIN + " to " + Plugins.BasicSiteAuth.USER_GROUP_TITLE_MAX + " characters in length!";
else
conn.Query_Execute("INSERT INTO bsa_user_groups (title) VALUES('" + Utils.Escape(groupAddTitle) + "')");
}
// Grab the current permissions
const string dbPermissionsQuery = "SELECT * FROM bsa_user_groups ORDER BY title ASC";
Result dbPermissions = conn.Query_Read(dbPermissionsQuery);
// Check for postback - permissions
string groupid, column, value;
string[] parts;
Dictionary<string, Dictionary<string, string>> groupRowsUpdate = new Dictionary<string, Dictionary<string, string>>();
for (int i = 0; i < request.Form.Count; i++)
{
parts = request.Form.Keys[i].Split('$');
if (parts.Length == 2 && parts[0].StartsWith("group_"))
{
groupid = parts[0].Substring(6);
column = parts[1];
value = request.Form[i];
if (!groupRowsUpdate.ContainsKey(groupid))
groupRowsUpdate.Add(groupid, new Dictionary<string, string>());
groupRowsUpdate[groupid].Add(column, value);
}
}
if (groupRowsUpdate.Count > 0)
{
// Postback made - generate query by going through each permissions row and checking for a state (or lack of state) change
StringBuilder queries = new StringBuilder();
StringBuilder query;
const string queryStart = "UPDATE bsa_user_groups SET ";
string currGroupId;
foreach (ResultRow dbPermissionsRow in dbPermissions)
{
currGroupId = dbPermissionsRow["groupid"];
// Check if this group has been updated at all
if (groupRowsUpdate.ContainsKey(currGroupId))
{
query = new StringBuilder(queryStart);
foreach (KeyValuePair<string, object> groupColumn in dbPermissionsRow.Columns)
{
//.........这里部分代码省略.........
示例7: pageUsers
public static void pageUsers(Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
{
if (request.QueryString["2"] != null)
{
// Editing a user
string error = null;
bool updatedAccount = false;
// Set SQL injection protection flag (to disable flag)
pageElements.setFlag(Plugins.BasicSiteAuth.FLAG_PASSWORD_ACCESSED);
// Grab the user's info, bans and available user groups
Result user = conn.Query_Read("SELECT * FROM bsa_users WHERE userid='" + Utils.Escape(request.QueryString["2"]) + "'");
if (user.Rows.Count != 1) return;
Result bans = conn.Query_Read("SELECT b.*, u.username FROM bsa_user_bans AS b LEFT OUTER JOIN bsa_users AS u ON u.userid=b.banner_userid ORDER BY datetime DESC");
Result userGroups = conn.Query_Read("SELECT groupid, title FROM bsa_user_groups ORDER BY access_login ASC, access_changeaccount ASC, access_media_create ASC, access_media_edit ASC, access_media_delete ASC, access_media_publish ASC, access_admin ASC, title ASC");
string dban = request.QueryString["dban"];
// Check for deleting a ban
if (dban != null)
{
conn.Query_Execute("DELETE FROM bsa_user_bans WHERE banid='" + Utils.Escape(dban) + "'");
conn.Disconnect();
response.Redirect(pageElements["ADMIN_URL"] + "/" + user[0]["userid"], true);
}
// Check for postback of banning the user
string ban = request.QueryString["ban"];
string banCustom = request.QueryString["ban_custom"];
string banReason = request.QueryString["ban_reason"];
if (ban != null || banCustom != null)
{
int banAmount = 0;
if (ban != null)
{
if (ban.Equals("Permanent"))
banAmount = 0;
else if (ban.Equals("1 Month"))
banAmount = 2628000;
else if (ban.Equals("1 Week"))
banAmount = 604800;
else if (ban.Equals("3 Days"))
banAmount = 259200;
else if (ban.Equals("1 Day"))
banAmount = 86400;
else
error = "Invalid ban period!";
}
else
{
if (banCustom != null && !int.TryParse(banCustom, out banAmount))
error = "Invalid ban period, not numeric!";
else if (banAmount < 0)
error = "Ban period cannot be less than zero!";
}
if(error == null)
{
// Get the time at which the user will be unbanned
DateTime dt = DateTime.Now.AddSeconds(-banAmount);
// Insert the record
conn.Query_Execute("INSERT INTO bsa_user_bans (userid, reason, unban_date, datetime, banner_userid) VALUES('" + Utils.Escape(user[0]["userid"]) + "', '" + Utils.Escape(banReason) + "', " + (banAmount == 0 ? "NULL" : "'" + Utils.Escape(dt.ToString("yyyy-MM-dd HH:mm:ss")) + "'") + ", NOW(), '" + Utils.Escape(HttpContext.Current.User.Identity.Name) + "')");
// Refresh the page
conn.Disconnect();
response.Redirect(pageElements["ADMIN_URL"] + "/" + user[0]["userid"], true);
}
}
// Check for postback of editing the user
string username = request.Form["username"];
string password = request.Form["password"];
string email = request.Form["email"];
string secretQuestion = request.Form["secret_question"];
string secretAnswer = request.Form["secret_answer"];
string groupid = request.Form["groupid"];
if (username != null && password != null && email != null && secretQuestion != null && secretAnswer != null && groupid != null)
{
if (username.Length < Plugins.BasicSiteAuth.USERNAME_MIN || username.Length > Plugins.BasicSiteAuth.USERNAME_MAX)
error = "Username must be " + Plugins.BasicSiteAuth.USERNAME_MIN + " to " + Plugins.BasicSiteAuth.USERNAME_MAX + " characters in length!";
else if ((error = Plugins.BasicSiteAuth.validUsernameChars(username)) != null)
;
else if (!Plugins.BasicSiteAuth.validEmail(email))
error = "Invalid e-mail!";
else if (password.Length != 0 && (password.Length < Plugins.BasicSiteAuth.PASSWORD_MIN || password.Length > Plugins.BasicSiteAuth.PASSWORD_MAX))
error = "Password must be " + Plugins.BasicSiteAuth.PASSWORD_MIN + " to " + Plugins.BasicSiteAuth.PASSWORD_MAX + " characters in length!";
else if (secretQuestion.Length < Plugins.BasicSiteAuth.SECRET_QUESTION_MIN || secretQuestion.Length > Plugins.BasicSiteAuth.SECRET_QUESTION_MAX)
error = "Secret question must be " + Plugins.BasicSiteAuth.SECRET_QUESTION_MIN + " to " + Plugins.BasicSiteAuth.SECRET_QUESTION_MAX + " characters in length!";
else if (secretAnswer.Length < Plugins.BasicSiteAuth.SECRET_ANSWER_MIN || secretAnswer.Length > Plugins.BasicSiteAuth.SECRET_ANSWER_MAX)
error = "Secret answer must be " + Plugins.BasicSiteAuth.SECRET_ANSWER_MIN + " to " + Plugins.BasicSiteAuth.SECRET_ANSWER_MAX + " characters in length!";
else
{
// Ensure the groupid is valid
bool groupFound = false;
foreach (ResultRow group in userGroups) if (group["groupid"] == groupid) groupFound = true;
if (!groupFound)
error = "Invalid group!";
else
{
// Attempt to update the user's details
try
{
conn.Query_Execute("UPDATE bsa_users SET username='" + Utils.Escape(username) + "', email='" + Utils.Escape(email) + "', " + (password.Length > 0 ? "password='" + Utils.Escape(Plugins.BasicSiteAuth.generateHash(password, Plugins.BasicSiteAuth.salt1, Plugins.BasicSiteAuth.salt2)) + "', " : string.Empty) + "secret_question='" + Utils.Escape(secretQuestion) + "', secret_answer='" + Utils.Escape(secretAnswer) + "', groupid='" + Utils.Escape(groupid) + "' WHERE userid='" + Utils.Escape(user[0]["userid"]) + "'");
updatedAccount = true;
}
catch (DuplicateEntryException ex)
{
//.........这里部分代码省略.........
示例8: pageArticles_Images_Upload
public static void pageArticles_Images_Upload(ref StringBuilder content, string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response, bool permCreate)
{
// Upload an image
// -- Ensure the user has creation permissions, else we'll 404
if (!permCreate) return;
string error = null;
HttpPostedFile image = request.Files["image"];
string title = request.Form["title"];
string captcha = request.Form["captcha"];
// Check for postback
if (title != null && captcha != null && image != null)
{
// Validate
if (!Common.Validation.validCaptcha(captcha))
error = "Incorrect captcha verification code, please try again!";
else if (title.Length < Core.settings[SETTINGS_KEY].getInt(SETTINGS_IMAGES_TITLE_MIN) || title.Length > Core.settings[SETTINGS_KEY].getInt(SETTINGS_TITLE_MAX))
error = "Title must be between " + Core.settings[SETTINGS_KEY][SETTINGS_TITLE_MIN] + " to " + Core.settings[SETTINGS_KEY][SETTINGS_IMAGES_TITLE_MAX] + " characters in length!";
else if (image.ContentLength == 0)
error = "The uploaded image contains no data, please try again!";
else if (image.ContentLength > Core.settings[SETTINGS_KEY].getInt(SETTINGS_IMAGES_MAXSIZE))
error = "The uploaded image is too large - maximum size allowed is " + Misc.Plugins.getBytesString(Core.settings[SETTINGS_KEY].getLong(SETTINGS_IMAGES_MAXSIZE)) + "!";
else if (!Core.settings[SETTINGS_KEY].getCommaArrayContains(SETTINGS_IMAGE_TYPES, image.ContentType))
error = "Invalid image type - ensure you've uploaded an actual image!";
else
{
// Compress the image data for database storage
byte[] imageData = compressImageData(image.InputStream, Core.settings[SETTINGS_KEY].getInt(SETTINGS_IMAGES_MAXWIDTH), Core.settings[SETTINGS_KEY].getInt(SETTINGS_IMAGES_MAXHEIGHT));
if (imageData == null)
error = "Failed to process image - please try your request again or ensure the uploaded image is not corrupt!";
else
{
// Write the data to the database
Dictionary<string, object> imageParams = new Dictionary<string, object>();
imageParams.Add("title", title);
imageParams.Add("userid", HttpContext.Current.User.Identity.Name);
imageParams.Add("data", imageData);
string imageid = conn.Query_Scalar_Parameters("INSERT INTO articles_images (title, userid, data, datetime) VALUES(@title, @userid, @data, NOW()); SELECT LAST_INSERT_ID();", imageParams).ToString();
// Redirect the user to view the image
conn.Disconnect();
response.Redirect(pageElements["URL"] + "/articles/images/view/" + imageid);
}
}
}
// Output form
content.Append(
Core.templates["articles"]["image_uploader"]
.Replace("<ERROR>", error != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", error) : string.Empty)
.Replace("<TITLE>", HttpUtility.HtmlEncode(title))
);
pageElements["TITLE"] = "Articles - Image Store - Upload";
}
示例9: pageArticles_Images_View
public static void pageArticles_Images_View(ref StringBuilder content, string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response, bool permCreate, bool permDelete)
{
string imageid = request.QueryString["3"];
if (imageid == null || imageid.Length == 0) return;
// Grab data about the image
Result imageData = conn.Query_Read("SELECT i.imageid, i.title, u.userid, u.username, i.datetime FROM articles_images AS i LEFT OUTER JOIN bsa_users AS u ON u.userid=i.userid WHERE i.imageid='" + Utils.Escape(imageid) + "'");
if (imageData.Rows.Count != 1) return;
ResultRow image = imageData[0];
// Set page flags and protection for deletion of photos
if (HttpContext.Current.User.Identity.IsAuthenticated && (permDelete || image["userid"] == HttpContext.Current.User.Identity.Name))
{
// Check if the article has been requested to be deleted
if (request.QueryString["4"] == "delete" && Common.AntiCSRF.isValidTokenCookie(request, response))
{
// Delete the article and redirect to the image store
conn.Query_Execute("DELETE FROM articles_images WHERE imageid='" + Utils.Escape(image["imageid"]) + "'");
conn.Disconnect();
response.Redirect(pageElements["URL"] + "/articles/images");
}
pageElements.setFlag("IMAGE_DELETE"); // Set flag
Common.AntiCSRF.setCookieToken(response); // Set cookie for anti-csrf protection
}
// Set upload flag
if (permCreate)
pageElements.setFlag("IMAGE_UPLOAD");
// Build the list of articles using the image
int page;
if (request.QueryString["bpg"] == null || !int.TryParse(request.QueryString["bpg"], out page) || page < 1) page = 1;
int referencesPerPage = Core.settings[SETTINGS_KEY].getInt(SETTINGS_IMAGES_VIEW_REFERENCES);
StringBuilder references = new StringBuilder();
Result referencesData = conn.Query_Read("SELECT a.articleid, a.title, a.datetime FROM articles_images_links AS ail LEFT OUTER JOIN articles AS a ON a.articleid=ail.articleid WHERE ail.imageid='" + Utils.Escape(image["imageid"]) + "' ORDER BY a.datetime DESC LIMIT " + ((referencesPerPage * page) - referencesPerPage) + "," + referencesPerPage);
if(referencesData.Rows.Count != 0)
foreach(ResultRow reference in referencesData)
references.Append(
Core.templates["articles"]["image_view_reference"]
.Replace("<ARTICLEID>", HttpUtility.HtmlEncode(reference["articleid"]))
.Replace("<TITLE>", HttpUtility.HtmlEncode(reference["title"]))
.Replace("<DATETIME_SHORT>", HttpUtility.HtmlEncode(Misc.Plugins.getTimeString(DateTime.Parse(reference["datetime"]))))
.Replace("<DATETIME>", HttpUtility.HtmlEncode(reference["datetime"]))
);
else
references.Append("No articles reference this image.");
// Output the page
content.Append(
Core.templates["articles"]["image_view"]
.Replace("<IMAGEID>", HttpUtility.HtmlEncode(image["imageid"]))
.Replace("<USERID>", HttpUtility.HtmlEncode(image["userid"]))
.Replace("<USERNAME>", HttpUtility.HtmlEncode(image["username"]))
.Replace("<DATETIME>", HttpUtility.HtmlEncode(image["datetime"]))
.Replace("<REFERENCES>", references.ToString())
);
pageElements["TITLE"] = "Articles - Image Store - " + HttpUtility.HtmlEncode(image["title"]);
// Add JS file for copypasta of embedding bbcode
Misc.Plugins.addHeaderJS(pageElements["URL"] + "/Content/JS/Article.js", ref pageElements);
// Append navigation
content.Append(
Core.templates["articles"]["browse_nav"]
.Replace("<URL>", "articles/images/view/" + image["imageid"])
.Replace("<PAGE>", page.ToString())
.Replace("<PAGE_PREVIOUS>", (page > 1 ? page - 1 : 1).ToString())
.Replace("<PAGE_NEXT>", (page < int.MaxValue ? page + 1 : int.MaxValue).ToString())
);
// Set navigation flags
if (page > 1) pageElements.setFlag("ARTICLES_PAGE_PREVIOUS");
if (page < int.MaxValue && referencesData.Rows.Count == referencesPerPage) pageElements.setFlag("ARTICLES_PAGE_NEXT");
}
示例10: pageArticles_Delete
public static void pageArticles_Delete(ref StringBuilder content, string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
{
string threadid = request.QueryString["2"];
if (threadid == null || !HttpContext.Current.User.Identity.IsAuthenticated) return;
// Attempt to retrieve information about the article thread, as well as the users permissions
Result threadData = conn.Query_Read("SELECT at.*, COUNT(a.articleid) AS article_count, ug.access_media_delete AS perm_delete, a2.title FROM (articles_thread AS at, bsa_users AS u) LEFT OUTER JOIN articles AS a ON a.articleid=at.articleid_current LEFT OUTER JOIN articles AS a2 ON a2.articleid=at.articleid_current LEFT OUTER JOIN bsa_user_groups AS ug ON ug.groupid=u.groupid WHERE at.threadid='" + Utils.Escape(threadid) + "' AND u.userid='" + Utils.Escape(HttpContext.Current.User.Identity.Name) + "'");
if (threadData.Rows.Count != 1 || threadData[0]["threadid"] != threadid || !threadData[0]["perm_delete"].Equals("1")) return;
// Check if the user has posted a confirmation to delete the thread
string error = null;
string csrf = request.Form["csrf"];
string captcha = request.Form["captcha"];
if (request.Form["confirm"] != null && csrf != null && captcha != null)
{
// Validate CSRF
if (!Common.AntiCSRF.isValidTokenForm(csrf))
error = "Invalid security verification, please try your request again!";
else if (!Common.Validation.validCaptcha(captcha))
error = "Incorrect captcha verification code!";
else
{
// Delete the thread, clear unused tags and clear unused thumbnail images
conn.Query_Execute("DELETE FROM articles_thread WHERE threadid='" + Utils.Escape(threadid) + "'; " + QUERY_TAGS_CLEANUP + QUERY_THUMBNAIL_CLEANUP + insertEvent(RecentChanges_EventType.DeletedThread, HttpContext.Current.User.Identity.Name, null, threadData[0]["threadid"]));
// Redirect to articles home
conn.Disconnect();
response.Redirect(pageElements["URL"] + "/articles");
}
}
// Display confirmation/security-verification form
content.Append(Core.templates["articles"]["thread_delete"]
.Replace("<THREADID>", HttpUtility.HtmlEncode(threadData[0]["threadid"]))
.Replace("<ERROR>", error != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", HttpUtility.HtmlEncode(error)) : string.Empty)
.Replace("<CSRF>", HttpUtility.HtmlEncode(Common.AntiCSRF.getFormToken()))
.Replace("<TITLE>", HttpUtility.HtmlEncode(threadData[0]["title"]))
.Replace("<ARTICLE_COUNT>", HttpUtility.HtmlEncode(threadData[0]["article_count"]))
.Replace("<RELATIVE_URL>", HttpUtility.HtmlEncode(threadData[0]["relative_url"]))
);
pageElements["TITLE"] = "Articles - Delete Thread";
}
示例11: pageArticles_Images_Data
public static void pageArticles_Images_Data(ref StringBuilder content, string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
{
string imageid = request.QueryString["3"];
if (imageid == null && imageid.Length > 0) return;
// Grab the image data from the database
Result data = conn.Query_Read("SELECT data FROM articles_images WHERE imageid='" + Utils.Escape(imageid) + "'");
if (data.Rows.Count != 1 || data[0].ColumnsByteArray == null) return;
// Output the image
response.ContentType = "image/png";
response.BinaryWrite(data[0].GetByteArray("data"));
conn.Disconnect();
response.End();
}
示例12: pageArticle_View_Set
public static void pageArticle_View_Set(ref string pluginid, ref Connector conn, ref Misc.PageElements pageElements, ref HttpRequest request, ref HttpResponse response, ref bool permCreate, ref bool permDelete, ref bool permPublish, ref bool owner, ref StringBuilder content, ref ResultRow article)
{
conn.Query_Execute("UPDATE articles_thread SET articleid_current='" + Utils.Escape(article["articleid"]) + "' WHERE threadid='" + Utils.Escape(article["threadid"]) + "';" + insertEvent(RecentChanges_EventType.SetAsSelected, HttpContext.Current.User.Identity.Name, article["articleid"], article["threadid"]));
conn.Disconnect();
response.Redirect(pageElements["URL"] + "/article/" + article["articleid"], true);
}
示例13: pageArticle_View_Rebuild
public static void pageArticle_View_Rebuild(ref string pluginid, ref Connector conn, ref Misc.PageElements pageElements, ref HttpRequest request, ref HttpResponse response, ref bool permCreate, ref bool permDelete, ref bool permPublish, ref bool owner, ref StringBuilder content, ref ResultRow article)
{
if (!permPublish) return;
StringBuilder cached = new StringBuilder(article["body"]);
// Rebuild article text
articleViewRebuildCache(conn, ref cached, article["allow_html"].Equals("1"), ref pageElements);
conn.Query_Execute("UPDATE articles SET body_cached='" + Utils.Escape(cached.ToString()) + "' WHERE articleid='" + Utils.Escape(article["articleid"]) + "';" + insertEvent(RecentChanges_EventType.RebuiltArticleCache, HttpContext.Current.User.Identity.Name, article["articleid"], article["threadid"]));
conn.Disconnect();
// Rebuild article pdf if this is the current article
string currentArticleID = (conn.Query_Scalar("SELECT articleid_current FROM articles_thread WHERE threadid='" + Utils.Escape(article["threadid"]) + "'") ?? string.Empty).ToString();
if(currentArticleID == article["articleid"])
pdfRebuild(pluginid, article["articleid"], article["title"], article["pdf_name"], article["threadid"], request);
// Redirect back to the article
response.Redirect(pageElements["URL"] + "/article/" + article["articleid"], true);
}
示例14: pageArticle_View_Publish
public static void pageArticle_View_Publish(ref string pluginid, ref Connector conn, ref Misc.PageElements pageElements, ref HttpRequest request, ref HttpResponse response, ref bool permCreate, ref bool permDelete, ref bool permPublish, ref bool owner, ref StringBuilder content, ref ResultRow article)
{
if (request.Form["confirm"] != null)
{
StringBuilder publishQuery = new StringBuilder();
publishQuery.Append("UPDATE articles SET published='1', moderator_userid='")
.Append(Utils.Escape(HttpContext.Current.User.Identity.Name)).Append("' WHERE articleid='")
.Append(Utils.Escape(article["articleid"])).Append("'; UPDATE articles_thread SET articleid_current='")
.Append(Utils.Escape(article["articleid"])).Append("' WHERE threadid='")
.Append(Utils.Escape(article["threadid"])).Append("';")
.Append(insertEvent(RecentChanges_EventType.Published, HttpContext.Current.User.Identity.Name, article["articleid"], article["threadid"]));
conn.Query_Execute(publishQuery.ToString());
conn.Disconnect();
response.Redirect(pageElements["URL"] + "/article/" + article["articleid"]);
}
content.Append(
Core.templates["articles"]["article_publish"]
);
}
示例15: pageDownload_ResetDownloads
public static void pageDownload_ResetDownloads(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response, bool admin, ResultRow file)
{
if (request.Form["confirm"] != null)
{
conn.Query_Execute("DELETE FROM downloads WHERE downloadid='" + Utils.Escape(file["downloadid"]) + "'");
conn.Disconnect();
response.Redirect(pageElements["URL"] + "/download/" + file["downloadid"]);
}
pageElements["CONTENT"] = Core.templates["downloads"]["download_reset"]
.Replace("%DOWNLOADID%", file["downloadid"]);
pageElements["TITLE"] = "Download - " + HttpUtility.HtmlEncode(file["title"]) + " - Reset Downloads";
}