本文整理汇总了C#中Connector.Query_Scalar方法的典型用法代码示例。如果您正苦于以下问题:C# Connector.Query_Scalar方法的具体用法?C# Connector.Query_Scalar怎么用?C# Connector.Query_Scalar使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Connector
的用法示例。
在下文中一共展示了Connector.Query_Scalar方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: getParentVITEMID
public static Dictionary<string, string> threadPoolStatus = new Dictionary<string, string>(); // Stores the status's of drive-indexing
#endregion Fields
#region Methods
public static string getParentVITEMID(string pfolderid, string pathofmedium, ref Dictionary<string, string> Cache, Connector Connector)
{
if (Cache.ContainsKey(pathofmedium)) return Cache[pathofmedium];
int lsep = pathofmedium.IndexOf('\\');
int rsep = pathofmedium.LastIndexOf('\\');
if (lsep == rsep) return null; // Item is at the top
else
{
string t = Connector.Query_Scalar("SELECT vitemid FROM um_virtual_items WHERE type_uid='100' AND pfolderid='" + Utils.Escape(pfolderid) + "' AND phy_path='" + Utils.Escape(pathofmedium.Substring(0, rsep)) + "'").ToString();
Cache.Add(pathofmedium, t);
return t;
}
}
示例2: pageRegister
/// <summary>
/// Used to register new accounts; this supports activation as well.
/// </summary>
/// <param name="pluginid"></param>
/// <param name="conn"></param>
/// <param name="pageElements"></param>
/// <param name="request"></param>
/// <param name="response"></param>
private static void pageRegister(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
{
switch (request.QueryString["1"])
{
case "success":
// Check which template to display - welcome or activation-required
bool activationNeeded = conn.Query_Scalar("SELECT access_login FROM bsa_user_groups WHERE groupid='" + Utils.Escape(Core.settings[SETTINGS_CATEGORY][SETTINGS_USER_GROUP_DEFAULT]) + "'").ToString().Equals("0");
if (activationNeeded)
{
pageElements["TITLE"] = "Register - Success - Verification Required";
pageElements["CONTENT"] = Core.templates["basic_site_auth"]["register_success_activate"];
// Add CSS file
Misc.Plugins.addHeaderCSS("/Content/CSS/BasicSiteAuth.css", ref pageElements);
}
else
{
pageElements["TITLE"] = "Register - Success";
pageElements["CONTENT"] = Core.templates["basic_site_auth"]["register_success"];
// Add CSS file
Misc.Plugins.addHeaderCSS("/Content/CSS/BasicSiteAuth.css", ref pageElements);
}
break;
case "activate":
case "deactivate":
bool activate = request.QueryString["1"].Equals("activate");
string dkey = request.QueryString["key"];
if (dkey != null)
{
// Locate the user-group associated with the key
Result res = conn.Query_Read("SELECT a.keyid, a.userid, u.groupid, u.username FROM bsa_activations AS a LEFT OUTER JOIN bsa_users AS u ON u.userid=a.userid");
// Ensure the condition is valid
if (res.Rows.Count == 1 && res[0]["groupid"] == Core.settings[SETTINGS_CATEGORY][SETTINGS_USER_GROUP_DEFAULT])
{
// Ensure the user wants to activate/deactivate their account
if (request.Form["confirm"] == null)
{
if (activate)
{
pageElements["TITLE"] = "Register - Activate Account";
pageElements["CONTENT"] = Core.templates["basic_site_auth"]["activate"]
.Replace("%KEY%", request.QueryString["key"])
.Replace("%USERNAME%", HttpUtility.HtmlEncode(res[0]["username"]));
}
else
{
pageElements["TITLE"] = "Register - Deactivate Account";
pageElements["CONTENT"] = Core.templates["basic_site_auth"]["deactivate"]
.Replace("%KEY%", request.QueryString["key"])
.Replace("%USERNAME%", HttpUtility.HtmlEncode(res[0]["username"]));
}
// Add CSS file
Misc.Plugins.addHeaderCSS("/Content/CSS/BasicSiteAuth.css", ref pageElements);
}
else
{
if (activate)
{
// Remove the activation key and change the groupid
conn.Query_Execute("DELETE FROM bsa_activations WHERE keyid='" + Utils.Escape(res[0]["keyid"]) + "'; UPDATE bsa_users SET groupid='" + Utils.Escape(Core.settings[SETTINGS_CATEGORY][SETTINGS_USER_GROUP_USER]) + "' WHERE userid='" + Utils.Escape(res[0]["userid"]) + "';");
// Log the event
logEvent(res[0]["userid"], LogEvents.Registration_Activated, request.UserHostAddress, conn);
// Display confirmation
pageElements["TITLE"] = "Account Activated";
pageElements["CONTENT"] = Core.templates["basic_site_auth"]["activate_success"];
}
else
{
// Delete the account
conn.Query_Execute("DELETE FROM bsa_users WHERE userid='" + Utils.Escape(res[0]["userid"]) + "';");
// Display confirmation
pageElements["TITLE"] = "Account Deactivated";
pageElements["CONTENT"] = Core.templates["basic_site_auth"]["deactivate_success"];
}
// Add CSS file
Misc.Plugins.addHeaderCSS("/Content/CSS/BasicSiteAuth.css", ref pageElements);
}
}
}
break;
case null:
string error = null;
string username = request.Form["username"];
string password = request.Form["password"];
string confirmPassword = request.Form["confirm_password"];
string email = request.Form["email"];
string secretQuestion = request.Form["secret_question"];
string secretAnswer = request.Form["secret_answer"];
string captcha = request.Form["captcha"];
if (username != null && password != null && confirmPassword != null && email != null && secretQuestion != null && secretAnswer != null)
{
// Validate
if (!Common.Validation.validCaptcha(captcha))
//.........这里部分代码省略.........
示例3: pageMyAccount
/// <summary>
/// Used by the user to update account details such as their password, e-mail and secret question+answer.
/// </summary>
/// <param name="pluginid"></param>
/// <param name="conn"></param>
/// <param name="pageElements"></param>
/// <param name="request"></param>
/// <param name="response"></param>
private static void pageMyAccount(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
{
// Add CSS file
Misc.Plugins.addHeaderCSS("/Content/CSS/BasicSiteAuth.css", ref pageElements);
string error = null;
string currentPassword = request.Form["currentpassword"];
string newPassword = request.Form["newpassword"];
string newPasswordConfirm = request.Form["newpassword_confirm"];
string email = request.Form["email"];
string secretQuestion = request.Form["secret_question"];
string secretAnswer = request.Form["secret_answer"];
bool updatedSettings = false;
if (currentPassword != null && newPassword != null && newPasswordConfirm != null && email != null && secretQuestion != null && secretAnswer != null)
{
if (currentPassword.Length < PASSWORD_MIN || currentPassword.Length > PASSWORD_MAX || generateHash(currentPassword, salt1, salt2) != conn.Query_Scalar("SELECT password FROM bsa_users WHERE userid='" + Utils.Escape(HttpContext.Current.User.Identity.Name) + "'").ToString())
error = "Incorrect current password!";
else if (newPassword.Length != 0 && newPassword.Length < PASSWORD_MIN || newPassword.Length > PASSWORD_MAX)
error = "Your new password must be between " + PASSWORD_MIN + " to " + PASSWORD_MAX + " characters in length!";
else if (newPassword.Length != 0 && newPassword != newPasswordConfirm)
error = "Your new password does not match, please retype it!";
else if (email.Length != 0 && !validEmail(email))
error = "Invalid e-mail address!";
else if (secretQuestion.Length < SECRET_QUESTION_MIN || secretQuestion.Length > SECRET_QUESTION_MAX)
error = "Secret question must be " + SECRET_QUESTION_MIN + " to " + SECRET_QUESTION_MAX + " characters in length!";
else if (secretAnswer.Length < SECRET_ANSWER_MIN || secretAnswer.Length > SECRET_ANSWER_MAX)
error = "Secret answer must be " + SECRET_ANSWER_MIN + " to " + SECRET_ANSWER_MAX + " characters in length!";
else
{
// Update main account details
StringBuilder query = new StringBuilder("UPDATE bsa_users SET secret_question='" + Utils.Escape(secretQuestion) + "', secret_answer='" + Utils.Escape(secretAnswer) + "',");
if (newPassword.Length > 0)
query.Append("password='" + Utils.Escape(generateHash(newPassword, salt1, salt2)) + "',");
if (email.Length > 0)
query.Append("email='" + Utils.Escape(email) + "',");
try
{
conn.Query_Execute(query.Remove(query.Length - 1, 1).Append(" WHERE userid='" + Utils.Escape(HttpContext.Current.User.Identity.Name) + "'").ToString());
updatedSettings = true;
// Log event
logEvent(HttpContext.Current.User.Identity.Name, LogEvents.MyAccountUpdated, request.UserHostAddress + " - " + request.UserAgent, conn);
}
catch (DuplicateEntryException)
{
error = "E-mail already in-use!";
}
catch (Exception ex)
{
error = "Unknown error occurred whilst updating your account settings!" + ex.Message;
}
}
}
// Grab account info
ResultRow userInfo = conn.Query_Read("SELECT email, secret_question, secret_answer FROM bsa_users WHERE userid='" + Utils.Escape(HttpContext.Current.User.Identity.Name) + "'")[0];
// Display form
pageElements["TITLE"] = "My Account";
pageElements["CONTENT"] = Core.templates["basic_site_auth"]["my_account"]
.Replace("%EMAIL%", HttpUtility.HtmlEncode(email ?? userInfo["email"]))
.Replace("%SECRET_QUESTION%", HttpUtility.HtmlEncode(secretQuestion ?? userInfo["secret_question"]))
.Replace("%SECRET_ANSWER%", HttpUtility.HtmlEncode(secretAnswer ?? userInfo["secret_answer"]))
.Replace("%ERROR%", error != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", HttpUtility.HtmlEncode(error)) : updatedSettings ? Core.templates[pageElements["TEMPLATE"]]["success"].Replace("<SUCCESS>", "Account settings successfully updated!") : string.Empty);
// Add CSS file
Misc.Plugins.addHeaderCSS("/Content/CSS/BasicSiteAuth.css", ref pageElements);
}
示例4: pageRecover_SecretQA
/// <summary>
/// Used to allow the user to recover their account using the secret question and answer mechanism.
/// </summary>
/// <param name="pluginid"></param>
/// <param name="conn"></param>
/// <param name="pageElements"></param>
/// <param name="request"></param>
/// <param name="response"></param>
private static void pageRecover_SecretQA(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
{
// Add CSS file
Misc.Plugins.addHeaderCSS("/Content/CSS/BasicSiteAuth.css", ref pageElements);
if (request.QueryString["2"] != null && request.QueryString["2"] == "success")
{
// Display success page
pageElements["TITLE"] = "Account Recovery - Secret Question - Success";
pageElements["CONTENT"] = Core.templates["basic_site_auth"]["recovery_qa_success"];
// Add CSS file
Misc.Plugins.addHeaderCSS("/Content/CSS/BasicSiteAuth.css", ref pageElements);
}
else
{
string error = null;
string username = request.Form["username"];
string captcha = request.Form["captcha"];
string userid = null;
// Check if the user is looking up a user for the first time - we'll allow the user to answer if the captcha is valid - this is security against brute-force to test if users exist
if (username != null && captcha != null)
{
// Verify captcha
if (!Common.Validation.validCaptcha(captcha))
error = "Incorrect captcha code!";
else
HttpContext.Current.Session["recover_sqa"] = username;
}
// Check if the user exists
if (username != null)
{
string rawUserid = (conn.Query_Scalar("SELECT userid FROM bsa_users WHERE username LIKE '" + Utils.Escape(username.Replace("%", "")) + "'") ?? string.Empty).ToString();
if (rawUserid.Length > 0)
userid = rawUserid;
else
error = "User does not exist!";
}
// Check the user has not exceeded the maximum secret answering attempts
if (conn.Query_Count("SELECT COUNT('') FROM bsa_recovery_sqa_attempts WHERE ip='" + Utils.Escape(request.UserHostAddress) + "' AND datetime >= DATE_SUB(NOW(), INTERVAL " + Core.settings[SETTINGS_CATEGORY].getInt(SETTINGS_RECOVERY_SQA_ATTEMPTS_INTERVAL) + " MINUTE)") >= Core.settings[SETTINGS_CATEGORY].getInt(SETTINGS_RECOVERY_SQA_ATTEMPTS_MAX))
error = "You have exceeded the maximum attempts at answering a secret-question from this IP, come back in " + Core.settings[SETTINGS_CATEGORY].getInt(SETTINGS_RECOVERY_SQA_ATTEMPTS_INTERVAL) + " minutes!";
// Check if the user wants the form for answering a secret question - but only if a username has been posted, exists and captcha is valid
if (error == null && userid != null && HttpContext.Current.Session["recover_sqa"] != null && username == (string)HttpContext.Current.Session["recover_sqa"])
{
// Fetch the secret question & password
ResultRow sqa = conn.Query_Read("SELECT secret_question, secret_answer FROM bsa_users WHERE userid='" + Utils.Escape(userid) + "'")[0];
if (sqa["secret_question"].Length == 0 || sqa["secret_answer"].Length == 0)
error = "Secret question recovery for this account has been disabled!";
else
{
// Check for postback
string secretAnswer = request.Form["secret_answer"];
string newPassword = request.Form["newpassword"];
string newPasswordConfirm = request.Form["newpassword_confirm"];
if (username != null && secretAnswer != null)
{
const string incorrectAnswer = "Incorrect secret answer!";
// Validate
if (secretAnswer.Length < SECRET_ANSWER_MIN || secretAnswer.Length > SECRET_ANSWER_MAX)
error = incorrectAnswer;
else if (newPassword != newPasswordConfirm)
error = "Your new password and the confirm password are different, retype your password!";
else if (newPassword.Length < PASSWORD_MIN || newPassword.Length > PASSWORD_MAX)
error = "Password must be " + PASSWORD_MIN + " to " + PASSWORD_MAX + " characters in length!";
else if (sqa["secret_answer"] != secretAnswer)
{
// Insert the attempt
conn.Query_Execute("INSERT INTO bsa_recovery_sqa_attempts (ip, datetime) VALUES('" + Utils.Escape(request.UserHostAddress) + "', NOW())");
// Log the event
logEvent(userid, LogEvents.AccountRecovery_SQA_Incorrect, request.UserHostAddress + " - " + request.UserAgent, conn);
// Inform the user
error = "Incorrect secret answer!";
}
else
{
// Log the event
logEvent(userid, LogEvents.AccountRecovered_SQA, request.UserHostAddress + " - " + request.UserAgent, conn);
// Change the password
conn.Query_Execute("UPDATE bsa_users SET password='" + Utils.Escape(generateHash(newPassword, salt1, salt2)) + "' WHERE userid='" + Utils.Escape(userid) + "'");
// Redirect to success page
response.Redirect(pageElements["URL"] + "/recover/secret_qa/success");
}
}
// Display form
pageElements["TITLE"] = "Account Recovery - Secret Question";
pageElements["CONTENT"] = Core.templates["basic_site_auth"]["recovery_qa_question"]
.Replace("%USERNAME%", HttpUtility.HtmlEncode(username ?? string.Empty))
.Replace("%SECRET_QUESTION%", HttpUtility.HtmlEncode(sqa["secret_question"]))
.Replace("%SECRET_ANSWER%", HttpUtility.HtmlEncode(secretAnswer ?? string.Empty))
.Replace("%ERROR%", error != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", HttpUtility.HtmlEncode(error)) : string.Empty);
// Add CSS file
Misc.Plugins.addHeaderCSS("/Content/CSS/BasicSiteAuth.css", ref pageElements);
}
}
//.........这里部分代码省略.........
示例5: getPluginBasePath
/// <summary>
/// Gets the directory of a plugin; returns null if not found.
/// </summary>
/// <param name="pluginid"></param>
/// <param name="conn"></param>
/// <returns></returns>
public static string getPluginBasePath(string pluginid, Connector conn)
{
string basePath = (string)conn.Query_Scalar("SELECT directory FROM plugins WHERE pluginid='" + Utils.Escape(pluginid) + "'");
if(basePath == null)
return null;
else
return Core.basePath + "\\App_Code\\Plugins\\" + basePath;
}
示例6: install
//.........这里部分代码省略.........
doc.LoadXml(File.ReadAllText(tempPath + "\\Config.xml"));
}
catch (Exception ex)
{
try { Directory.Delete(tempPath, true); } catch { }
return "Could not load plugin configuration - " + ex.Message + "!";
}
}
else
{
try
{
doc.LoadXml(File.ReadAllText(basePath + "\\Config.xml"));
}
catch (Exception ex)
{
return "Could not load plugin configuration - " + ex.Message + "!";
}
}
// Read config values if pluginid is null
string directory;
string title;
string classpath;
string cycleInterval;
string invokeOrder;
bool handles404;
bool handlesRequestStart;
bool handlesRequestEnd;
if (pluginid == null)
try
{
directory = doc["settings"]["directory"].InnerText;
title = doc["settings"]["title"].InnerText;
classpath = doc["settings"]["classpath"].InnerText;
cycleInterval = doc["settings"]["cycle_interval"].InnerText;
invokeOrder = doc["settings"]["invoke_order"].InnerText;
handles404 = doc["settings"]["handles_404"].InnerText.Equals("1");
handlesRequestStart = doc["settings"]["handles_request_start"].InnerText.Equals("1");
handlesRequestEnd = doc["settings"]["handles_request_end"].InnerText.Equals("1");
}
catch (Exception ex)
{
if (pathIsZipFile)
try { Directory.Delete(tempPath, true); }
catch { }
return "Could not read configuration, it's most likely a piece of data is missing; this could be a plugin designed for a different version of Uber CMS - " + ex.Message + "!";
}
else
{
directory = title = classpath = cycleInterval = invokeOrder = null;
handles404 = handlesRequestStart = handlesRequestEnd = false;
}
if (pathIsZipFile)
{
// Check plugin directory doesn't exist
pluginDir = Core.basePath + "\\App_code\\Plugins\\" + directory;
if (Directory.Exists(pluginDir))
{
try { Directory.Delete(tempPath, true); }
catch { }
return "Failed to create new plugin directory - '" + pluginDir + "' already exists! The plugin may already be installed...";
}
// Move extracted directory
try
{
Directory.Move(tempPath, pluginDir);
}
catch (Exception ex)
{
try { Directory.Delete(tempPath, true); }
catch { }
return "Failed to move extracted directory '" + tempPath + "' to '" + pluginDir + "' - " + ex.Message + "!";
}
}
// Update the database
try
{
if (pluginid == null) // Insert if the pluginid is null, else we'll just update the status
finalPluginid = conn.Query_Scalar("INSERT INTO plugins (title, directory, classpath, cycle_interval, invoke_order, state, handles_404, handles_request_start, handles_request_end) VALUES('" + Utils.Escape(title) + "', '" + Utils.Escape(directory) + "', '" + Utils.Escape(classpath) + "', '" + Utils.Escape(cycleInterval) + "', '" + Utils.Escape(invokeOrder) + "', '" + (int)(UberCMS.Plugins.Base.State.Disabled) + "', '" + (handles404 ? "1" : "0") + "', '" + (handlesRequestStart ? "1" : "0") + "', '" + (handlesRequestEnd ? "1" : "0") + "'); SELECT LAST_INSERT_ID();").ToString();
else
{
conn.Query_Execute("UPDATE plugins SET state='" + (int)UberCMS.Plugins.Base.State.Disabled + "' WHERE pluginid='" + Utils.Escape(pluginid) + "'");
finalPluginid = pluginid;
}
}
catch (Exception ex)
{
if (pathIsZipFile)
{
// Delete the directory we copied - error occurred during installation, no point of wasting space/risking probabal future issues
try
{
Directory.Delete(pluginDir, true);
}
catch { }
}
return "Failed to insert plugin into database - " + ex.Message + " - " + ex.GetBaseException().Message + "!";
}
return null;
}
示例7: pageDownloads_Upload
public static void pageDownloads_Upload(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response, bool admin)
{
// Check the user is an admin
if (!admin) return;
string folderid = request.QueryString["2"];
if (folderid == null || folderid.Length == 0) return; // Invalid folderid
// Fetch folder details
Result folderRaw = conn.Query_Read("SELECT folderid, title, path FROM downloads_folders WHERE folderid='" + Utils.Escape(folderid) + "'");
if (folderRaw.Rows.Count != 1) return; // No folder found
ResultRow folder = folderRaw[0];
string path = folder["path"] + (folder["title"].Length > 0 ? (folder["path"].Length > 0 ? "/" : string.Empty) + folder["title"] : string.Empty);
string physicalPath = downloadsPath.Replace("\\", "/") + "/" + path;
string error = null;
HttpPostedFile file = request.Files["file_upload"];
if (file != null)
{
string dest = physicalPath + "/" + file.FileName;
// Check the file doesn't already exist
if (file.ContentLength == 0)
error = "No file uploaded!";
else if (File.Exists(dest))
error = "Cannot save file - already exists at '" + dest + "'!";
else
{
string downloadid = null;
try
{
string title = file.FileName;
string extension = file.FileName.LastIndexOf('.') != -1 ? file.FileName.Substring(file.FileName.LastIndexOf('.') + 1) : string.Empty;
// Create an entry for the file
downloadid = conn.Query_Scalar("INSERT INTO downloads_files (folderid, title, extension, physical_path, datetime) VALUES('" + Utils.Escape(folder["folderid"]) + "', '" + Utils.Escape(title) + "', '" + Utils.Escape(extension) + "', '" + Utils.Escape(physicalPath + "/" + title) + "', NOW()); SELECT LAST_INSERT_ID();").ToString();
// Save the file
file.SaveAs(dest);
// Update the file-size and iconid
string iconid = null;
processFileIcon(ref iconid, dest, extension);
FileInfo fi = new FileInfo(dest);
conn.Query_Execute("UPDATE downloads_files SET file_size='" + Utils.Escape(file.ContentLength.ToString()) + "', iconid=" + (iconid != null ? "'" + Utils.Escape(iconid) + "'" : "NULL") + " WHERE downloadid='" + Utils.Escape(downloadid) + "'");
// End the response
conn.Disconnect();
response.Redirect(pageElements["URL"] + "/download/" + downloadid);
}
catch (Exception ex)
{
if (downloadid != null)
// Remove the download from the database - an error occurred
conn.Query_Execute("DELETE FROM downloads_files WHERE downloadid='" + Utils.Escape(downloadid) + "'");
// The error will be pretty detailed, since the user is an admin and therefore most likely the site administrator
error = "Failed to handle uploaded-file: " + ex.Message + "(" + ex.GetBaseException().Message + ") - " + ex.StackTrace;
}
}
}
pageElements["CONTENT"] = Core.templates["downloads"]["upload"]
.Replace("%ERROR%", error != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", HttpUtility.HtmlEncode(error)) : string.Empty)
.Replace("%FOLDERID%", folderid)
.Replace("%PATH%", HttpUtility.HtmlEncode(path))
.Replace("%PHYSICAL_PATH%", HttpUtility.HtmlEncode(physicalPath))
;
pageElements["TITLE"] = "Downloads - Upload";
}
示例8: pageDownload_Thumb
public static void pageDownload_Thumb(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response, bool admin, ResultRow file)
{
// Check the background has been loaded/cached
if (pageDownload_Thumb_bbcode == null)
pageDownload_Thumb_bbcode = (Bitmap)Image.FromFile(Core.basePath + "\\Content\\Images\\downloads\\bbcode.png");
// Construct the image
Bitmap output = (Bitmap)pageDownload_Thumb_bbcode.Clone();
Graphics g = Graphics.FromImage(output);
// Grab the associated icon
byte[] rawIcon = null;
if (file["iconid"].Length > 0 && file["iconid"] != "0")
{
// Grab the icon generated of the file
Result data = conn.Query_Read("SELECT data FROM downloads_files_icons WHERE iconid='" + Utils.Escape(file["iconid"]) + "'");
if (data.Rows.Count == 1)
rawIcon = data[0].GetByteArray("data");
}
if (rawIcon == null && file["extension"].Length > 0)
{
// Grab the icon associated with the extension
Result data = conn.Query_Read("SELECT icon FROM downloads_ext_icons WHERE extension='" + Utils.Escape(file["extension"]) + "'");
if (data.Rows.Count == 1)
rawIcon = data[0].GetByteArray("icon");
}
if (rawIcon == null)
{
// Associate unknown extension with this file
if (pageDownloads_Icon_Unknown == null)
loadUknownIcon();
rawIcon = pageDownloads_Icon_Unknown;
}
// Draw icon
MemoryStream ms = new MemoryStream(rawIcon);
Bitmap icon = (Bitmap)Image.FromStream(ms);
// Apply fake rounded edges
icon.SetPixel(0, 0, Color.Transparent); // Top-left
icon.SetPixel(1, 0, Color.Transparent);
icon.SetPixel(0, 1, Color.Transparent);
icon.SetPixel(31, 0, Color.Transparent); // Top-right
icon.SetPixel(30, 0, Color.Transparent);
icon.SetPixel(31, 1, Color.Transparent);
icon.SetPixel(0, 31, Color.Transparent); // Bottom-left
icon.SetPixel(0, 30, Color.Transparent);
icon.SetPixel(1, 31, Color.Transparent);
icon.SetPixel(31, 31, Color.Transparent); // Bottom-right
icon.SetPixel(31, 30, Color.Transparent);
icon.SetPixel(30, 31, Color.Transparent);
g.DrawImage(icon, 5, 8, 32, 32);
icon.Dispose();
ms.Dispose();
// Draw title
g.DrawString(file["title"], new Font("Arial", 12.0f, FontStyle.Regular, GraphicsUnit.Pixel), new SolidBrush(Color.White), 40, 8);
// Draw downloads
g.DrawString(conn.Query_Scalar("SELECT COUNT('') FROM (SELECT ip_addr FROM downloads WHERE downloadid='" + Utils.Escape(file["downloadid"]) + "' GROUP BY ip_addr) AS a").ToString() + " downloads", new Font("Arial", 12.0f, FontStyle.Regular, GraphicsUnit.Pixel), new SolidBrush(Color.LightGray), 40, 24);
// Output it to the user
ms = new MemoryStream();
output.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
output.Dispose();
response.ContentType = "image/png";
response.BinaryWrite(ms.ToArray());
ms.Dispose();
conn.Disconnect();
response.End();
}
示例9: 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);
}
示例10: pageArticle_View_History
public static void pageArticle_View_History(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)
{
// Setup the page being viewed
int page;
string rawPage = request.QueryString["apg"];
if (rawPage == null || !int.TryParse(rawPage, out page) || page < 1) page = 1;
// Append header
content.Append(
Core.templates["articles"]["history_header"]
);
// Grab the current selected article
string currentArticleID = (conn.Query_Scalar("SELECT articleid_current FROM articles_thread WHERE threadid='" + Utils.Escape(article["threadid"]) + "'") ?? string.Empty).ToString();
// Append each article revision
int historyPerPage = Core.settings[SETTINGS_KEY].getInt(SETTINGS_HISTORY_PER_PAGE);
Result articles = conn.Query_Read("SELECT a.*, u.username, u2.username AS author FROM articles AS a LEFT OUTER JOIN bsa_users AS u ON u.userid=a.moderator_userid LEFT OUTER JOIN bsa_users AS u2 ON u2.userid=a.userid WHERE a.threadid='" + Utils.Escape(article["threadid"]) + "' ORDER BY a.articleid DESC LIMIT " + ((historyPerPage * page) - historyPerPage) + "," + historyPerPage);
foreach (ResultRow a in articles)
{
content.Append(
Core.templates["articles"]["history_row"]
.Replace("<ARTICLEID>", HttpUtility.HtmlEncode(a["articleid"]))
.Replace("<SELECTED>", a["articleid"] == currentArticleID ? "SELECTED" : string.Empty)
.Replace("<TITLE>", HttpUtility.HtmlEncode(a["title"]))
.Replace("<PUBLISHED>", a["published"].Equals("1") ? "Published by " + HttpUtility.HtmlEncode(a["username"]) : "Pending publication.")
.Replace("<DATETIME>", a["datetime"].Length > 0 ? a["datetime"] : "Unknown")
.Replace("<DATETIME_SHORT>", a["datetime"].Length > 0 ? Misc.Plugins.getTimeString(DateTime.Parse(a["datetime"])) : "Unknown")
.Replace("<CREATOR_USERID>", HttpUtility.HtmlEncode(a["userid"]))
.Replace("<CREATOR>", HttpUtility.HtmlEncode(a["author"]))
);
}
// Append navigator
content.Append(
Core.templates["articles"]["page_nav"]
.Replace("<SUBPAGE>", "history")
.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 navigator flags
if (page > 1)
pageElements.setFlag("ARTICLE_PAGE_PREVIOUS");
if (page < int.MaxValue && articles.Rows.Count == historyPerPage)
pageElements.setFlag("ARTICLE_PAGE_NEXT");
}
示例11: pageArticle_View
/// <summary>
/// Used to view an article.
/// </summary>
/// <param name="pluginid"></param>
/// <param name="conn"></param>
/// <param name="pageElements"></param>
/// <param name="request"></param>
/// <param name="response"></param>
public static void pageArticle_View(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
{
// Retrieve the article ID
string articleid;
if (request.QueryString["page"] == "article")
articleid = request.QueryString["1"];
else
{
// Build the relative URL
StringBuilder relativeUrl = new StringBuilder();
relativeUrl.Append(request.QueryString["page"]).Append("/"); // The querystring "pg" should never be null, however no null exception will occur with stringbuilder anyhow
string chunk;
int relativeUrlMaxChunks = Core.settings[SETTINGS_KEY].getInt(SETTINGS_RELATIVE_URL_MAXCHUNKS);
int relativeUrlChunkMax = Core.settings[SETTINGS_KEY].getInt(SETTINGS_RELATIVE_URL_CHUNK_MAX);
int relativeUrlChunkMin = Core.settings[SETTINGS_KEY].getInt(SETTINGS_RELATIVE_URL_CHUNK_MIN);
for (int i = 1; i <= relativeUrlMaxChunks; i++)
{
chunk = request.QueryString[i.ToString()];
if (chunk != null)
{
if (chunk.Length < relativeUrlChunkMin || chunk.Length > relativeUrlChunkMax)
return; // Invalid request - hence 404...
else
relativeUrl.Append(chunk).Append("/");
}
else
break;
}
// Check if we've grabbed anything
if (relativeUrl.Length == 0)
return; // No URL captured - 404...
else
relativeUrl.Remove(relativeUrl.Length - 1, 1); // Remove tailing slash
// Grab the article ID from the database
articleid = (conn.Query_Scalar("SELECT articleid_current FROM articles_thread WHERE relative_url='" + Utils.Escape(relativeUrl.ToString()) + "'") ?? string.Empty).ToString();
}
// Check we have an articleid that is not null and greater than zero, else 404
if (articleid == null || articleid.Length == 0) return;
// Load the article's data
Result articleRaw = conn.Query_Read("SELECT (SELECT COUNT('') FROM articles_thread_permissions WHERE threadid=at.threadid LIMIT 1) AS perms_enabled, (SELECT COUNT('') FROM articles WHERE threadid=a.threadid AND articleid <= a.articleid ORDER BY articleid ASC) AS revision, (SELECT ac.allow_comments FROM articles_thread AS act LEFT OUTER JOIN articles AS ac ON ac.articleid=act.articleid_current WHERE act.threadid=at.threadid) AS allow_comments_thread, a.articleid, a.threadid, a.title, a.userid, a.body, a.body_cached, a.moderator_userid, a.published, a.allow_comments, a.allow_html, a.show_pane, a.datetime, at.relative_url, at.articleid_current, at.pdf_name, u.username FROM (articles AS a, articles_thread AS at) LEFT OUTER JOIN bsa_users AS u ON u.userid=a.userid WHERE a.articleid='" + Utils.Escape(articleid) + "' AND at.threadid=a.threadid");
if (articleRaw.Rows.Count != 1)
return; // 404 - no data found - the article is corrupt (thread and article not linked) or the article does not exist
ResultRow article = articleRaw[0];
// Load the users permissions
bool published = article["published"].Equals("1");
bool permCreate;
bool permDelete;
bool permPublish;
bool owner;
// Grab the user's permissions and check they're allowed to access the thread - with overriding for PDF generator via access-code
// -- Check for override
string pdfc = request.QueryString["pdfc"];
bool pdfOverride = pdfc != null && pdfc.Length == 16 && pdfAccessCodes.ContainsKey(pdfc) && pdfAccessCodes[pdfc] == article["articleid"];
// -- Check actual permissions
bool threadRequiresPermissions = !pdfOverride && article["perms_enabled"] != "0";
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
Result permsRaw = conn.Query_Read("SELECT " + (threadRequiresPermissions ? "(SELECT COUNT('') FROM articles_thread_permissions WHERE threadid='" + Utils.Escape(article["threadid"]) + "' AND groupid=g.groupid) AS role_exists," : string.Empty) + " g.access_media_create, g.access_media_delete, g.access_media_publish 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(permsRaw.Rows.Count != 1) return; // Something has gone wrong
ResultRow perms = permsRaw[0];
permPublish = perms["access_media_publish"].Equals("1");
// Check if the user has permission to view the thread; if the user has publish permissions, they are automatically allowed to view the thread
if (!permPublish && threadRequiresPermissions && perms["role_exists"] == "0")
{
pageArticle_View_AccessDenied(conn, pageElements);
return;
}
permCreate = perms["access_media_create"].Equals("1");
permDelete = perms["access_media_delete"].Equals("1");
owner = article["userid"] == HttpContext.Current.User.Identity.Name;
}
else if (threadRequiresPermissions)
{
pageArticle_View_AccessDenied(conn, pageElements);
return;
}
else
{
permCreate = false;
permDelete = false;
permPublish = false;
owner = false;
}
// Create stringbuilder for assembling the article
StringBuilder content = new StringBuilder();
// Check the article is published *or* the user is admin/owner of the article
if (!published && (!HttpContext.Current.User.Identity.IsAuthenticated || (!owner && !permPublish)))
return;
// Append the main body of the article
content.Append(Core.templates["articles"]["article"]);
//.........这里部分代码省略.........
示例12: pageArticle_Editor
/// <summary>
/// Used to create/modify an article.
/// </summary>
/// <param name="pluginid"></param>
/// <param name="conn"></param>
/// <param name="pageElements"></param>
/// <param name="request"></param>
/// <param name="response"></param>
public static void pageArticle_Editor(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
{
// Check the user is logged-in, else redirect to the login page
if (!HttpContext.Current.User.Identity.IsAuthenticated)
response.Redirect(pageElements["URL"] + "/login", true);
// Load the users permissions and check they're able to create articles
Result perms = conn.Query_Read("SELECT ug.access_media_create, ug.access_media_publish, ug.access_media_edit, ug.access_admin FROM bsa_users AS u LEFT OUTER JOIN bsa_user_groups AS ug ON ug.groupid=u.groupid WHERE u.userid='" + Utils.Escape(HttpContext.Current.User.Identity.Name) + "'");
if (perms.Rows.Count != 1 || !perms[0]["access_media_create"].Equals("1")) return;
bool permAdmin = perms[0]["access_admin"].Equals("1");
bool permEdit = perms[0]["access_media_edit"].Equals("1");
bool permPublish = perms[0]["access_media_publish"].Equals("1");
string error = null;
Result preData = null;
ResultRow preDataRow = null;
// Check if we're modifying an existing article, if so we'll load the data
string articleid = request.QueryString["articleid"];
if (articleid != null && Misc.Plugins.isNumeric(articleid))
{
// Attempt to load the pre-existing article's data
preData = conn.Query_Read("SELECT a.*, at.relative_url, at.pdf_name, GROUP_CONCAT(at2.keyword SEPARATOR ',') AS tags FROM articles AS a LEFT OUTER JOIN articles_tags AS at2 ON (EXISTS (SELECT tagid FROM articles_tags_article WHERE tagid=at2.tagid AND articleid='" + Utils.Escape(articleid) + "')) LEFT OUTER JOIN articles_thread AS at ON at.threadid=a.threadid WHERE articleid='" + Utils.Escape(articleid) + "'");
if (preData.Rows.Count != 1) preData = null;
else
preDataRow = preData[0];
}
// Check for postback
string title = request.Form["title"];
string body = request.Form["body"];
string relativeUrl = request.Form["relative_url"] ?? request.QueryString["relative_url"];
string tags = request.Form["tags"];
bool allowHTML = request.Form["allow_html"] != null;
bool allowComments = request.Form["allow_comments"] != null;
bool showPane = request.Form["show_pane"] != null;
bool inheritThumbnail = request.Form["inherit_thumbnail"] != null;
bool updateExisting = request.Form["update_existing"] != null;
HttpPostedFile thumbnail = request.Files["thumbnail"];
if (title != null && body != null && relativeUrl != null && tags != null)
{
// Validate
if (title.Length < Core.settings[SETTINGS_KEY].getInt(SETTINGS_TITLE_MIN) || title.Length > Core.settings[SETTINGS_KEY].getInt(SETTINGS_TITLE_MAX))
error = "Title must be " + Core.settings[SETTINGS_KEY][SETTINGS_TITLE_MIN] + " to " + Core.settings[SETTINGS_KEY][SETTINGS_TITLE_MAX] + " characters in length!";
else if (body.Length < Core.settings[SETTINGS_KEY].getInt(SETTINGS_BODY_MIN) || body.Length > Core.settings[SETTINGS_KEY].getInt(SETTINGS_BODY_MAX))
error = "Body must be " + Core.settings[SETTINGS_KEY][SETTINGS_BODY_MIN] + " to " + Core.settings[SETTINGS_KEY][SETTINGS_BODY_MAX] + " characters in length!";
else if (body.Replace(" ", string.Empty).Length == 0)
error = "Body cannot be empty/contain just spaces!";
else if (thumbnail != null && thumbnail.ContentLength > 0 && thumbnail.ContentLength > Core.settings[SETTINGS_KEY].getInt(SETTINGS_THUMBNAIL_MAXSIZE))
error = "Thumbnail cannot exceed " + Core.settings[SETTINGS_KEY][SETTINGS_THUMBNAIL_MAXSIZE] + " bytes (" + Misc.Plugins.getBytesString(Core.settings[SETTINGS_KEY].getInt(SETTINGS_THUMBNAIL_MAXSIZE)) + ")!";
else if (thumbnail != null && thumbnail.ContentLength > 0 && !Core.settings[SETTINGS_KEY].getCommaArrayContains(SETTINGS_IMAGE_TYPES, thumbnail.ContentType))
error = "Invalid thumbnail image format - ensure you uploaded an image!";
else if ((error = validRelativeUrl(relativeUrl, Core.settings[SETTINGS_KEY].getInt(SETTINGS_RELATIVE_URL_MAXCHUNKS), Core.settings[SETTINGS_KEY].getInt(SETTINGS_RELATIVE_URL_CHUNK_MIN), Core.settings[SETTINGS_KEY].getInt(SETTINGS_RELATIVE_URL_CHUNK_MAX))) != null)
;
else
{
// Verify the user has not exceeded post limits for today - unless they're admin, we'll just skip the checks
ResultRow postLimits = permAdmin ? null : conn.Query_Read("SELECT (SELECT COUNT('') FROM articles WHERE userid='" + Utils.Escape(HttpContext.Current.User.Identity.Name) + "' AND datetime >= DATE_SUB(NOW(), INTERVAL 1 HOUR)) AS articles_hour, (SELECT COUNT('') FROM articles WHERE userid='" + Utils.Escape(HttpContext.Current.User.Identity.Name) + "' AND datetime >= DATE_SUB(NOW(), INTERVAL 1 DAY)) AS articles_day")[0];
if (postLimits != null && int.Parse(postLimits["articles_hour"]) >= Core.settings[SETTINGS_KEY].getInt(SETTINGS_ARTICLES_EDIT_PER_HOUR))
error = "You've already posted the maximum amount of articles allowed within an hour, please try again later!";
else if (postLimits != null && int.Parse(postLimits["articles_day"]) >= Core.settings[SETTINGS_KEY].getInt(SETTINGS_ARTICLES_EDIT_PER_DAY))
error = "You've already posted the maximum amount of articles allowed today, please try again later!";
else
{
// Verify tags
ArticleTags parsedTags = getTags(tags, Core.settings[SETTINGS_KEY].getInt(SETTINGS_TAGS_TITLE_MIN), Core.settings[SETTINGS_KEY].getInt(SETTINGS_TAGS_TITLE_MAX), Core.settings[SETTINGS_KEY].getInt(SETTINGS_TAGS_MAX));
if (parsedTags.error != null) error = parsedTags.error;
else
{
// Check if we're inserting, else perhaps inheriting, a thumbnail
string thumbnailid = null;
if (thumbnail != null && thumbnail.ContentLength > 0)
{
byte[] imageData = compressImageData(thumbnail.InputStream, Core.settings[SETTINGS_KEY].getInt(SETTINGS_THUMBNAIL_MAXWIDTH), Core.settings[SETTINGS_KEY].getInt(SETTINGS_THUMBNAIL_MAXHEIGHT));
if (imageData != null)
{
// Success - insert thumbnail and get thumbnailid
Dictionary<string, object> thumbParams = new Dictionary<string, object>();
thumbParams.Add("thumb", imageData);
thumbnailid = conn.Query_Scalar_Parameters("INSERT INTO articles_thumbnails (data) VALUES(@thumb); SELECT LAST_INSERT_ID();", thumbParams).ToString();
}
else
error = "Failed to process thumbnail image, please try again or report this to the site administrator!";
}
else if (inheritThumbnail && preDataRow != null && preDataRow["thumbnailid"].Length != 0)
{
// Grab pre-existing thumbnailid
thumbnailid = preDataRow["thumbnailid"];
}
// Ensure no thumbnail processing errors occur, else do not continue
if (error == null)
{
// Format the body formatting for caching
StringBuilder cached = new StringBuilder(body);
//.........这里部分代码省略.........
示例13: pageArticles_Pending
public static void pageArticles_Pending(ref StringBuilder content, string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
{
// Check the user has publishing permissions
if (!HttpContext.Current.User.Identity.IsAuthenticated || !conn.Query_Scalar("SELECT ug.access_media_publish FROM bsa_users AS u LEFT OUTER JOIN bsa_user_groups AS ug ON ug.groupid=u.groupid WHERE u.userid='" + Utils.Escape(HttpContext.Current.User.Identity.Name) + "'").ToString().Equals("1"))
return;
// Get the current page
int page;
if (!int.TryParse(request.QueryString["pg"], out page) || page < 1) page = 1;
// Build a list of pending articles
StringBuilder articlesPending = new StringBuilder();
int pendingPerPage = Core.settings[SETTINGS_KEY].getInt(SETTINGS_PENDING_PER_PAGE);
Result pending = conn.Query_Read("SELECT a.articleid, a.title, u.username, a.userid, a.datetime, a.allow_html FROM articles AS a LEFT OUTER JOIN bsa_users AS u ON u.userid=a.userid WHERE a.published='0' ORDER BY a.datetime ASC LIMIT " + ((page * pendingPerPage) - pendingPerPage) + "," + pendingPerPage);
if (pending.Rows.Count > 0)
foreach (ResultRow article in pending)
articlesPending.Append(
Core.templates["articles"]["articles_pending_row"]
.Replace("<ARTICLEID>", HttpUtility.HtmlEncode(article["articleid"]))
.Replace("<TITLE>", HttpUtility.HtmlEncode(article["title"]))
.Replace("<USERNAME>", HttpUtility.HtmlEncode(article["username"]))
.Replace("<USERID>", HttpUtility.HtmlEncode(article["userid"]))
.Replace("<CREATED>", HttpUtility.HtmlEncode(article["datetime"]))
.Replace("<WARNINGS>", article["allow_html"].Equals("1") ? "HTML" : " ")
);
else
articlesPending.Append("No pending articles.");
// Append navigation
articlesPending.Append(
Core.templates["articles"]["pending_nav"]
.Replace("<PAGE_PREVIOUS>", (page > 1 ? page - 1 : 1).ToString())
.Replace("<PAGE>", page.ToString())
.Replace("<PAGE_NEXT>", (page < int.MaxValue ? page + 1 : int.MaxValue).ToString())
);
// Set navigation flags
if (page > 1) pageElements.setFlag("ARTICLE_PAGE_PREVIOUS");
if (page < int.MaxValue && pending.Rows.Count == pendingPerPage) pageElements.setFlag("ARTICLE_PAGE_NEXT");
// Output the page
Misc.Plugins.addHeaderCSS(pageElements["URL"] + "/Content/CSS/Article.css", ref pageElements);
content.Append(Core.templates["articles"]["articles_pending"]
.Replace("<PENDING>", articlesPending.ToString())
);
pageElements["TITLE"] = "Articles - Pending";
}