当前位置: 首页>>代码示例>>C#>>正文


C# Misc.setFlag方法代码示例

本文整理汇总了C#中Misc.setFlag方法的典型用法代码示例。如果您正苦于以下问题:C# Misc.setFlag方法的具体用法?C# Misc.setFlag怎么用?C# Misc.setFlag使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Misc的用法示例。


在下文中一共展示了Misc.setFlag方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: requestEnd

 public static void requestEnd(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
 {
     bool cookiesEnabled = request.Cookies["cookie-control"] != null;
     // Add styling and toggle button
     Misc.Plugins.addHeaderCSS(pageElements["URL"] + "/Content/CSS/CookieControl.css", ref pageElements);
     Misc.Plugins.addHeaderJS(pageElements["URL"] + "/Content/JS/CookieControl.js", ref pageElements);
     // Add toggle button
     pageElements.appendToKey("BODY_FOOTER", Core.templates["cookiecontrol"]["toggle"]);
     // Add warning banner
     if (!cookiesEnabled)
         pageElements.appendToKey("BODY_HEADER", Core.templates["cookiecontrol"]["banner"]);
     else
     {
         // Check if cookies have been enabled, if so return - no need to remove cookies
         pageElements.setFlag("COOKIES_ON");
         return;
     }
     // Clear all the response cookies - these may have been added programmatically
     response.Cookies.Clear();
     // Add each cookie, sent in the request, in the response - to expire
     HttpCookie cookie;
     for (int i = 0; i < request.Cookies.Count; i++)
     {
         cookie = request.Cookies[i];
         if (cookie.Name != "ASP.NET_SessionId")
         {
             cookie.Expires = DateTime.Now.AddDays(-2);
             response.Cookies.Add(cookie);
         }
     }
 }
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:31,代码来源:Base.cs

示例2: 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" : "&nbsp;")
                 );
     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";
 }
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:42,代码来源:Base.cs

示例3: pageDownload_View

 public static void pageDownload_View(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response, bool admin, ResultRow file)
 {
     // Get downloads
     ResultRow downloads = conn.Query_Read("SELECT (SELECT COUNT('') FROM downloads WHERE downloadid='" + Utils.Escape(file["downloadid"]) + "') AS downloads_total, (SELECT COUNT('') FROM (SELECT ip_addr FROM downloads WHERE downloadid='" + Utils.Escape(file["downloadid"]) + "' GROUP BY ip_addr) AS a) AS downloads_unique")[0];
     // Render page
     pageElements["CONTENT"] = Core.templates["downloads"]["download_get"]
         .Replace("%DOWNLOADID%", file["downloadid"])
         .Replace("%NAV%", getNavBar(file["physical_path"].LastIndexOf('/') == -1 ? string.Empty : file["physical_path"].Substring(0, file["physical_path"].LastIndexOf('/'))))
         .Replace("%EXTENSION%", HttpUtility.HtmlEncode(file["extension"]))
         .Replace("%FILESIZE%", HttpUtility.HtmlEncode(file["file_size"].Length > 0 ? Misc.Plugins.getBytesString(float.Parse(file["file_size"])) : "unknown bytes"))
         .Replace("%DESCRIPTION%", file["description"].Length > 0 ? HttpUtility.HtmlEncode(file["description"]) : "(no description)")
         .Replace("%ICONID%", HttpUtility.HtmlEncode(file["iconid"]))
         .Replace("%DOWNLOADS_TOTAL%", downloads["downloads_total"])
         .Replace("%DOWNLOADS_UNIQUE%", downloads["downloads_unique"])
         .Replace("%DIRECT_LINK%", "http://" + request.Url.Host + (request.Url.Port != 80 ? ":" + request.Url.Port : string.Empty) + "/download/" + file["downloadid"] + "." + file["extension"])
         ;
     pageElements["TITLE"] = "Download - " + HttpUtility.HtmlEncode(file["title"]);
     // Admin flag
     if (admin) pageElements.setFlag("DOWNLOADS_ADMIN");
     // Add CSS
     Misc.Plugins.addHeaderCSS(pageElements["URL"] + "/Content/CSS/Downloads.css", ref pageElements);
 }
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:22,代码来源:Downloads.cs

示例4: 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");
 }
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:67,代码来源:Base.cs

示例5: pageHistory


