示例#1
0
        private static async Task ConvertMessages()
        {
            // display total amount of messages to process
            int totalNumberOfMessages = await MessageGuiHelper.GetTotalNumberOfMessagesAsync();

            Console.WriteLine("Total # of messages to process: {0}. Using batch size: {1}", totalNumberOfMessages, BATCHSIZE);
            var numberOfBatches = (totalNumberOfMessages / BATCHSIZE) + 1;
            var qf = new QueryFactory();
            var q  = qf.Message.OrderBy(MessageFields.MessageID.Ascending())
                     .Exclude(MessageFields.MessageTextAsHTML);

            using (var adapter = new DataAccessAdapter())
            {
                await adapter.StartTransactionAsync(IsolationLevel.ReadCommitted, "Converting UBB to Markdown").ConfigureAwait(false);

                adapter.KeepTrackOfTransactionParticipants = false;
                try
                {
                    var messages = new EntityCollection <MessageEntity>();
                    for (int batchNo = 1; batchNo <= numberOfBatches; batchNo++)
                    {
                        messages.Clear();
                        Console.WriteLine("Batch {0} of {1}", batchNo, numberOfBatches);
                        q.Page(batchNo, BATCHSIZE);
                        Console.Write("\tFetching messages...");
                        adapter.FetchQuery(q, messages);
                        Console.WriteLine("DONE. Messages fetched: {0}", messages.Count);
                        Console.Write("\tParsing messages...");
                        foreach (var message in messages)
                        {
                            string parserLog;
                            string messageAsXml;
                            bool   errorsOccurred;
                            string convertedText = TextParser.TransformUBBMessageStringToHTML(message.MessageText, _parserData, out parserLog, out errorsOccurred, out messageAsXml);
                            if (errorsOccurred)
                            {
                                Console.WriteLine("\nERRORS: {0}", parserLog);
                                Console.WriteLine("MessageID: {0}\nMessage as text:\n{1}--------------\n", message.MessageID, message.MessageText);
                            }
                            else
                            {
                                // html decode, so any &lt; etc. are converted back to the regular characters.
                                message.MessageText = HttpUtility.HtmlDecode(convertedText);
                            }
                        }
                        Console.WriteLine("DONE");
                        Console.Write("\tPersisting batch...");
                        await adapter.SaveEntityCollectionAsync(messages).ConfigureAwait(false);

                        Console.WriteLine("DONE\n");
                    }
                    adapter.Commit();
                }
                catch
                {
                    adapter.Rollback();
                    throw;
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // check if the calling user is able to approve attachments in 1 or more forums
            List <int> forumsWithApprovalRight = SessionAdapter.GetForumsWithActionRight(ActionRights.ApproveAttachment);
            List <int> accessableForums        = SessionAdapter.GetForumsWithActionRight(ActionRights.AccessForum);

            if (((forumsWithApprovalRight == null) || (forumsWithApprovalRight.Count <= 0)) ||
                ((accessableForums == null) || (accessableForums.Count <= 0)))
            {
                // no, this user doesn't have the right to approve attachments or doesn't have access to any forums.
                Response.Redirect("default.aspx", true);
            }

            List <int> forumsWithAttachmentDeleteRight = SessionAdapter.GetForumsWithActionRight(ActionRights.ManageOtherUsersAttachments);

            phAttachmentDelete.Visible = ((forumsWithAttachmentDeleteRight != null) && (forumsWithAttachmentDeleteRight.Count > 0));

            if (!Page.IsPostBack)
            {
                // get all attachments which aren't approved yet as a dataview.
                DataView allAttachmentsToApprove = MessageGuiHelper.GetAllAttachmentsToApproveAsDataView(accessableForums,
                                                                                                         forumsWithApprovalRight, SessionAdapter.GetForumsWithActionRight(ActionRights.ViewNormalThreadsStartedByOthers),
                                                                                                         SessionAdapter.GetUserID());
                rpAttachments.DataSource = allAttachmentsToApprove;
                rpAttachments.DataBind();
            }
        }
示例#3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int attachmentID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["AttachmentID"]);

            MessageEntity relatedMessage = MessageGuiHelper.GetMessageWithAttachmentLogic(attachmentID);

            if (relatedMessage == null)
            {
                // not found
                Response.Redirect("default.aspx", true);
            }

            // thread has been loaded into the related message object as well. This is needed for the forum access right check
            if (!SessionAdapter.CanPerformForumActionRight(relatedMessage.Thread.ForumID, ActionRights.AccessForum))
            {
                // user can't access this forum
                Response.Redirect("default.aspx", true);
            }

            // Check if the thread is sticky, or that the user can see normal threads started
            // by others. If not, the user isn't allowed to view the thread the message is in, and therefore is denied access.
            if ((relatedMessage.Thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(relatedMessage.Thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers) &&
                !relatedMessage.Thread.IsSticky)
            {
                // user can't view the thread the message is in, because:
                // - the thread isn't sticky
                // AND
                // - the thread isn't posted by the calling user and the user doesn't have the right to view normal threads started by others
                Response.Redirect("default.aspx", true);
            }

            AttachmentEntity toStream = MessageGuiHelper.GetAttachment(attachmentID);

            if (toStream == null)
            {
                // not found
                Response.Redirect("default.aspx", true);
            }

            if (!toStream.Approved && !SessionAdapter.CanPerformForumActionRight(relatedMessage.Thread.ForumID, ActionRights.ApproveAttachment))
            {
                // the attachment hasn't been approved yet, and the caller isn't entitled to approve attachments, so deny.
                // approval of attachments requires to be able to load the attachment without the attachment being approved
                Response.Redirect("default.aspx", true);
            }

            // all set, load stream the attachment data to the browser
            // create header
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AddHeader("Content-Type", "application/unknown");
            Response.AddHeader("Content-length", toStream.Filecontents.Length.ToString());
            Response.AddHeader("Content-Disposition", "attachment; filename=" + toStream.Filename.Replace(" ", "_"));
            Response.AddHeader("Content-Transfer-Encoding", "Binary");
            // stream the data
            Response.BinaryWrite(toStream.Filecontents);
            Response.Flush();
            Response.End();
        }
示例#4
0
        public async Task <ActionResult> Delete(int id = 0)
        {
            if (this.HttpContext.Session.IsAnonymousUser())
            {
                return(RedirectToAction("Index", "Home"));
            }

            var message = await MessageGuiHelper.GetMessageAsync(id);

            if (message == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var thread = await ThreadGuiHelper.GetThreadAsync(message.ThreadID);

            if (thread == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            // Only delete if the message isn't the first in the thread (as that's not allowed), and whether the user is allowed to delete messages in that forum at all.
            var messageIsFirstInThread = await ThreadGuiHelper.CheckIfMessageIsFirstInThreadAsync(thread.ThreadID, id);

            if (!messageIsFirstInThread && this.HttpContext.Session.CanPerformForumActionRight(thread.ForumID, ActionRights.EditDeleteOtherUsersMessages))
            {
                await MessageManager.DeleteMessageAsync(id, thread.ThreadID);
            }

            return(RedirectToAction("Index", "Thread", new { threadId = thread.ThreadID, pageNo = 1 }));
        }
示例#5
0
        private async Task <(bool userMayEditMessages, MessageEntity message)> PerformEditMessageSecurityChecksAsync(int id)
        {
            if (this.HttpContext.Session.IsAnonymousUser())
            {
                return(false, null);
            }

            var message = await MessageGuiHelper.GetMessageAsync(id, prefetchThread : true);

            if (message == null)
            {
                return(false, null);
            }

            var thread = message.Thread;

            if (thread == null)
            {
                return(false, null);
            }

            if (!this.HttpContext.Session.CanPerformForumActionRight(thread.ForumID, ActionRights.AccessForum))
            {
                return(false, null);
            }

            var userMayEditMessages = false;

            if (!thread.IsClosed)
            {
                userMayEditMessages = this.HttpContext.Session.CanPerformForumActionRight(thread.ForumID,
                                                                                          thread.IsSticky
                                                                                                                                                                                          ? ActionRights.AddAndEditMessageInSticky
                                                                                                                                                                                          : ActionRights.AddAndEditMessage);
            }

            // User has the right to generally edit messages. Check if the user has the right to edit other peoples messages
            // and if not, if the user is the poster of this message. If not, no can do.
            if (!this.HttpContext.Session.CanPerformForumActionRight(thread.ForumID, ActionRights.EditDeleteOtherUsersMessages))
            {
                // cannot edit other people's messages. Check if this message is posted by the current user.
                if (message.PostedByUserID != this.HttpContext.Session.GetUserID())
                {
                    // not allowed
                    userMayEditMessages = false;
                }
            }

            // check if the user can view the thread the message is in. If not, don't continue.
            if (thread.StartedByUserID != this.HttpContext.Session.GetUserID() &&
                !this.HttpContext.Session.CanPerformForumActionRight(thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers))
            {
                // can't edit this message, it's in a thread which isn't visible to the user
                userMayEditMessages = false;
            }

            return(userMayEditMessages, message);
        }
示例#6
0
        private async Task <(bool fetchResult, MessageEntity message)> GetMessageAndThreadAsync(int id)
        {
            if (id <= 0)
            {
                return(false, null);
            }

            var message = await MessageGuiHelper.GetMessageAsync(id, prefetchThread : true);

            return(message?.Thread != null, message);
        }
示例#7
0
 /// <summary>
 /// Invalidates the number of unapproved attachments by fetching the total number of unapproved attachments from the database.
 /// </summary>
 /// <returns></returns>
 /// <remarks>Not using async as it relies on locks to work so we need predictability.</remarks>
 public int InvalidateCachedNumberOfUnapprovedAttachments()
 {
     _volatileDataLock.EnterWriteLock();
     try
     {
         _cachedNumberOfUnapprovedAttachments = MessageGuiHelper.GetTotalNumberOfAttachmentsToApprove();
         return(_cachedNumberOfUnapprovedAttachments.Value);
     }
     finally
     {
         _volatileDataLock.ExitWriteLock();
     }
 }
示例#8
0
        public async Task <ActionResult> AdvancedSearch()
        {
            var allAccessibleForumIDs     = this.HttpContext.Session.GetForumsWithActionRight(ActionRights.AccessForum).ToHashSet();
            var allForumsWithSectionNames = await ForumGuiHelper.GetAllForumsWithSectionNamesAsync();

            var viewData = new AdvancedSearchUIData()
            {
                NumberOfMessages = await MessageGuiHelper.GetTotalNumberOfMessagesAsync(),
                AllAccessibleForumsWithSectionName = allForumsWithSectionNames.Where(r => allAccessibleForumIDs.Contains(r.ForumID)).ToList()
            };

            return(View(viewData));
        }
示例#9
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Page_Load(object sender, System.EventArgs e)
        {
            // this is necessary so the 'clever' IE will also understand what to do: the enter key will then submit the form.
            this.ClientScript.RegisterHiddenField("__EVENTTARGET", "btnSearch");

            if (!Page.IsPostBack)
            {
                // clear tmp results in session
                SessionAdapter.AddSearchTermsAndResults(string.Empty, null);

                // Read all the current existing forums and their section names.
                ForumsWithSectionNameTypedList forumsWithSectionName = ForumGuiHelper.GetAllForumsWithSectionNames();

                // Get a list of Forum IDs to which the user has access right.
                List <int> accessableForums = SessionAdapter.GetForumsWithActionRight(ActionRights.AccessForum);

                foreach (ForumsWithSectionNameRow currentRow in forumsWithSectionName)
                {
                    // filter out forums the user doesn't have access rights for.
                    if (accessableForums.Contains(currentRow.ForumID))
                    {
                        // forum is accessable to the user
                        ListItem newItem = new ListItem(String.Format("{0} - {1}", currentRow.SectionName, currentRow.ForumName), currentRow.ForumID.ToString());
                        newItem.Selected = true;
                        lbxForums.Items.Add(newItem);
                    }
                }

                // make listbox as high as # of forums, with a maximum of 15 and a minimum of 8
                if (lbxForums.Items.Count <= 15)
                {
                    if (lbxForums.Items.Count > 8)
                    {
                        lbxForums.Rows = lbxForums.Items.Count;
                    }
                    else
                    {
                        lbxForums.Rows = 8;
                    }
                }
                else
                {
                    lbxForums.Rows = 15;
                }

                lblNumberOfPosts.Text = MessageGuiHelper.GetTotalNumberOfMessages().ToString();
            }
        }
示例#10
0
        public async Task <ActionResult> Get(int messageId = 0, int attachmentId = 0)
        {
            // loads Message and related thread based on the attachmentId
            var relatedMessage = await MessageGuiHelper.GetMessageWithAttachmentLogicAsync(attachmentId);

            if (relatedMessage == null || relatedMessage.MessageID != messageId)
            {
                return(RedirectToAction("Index", "Home"));
            }

            if (!this.HttpContext.Session.CanPerformForumActionRight(relatedMessage.Thread.ForumID, ActionRights.AccessForum))
            {
                return(RedirectToAction("Index", "Home"));
            }

            // Check if the thread is sticky, or that the user can see normal threads started
            // by others. If not, the user isn't allowed to view the thread the message is in, and therefore is denied access.
            if ((relatedMessage.Thread.StartedByUserID != this.HttpContext.Session.GetUserID()) &&
                !this.HttpContext.Session.CanPerformForumActionRight(relatedMessage.Thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers) &&
                !relatedMessage.Thread.IsSticky)
            {
                // user can't view the thread the message is in, because:
                // - the thread isn't sticky
                // AND
                // - the thread isn't posted by the calling user and the user doesn't have the right to view normal threads started by others
                return(RedirectToAction("Index", "Home"));
            }

            var attachmentToStream = await MessageGuiHelper.GetAttachmentAsync(messageId, attachmentId);

            if (attachmentToStream == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            if (!attachmentToStream.Approved && !this.HttpContext.Session.CanPerformForumActionRight(relatedMessage.Thread.ForumID, ActionRights.ApproveAttachment))
            {
                // the attachment hasn't been approved yet, and the caller isn't entitled to approve attachments, so deny.
                // approval of attachments requires to be able to load the attachment without the attachment being approved
                return(RedirectToAction("Index", "Home"));
            }

            // all good, return the file contents.
            return(File(attachmentToStream.Filecontents, "application/unknown", attachmentToStream.Filename));
        }
示例#11
0
        public async Task <ActionResult> Unapproved()
        {
            var forumsWithApprovalRight = this.HttpContext.Session.GetForumsWithActionRight(ActionRights.ApproveAttachment);
            var accessableForums        = this.HttpContext.Session.GetForumsWithActionRight(ActionRights.AccessForum);

            if (forumsWithApprovalRight == null || forumsWithApprovalRight.Count <= 0 || accessableForums == null || accessableForums.Count <= 0)
            {
                // no, this user doesn't have the right to approve attachments or doesn't have access to any forums.
                return(RedirectToAction("Index", "Home"));
            }

            var messageIDsWithUnaprovedAttachments = await MessageGuiHelper.GetAllMessagesIDsWithUnapprovedAttachments(accessableForums, forumsWithApprovalRight,
                                                                                                                       this.HttpContext.Session.GetForumsWithActionRight(ActionRights.ViewNormalThreadsStartedByOthers),
                                                                                                                       this.HttpContext.Session.GetUserID());

            return(View(new UnapprovedAttachmentsData()
            {
                MessageIdsWithUnapprovedAttachments = messageIDsWithUnaprovedAttachments
            }));
        }
示例#12
0
        /// <summary>
        /// Binds the attachments.
        /// </summary>
        private void BindAttachments()
        {
            // get all attachments for the given message and bind them to the repeater
            DataView attachments = MessageGuiHelper.GetAttachmentsAsDataView(_message.MessageID);

            rpAttachments.DataSource = attachments;
            rpAttachments.DataBind();

            // if max number of attachments has been reached, disable the add attachment placeholder
            if (_forum.MaxNoOfAttachmentsPerMessage <= attachments.Count)
            {
                // maximum has been reached
                phAddNewAttachment.Visible = false;
            }
            else
            {
                phAddNewAttachment.Visible = _userCanAddAttachments;
            }

            _numberOfAttachments             = attachments.Count;
            ViewState["numberOfAttachments"] = _numberOfAttachments;
        }
示例#13
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.Title += ApplicationAdapter.GetSiteName();

                // first time loaded, fill in properties
                lblUserName.Text = SessionAdapter.GetUserNickName();

                HttpContext hcCurrent          = HttpContext.Current;
                DataTable   bookmarkStatistics = null;

                // check if user is authenticated
                if (hcCurrent.Request.IsAuthenticated)
                {
                    lblWelcomeTextLoggedIn.Visible = true;
                    bookmarkStatistics             = UserGuiHelper.GetBookmarkStatisticsAsDataTable(SessionAdapter.GetUserID());
                }
                else
                {
                    lblWelcomeTextNotLoggedIn.Visible = true;
                    bookmarkStatistics = new DataTable();
                }

                // check if the user has the action right to approve attachments on some forum. If so, show the # of attachments which need approval
                List <int> forumsWithApprovalRight = SessionAdapter.GetForumsWithActionRight(ActionRights.ApproveAttachment);
                bool       canApproveAttachments   = ((forumsWithApprovalRight != null) && (forumsWithApprovalRight.Count > 0));
                if (canApproveAttachments)
                {
                    int numberOfAttachmentsToApprove = MessageGuiHelper.GetTotalNumberOfAttachmentsToApprove(
                        SessionAdapter.GetForumsWithActionRight(ActionRights.AccessForum),
                        SessionAdapter.GetForumsWithActionRight(ActionRights.ApproveAttachment),
                        SessionAdapter.GetForumsWithActionRight(ActionRights.ViewNormalThreadsStartedByOthers), SessionAdapter.GetUserID());
                    if (numberOfAttachmentsToApprove > 0)
                    {
                        phAttachmentsToApprove.Visible = true;
                        phAttentionRemarks.Visible     = true;
                    }
                }
                if (SessionAdapter.HasSystemActionRight(ActionRights.QueueContentManagement))
                {
                    int numberOfThreadsInSupportQueues = SupportQueueGuiHelper.GetTotalNumberOfThreadsInSupportQueues(
                        SessionAdapter.GetForumsWithActionRight(ActionRights.AccessForum));
                    if (numberOfThreadsInSupportQueues > 0)
                    {
                        phThreadsToSupport.Visible = true;
                        phAttentionRemarks.Visible = true;
                    }
                }

                DateTime lastVisitDate = SessionAdapter.GetLastVisitDate();

                if (SessionAdapter.IsLastVisitDateValid())
                {
                    phLastVisitDate.Visible = true;
                    lblLastVisitDate.Text   = lastVisitDate.ToString("dd-MMM-yyyy HH:mm");
                }

                // Get all sections which possibly can be displayed. Obtain this from the cache, as it's hardly changing data, and
                // this page is read a lot.
                _sectionsToDisplay = CacheManager.GetAllSections();

                // Per section, create a view with all the forumdata and filter out the forums not visible for the current user.
                List <int> accessableForums            = SessionAdapter.GetForumsWithActionRight(ActionRights.AccessForum);
                List <int> forumsWithThreadsFromOthers = SessionAdapter.GetForumsWithActionRight(ActionRights.ViewNormalThreadsStartedByOthers);
                _forumViewsPerDisplayedSection = ForumGuiHelper.GetAllAvailableForumsDataViews(_sectionsToDisplay, accessableForums,
                                                                                               forumsWithThreadsFromOthers, SessionAdapter.GetUserID());

                // filter out sections which do not have displayable forums for this user
                EntityView <SectionEntity> sectionsToUse = CreateFilteredSectionsCollection();

                // show the sections with displayable forums, thus the displayable sections.
                rpSections.DataSource = sectionsToUse;
                rpSections.DataBind();

                // get bookmarks and show them in the gui
                if ((bookmarkStatistics.Rows.Count <= 0) || ((bookmarkStatistics.Rows.Count == 1) && ((int)bookmarkStatistics.Rows[0][0] == 0)))
                {
                    // no bookmarks yet
                    lblAmountBookmarks.Text           = "0";
                    lblAmountPostingsInBookmarks.Text = "0";
                    lblBookmarksLastPostingDate.Text  = "Never";
                    imgIconBookmarkNoNewPosts.Visible = true;
                }
                else
                {
                    lblAmountBookmarks.Text           = bookmarkStatistics.Rows[0]["AmountThreads"].ToString();
                    lblAmountPostingsInBookmarks.Text = bookmarkStatistics.Rows[0]["AmountPostings"].ToString();
                    DateTime dateLastPosting = (DateTime)bookmarkStatistics.Rows[0]["LastPostingDate"];
                    lblBookmarksLastPostingDate.Text = dateLastPosting.ToString("dd-MMM-yyyy HH:mm");
                    if (dateLastPosting > lastVisitDate)
                    {
                        imgIconBookmarkNewPosts.Visible = true;
                    }
                    else
                    {
                        imgIconBookmarkNoNewPosts.Visible = true;
                    }
                }

                DataTable activeThreadsStatistics = ThreadGuiHelper.GetActiveThreadsStatisticsAsDataTable(accessableForums,
                                                                                                          CacheManager.GetSystemData().HoursThresholdForActiveThreads,
                                                                                                          SessionAdapter.GetForumsWithActionRight(ActionRights.ViewNormalThreadsStartedByOthers), SessionAdapter.GetUserID());
                if (activeThreadsStatistics != null)
                {
                    if ((activeThreadsStatistics.Rows.Count <= 0) || ((activeThreadsStatistics.Rows.Count == 1) && ((int)activeThreadsStatistics.Rows[0][0] == 0)))
                    {
                        lblAmountActiveThreads.Text            = "0";
                        lblAmountPostingsInActiveThreads.Text  = "0";
                        lblActiveThreadsLastPostingDate.Text   = "Never";
                        imgIconActiveThreadsNoNewPosts.Visible = true;
                    }
                    else
                    {
                        lblAmountActiveThreads.Text           = activeThreadsStatistics.Rows[0]["AmountThreads"].ToString();
                        lblAmountPostingsInActiveThreads.Text = activeThreadsStatistics.Rows[0]["AmountPostings"].ToString();
                        DateTime dateLastPosting = (DateTime)activeThreadsStatistics.Rows[0]["LastPostingDate"];
                        lblActiveThreadsLastPostingDate.Text = dateLastPosting.ToString("dd-MMM-yyyy HH:mm");
                        if (dateLastPosting > lastVisitDate)
                        {
                            imgIconActiveThreadsNewPosts.Visible = true;
                        }
                        else
                        {
                            imgIconActiveThreadsNoNewPosts.Visible = true;
                        }
                    }
                }
            }

            RegisterCollapseExpandClientScript();
        }
示例#14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int messageID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["MessageID"]);

            _message = MessageGuiHelper.GetMessage(messageID);
            if (_message == null)
            {
                // not found
                Response.Redirect("default.aspx", true);
            }

            _sourceType = HnDGeneralUtils.TryConvertToInt(Request.QueryString["SourceType"]);
            switch (_sourceType)
            {
            case 1:
                // new message, or message view, for now no action needed
                break;

            case 2:
                // new thread, for now no action needed
                break;

            default:
                // unknown, redirect
                Response.Redirect("default.aspx", true);
                break;
            }

            // We could have used Lazy loading here, but for the sake of separation, we use the BL method.
            _thread = ThreadGuiHelper.GetThread(_message.ThreadID);
            if (_thread == null)
            {
                // not found. Orphaned message.
                Response.Redirect("default.aspx", true);
            }

            _forum = CacheManager.GetForum(_thread.ForumID);
            if (_forum == null)
            {
                // not found.
                Response.Redirect("default.aspx", true);
            }

            // check if this forum accepts attachments.
            if (_forum.MaxNoOfAttachmentsPerMessage <= 0)
            {
                // no, so no right to be here nor is the user here via a legitimate route.
                Response.Redirect("default.aspx", true);
            }

            // Check credentials
            bool userHasAccess = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AccessForum);

            if (!userHasAccess)
            {
                // doesn't have access to this forum. redirect
                Response.Redirect("default.aspx", true);
            }

            // check if the user can view this thread. If not, don't continue.
            if ((_thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers) &&
                !_thread.IsSticky)
            {
                // can't view this thread, it isn't visible to the user
                Response.Redirect("default.aspx", true);
            }

            // Check if the current user is allowed to manage attachments of this message, and other rights.
            _userMayManageAttachments = ((_message.PostedByUserID == SessionAdapter.GetUserID()) ||
                                         SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ManageOtherUsersAttachments));
            _userCanAddAttachments = (((_message.PostedByUserID == SessionAdapter.GetUserID()) ||
                                       SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ManageOtherUsersAttachments)) &&
                                      SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAttachment));
            _userCanApproveAttachments = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ApproveAttachment);

            phAttachmentLimits.Visible = _userMayManageAttachments;

            if (!Page.IsPostBack)
            {
                // fill the page's content
                lnkThreads.Text          = HttpUtility.HtmlEncode(_forum.ForumName);
                lnkThreads.NavigateUrl  += "?ForumID=" + _thread.ForumID;
                lblSectionName.Text      = CacheManager.GetSectionName(_forum.SectionID);
                lnkMessages.NavigateUrl += _message.ThreadID;
                lnkMessages.Text         = HttpUtility.HtmlEncode(_thread.Subject);

                lblMaxFileSize.Text = String.Format("{0} KB", _forum.MaxAttachmentSize);
                lblMaxNoOfAttachmentsPerMessage.Text = _forum.MaxNoOfAttachmentsPerMessage.ToString();
                lnkMessage.Text        += messageID.ToString();
                lnkMessage.NavigateUrl += String.Format("MessageID={0}&ThreadID={1}", messageID, _thread.ThreadID);

                phAddNewAttachment.Visible = _userCanAddAttachments;

                BindAttachments();
            }
            else
            {
                object numberOfAttachments = ViewState["numberOfAttachments"];
                if (numberOfAttachments != null)
                {
                    _numberOfAttachments = (int)numberOfAttachments;
                }
            }
        }
示例#15
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            int threadID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ThreadID"]);

            _deleteMessageID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["MessageID"]);

            _thread = ThreadGuiHelper.GetThread(threadID);
            if (_thread == null)

            {
                // not found, return to default page
                Response.Redirect("default.aspx", true);
            }

            // Check if the current user is allowed to delete the message. If not, don't continue.
            _userMayDeleteMessages = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.EditDeleteOtherUsersMessages);
            if (!_userMayDeleteMessages)
            {
                // is not allowed to delete the message
                Response.Redirect("Messages.aspx?ThreadID=" + threadID, true);
            }

            // check if the user can view this thread. If not, don't continue.
            if ((_thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers) &&
                !_thread.IsSticky)
            {
                // can't view this thread, it isn't visible to the user
                Response.Redirect("default.aspx", true);
            }

            // check if the message is the first message in the thread. If so, delete isn't allowed.
            if (ThreadGuiHelper.CheckIfMessageIsFirstInThread(threadID, _deleteMessageID))
            {
                // is first in thread, don't proceed. Caller has fabricated the url manually.
                Response.Redirect("default.aspx", true);
            }

            // Get the message
            MessageEntity message = MessageGuiHelper.GetMessage(_deleteMessageID);

            // User may delete current message.
            if (!Page.IsPostBack)
            {
                if (message != null)
                {
                    // message is found.
                    ForumEntity forum = CacheManager.GetForum(_thread.ForumID);
                    if (forum == null)
                    {
                        // Orphaned thread
                        Response.Redirect("default.aspx", true);
                    }
                    lblForumName_Header.Text = forum.ForumName;
                    lblMessageBody.Text      = message.MessageTextAsHTML;
                    lblPostingDate.Text      = message.PostingDate.ToString(@"dd-MMM-yyyy HH:mm:ss");
                }
                else
                {
                    btnYes.Visible = false;
                }
            }
        }