//.........这里部分代码省略.........
                            foreach (ResultRow reading in conn.Query_Read("SELECT watts, datetime FROM cc128_readings WHERE DATE(datetime) = " + (year != -1 && month != -1 && day != -1 ? "'" + year + "-" + month + "-" + day + "'" : "CURDATE()")))
                            {
                                seconds = DateTime.Parse(reading["datetime"]).Subtract(secondsStart).TotalSeconds; // 86400 seconds in a day
                                newX = (int)((seconds / 86400) * plotWidth);
                                newY = (int)(((double)int.Parse(reading["watts"]) / (double)maxValue) * plotHeight);
                                g.DrawLine(penDataWatts, graphPaddingLeft + (lastX != 0 ? lastX : newX - 1), (int)(graphPaddingTop + plotHeight) - (lasty != 0 ? lasty : newY), graphPaddingLeft + newX, (int)(graphPaddingTop + plotHeight) - newY);
                                lastX = newX;
                                lasty = newY;
                            }
                        }
                        g.Dispose();
                        response.ContentType = "image/png";
                        graph.Save(response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
                        response.End();
                    }
                    else
                    {
                        StringBuilder itemsDay = new StringBuilder();
                        for (int i = 1; i <= 32; i++)
                            itemsDay.Append("<option").Append(i == DateTime.Now.Day ? " selected=\"selected\">" : ">").Append(i).Append("</option>");
                        StringBuilder itemsMonth = new StringBuilder();
                        for (int i = 1; i <= 12; i++)
                            itemsMonth.Append("<option value=\"").Append(i).Append("\"").Append(i == DateTime.Now.Month ? " selected=\"selected\">" : ">").Append(DateTime.Parse("2000-" + i + "-01").ToString("MMMM")).Append("</option>");
                        StringBuilder itemsYear = new StringBuilder();
                        for (int i = DateTime.Now.AddYears(-5).Year; i <= DateTime.Now.Year; i++)
                            itemsYear.Append("<option").Append(i == DateTime.Now.Year ? " selected=\"selected\">" : ">").Append(i).Append("</option>");
                        // Output the content to display an image (above) of todays data
                        pageElements["CC128_CONTENT"] = Core.templates["cc128"]["history_today"]
                            .Replace("%ITEMS_DAY%", itemsDay.ToString())
                            .Replace("%ITEMS_MONTH%", itemsMonth.ToString())
                            .Replace("%ITEMS_YEAR%", itemsYear.ToString())
                            ;
                        pageElements["CC128_TITLE"] = "History - Today";
                        pageElements.setFlag("CC128_H_TODAY");
                    }
                    break;
                case "month":
                    // Month
                    string monthCurr = DateTime.Now.Year + "-" + DateTime.Now.Month + "-01";
                    // Get the max value for the month
                    Result monthMaxVal = conn.Query_Read("SELECT AVG(watts) AS watts FROM cc128_readings WHERE datetime >= '" + Utils.Escape(monthCurr) + "' ORDER BY watts DESC LIMIT 1");
                    if (monthMaxVal.Rows.Count != 1 || monthMaxVal[0]["watts"].Length == 0)
                        pageElements["CC128_CONTENT"] = "<p>No data available.</p>";
                    else
                    {
                        double maxValue = double.Parse(monthMaxVal[0]["watts"]);
                        // Process every day
                        StringBuilder monthBars = new StringBuilder();
                        double percent;
                        foreach (ResultRow day in conn.Query_Read("SELECT AVG(watts) AS watts, DAY(datetime) AS day FROM cc128_readings WHERE datetime >= '" + Utils.Escape(monthCurr) + "' GROUP BY DATE(datetime)"))
                        {
                            percent = Math.Floor(100 * (double.Parse(day["watts"]) / maxValue));
                            monthBars.Append(
                                Core.templates["cc128"]["history_bar"]
                                .Replace("%TITLE%", int.Parse(day["day"]).ToString("0#") + " - " + day["watts"] + " watts average")
                                .Replace("%PERCENT%", (percent > 100 ? 100 : percent).ToString())
                                );
                        }
                        pageElements["CC128_CONTENT"] = Core.templates["cc128"]["history_month"]
                        .Replace("%ITEMS%", monthBars.ToString())
                        ;
                    }
                    pageElements["CC128_TITLE"] = "History - This Month";
                    pageElements.setFlag("CC128_H_MONTH");
                    break;
                case "year":
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:67,代码来源:Base.cs

示例6: 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);
 }
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:87,代码来源:BasicSiteAuth.cs

示例7: pageProfile_Profile

 public static void pageProfile_Profile(string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
 {
     // Decide which user to display
     string userid = null;
     if (request.QueryString["userid"] != null) // Load via userid
     {
         // Ensure the userid is valid
         if (conn.Query_Count("SELECT COUNT('') FROM bsa_users WHERE userid='" + Utils.Escape(request.QueryString["userid"]) + "'") != 1)
             return;
         userid = request.QueryString["userid"];
     }
     else if (request.QueryString["username"] != null) // Load via username
     {
         // Fetch the userid, if not found we'll 404 the request by returning
         Result usernameToUserid = conn.Query_Read("SELECT userid FROM bsa_users WHERE username LIKE '" + Utils.Escape(request.QueryString["username"].Replace("%", "")) + "'");
         if (usernameToUserid.Rows.Count != 1) return;
         userid = usernameToUserid[0]["userid"];
     }
     else if (HttpContext.Current.User.Identity.IsAuthenticated) // Load the current logged-in user
         userid = HttpContext.Current.User.Identity.Name;
     else // No user specified, user is not authenticated - tell them to register
         response.Redirect(pageElements["URL"] + "/register", true);
     // By this point the userid should be valid and exist, hence we just need to grab the profile data
     string rawProfileDataQuery = "SELECT p.*, u.username, u.registered, g.title AS group_title, g.access_admin FROM bsa_profiles AS p LEFT OUTER JOIN bsa_users AS u ON u.userid=p.userid LEFT OUTER JOIN bsa_user_groups AS g ON g.groupid=u.groupid WHERE p.userid='" + Utils.Escape(userid) + "'";
     Result rawProfileData = conn.Query_Read(rawProfileDataQuery);
     if (rawProfileData.Rows.Count == 0) // Profile doesn't exist, create it
     {
         conn.Query_Execute("INSERT INTO bsa_profiles (userid) VALUES('" + Utils.Escape(userid) + "')");
         rawProfileData = conn.Query_Read(rawProfileDataQuery);
         if (rawProfileData.Rows.Count == 0) return; // Something is wrong...
     }
     ResultRow profileData = rawProfileData[0];
     // Check if admin or the owner of the profile - if so, we'll set the PROFILE_OWNER FLAG
     bool owner = false;
     if (HttpContext.Current.User.Identity.IsAuthenticated && (profileData["userid"] == HttpContext.Current.User.Identity.Name))
     {
         pageElements.setFlag("PROFILE_OWNER");
         owner = true;
     }
     // Check the user is allowed to access the profile - if it's disabled, only the owner or an admin can access it
     if (!owner && !profileData["disabled"].Equals("0"))
         return;
     // Check which page the user wants to access
     switch (request.QueryString["1"])
     {
         default:
             // -- About page is default
             pageProfile_About(pluginid, ref profileData, conn, ref pageElements, request, response);
             break;
         case "settings":
             pageProfile_Settings(pluginid, ref rawProfileDataQuery, ref profileData, conn, ref pageElements, request, response);
             break;
         case "upload":
             pageProfile_Upload(pluginid, ref profileData, conn, ref pageElements, request, response);
             break;
     }
     if (pageElements["PROFILE_CONTENT"] == null) return; // No content set, 404..
     // Build frame
     DateTime registered = profileData["registered"].Length > 0 ? DateTime.Parse(profileData["registered"]) : DateTime.MinValue;
     pageElements["CONTENT"] =
         Core.templates["bsa_profiles"]["profile_frame"]
         .Replace("<USERID>", HttpUtility.HtmlEncode(profileData["userid"]))
         .Replace("<PANE_BG_COLOUR>", profileData["colour_background"])
         .Replace("<PANE_TEXT_COLOUR>", profileData["colour_text"])
         .Replace("<BACKGROUND>", (profileData["background_url"].Length > 0 ? "url('" + HttpUtility.HtmlEncode(profileData["background_url"]) + "') " : string.Empty) + (profileData["background_colour"].Length > 0 ? "#" + profileData["background_colour"] : string.Empty))
         .Replace("<USERNAME>", HttpUtility.HtmlEncode(profileData["username"]))
         .Replace("<GROUP>", HttpUtility.HtmlEncode(profileData["group_title"]))
         .Replace("<REGISTERED>", HttpUtility.HtmlEncode(registered.ToString("dd MMMM yyyy")))
         .Replace("<REGISTERED_DAYS>", HttpUtility.HtmlEncode(Misc.Plugins.getTimeString(registered)))
         .Replace("<COUNTRY_FLAG>", profileData["country_code"].Length > 0 ? profileData["country_code"] : "unknown")
         .Replace("<COUNTRY_TITLE>", Common.Country.getCountryTitle(profileData["country_code"], conn) ?? "Unknown")
         .Replace("<GENDER_CODE>", profileData["gender"])
         .Replace("<GENDER>", profileData["gender"] == "1" ? "Male" : profileData["gender"] == "2" ? "Female" : "Not specified.")
         .Replace("<OCCUPATION>", profileData["occupation"].Length > 0 ? HttpUtility.HtmlEncode(profileData["occupation"]) : "Not specified.");
     ;
     pageElements["TITLE"] = "Profile - " + HttpUtility.HtmlEncode(profileData["username"]);
 }
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:77,代码来源:Base.cs

示例8: pageArticle_View_Comments

        public static void pageArticle_View_Comments(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)
        {
            bool allowComments = article["allow_comments_thread"].Equals("1");
            if (!allowComments)
                content.Append(Core.templates["articles"]["comments_disabled"]);

            // -- Check for a new comment posted by the user
            string commentError = null;
            string commentBody = request.Form["comment_body"];
            string commentCaptcha = request.Form["comment_captcha"];
            if (commentBody != null && commentCaptcha != null)
            {
                if (!Common.Validation.validCaptcha(commentCaptcha))
                    commentError = "Incorrect captcha verification code!";
                else if (commentBody.Length < Core.settings[SETTINGS_KEY].getInt(SETTINGS_COMMENTS_LENGTH_MIN) || commentBody.Length > Core.settings[SETTINGS_KEY].getInt(SETTINGS_COMMENTS_LENGTH_MAX))
                    commentError = "Your comment must be " + Core.settings[SETTINGS_KEY][SETTINGS_COMMENTS_LENGTH_MIN] + " to  " + Core.settings[SETTINGS_KEY][SETTINGS_COMMENTS_LENGTH_MAX] + " in length!";
                else if (commentBody.Replace(" ", string.Empty).Length == 0)
                    commentError = "Comment cannot be empty/contain just spaces!";
                else if (conn.Query_Count("SELECT COUNT('') FROM articles_thread_comments WHERE userid='" + Utils.Escape(HttpContext.Current.User.Identity.Name) + "' AND datetime >= DATE_SUB(NOW(), INTERVAL 1 HOUR)") >= Core.settings[SETTINGS_KEY].getInt(SETTINGS_COMMENTS_MAX_PER_HOUR))
                    commentError = "You've already posted the maximum of " + Core.settings[SETTINGS_KEY][SETTINGS_COMMENTS_MAX_PER_HOUR] + " comments per an hour - try again later!";
                else
                {
                    // Insert the post
                    conn.Query_Execute("INSERT INTO articles_thread_comments (threadid, userid, message, datetime) VALUES('" + Utils.Escape(article["threadid"]) + "', '" + Utils.Escape(HttpContext.Current.User.Identity.Name) + "', '" + Utils.Escape(commentBody) + "', NOW())");
                    // Reset comment body
                    commentBody = null;
                }
            }
            // -- Check if to delete a comment
            string dcom = request.QueryString["dcom"];
            if (dcom != null && HttpContext.Current.User.Identity.IsAuthenticated && Misc.Plugins.isNumeric(dcom))
            {
                bool canDelete = permDelete;
                if (!canDelete)
                {
                    // -- User cannot delete all comments, check if they're the owner
                    Result dcomData = conn.Query_Read("SELECT userid FROM articles_thread_comments WHERE commentid='" + Utils.Escape(dcom) + "'");
                    if (dcomData.Rows.Count == 1 && dcomData[0]["userid"] == HttpContext.Current.User.Identity.Name)
                        canDelete = true;
                }
                if (!canDelete) return;
                else
                    conn.Query_Execute("DELETE FROM articles_thread_comments WHERE commentid='" + Utils.Escape(dcom) + "'");
            }
            // Build comments body
            string commentsPageRaw = request.QueryString["apg"];
            // -- Get the page
            int commentsPage;
            if (!int.TryParse(commentsPageRaw, out commentsPage) || commentsPage < 1) commentsPage = 1;
            // -- Get the comments data associated with that page
            int commentsPerPage = Core.settings[SETTINGS_KEY].getInt(SETTINGS_COMMENTS_PER_PAGE);
            Result commentsData = conn.Query_Read("SELECT atc.*, u.username FROM articles_thread_comments AS atc LEFT OUTER JOIN bsa_users AS u ON u.userid=atc.userid WHERE threadid='" + Utils.Escape(article["threadid"]) + "' ORDER BY datetime DESC LIMIT " + ((commentsPerPage * commentsPage) - commentsPerPage) + "," + commentsPerPage);
            // -- Build the data
            if (commentsData.Rows.Count == 0)
                content.Append(Core.templates["articles"]["comments_empty"]);
            else
                foreach (ResultRow comment in commentsData)
                {
                    content.Append(
                        (HttpContext.Current.User.Identity.IsAuthenticated && (permDelete || HttpContext.Current.User.Identity.Name == comment["userid"]) ? Core.templates["articles"]["comment_delete"] : Core.templates["articles"]["comment"])
                        .Replace("<USERID>", comment["userid"])
                        .Replace("<ARTICLEID>", article["articleid"])
                        .Replace("<COMMENTID>", comment["commentid"])
                        .Replace("<USERNAME>", HttpUtility.HtmlEncode(comment["username"]))
                        .Replace("<DATETIME>", HttpUtility.HtmlEncode(comment["datetime"]))
                        .Replace("<BODY>", HttpUtility.HtmlEncode(comment["message"]))
                        );
                }
            // Set navigator
            content.Append(
                Core.templates["articles"]["page_nav"]
                .Replace("<SUBPAGE>", "comments")
                .Replace("<PAGE>", commentsPage.ToString())
                .Replace("<PAGE_PREVIOUS>", (commentsPage > 1 ? commentsPage - 1 : 1).ToString())
                .Replace("<PAGE_NEXT>", (commentsPage < int.MaxValue ? commentsPage + 1 : int.MaxValue).ToString())
                );
            // -- Set flags for the previous and next buttons - very simple solution but highly efficient
            if (commentsPage > 1)
                pageElements.setFlag("ARTICLE_PAGE_PREVIOUS");
            if (commentsData.Rows.Count == commentsPerPage)
                pageElements.setFlag("ARTICLE_PAGE_NEXT");
            // Set the postbox
            if (HttpContext.Current.User.Identity.IsAuthenticated && allowComments)
                content.Append(
                        Core.templates["articles"]["comments_postbox"]
                    .Replace("<ERROR>", commentError != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", commentError) : string.Empty)
                    .Replace("<COMMENT_BODY>", HttpUtility.HtmlEncode(commentBody))
                    );
        }
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:89,代码来源:Base.cs

示例9: 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");
 }
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:43,代码来源:Base.cs

示例10: pageArticle_Editor


//.........这里部分代码省略.........
                                        .Append(Utils.Escape(threadid))
                                        .Append("', '").Append(Utils.Escape(title))
                                        .Append("', '").Append(Utils.Escape(HttpContext.Current.User.Identity.Name))
                                        .Append("', '").Append(Utils.Escape(body))
                                        .Append("', '").Append(Utils.Escape(cached.ToString()))
                                        .Append("', ").Append(permPublish ? "'" + Utils.Escape(HttpContext.Current.User.Identity.Name) + "'" : "NULL")
                                        .Append(", '").Append(permPublish ? "1" : "0")
                                        .Append("', '").Append(allowComments ? "1" : "0")
                                        .Append("', '").Append(allowHTML ? "1" : "0")
                                        .Append("', '").Append(showPane ? "1" : "0")
                                        .Append("', ").Append(thumbnailid != null ? "'" + Utils.Escape(thumbnailid) + "'" : "NULL")
                                        .Append(", NOW()); SELECT LAST_INSERT_ID();");
                                    articleid = conn.Query_Scalar(query.ToString()).ToString();
                                    // If this was automatically published, set it as the current article for the thread
                                    if (permPublish)
                                        conn.Query_Execute("UPDATE articles_thread SET articleid_current='" + Utils.Escape(articleid) + "' WHERE relative_url='" + Utils.Escape(relativeUrl) + "'");
                                }
                                // Add/update pdf
                                pdfRebuild(pluginid, articleid, title, preData != null ? preDataRow["pdf_name"] : string.Empty, threadid, request);
                                // Add the new tags and delete any tags not used by any other articles, as well as cleanup unused thumbnails
                                StringBuilder finalQuery = new StringBuilder();
                                if (parsedTags.tags.Count > 0)
                                {
                                    StringBuilder tagsInsertQuery = new StringBuilder();
                                    StringBuilder tagsArticleQuery = new StringBuilder();
                                    foreach (string tag in parsedTags.tags)
                                    {
                                        // -- Attempt to insert the tags - if they exist, they wont be inserted
                                        tagsInsertQuery.Append("('" + Utils.Escape(tag) + "'),");
                                        tagsArticleQuery.Append("((SELECT tagid FROM articles_tags WHERE keyword='" + Utils.Escape(tag) + "'), '" + Utils.Escape(articleid) + "'),");
                                    }
                                    // -- Build final query
                                    finalQuery.Append("INSERT IGNORE INTO articles_tags (keyword) VALUES")
                                        .Append(tagsInsertQuery.Remove(tagsInsertQuery.Length - 1, 1).ToString())
                                        .Append("; INSERT IGNORE INTO articles_tags_article (tagid, articleid) VALUES")
                                        .Append(tagsArticleQuery.Remove(tagsArticleQuery.Length - 1, 1).ToString())
                                        .Append(";");
                                }
                                // Add any linked imagery
                                // -- Find the unique valid image IDs
                                List<string> images = new List<string>();
                                foreach (Match m in Regex.Matches(body, REGEX_IMAGE_STORE, RegexOptions.Multiline))
                                    if (!images.Contains(m.Groups[1].Value))
                                        images.Add(m.Groups[1].Value);
                                foreach (Match m in Regex.Matches(body, REGEX_IMAGE_STORE_CUSTOM_W, RegexOptions.Multiline))
                                    if (!images.Contains(m.Groups[3].Value))
                                        images.Add(m.Groups[3].Value);
                                foreach (Match m in Regex.Matches(body, REGEX_IMAGE_STORE_CUSTOM_WH, RegexOptions.Multiline))
                                    if (!images.Contains(m.Groups[3].Value))
                                        images.Add(m.Groups[3].Value);
                                if (images.Count != 0)
                                {
                                    // -- Insert all the valid IDs which exist in the actual articles_images table
                                    finalQuery.Append("INSERT IGNORE INTO articles_images_links (articleid, imageid) SELECT '" + Utils.Escape(articleid) + "' AS articleid, imageid FROM articles_images WHERE imageid IN (");
                                    foreach (string s in images)
                                        finalQuery.Append("'").Append(Utils.Escape(s)).Append("',");
                                    finalQuery.Remove(finalQuery.Length - 1, 1).Append(");");
                                }
                                // -- This will delete any tags in the main table no longer used in the articles tags table
                                finalQuery.Append(QUERY_TAGS_CLEANUP);
                                // -- This will delete any unused thumbnail images
                                finalQuery.Append(QUERY_THUMBNAIL_CLEANUP);
                                // -- This will log the event
                                finalQuery.Append(insertEvent(updateArticle ? RecentChanges_EventType.Edited : RecentChanges_EventType.Created, HttpContext.Current.User.Identity.Name, articleid, threadid));
                                // -- Execute final query
                                conn.Query_Execute(finalQuery.ToString());
                                // Redirect to the new article
                                conn.Disconnect();
                                response.Redirect(pageElements["URL"] + "/article/" + articleid, true);
                            }
                        }
                    }
                }
            }
            // Display form
            pageElements["CONTENT"] = Core.templates["articles"]["editor"]
                .Replace("<ERROR>", error != null ? Core.templates[pageElements["TEMPLATE"]]["error"].Replace("<ERROR>", HttpUtility.HtmlEncode(error)) : string.Empty)
                .Replace("<PARAMS>", preData != null ? "articleid=" + HttpUtility.UrlEncode(preData[0]["articleid"]) : string.Empty)
                .Replace("<TITLE>", HttpUtility.HtmlEncode(title ?? (preDataRow != null ? preDataRow["title"] : string.Empty)))
                .Replace("<RELATIVE_PATH>", HttpUtility.HtmlEncode(relativeUrl ?? (preDataRow != null ? preDataRow["relative_url"] : string.Empty)))
                .Replace("<TAGS>", HttpUtility.HtmlEncode(tags ?? (preDataRow != null ? preDataRow["tags"] : string.Empty)))
                .Replace("<ALLOW_HTML>", allowHTML || (title == null && preDataRow != null && preDataRow["allow_html"].Equals("1")) ? "checked" : string.Empty)
                .Replace("<ALLOW_COMMENTS>", allowComments || (title == null && preDataRow != null && preDataRow["allow_comments"].Equals("1")) ? "checked" : string.Empty)
                .Replace("<SHOW_PANE>", showPane || (title == null && preDataRow != null && preDataRow["show_pane"].Equals("1")) ? "checked" : string.Empty)
                .Replace("<INHERIT>", inheritThumbnail || (title == null && preDataRow != null && preDataRow["thumbnailid"].Length > 0) ? "checked" : string.Empty)
                .Replace("<UPDATE_EXISTING>", updateExisting || (title == null && preDataRow != null) ? "checked" : string.Empty)
                .Replace("<BODY>", HttpUtility.HtmlEncode(body ?? (preDataRow != null ? preDataRow["body"] : string.Empty)))
                ;
            // Set flags
            // -- Update existing checkbox
            if ((permAdmin || permEdit) && preData != null)
                pageElements.setFlag("UPDATE_EXISTING");
            // Finalize page
            Misc.Plugins.addHeaderJS(pageElements["URL"] + "/Content/JS/Article.js", ref pageElements);
            Misc.Plugins.addHeaderCSS(pageElements["URL"] + "/Content/CSS/Article.css", ref pageElements);
            Misc.Plugins.addHeaderCSS(pageElements["URL"] + "/Content/CSS/Common.css", ref pageElements);
            // Add includes
            Common.formatProvider_formatIncludes(request, response, conn, ref pageElements, true, true);
            pageElements["TITLE"] = "Articles - Editor";
        }
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:101,代码来源:Base.cs