示例#16
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Page_Load(object sender, System.EventArgs e)
        {
            int threadID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ThreadID"]);

            _thread = ThreadGuiHelper.GetThread(threadID);
            if (_thread == null)
            {
                // not found, return to default page
                Response.Redirect("default.aspx", true);
            }

            _startAtMessageIndex = HnDGeneralUtils.TryConvertToInt(Request.QueryString["StartAtMessage"]);
            _quoteMessageID      = HnDGeneralUtils.TryConvertToInt(Request.QueryString["QuoteMessageID"]);

            // Check credentials
            bool userHasAccess = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AccessForum);

            if (!userHasAccess)
            {
                // doesn't have access to this forum. redirect
                Response.Redirect("default.aspx");
            }

            // Check if the current user is allowed to add new messages to the thread.
            bool userMayAddNewMessages = false;

            if (!_thread.IsClosed)
            {
                if (_thread.IsSticky)
                {
                    if (SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAndEditMessageInSticky))
                    {
                        userMayAddNewMessages = true;
                    }
                }
                else
                {
                    if (SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAndEditMessage))
                    {
                        userMayAddNewMessages = true;
                    }
                }
            }

            if (!userMayAddNewMessages)
            {
                // is not allowed to post a new message
                Response.Redirect("Messages.aspx?ThreadID=" + threadID, true);
            }

            // use BL class. We could have used Lazy loading, though for the sake of separation, we'll call into the BL class.
            ForumEntity forum = CacheManager.GetForum(_thread.ForumID);

            if (forum == null)
            {
                // orphaned thread
                Response.Redirect("default.aspx");
            }

            // check if the user can view the thread the message is in. If not, don't continue.
            if ((_thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers))
            {
                // can't add a message, it's in a thread which isn't visible to the user
                Response.Redirect("default.aspx", true);
            }

            meMessageEditor.ShowAddAttachment = ((forum.MaxNoOfAttachmentsPerMessage > 0) &&
                                                 SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAttachment));
            meMessageEditor.ShowSubscribeToThread = !UserGuiHelper.CheckIfThreadIsAlreadySubscribed(SessionAdapter.GetUserID(), _thread.ThreadID);

            // User is able to post a new message to the current thread.
            if (!Page.IsPostBack)
            {
                // fill the page's content
                lnkThreads.Text               = HttpUtility.HtmlEncode(forum.ForumName);
                lnkThreads.NavigateUrl       += "?ForumID=" + _thread.ForumID;
                meMessageEditor.ForumName     = forum.ForumName;
                meMessageEditor.ThreadSubject = _thread.Subject;
                lblSectionName.Text           = CacheManager.GetSectionName(forum.SectionID);
                lnkMessages.NavigateUrl      += threadID;
                lnkMessages.Text              = HttpUtility.HtmlEncode(_thread.Subject);
                phLastPostingInThread.Visible = (_quoteMessageID <= 0);

                bool userMayEditMemo = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.EditThreadMemo);

                // get quoted message if passed in.
                if (_quoteMessageID > 0)
                {
                    // get message and insert it into the textbox including quote tags.
                    MessageEntity messageToQuote = MessageGuiHelper.GetMessage(_quoteMessageID);
                    if (messageToQuote != null)
                    {
                        // message found.
                        UserEntity quotedUser = UserGuiHelper.GetUser(messageToQuote.PostedByUserID);
                        if (quotedUser != null)
                        {
                            // user found. proceed
                            meMessageEditor.OriginalMessageText = TextParser.MakeStringQuoted(messageToQuote.MessageText, quotedUser.NickName);
                        }
                    }
                }
                else
                {
                    // no quoted message. Load the last message from the active thread and display it in the form. This
                    // message entity has the poster user entity prefetched, together with the usertitle of the user.
                    MessageEntity lastMessageInThread = ThreadGuiHelper.GetLastMessageInThreadWithUserInfo(threadID);
                    if (lastMessageInThread != null)
                    {
                        litMessageBody.Text = lastMessageInThread.MessageTextAsHTML;
                        lblPostingDate.Text = lastMessageInThread.PostingDate.ToString("dd-MMM-yyyy HH:mm:ss");
                        if (lastMessageInThread.PostedByUser != null)
                        {
                            UserEntity messagePoster = lastMessageInThread.PostedByUser;
                            if (messagePoster.UserTitle != null)
                            {
                                lblUserTitleDescription.Text = messagePoster.UserTitle.UserTitleDescription;
                            }
                            lblLocation.Text = messagePoster.Location;
                            if (messagePoster.JoinDate.HasValue)
                            {
                                lblJoinDate.Text = messagePoster.JoinDate.Value.ToString("dd-MMM-yyyy HH:mm:ss");
                            }
                            if (messagePoster.AmountOfPostings.HasValue)
                            {
                                lblAmountOfPostings.Text = messagePoster.AmountOfPostings.Value.ToString();
                            }
                            if (messagePoster.SignatureAsHTML != null)
                            {
                                litSignature.Text = messagePoster.SignatureAsHTML;
                            }
                            lblNickname.Text = messagePoster.NickName;
                        }
                    }
                }

                if ((_thread.Memo.Length > 0) && userMayEditMemo)
                {
                    // convert memo contents to HTML so it's displayed above the thread.
                    string parserLog, messageTextXml;
                    bool   errorsOccured = false;
                    string memoAsHTML    = TextParser.TransformUBBMessageStringToHTML(_thread.Memo, ApplicationAdapter.GetParserData(), out parserLog, out errorsOccured, out messageTextXml);
                    lblMemo.Text = memoAsHTML;
                }
                phMemo.Visible = userMayEditMemo;
            }
        }