示例11: pageArticle_View


//.........这里部分代码省略.........
                    case "permissions":
                        if (!permPublish) return;
                        pageArticle_View_Permissions(ref pluginid, ref conn, ref pageElements, ref request, ref response, ref permCreate, ref permDelete, ref permPublish, ref owner, ref subpageContent, ref article);
                        break;
                    case "pdf":
                        pageArticle_View_Pdf(ref pluginid, ref conn, ref pageElements, ref request, ref response, ref article);
                        break;
                    default:
                        return; // 404 - unknown sub-page
                }
                content.Replace("<BODY>", subpageContent.ToString());
            }
            else
            {
                if (!published && article["allow_html"].Equals("1"))
                {
                    // Wrap content in HTML protection container (against e.g. malicious uploads)
                    subpageContent.Append(
                        Core.templates["articles"]["article_html_protect"]
                        .Replace("<DATA>", article["body_cached"].Replace("<", "&lt;").Replace(">", "&gt;"))
                        );
                }
                else
                    subpageContent.Append(article["body_cached"]);
                // Insert article dependencies
                Common.formatProvider_formatIncludes(request, response, conn, ref pageElements, true, true);
                // Generate tags
                StringBuilder tags = new StringBuilder();
                StringBuilder metaTags = new StringBuilder("<meta name=\"keywords\" content=\"");
                foreach (ResultRow tag in conn.Query_Read("SELECT at.keyword FROM articles_tags_article AS ata LEFT OUTER JOIN articles_tags AS at ON at.tagid=ata.tagid WHERE ata.articleid='" + Utils.Escape(article["articleid"]) + "'"))
                {
                    // Append tag for the bottom of the article
                    tags.Append(
                        Core.templates["articles"]["article_tag"].Replace("<TITLE_ENCODED>", HttpUtility.HtmlEncode(tag["keyword"])).Replace("<TITLE>", HttpUtility.HtmlEncode(tag["keyword"]))
                        );
                    // Append tag for meta
                    metaTags.Append(HttpUtility.HtmlEncode(tag["keyword"])).Append(",");
                }
                metaTags.Remove(metaTags.Length - 1, 1);
                // -- Append meta keywords
                pageElements["HEADER"] += metaTags.Append("\">").ToString();
                // -- Append meta author
                pageElements["HEADER"] += "<meta name=\"author\" content=\"" + article["username"] + "\" />";
                // Set the article's body
                content.Replace("<BODY>", subpageContent.ToString())
                    .Append(
                        Core.templates["articles"]["article_footer"]
                            .Replace("<TAGS>", tags.Length == 0 ? "(none)" : tags.ToString()))
                            .Replace("<DATE>", article["datetime"].Length > 0 ? Misc.Plugins.getTimeString(DateTime.Parse(article["datetime"])) : "unknown")
                            .Replace("<FULL_DATE>", article["datetime"].Length > 0 ? DateTime.Parse(article["datetime"]).ToString("dd/MM/yyyy HH:mm:ss") : "unknown")
                            .Replace("<REVISION>", HttpUtility.HtmlEncode(article["revision"]))
                    ;
            }

            // Add pane
            content
                .Replace("<ARTICLEID>", HttpUtility.HtmlEncode(article["articleid"]))
                .Replace("<THREADID>", HttpUtility.HtmlEncode(article["threadid"]))
                .Replace("<COMMENTS>", conn.Query_Count("SELECT COUNT('') FROM articles_thread_comments WHERE threadid='" + Utils.Escape(article["threadid"]) + "'").ToString())
                .Replace("<PDF_NAME>", HttpUtility.HtmlEncode(article["pdf_name"]))
                ;

            bool pdf = request.QueryString["pdf"] != null;

            // Set flag for showing pane - this can be overriden if a querystring force_pane is specified
            if (article["show_pane"].Equals("1") || !published || request.QueryString["force_pane"] != null || subpage)
                pageElements.setFlag("ARTICLE_SHOW_PANE");

            // Set published flag
            if (published)
                pageElements.setFlag("ARTICLE_PUBLISHED");

            // Set download as PDF flag
            if (Core.settings[SETTINGS_KEY].getBool(SETTINGS_PDF_ENABLED) && article["pdf_name"].Length > 0)
                pageElements.setFlag("ARTICLE_PDF_DOWNLOAD");

            //Set current article flag
            if (article["articleid_current"] == article["articleid"])
                pageElements.setFlag("ARTICLE_CURRENT");

            // Check if to use the PDF template
            if (pdf)
            {
                pageElements["TEMPLATE"] = "articles_pdf";
                pageElements.setFlag("ARTICLE_PDF_MODE");
            }

            // Set permission flags
            if (permCreate)
                pageElements.setFlag("ARTICLE_PERM_CREATE");
            if (permDelete)
                pageElements.setFlag("ARTICLE_PERM_DELETE");
            if (permPublish)
                pageElements.setFlag("ARTICLE_PERM_PUBLISH");

            pageElements["TITLE"] = HttpUtility.HtmlEncode(article["title"]);
            pageElements["CONTENT"] = content.ToString();
            Misc.Plugins.addHeaderCSS(pageElements["URL"] + "/Content/CSS/Article.css", ref pageElements);
            Misc.Plugins.addHeaderJS(pageElements["URL"] + "/Content/JS/Article.js", ref pageElements);
        }
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:101,代码来源:Base.cs