示例#17
0
        public async Task <ActionResult> Add(int messageId = 0)
        {
            var(messageGetResult, message) = await GetMessageAndThreadAsync(messageId);

            if (!messageGetResult)
            {
                return(Json(new { success = false, responseMessage = "Upload failed." }));
            }

            var forum = await _cache.GetForumAsync(message.Thread.ForumID);

            if (forum == null)
            {
                return(Json(new { success = false, responseMessage = "Upload failed." }));
            }

            // Check if the thread is sticky, or that the user can see normal threads started
            // by others. If not, the user isn't allowed to view the thread the message is in, and therefore is denied access.
            if ((message.Thread.StartedByUserID != this.HttpContext.Session.GetUserID()) &&
                !this.HttpContext.Session.CanPerformForumActionRight(message.Thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers) &&
                !message.Thread.IsSticky)
            {
                // user can't view the thread the message is in, because:
                // - the thread isn't sticky
                // AND
                // - the thread isn't posted by the calling user and the user doesn't have the right to view normal threads started by others
                return(Json(new { success = false, responseMessage = "Upload failed." }));
            }

            var totalNumberOfAttachmentsOfMessage = await MessageGuiHelper.GetTotalNumberOfAttachmentsOfMessageAsync(messageId);

            bool userMayAddAttachment = forum.MaxNoOfAttachmentsPerMessage > 0 &&
                                        this.HttpContext.Session.CanPerformForumActionRight(forum.ForumID, ActionRights.AddAttachment) &&
                                        this.HttpContext.Session.GetUserID() == message.PostedByUserID &&
                                        totalNumberOfAttachmentsOfMessage < forum.MaxNoOfAttachmentsPerMessage;

            if (!userMayAddAttachment)
            {
                return(Json(new { success = false, responseMessage = "Upload failed." }));
            }

            try
            {
                if (this.Request.Form.Files.Count <= 0)
                {
                    return(Json(new { success = false, responseMessage = "No file attached!" }));
                }

                var fileContent = this.Request.Form.Files[0];
                if (fileContent == null || fileContent.Length <= 0)
                {
                    return(Json(new { success = false, responseMessage = "The file uploaded is empty (0KB)." }));
                }

                var fileLengthInKB = fileContent.Length / 1024;
                if (fileLengthInKB > forum.MaxAttachmentSize)
                {
                    return(Json(new { success = false, responseMessage = $"The file uploaded is too large ({fileLengthInKB}KB). The max. file size is {forum.MaxAttachmentSize}KB" }));
                }

                // all is well, save the attachment!
                var fileData = new byte[fileContent.Length];
                await using (var reader = fileContent.OpenReadStream())
                {
                    await reader.ReadAsync(fileData, 0, (int)fileContent.Length);
                }

                await MessageManager.AddAttachmentAsync(messageId, fileContent.FileName, fileData,
                                                        this.HttpContext.Session.CanPerformForumActionRight(forum.ForumID, ActionRights.GetsAttachmentsApprovedAutomatically));

                ApplicationAdapter.InvalidateCachedNumberOfUnapprovedAttachments();
                return(Json(new { success = true, responseMessage = string.Empty }));
            }
            catch (Exception)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(new { success = false, responseMessage = "Upload failed." }));
            }
        }
示例#18
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Page_Load(object sender, System.EventArgs e)
        {
            _editMessageID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["MessageID"]);
            _message       = MessageGuiHelper.GetMessage(_editMessageID);
            if (_message == null)
            {
                // not found
                Response.Redirect("default.aspx");
            }

            // We could have used Lazy loading here, but for the sake of separation, we use the BL method.
            _thread = ThreadGuiHelper.GetThread(_message.ThreadID);
            if (_thread == null)
            {
                // not found. Orphaned message.
                Response.Redirect("default.aspx");
            }

            // Check credentials
            bool userHasAccess = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AccessForum);

            if (!userHasAccess)
            {
                // doesn't have access to this forum. redirect
                Response.Redirect("default.aspx", true);
            }

            // Check if the current user is allowed to edit the message.
            bool userMayEditMessages = false;

            if (!_thread.IsClosed)
            {
                if (_thread.IsSticky)
                {
                    userMayEditMessages = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAndEditMessageInSticky);
                }
                else
                {
                    userMayEditMessages = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAndEditMessage);
                }
            }

            // User has the right to generally edit messages. Check if the user has the right to edit other peoples messages
            // and if not, if the user is the poster of this message. If not, no can do.
            if (!SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.EditDeleteOtherUsersMessages))
            {
                // cannot edit other people's messages. Check if this message is posted by the current user.
                if (_message.PostedByUserID != SessionAdapter.GetUserID())
                {
                    // not allowed
                    userMayEditMessages = false;
                }
            }
            if (!userMayEditMessages)
            {
                // is not allowed to edit the message
                Response.Redirect("Messages.aspx?ThreadID=" + _message.ThreadID, true);
            }

            // use BL class. We could have used Lazy loading, though for the sake of separation, we'll call into the BL class.
            ForumEntity forum = CacheManager.GetForum(_thread.ForumID);

            if (forum == null)
            {
                // orphaned thread
                Response.Redirect("default.aspx");
            }

            // check if the user can view the thread the message is in. If not, don't continue.
            if ((_thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers))
            {
                // can't edit this message, it's in a thread which isn't visible to the user
                Response.Redirect("default.aspx", true);
            }

            _startAtMessageIndex = HnDGeneralUtils.TryConvertToInt(Request.QueryString["StartAtMessage"]);

            // User may edit current message.
            if (!Page.IsPostBack)
            {
                // fill the page's content
                lnkThreads.Text               = HttpUtility.HtmlEncode(forum.ForumName);
                lnkThreads.NavigateUrl       += "?ForumID=" + _thread.ForumID;
                meMessageEditor.ForumName     = forum.ForumName;
                meMessageEditor.ThreadSubject = _thread.Subject;
                lblSectionName.Text           = CacheManager.GetSectionName(forum.SectionID);
                lnkMessages.NavigateUrl      += _message.ThreadID;
                lnkMessages.Text              = HttpUtility.HtmlEncode(_thread.Subject);

                meMessageEditor.OriginalMessageText = _message.MessageText;
            }
        }