示例12: pageArticles_Tag

        public static void pageArticles_Tag(ref StringBuilder content, string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
        {
            string tag = request.QueryString["2"];
            int browseArticlesPage = Core.settings[SETTINGS_KEY].getInt(SETTINGS_BROWSE_ARTICLES_PAGE);
            // Viewing articles by tag
            int page;
            if (request.QueryString["bpg"] == null || !int.TryParse(request.QueryString["bpg"], out page) || page < 1) page = 1;
            string sort = request.QueryString["sort"];
            // Security
            tag = tag.Replace("%", string.Empty);

            content.Append(Core.templates["articles"]["browse_header"].Replace("<TITLE>", "Tag `" + HttpUtility.HtmlEncode(tag) + "`"));
            // Add sorting
            content.Append(
                Core.templates["articles"]["browse_sorting"]
                .Replace("<URL>", "articles/tag/" + HttpUtility.HtmlEncode(tag) + "?bpg=" + page)
                );
            // Display all the articles belonging to a tag
            Result rawArticles = conn.Query_Read("SELECT ata.articleid, a.title, a.datetime, ath.relative_url FROM articles_tags_article AS ata, articles_tags AS at, articles AS a, articles_thread AS ath WHERE a.articleid=ath.articleid_current AND ata.articleid=a.articleid AND ata.tagid=at.tagid AND at.keyword LIKE '" + Utils.Escape(tag) + "' ORDER BY " + (sort == "t_a" ? "a.title ASC" : sort == "t_d" ? "a.title DESC" : sort == "d_a" ? "a.datetime ASC" : "a.datetime DESC") + " LIMIT " + ((browseArticlesPage * page) - browseArticlesPage) + "," + browseArticlesPage);
            if (rawArticles.Rows.Count != 0)
                foreach (ResultRow article in rawArticles)
                    content.Append(
                        Core.templates["articles"]["browse_article"]
                        .Replace("<RELATIVE_URL>", article["relative_url"])
                        .Replace("<ARTICLEID>", HttpUtility.UrlEncode(article["articleid"]))
                        .Replace("<TITLE>", HttpUtility.HtmlEncode(article["title"]))
                        .Replace("<DATETIME>", HttpUtility.HtmlEncode(article["datetime"]))
                        .Replace("<DATETIME_SHORT>", HttpUtility.HtmlEncode(article["datetime"].Length > 0 ? Misc.Plugins.getTimeString(DateTime.Parse(article["datetime"])) : "Unknown"))
                        );
            else
                content.Append("None.");
            // Add page navigation
            content.Append(
                Core.templates["articles"]["browse_nav"]
                .Replace("<TAG>", HttpUtility.UrlEncode(tag))
                .Replace("<URL>", "articles/tag/<TAG>?sort=" + HttpUtility.UrlEncode(sort))
                .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 && rawArticles.Rows.Count == browseArticlesPage) pageElements.setFlag("ARTICLES_PAGE_NEXT");
            pageElements["TITLE"] = "Articles - Tag - " + HttpUtility.HtmlEncode(tag);
        }
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:45,代码来源:Base.cs

示例13: pageArticles_Search

 public static void pageArticles_Search(ref StringBuilder content, string pluginid, Connector conn, ref Misc.PageElements pageElements, HttpRequest request, HttpResponse response)
 {
     string search = request.QueryString["keywords"];
     int browseArticlesPage = Core.settings[SETTINGS_KEY].getInt(SETTINGS_BROWSE_ARTICLES_PAGE);
     int page;
     if (request.QueryString["bpg"] == null || !int.TryParse(request.QueryString["bpg"], out page) || page < 1) page = 1;
     // Viewing articles by search
     content.Append(Core.templates["articles"]["browse_header"].Replace("<TITLE>", "Search Results for `" + HttpUtility.HtmlEncode(search) + "`"));
     string escapedKeywords = Utils.Escape(search.Replace("%", string.Empty));
     Result results = conn.Query_Read("SELECT a.articleid, a.title, a.datetime, at.relative_url FROM articles_thread AS at LEFT OUTER JOIN articles AS a ON a.articleid=at.articleid_current WHERE at.relative_url LIKE '" + escapedKeywords + "' OR a.title LIKE '%" + escapedKeywords + "%' OR a.body LIKE '%" + escapedKeywords + "%' LIMIT " + ((browseArticlesPage * page) - browseArticlesPage) + "," + browseArticlesPage);
     if (results.Rows.Count != 0)
         foreach (ResultRow foundItem in results)
             content.Append(
                 Core.templates["articles"]["browse_article"]
                 .Replace("<RELATIVE_URL>", foundItem["relative_url"])
                 .Replace("<ARTICLEID>", HttpUtility.UrlEncode(foundItem["articleid"]))
                 .Replace("<TITLE>", HttpUtility.HtmlEncode(foundItem["title"]))
                 .Replace("<DATETIME>", HttpUtility.HtmlEncode(foundItem["datetime"]))
                 .Replace("<DATETIME_SHORT>", HttpUtility.HtmlEncode(foundItem["datetime"].Length > 0 ? Misc.Plugins.getTimeString(DateTime.Parse(foundItem["datetime"])) : "Unknown"))
                 );
     else
         content.Append("None.");
     // Add page navigation
     content.Append(
         Core.templates["articles"]["browse_nav"]
         .Replace("<URL>", "articles/search?keywords=" + HttpUtility.HtmlEncode(search))
         .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 && results.Rows.Count == browseArticlesPage) pageElements.setFlag("ARTICLES_PAGE_NEXT");
     pageElements["TITLE"] = "Articles - Search";
 }
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:35,代码来源:Base.cs

示例14: pageArticles_RecentChanges


//.........这里部分代码省略.........
         {
             // Wipe all log entries and reload the page
             conn.Query_Execute("DELETE FROM articles_log_events");
             conn.Disconnect();
             response.Redirect(pageElements["URL"] + "/articles/recent_changes");
         }
         // Append options pane
         content.Append(
             Core.templates["articles"]["change_options"]
         );
         // Set anti-csrf protection
         Common.AntiCSRF.setCookieToken(response);
     }
     // Begin building each log event
     int changesPerPage = Core.settings[SETTINGS_KEY].getInt(SETTINGS_CHANGES_PER_PAGE);
     RecentChanges_EventType type;
     DateTime eventDate;
     int year, month, day;
     year = month = day = 0;
     Result logData = conn.Query_Read("SELECT ale.*, at.relative_url, a.title, u.username FROM articles_log_events AS ale LEFT OUTER JOIN articles AS a ON a.articleid=ale.articleid LEFT OUTER JOIN articles_thread AS at ON at.threadid=ale.threadid LEFT OUTER JOIN bsa_users AS u ON u.userid=ale.userid ORDER BY datetime DESC LIMIT " + ((changesPerPage * page) - changesPerPage) + "," + changesPerPage);
     if (logData.Rows.Count != 0)
     {
         string logHtml;
         foreach (ResultRow logEvent in logData)
         {
             eventDate = DateTime.Parse(logEvent["datetime"]);
             // Check if to change the datetime
             if (eventDate.Day != day || eventDate.Month != month || eventDate.Year != year)
             {
                 day = eventDate.Day;
                 month = eventDate.Month;
                 year = eventDate.Year;
                 // Output date header
                 content.Append(
                     Core.templates["articles"]["change_date"]
                     .Replace("<TITLE>", eventDate.ToString("dd MMMM yyyy, dddd"))
                     );
             }
             // Append item
             type = (RecentChanges_EventType)Enum.Parse(typeof(RecentChanges_EventType), logEvent["event_type"]);
             switch (type)
             {
                 case RecentChanges_EventType.Created:
                     logHtml = Core.templates["articles"]["change_created"];
                     break;
                 case RecentChanges_EventType.Deleted:
                     logHtml = Core.templates["articles"]["change_deleted"];
                     break;
                 case RecentChanges_EventType.DeletedThread:
                     logHtml = Core.templates["articles"]["change_deletedthread"];
                     break;
                 case RecentChanges_EventType.Edited:
                     logHtml = Core.templates["articles"]["change_edited"];
                     break;
                 case RecentChanges_EventType.Published:
                     logHtml = Core.templates["articles"]["change_published"];
                     break;
                 case RecentChanges_EventType.SetAsSelected:
                     logHtml = Core.templates["articles"]["change_selected"];
                     break;
                 case RecentChanges_EventType.RebuiltArticleCache:
                     logHtml = Core.templates["articles"]["change_rebuild_cache"];
                     break;
                 default:
                     logHtml = null;
                     break;
             }
             // Replace text and append
             if (logHtml != null)
             {
                 content.Append(
                             logHtml
                             .Replace("<ARTICLEID>", HttpUtility.HtmlEncode(logEvent["articleid"]))
                             .Replace("<THREADID>", HttpUtility.HtmlEncode(logEvent["threadid"]))
                             .Replace("<RELATIVE_URL>", logEvent["relative_url"].Length > 0 ? HttpUtility.UrlEncode(logEvent["relative_url"]) : "(unknown)")
                             .Replace("<USERID>", HttpUtility.HtmlEncode(logEvent["userid"]))
                             .Replace("<USERNAME>", HttpUtility.HtmlEncode(logEvent["username"]))
                             .Replace("<DATETIME>", HttpUtility.HtmlEncode(logEvent["datetime"]))
                             .Replace("<TIME>", HttpUtility.HtmlEncode(Misc.Plugins.getTimeString(eventDate)))
                             .Replace("<TITLE>", HttpUtility.HtmlEncode(logEvent["title"]))
                             );
             }
         }
     }
     else
         content.Append("No recent changes have occurred or the log has been wiped.");
     // Append navigation
     content.Append(
         Core.templates["articles"]["browse_nav"]
         .Replace("<URL>", "articles/recent_changes")
         .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 && logData.Rows.Count == changesPerPage) pageElements.setFlag("ARTICLES_PAGE_NEXT");
     // Output the page
     pageElements["TITLE"] = "Articles - Recent Changes";
 }
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:101,代码来源:Base.cs

示例15: 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)
                     {
//.........这里部分代码省略.........
开发者ID:kassemshehady,项目名称:Uber-CMS,代码行数:101,代码来源:BasicSiteAuth.cs


注:本文中的Misc.setFlag方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。