示例#19
0
        public async Task <ActionResult> Goto(int id = 0)
        {
            var message = await MessageGuiHelper.GetMessageAsync(id);

            return(message == null?RedirectToAction("Index", "Home") : await CalculateRedirectToMessageAsync(message.ThreadID, message.MessageID));
        }
示例#20
0
        public async Task <ActionResult> Add(int threadId = 0, int messageIdToQuote = 0)
        {
            if (this.HttpContext.Session.IsAnonymousUser())
            {
                return(RedirectToAction("Index", "Home"));
            }

            var(userMayAddMessages, thread) = await PerformAddMessageSecurityChecksAsync(threadId);

            if (!userMayAddMessages)
            {
                return(RedirectToAction("Index", "Home"));
            }

            MessageEntity messageToQuote       = null;
            UserEntity    userOfMessageToQuote = null;

            if (messageIdToQuote > 0)
            {
                messageToQuote = await MessageGuiHelper.GetMessageAsync(messageIdToQuote);

                if (messageToQuote == null || messageToQuote.ThreadID != threadId)
                {
                    // doesn't exist, or is in another thread, ignore.
                    return(RedirectToAction("Index", "Home"));
                }

                userOfMessageToQuote = await UserGuiHelper.GetUserAsync(messageToQuote.PostedByUserID);

                if (userOfMessageToQuote == null)
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }

            var forum = await _cache.GetForumAsync(thread.ForumID);

            if (forum == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            string messageTextForEditor = messageToQuote == null
                                ? string.Empty
                                : string.Format("@quote {0}{1}{2}{1}@end{1}", userOfMessageToQuote.NickName, Environment.NewLine,
                                                messageToQuote.MessageText);
            var messageData = new MessageData()
            {
                MessageText         = messageTextForEditor,
                CurrentUserID       = this.HttpContext.Session.GetUserID(),
                ForumID             = forum.ForumID,
                ThreadID            = thread.ThreadID,
                ForumName           = forum.ForumName,
                SectionName         = await _cache.GetSectionNameAsync(forum.SectionID),
                ThreadSubject       = thread.Subject,
                PageNo              = 1,
                LastMessageInThread = await ThreadGuiHelper.GetLastMessageInThreadDtoAsync(threadId),
            };

            return(View(messageData));
        }