예제 #1
0
        public static bool PublishPost(Core core, Job job)
        {
            core.LoadUserProfile(job.UserId);
            User owner = core.PrimitiveCache[job.UserId];
            ItemKey sharedItemKey = new ItemKey(job.ItemId, job.ItemTypeId);
            IActionableItem sharedItem = null;

            core.ItemCache.RequestItem(sharedItemKey);
            try
            {
                sharedItem = (IActionableItem)core.ItemCache[sharedItemKey];
            }
            catch
            {
                try
                {
                    sharedItem = (IActionableItem)NumberedItem.Reflect(core, sharedItemKey);
                    HttpContext.Current.Response.Write("<br />Fallback, had to reflect: " + sharedItemKey.ToString());
                }
                catch
                {
                    return true; // Item is probably deleted, report success to delete from queue
                }
            }

            UpdateQuery uQuery = new UpdateQuery(typeof(ItemInfo));
            uQuery.AddCondition("info_item_id", sharedItemKey.Id);
            uQuery.AddCondition("info_item_type_id", sharedItemKey.TypeId);

            try
            {
                if (owner.UserInfo.FacebookAuthenticated) // are we still authenticated
                {
                    string postDescription = job.Body;

                    Facebook fb = new Facebook(core.Settings.FacebookApiAppid, core.Settings.FacebookApiSecret);

                    FacebookAccessToken token = fb.OAuthAppAccessToken(core, owner.UserInfo.FacebookUserId);
                    FacebookPost post = fb.StatusesUpdate(token, postDescription, sharedItem.Info.ShareUri, owner.UserInfo.FacebookSharePermissions);

                    if (post != null)
                    {
                        uQuery.AddField("info_facebook_post_id", post.PostId);
                    }

                    core.Db.Query(uQuery);
                }
            }
            catch (System.Net.WebException ex)
            {
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                if (response.StatusCode == HttpStatusCode.Forbidden)
                {
                    return true; // This request cannot succeed, so remove it from the queue
                }
                return false; // Failed for other reasons, retry
            }

            return true; // success
        }
예제 #2
0
        public static bool PublishPost(Core core, Job job)
        {
            core.LoadUserProfile(job.UserId);
            User owner = core.PrimitiveCache[job.UserId];
            ItemKey sharedItemKey = new ItemKey(job.ItemId, job.ItemTypeId);
            IActionableItem sharedItem = null;

            core.ItemCache.RequestItem(sharedItemKey);
            try
            {
                sharedItem = (IActionableItem)core.ItemCache[sharedItemKey];
            }
            catch
            {
                try
                {
                    sharedItem = (IActionableItem)NumberedItem.Reflect(core, sharedItemKey);
                    HttpContext.Current.Response.Write("<br />Fallback, had to reflect: " + sharedItemKey.ToString());
                }
                catch
                {
                    job.Cancel = true;
                    return true; // Item is probably deleted, report success to delete from queue
                }
            }

            UpdateQuery uQuery = new UpdateQuery(typeof(ItemInfo));
            uQuery.AddCondition("info_item_id", sharedItemKey.Id);
            uQuery.AddCondition("info_item_type_id", sharedItemKey.TypeId);

            try
            {
                if (owner.UserInfo.TumblrAuthenticated) // are we still authenticated
                {
                    string postDescription = job.Body;

                    Tumblr t = new Tumblr(core.Settings.TumblrApiKey, core.Settings.TumblrApiSecret);
                    TumblrPost post = t.StatusesUpdate(new TumblrAccessToken(owner.UserInfo.TumblrToken, owner.UserInfo.TumblrTokenSecret), owner.UserInfo.TumblrHostname, sharedItem.PostType, string.Empty, postDescription, sharedItem.Info.ShareUri, sharedItem.Data, sharedItem.DataContentType);

                    if (post != null)
                    {
                        uQuery.AddField("info_tumblr_post_id", post.Id);
                    }

                    core.Db.Query(uQuery);
                }
            }
            catch (System.Net.WebException ex)
            {
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                if (response.StatusCode == HttpStatusCode.Forbidden)
                {
                    return true; // This request cannot succeed, so remove it from the queue
                }
                job.Error = ex.ToString();
                return false; // Failed for other reasons, retry
            }

            return true; // success
        }
예제 #3
0
        internal static void NotifyFriendRequest(Core core, Job job)
        {
            core.LoadUserProfile(job.ItemId);
            User friendProfile = core.PrimitiveCache[job.ItemId];

            ApplicationEntry ae = core.GetApplication("Profile");
            ae.SendNotification(core, core.Session.LoggedInMember, friendProfile, core.LoggedInMemberItemKey, core.LoggedInMemberItemKey, "_WANTS_FRIENDSHIP", core.Session.LoggedInMember.Uri, "friend");
        }
예제 #4
0
        public static void NotifyUserComment(Core core, Job job)
        {
            Comment comment = new Comment(core, job.ItemId);
            core.LoadUserProfile(comment.CommentedItemKey.Id);
            User ev = core.PrimitiveCache[comment.CommentedItemKey.Id];

            if (ev.Owner is User && (!comment.OwnerKey.Equals(ev.ItemKey)))
            {
                core.CallingApplication.SendNotification(core, comment.User, (User)ev.Owner, ev.ItemKey, ev.ItemKey, "_COMMENTED_GUEST_BOOK", comment.BuildUri(ev));
            }

            //core.CallingApplication.SendNotification(core, comment.OwnerKey, ev.ItemKey, string.Format("[user]{0}[/user] commented on [user]{2}[/user] [iurl=\"{1}\"]blog post[/iurl]", comment.OwnerKey.Id, comment.BuildUri(ev), ev.OwnerKey.Id), string.Empty, emailTemplate);
        }
예제 #5
0
        public static Comment Create(Core core, ItemKey itemKey, string comment)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            if (!core.Session.IsLoggedIn)
            {
                throw new NotLoggedInException();
            }

            if (core.Db.Query(string.Format("SELECT user_id FROM comments WHERE (user_id = {0} OR comment_ip = '{1}') AND (UNIX_TIMESTAMP() - comment_time_ut) < 20",
                    core.LoggedInMemberId, core.Session.IPAddress.ToString())).Rows.Count > 0)
            {
                throw new CommentFloodException();
            }

            if (comment.Length > COMMENT_MAX_LENGTH)
            {
                throw new CommentTooLongException();
            }

            if (comment.Length < 2)
            {
                throw new CommentTooShortException();
            }

            Relation relations = Relation.None;
            // A little bit of hard coding we can't avoid
            if (itemKey.TypeId == ItemKey.GetTypeId(core, typeof(User)))
            {
                core.LoadUserProfile(itemKey.Id);
                relations = core.PrimitiveCache[itemKey.Id].GetRelations(core.Session.LoggedInMember.ItemKey);
            }

            string commentCache = string.Empty;

            if (!comment.Contains("[user") && !comment.Contains("sid=true]"))
            {
                commentCache = core.Bbcode.Parse(HttpUtility.HtmlEncode(comment), null, core.Session.LoggedInMember, true, string.Empty, string.Empty);
            }

            core.Db.BeginTransaction();

            Comment newComment = (Comment)Item.Create(core, typeof(Comment), new FieldValuePair("comment_item_id", itemKey.Id),
                new FieldValuePair("comment_item_type_id", itemKey.TypeId),
                new FieldValuePair("user_id", core.LoggedInMemberId),
                new FieldValuePair("comment_time_ut", UnixTime.UnixTimeStamp()),
                new FieldValuePair("comment_text", comment),
                new FieldValuePair("comment_text_cache", commentCache),
                new FieldValuePair("comment_ip", core.Session.IPAddress.ToString()),
                new FieldValuePair("comment_spam_score", CalculateSpamScore(core, comment, relations)),
                new FieldValuePair("comment_hash", MessageMd5(comment)));

            return newComment;
        }
예제 #6
0
        public MusicianMember(Core core, Musician musician, long userId)
            : base(core)
        {
            this.db = db;

            SelectQuery query = GetSelectQueryStub(core, UserLoadOptions.All);
            query.AddCondition("user_keys.user_id", userId);
            query.AddCondition("musician_members.musician_id", musician.Id);

            DataTable memberTable = db.Query(query);

            if (memberTable.Rows.Count == 1)
            {
                loadItemInfo(typeof(MusicianMember), memberTable.Rows[0]);
                core.LoadUserProfile(userId);
                loadUserFromUser(core.PrimitiveCache[userId]);
            }
            else
            {
                throw new InvalidUserException();
            }
        }
예제 #7
0
 public MusicianMember(Core core, DataRow memberRow)
     : base(core)
 {
     loadItemInfo(typeof(MusicianMember), memberRow);
     core.LoadUserProfile(userId);
     loadUserFromUser(core.PrimitiveCache[userId]);
 }
예제 #8
0
        // TODO: use user
        public static void Show(Core core, UPage page, string user)
        {
            core.Template.SetTemplate("GuestBook", "viewguestbook");

            page.User.LoadProfileInfo();

            if (!page.User.Access.Can("VIEW"))
            {
                core.Functions.Generate403();
                return;
            }

            /* pages */
            core.Display.ParsePageList(page.Owner, true);

            core.Template.Parse("PAGE_TITLE", string.Format(core.Prose.GetString("USERS_GUEST_BOOK"), page.Owner.DisplayNameOwnership));

            if (core.Session.IsLoggedIn)
            {
                if (page.User.Access.Can("COMMENT"))
                {
                    core.Template.Parse("CAN_COMMENT", "TRUE");
                }
            }

            core.Template.Parse("IS_USER_GUESTBOOK", "TRUE");

            long userId = core.LoadUserProfile(user);

            List<User> commenters = new List<User>();
            commenters.Add(page.User);
            commenters.Add(core.PrimitiveCache[userId]);

            List<string[]> breadCrumbParts = new List<string[]>();
            breadCrumbParts.Add(new string[] { "profile", core.Prose.GetString("PROFILE") });
            breadCrumbParts.Add(new string[] { "comments", core.Prose.GetString("COMMENTS") });
            breadCrumbParts.Add(new string[] {core.PrimitiveCache[userId].Key, core.PrimitiveCache[userId].DisplayName});

            // Load the comment count
            long comments = 0;

            SelectQuery query = new SelectQuery("guestbook_comment_counts");
            query.AddField(new QueryFunction("comment_comments", QueryFunctions.Sum, "comments"));

            QueryCondition qc1 = query.AddCondition("owner_id", commenters[0].Id);
            qc1.AddCondition("user_id", commenters[1].Id);

            QueryCondition qc2 = query.AddCondition(ConditionRelations.Or, "owner_id", commenters[1].Id);
            qc2.AddCondition("user_id", commenters[0].Id);

            DataTable commentCountDataTable = core.Db.Query(query);

            if (commentCountDataTable.Rows.Count > 0)
            {
                if (!(commentCountDataTable.Rows[0]["comments"] is DBNull))
                {
                    comments = (long)(Decimal)commentCountDataTable.Rows[0]["comments"];
                }
            }

            core.Display.DisplayComments(core.Template, page.User, page.User, commenters, comments, UserGuestBookHook);

            core.Display.ParsePagination("COMMENT_PAGINATION", core.Hyperlink.BuildGuestBookUri(page.User, core.PrimitiveCache[userId]), 10, comments);
            page.User.ParseBreadCrumbs(breadCrumbParts);
        }
예제 #9
0
        public void Invite(Core core, List<User> invitees)
        {
            core.LoadUserProfile(userId);
            User user = core.PrimitiveCache[userId];
            // only the person who created the event can invite people to it
            if (core.LoggedInMemberId == userId)
            {
                long friends = 0;
                foreach (User invitee in invitees)
                {
                    // we can only invite people friends with us to an event
                    if (invitee.IsFriend(user.ItemKey))
                    {
                        friends++;

                        InsertQuery iQuery = new InsertQuery("event_invites");
                        iQuery.AddField("event_id", EventId);
                        iQuery.AddField("item_id", invitee.Id);
                        iQuery.AddField("item_typeId", invitee.TypeId);
                        iQuery.AddField("inviter_id", userId);
                        iQuery.AddField("invite_date_ut", UnixTime.UnixTimeStamp());
                        iQuery.AddField("invite_accepted", false);
                        iQuery.AddField("invite_status", (byte)EventAttendance.Unknown);

                        long invitationId = db.Query(iQuery);

                        core.CallingApplication.SendNotification(core, user, invitee, OwnerKey, ItemKey, "_INVITED_EVENT", Uri, "invite");

                    }
                    else
                    {
                        // ignore
                    }

                    UpdateQuery uQuery = new UpdateQuery("events");
                    uQuery.AddField("event_invitees", new QueryOperation("event_invitees", QueryOperations.Addition, friends));
                    uQuery.AddCondition("event_id", EventId);

                    db.Query(uQuery);
                }
            }
            else
            {
                throw new CouldNotInviteEventException();
            }
        }
예제 #10
0
        public static void NotifyMessage(Core core, Job job)
        {
            Message ev = new Message(core, job.ItemId);

            List<MessageRecipient> recipients = ev.GetRecipients();

            foreach (MessageRecipient recipient in recipients)
            {
                core.LoadUserProfile(recipient.UserId);
            }

            foreach (MessageRecipient recipient in recipients)
            {
                // TODO: notify everyone via push notifications

                if (ev.SenderId == recipient.UserId)
                {
                    // don't need to notify ourselves via e-mail
                    continue;
                }

                User receiver = core.PrimitiveCache[recipient.UserId];

                if (receiver.UserInfo.EmailNotifications)
                {
                    string notificationString = string.Format("[user]{0}[/user] [iurl=\"{1}\"]" + core.Prose.GetString("_SENT_YOU_A_MESSAGE") + "[/iurl]",
                        ev.SenderId, ev.Uri);

                    Template emailTemplate = new Template(core.TemplateEmailPath, "notification.html");

                    emailTemplate.Parse("SITE_TITLE", core.Settings.SiteTitle);
                    emailTemplate.Parse("U_SITE", core.Hyperlink.StripSid(core.Hyperlink.AppendAbsoluteSid(core.Hyperlink.BuildHomeUri())));
                    emailTemplate.Parse("TO_NAME", receiver.DisplayName);
                    core.Display.ParseBbcode(emailTemplate, "NOTIFICATION_MESSAGE", notificationString, receiver, false, string.Empty, string.Empty, true);
                    emailTemplate.Parse("NOTIFICATION_BODY", job.Body);

                    core.Email.SendEmail(receiver.UserInfo.PrimaryEmail, HttpUtility.HtmlDecode(core.Bbcode.Flatten(HttpUtility.HtmlEncode(notificationString))), emailTemplate);
                }
            }
        }
예제 #11
0
        protected void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            int wait = 15;
            for (int i = 0; i < wait * 100; i++)
            {
                // The sleep should happen on the worker thread rather than the application thread
                System.Threading.Thread.Sleep(10);
                if (e.Cancel)
                {
                    // Poll the thread every [wait] seconds to work out if the worker should be cancelled
                    return;
                }
            }

            //HttpContext.Current = (HttpContext)e.Argument;

            Mysql db = new Mysql(WebConfigurationManager.AppSettings["mysql-user"],
                WebConfigurationManager.AppSettings["mysql-password"],
                WebConfigurationManager.AppSettings["mysql-database"],
                WebConfigurationManager.AppSettings["mysql-host"]);

            Core core = new Core(db);

            string processViews = WebConfigurationManager.AppSettings["queue-process-views"];

            if (!string.IsNullOrEmpty(processViews) && processViews.ToLower() == "true")
            {
                try
                {
                    ItemView.ProcessViews(core);
                }
                catch (Exception ex)
                {
                    InsertQuery iQuery = new InsertQuery(typeof(ApplicationError));
                    iQuery.AddField("error_title", "An Error occured at " + Hyperlink.Domain + " in global.asax");
                    iQuery.AddField("error_body", "EXCEPTION THROWN:\n" + ex.ToString());
                    core.Db.Query(iQuery);
                }
            }

            string cronApplication = WebConfigurationManager.AppSettings["queue-cron-application"];
            if (!string.IsNullOrEmpty(cronApplication))
            {
                List<ApplicationEntry> aes = new List<ApplicationEntry>();

                if (cronApplication == "*")
                {
                    aes.AddRange(core.GetCronApplications());
                }
                else
                {
                    ApplicationEntry ae = core.GetApplication(cronApplication);
                    if (ae != null)
                    {
                        BoxSocial.Internals.Application.LoadApplication(core, AppPrimitives.Any, ae);
                        aes.Add(ae);
                    }
                }

                foreach (ApplicationEntry ae in aes)
                {
                    if (UnixTime.UnixTimeStamp() % ae.CronFrequency < 15)
                    {
                        Application jobApplication = BoxSocial.Internals.Application.GetApplication(core, AppPrimitives.Any, ae);

                        if (jobApplication != null)
                        {
                            try
                            {
                                if (!jobApplication.ExecuteCron())
                                {
                                    StringBuilder failedCronLog = new StringBuilder();
                                    failedCronLog.AppendLine("Application Id: " + ae.ApplicationId);

                                    InsertQuery iQuery = new InsertQuery(typeof(ApplicationError));
                                    iQuery.AddField("error_title", "Cron failed at " + Hyperlink.Domain);
                                    iQuery.AddField("error_body", "FAILED CRON:\n" + failedCronLog.ToString());
                                    core.Db.Query(iQuery);
                                }
                            }
                            catch (Exception ex)
                            {
                                InsertQuery iQuery = new InsertQuery(typeof(ApplicationError));
                                iQuery.AddField("error_title", "An Error occured at " + Hyperlink.Domain + " in global.asax");
                                iQuery.AddField("error_body", "EXCEPTION THROWN:\n" + ex.ToString() + "\n\n" + core.Console.ToString());
                                core.Db.Query(iQuery);
                            }
                        }
                    }
                }
            }

            try
            {
                bool flag = false;
                lock (queueLock)
                {
                    if (queue != null)
                    {
                        flag = true;
                    }
                }

                if (flag)
                {
                    int failedJobs = 0;

                    // Retrieve Jobs
                    Dictionary<string, int> queues = new Dictionary<string, int>();
                    queues.Add(WebConfigurationManager.AppSettings["queue-default-priority"], 10);

                    StringBuilder failedJobsLog = new StringBuilder();

                    foreach (string queueName in queues.Keys)
                    {
                        List<Job> jobs = null;
                        lock (queueLock)
                        {
                            try
                            {
                                jobs = Queue.ClaimJobs(queueName, queues[queueName]);
                            }
                            catch
                            {
                                return;
                            }
                        }

                        foreach (Job job in jobs)
                        {
                            core.LoadUserProfile(job.UserId);
                        }

                        foreach (Job job in jobs)
                        {
                            core.CreateNewSession(core.PrimitiveCache[job.UserId]);

                            // Load Application
                            if (job.ApplicationId > 0)
                            {
                                ApplicationEntry ae = core.GetApplication(job.ApplicationId);
                                BoxSocial.Internals.Application.LoadApplication(core, AppPrimitives.Any, ae);
                            }

                            // Execute Job
                            if (core.InvokeJob(job))
                            {
                                lock (queueLock)
                                {
                                    Queue.DeleteJob(job);
                                }
                            }
                            else
                            {
                                failedJobs++;
                                //queue.ReleaseJob(job);
            #if DEBUG
                                failedJobsLog.AppendLine("Application Id: " + job.ApplicationId);
                                failedJobsLog.AppendLine("Item Id: " + job.ItemId);
                                failedJobsLog.AppendLine("Item Type Id: " + job.ItemTypeId);
                                failedJobsLog.AppendLine("Function: " + job.Function);
                                failedJobsLog.AppendLine("Body: " + job.Body);
                                failedJobsLog.AppendLine("Message: " + job.Message);
                                failedJobsLog.AppendLine("Error: " + job.Error);
                                failedJobsLog.AppendLine("====================");
            #endif
                            }
                        }
                    }

                    if (failedJobs > 0)
                    {
                        InsertQuery iQuery = new InsertQuery(typeof(ApplicationError));
                        iQuery.AddField("error_title", "Jobs failed at " + Hyperlink.Domain);
                        iQuery.AddField("error_body", "FAILED JOB COUNT:\n" + failedJobs.ToString() + "\n\n" + failedJobsLog.ToString());
                        core.Db.Query(iQuery);
            #if DEBUG
                        core.Email.SendEmail(WebConfigurationManager.AppSettings["error-email"], "Jobs failed at " + Hyperlink.Domain, "FAILED JOB COUNT:\n" + failedJobs.ToString() + "\n\n" + failedJobsLog.ToString());
            #endif
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    InsertQuery iQuery = new InsertQuery(typeof(ApplicationError));
                    iQuery.AddField("error_title", "An Error occured at " + Hyperlink.Domain + " in global.asax");
                    iQuery.AddField("error_body", "EXCEPTION THROWN:\n" + ex.ToString());
                    core.Db.Query(iQuery);
                    core.Email.SendEmail(WebConfigurationManager.AppSettings["error-email"], "An Error occured at " + Hyperlink.Domain + " in global.asax", "EXCEPTION THROWN:\n" + ex.ToString());
                }
                catch
                {
                    try
                    {
                        core.Email.SendEmail(WebConfigurationManager.AppSettings["error-email"], "An Error occured at " + Hyperlink.Domain + " in global.asax", "EXCEPTION THROWN:\n" + ex.ToString());
                    }
                    catch
                    {
                    }
                }
            }

            // Cleanup

            lock (queueLock)
            {
                if (queue != null)
                {
                    Queue.CloseConnection();
                    Queue = null;
                }
            }

            core.CloseProse();
            core.CloseSearch();
            core.CloseCache();
            core = null;
            db.CloseConnection();
            db = null;
        }
예제 #12
0
        public GroupMember(Core core, DataRow memberRow)
            : base(core)
        {
            loadItemInfo(memberRow);
            core.LoadUserProfile(userId);
            loadUserFromUser(core.PrimitiveCache[userId]);

            /*try
            {*/
            if (memberRow != null && memberRow.Table.Columns.Contains("user_id_go"))
            {
                if (!(memberRow["user_id_go"] is DBNull))
                {
                    isOperator = true;
                }
            }
            /*}
            catch
            {
                // TODO: is there a better way?
                //isOperator = false;
            }*/
        }
예제 #13
0
        public static void Show(Core core, GPage page, long forumId)
        {
            string mark = core.Http.Query["mark"];
            ForumSettings settings;
            try
            {
                settings = new ForumSettings(core, page.Group);
            }
            catch (InvalidForumSettingsException)
            {
                ForumSettings.Create(core, page.Group);
                settings = new ForumSettings(core, page.Group);
            }
            Forum thisForum = null;
            long topicsCount = 0;

            core.Template.SetTemplate("Forum", "viewforum");
            ForumSettings.ShowForumHeader(core, page);

            try
            {
                if (forumId > 0)
                {
                    thisForum = new Forum(page.Core, settings, forumId);

                    core.Template.Parse("PAGE_TITLE", thisForum.Title);
                    core.Template.Parse("FORUM_TITLE", thisForum.Title);

                    core.Template.Parse("SHOW_TOPICS", "TRUE");
                }
                else
                {
                    thisForum = new Forum(page.Core, settings);

                    core.Template.Parse("PAGE_TITLE", core.Prose.GetString("FORUM"));
                    core.Template.Parse("FORUM_TITLE", core.Prose.GetString("FORUM"));

                    if (settings.AllowTopicsAtRoot)
                    {
                        core.Template.Parse("SHOW_TOPICS", "TRUE");
                    }
                }
            }
            catch (InvalidForumException)
            {
                return;
            }

            if (mark == "topics")
            {
                thisForum.ReadAll(false);
            }

            if (mark == "forums")
            {
                thisForum.ReadAll(true);
            }

            if (core.LoggedInMemberId > 0 && (!page.Group.IsGroupMember(core.Session.LoggedInMember.ItemKey)))
            {
                core.Template.Parse("U_JOIN", page.Group.JoinUri);
            }

            topicsCount = thisForum.Topics;

            if (!string.IsNullOrEmpty(thisForum.Rules))
            {
                core.Display.ParseBbcode(core.Template, "RULES", thisForum.Rules);
            }

            List<Forum> forums = GetForumLevels(core, thisForum, 2);
            List<IPermissibleItem> items = new List<IPermissibleItem>();

            //List<Forum> forums = thisForum.GetForums();
            List<Forum> accessibleForums = new List<Forum>();

            foreach (Forum forum in forums)
            {
                items.Add(forum);
            }
            items.Add(thisForum);

            core.AcessControlCache.CacheGrants(items);

            foreach (Forum forum in forums)
            {
                if (forum.Access.Can("VIEW"))
                {
                    accessibleForums.Add(forum);
                }
            }
            forums = accessibleForums;

            if (!thisForum.Access.Can("VIEW"))
            {
                core.Functions.Generate403();
                return;
            }

            core.Template.Parse("FORUMS", forums.Count.ToString());

            // ForumId, TopicPost
            Dictionary<long, TopicPost> lastPosts;
            List<long> lastPostIds = new List<long>();

            foreach (Forum forum in forums)
            {
                lastPostIds.Add(forum.LastPostId);
            }

            lastPosts = TopicPost.GetPosts(core, lastPostIds);

            VariableCollection lastForumVariableCollection = null;
            bool lastCategory = true;
            bool first = true;
            long lastCategoryId = 0;
            Forum lastForum = null;
            foreach (Forum forum in forums)
            {
                if (lastForum != null && (!lastForum.IsCategory) && lastForum.Id == forum.parentId && lastForumVariableCollection != null)
                {
                    VariableCollection subForumVariableCollection = lastForumVariableCollection.CreateChild("sub_forum_list");

                    subForumVariableCollection.Parse("TITLE", forum.Title);
                    subForumVariableCollection.Parse("URI", forum.Uri);

                    continue;
                }

                if ((first && (!forum.IsCategory)) || (lastCategoryId != forum.parentId && (!forum.IsCategory)))
                {
                    VariableCollection defaultVariableCollection = core.Template.CreateChild("forum_list");
                    defaultVariableCollection.Parse("TITLE", "Forum");
                    defaultVariableCollection.Parse("IS_CATEGORY", "TRUE");
                    if (lastForumVariableCollection != null)
                    {
                        lastForumVariableCollection.Parse("IS_LAST", "TRUE");
                    }
                    first = false;
                    lastCategoryId = forum.parentId;
                    lastCategory = true;
                }

                VariableCollection forumVariableCollection = core.Template.CreateChild("forum_list");

                forumVariableCollection.Parse("TITLE", forum.Title);
                core.Display.ParseBbcode(forumVariableCollection, "DESCRIPTION", forum.Description);
                forumVariableCollection.Parse("URI", forum.Uri);
                forumVariableCollection.Parse("POSTS", forum.Posts.ToString());
                forumVariableCollection.Parse("TOPICS", forum.Topics.ToString());

                if (lastPosts.ContainsKey(forum.LastPostId))
                {
                    forumVariableCollection.Parse("LAST_POST_URI", lastPosts[forum.LastPostId].Uri);
                    forumVariableCollection.Parse("LAST_POST_TITLE", lastPosts[forum.LastPostId].Title);
                    core.Display.ParseBbcode(forumVariableCollection, "LAST_POST", string.Format("[iurl={0}]{1}[/iurl]\n{2}",
                        lastPosts[forum.LastPostId].Uri, Functions.TrimStringToWord(lastPosts[forum.LastPostId].Title, 20), core.Tz.DateTimeToString(lastPosts[forum.LastPostId].GetCreatedDate(core.Tz))));
                }
                else
                {
                    forumVariableCollection.Parse("LAST_POST", "No posts");
                }

                if (forum.IsRead)
                {
                    forumVariableCollection.Parse("IS_READ", "TRUE");
                }
                else
                {
                    forumVariableCollection.Parse("IS_READ", "FALSE");
                }

                if (forum.IsCategory)
                {
                    forumVariableCollection.Parse("IS_CATEGORY", "TRUE");
                    if (lastForumVariableCollection != null)
                    {
                        lastForumVariableCollection.Parse("IS_LAST", "TRUE");
                    }
                    lastCategoryId = forum.Id;
                    lastCategory = true;
                }
                else
                {
                    topicsCount -= forum.Topics;
                    forumVariableCollection.Parse("IS_FORUM", "TRUE");
                    if (lastCategory)
                    {
                        forumVariableCollection.Parse("IS_FIRST", "TRUE");
                    }
                    lastForumVariableCollection = forumVariableCollection;
                    lastCategory = false;
                }
                first = false;
                lastForum = forum;
            }

            if (lastForumVariableCollection != null)
            {
                lastForumVariableCollection.Parse("IS_LAST", "TRUE");
            }

            if ((settings.AllowTopicsAtRoot && forumId == 0) || forumId > 0)
            {
                if (thisForum.TopicsPaged > 0)
                {
                    List<ForumTopic> announcements = thisForum.GetAnnouncements();
                    List<ForumTopic> topics = thisForum.GetTopics(page.TopLevelPageNumber, settings.TopicsPerPage);
                    List<ForumTopic> allTopics = new List<ForumTopic>();
                    allTopics.AddRange(announcements);
                    allTopics.AddRange(topics);

                    topicsCount -= announcements.Count; // aren't counted in pagination

                    core.Template.Parse("ANNOUNCEMENTS", announcements.Count.ToString());
                    //page.template.Parse("TOPICS", topics.Count.ToString());

                    // PostId, TopicPost
                    Dictionary<long, TopicPost> topicLastPosts;

                    topicLastPosts = TopicPost.GetTopicLastPosts(core, allTopics);

                    core.Template.Parse("TOPICS", allTopics.Count.ToString());

                    foreach (ForumTopic topic in allTopics)
                    {
                        core.LoadUserProfile(topic.PosterId);
                    }

                    foreach (ForumTopic topic in allTopics)
                    {
                        VariableCollection topicVariableCollection = core.Template.CreateChild("topic_list");

                        if (topic.Posts > settings.PostsPerPage)
                        {
                            core.Display.ParseMinimalPagination(topicVariableCollection, "PAGINATION", topic.Uri, 0, settings.PostsPerPage, topic.Posts);
                        }
                        else
                        {
                            topicVariableCollection.Parse("PAGINATION", "FALSE");
                        }

                        topicVariableCollection.Parse("TITLE", topic.Title);
                        topicVariableCollection.Parse("URI", topic.Uri);
                        topicVariableCollection.Parse("VIEWS", topic.Views.ToString());
                        topicVariableCollection.Parse("REPLIES", topic.Posts.ToString());
                        topicVariableCollection.Parse("DATE", core.Tz.DateTimeToString(topic.GetCreatedDate(core.Tz)));
                        topicVariableCollection.Parse("USERNAME", core.PrimitiveCache[topic.PosterId].DisplayName);
                        topicVariableCollection.Parse("U_POSTER", core.PrimitiveCache[topic.PosterId].Uri);

                        if (topicLastPosts.ContainsKey(topic.LastPostId))
                        {
                            topicVariableCollection.Parse("LAST_POST_URI", topicLastPosts[topic.LastPostId].Uri);
                            topicVariableCollection.Parse("LAST_POST_TITLE", topicLastPosts[topic.LastPostId].Title);
                            core.Display.ParseBbcode(topicVariableCollection, "LAST_POST", string.Format("[iurl={0}]{1}[/iurl]\n{2}",
                                topicLastPosts[topic.LastPostId].Uri, Functions.TrimStringToWord(topicLastPosts[topic.LastPostId].Title, 20), core.Tz.DateTimeToString(topicLastPosts[topic.LastPostId].GetCreatedDate(core.Tz))));
                        }
                        else
                        {
                            topicVariableCollection.Parse("LAST_POST", "No posts");
                        }

                        switch (topic.Status)
                        {
                            case TopicStates.Normal:
                                if (topic.IsRead)
                                {
                                    if (topic.IsLocked)
                                    {
                                        topicVariableCollection.Parse("IS_NORMAL_READ_LOCKED", "TRUE");
                                    }
                                    else
                                    {
                                        topicVariableCollection.Parse("IS_NORMAL_READ_UNLOCKED", "TRUE");
                                    }
                                }
                                else
                                {
                                    if (topic.IsLocked)
                                    {
                                        topicVariableCollection.Parse("IS_NORMAL_UNREAD_LOCKED", "TRUE");
                                    }
                                    else
                                    {
                                        topicVariableCollection.Parse("IS_NORMAL_UNREAD_UNLOCKED", "TRUE");
                                    }
                                }
                                break;
                            case TopicStates.Sticky:
                                if (topic.IsRead)
                                {
                                    if (topic.IsLocked)
                                    {
                                        topicVariableCollection.Parse("IS_STICKY_READ_LOCKED", "TRUE");
                                    }
                                    else
                                    {
                                        topicVariableCollection.Parse("IS_STICKY_READ_UNLOCKED", "TRUE");
                                    }
                                }
                                else
                                {
                                    if (topic.IsLocked)
                                    {
                                        topicVariableCollection.Parse("IS_STICKY_UNREAD_LOCKED", "TRUE");
                                    }
                                    else
                                    {
                                        topicVariableCollection.Parse("IS_STICKY_UNREAD_UNLOCKED", "TRUE");
                                    }
                                }

                                break;
                            case TopicStates.Announcement:
                            case TopicStates.Global:
                                if (topic.IsRead)
                                {
                                    if (topic.IsLocked)
                                    {
                                        topicVariableCollection.Parse("IS_ANNOUNCEMENT_READ_LOCKED", "TRUE");
                                    }
                                    else
                                    {
                                        topicVariableCollection.Parse("IS_ANNOUNCEMENT_READ_UNLOCKED", "TRUE");
                                    }
                                }
                                else
                                {
                                    if (topic.IsLocked)
                                    {
                                        topicVariableCollection.Parse("IS_ANNOUNCEMENT_UNREAD_LOCKED", "TRUE");
                                    }
                                    else
                                    {
                                        topicVariableCollection.Parse("IS_ANNOUNCEMENT_UNREAD_UNLOCKED", "TRUE");
                                    }
                                }

                                break;
                        }
                    }
                }

                if (!thisForum.IsCategory)
                {
                    if (thisForum.Access.Can("CREATE_TOPICS"))
                    {
                        core.Template.Parse("U_NEW_TOPIC", thisForum.NewTopicUri);
                    }
                }

                core.Display.ParsePagination(thisForum.Uri, settings.TopicsPerPage, thisForum.TopicsPaged);
            }

            List<string[]> breadCrumbParts = new List<string[]>();
            breadCrumbParts.Add(new string[] { "forum", core.Prose.GetString("FORUM") });

            if (thisForum.Parents != null)
            {
                foreach (ParentTreeNode ptn in thisForum.Parents.Nodes)
                {
                    breadCrumbParts.Add(new string[] { "*" + ptn.ParentId.ToString(), ptn.ParentTitle });
                }
            }

            if (thisForum.Id > 0)
            {
                breadCrumbParts.Add(new string[] { thisForum.Id.ToString(), thisForum.Title });
            }

            page.Group.ParseBreadCrumbs(breadCrumbParts);

            if (thisForum.Id == 0)
            {
                core.Template.Parse("INDEX_STATISTICS", "TRUE");
                core.Template.Parse("FORUM_POSTS", core.Functions.LargeIntegerToString(settings.Posts));
                core.Template.Parse("FORUM_TOPICS", core.Functions.LargeIntegerToString(settings.Topics));
                core.Template.Parse("GROUP_MEMBERS", core.Functions.LargeIntegerToString(page.Group.Members));
            }

            PermissionsList permissions = new PermissionsList(core);
            bool flagPermissionsBlock = false;

            if (thisForum.Access.Can("CREATE_TOPICS"))
            {
                permissions.Add(core.Prose.GetString("YOU_CAN_CREATE_TOPICS"), true);
                flagPermissionsBlock = true;
            }
            else
            {
                permissions.Add(core.Prose.GetString("YOU_CAN_CREATE_TOPICS"), false);
                flagPermissionsBlock = true;
            }
            if (thisForum.Access.Can("REPLY_TOPICS"))
            {
                permissions.Add(core.Prose.GetString("YOU_CAN_POST_REPLIES"), true);
                flagPermissionsBlock = true;
            }
            else
            {
                permissions.Add(core.Prose.GetString("YOU_CAN_POST_REPLIES"), false);
                flagPermissionsBlock = true;
            }
            if (thisForum.Access.Can("EDIT_OWN_POSTS"))
            {
                permissions.Add(core.Prose.GetString("YOU_CAN_EDIT_YOUR_POSTS"), true);
                flagPermissionsBlock = true;
            }
            if (thisForum.Access.Can("DELETE_OWN_POSTS"))
            {
                permissions.Add(core.Prose.GetString("YOU_CAN_DELETE_YOUR_POSTS"), true);
                flagPermissionsBlock = true;
            }
            if (thisForum.Access.Can("DELETE_TOPICS") || thisForum.Access.Can("LOCK_TOPICS"))
            {
                permissions.Add(core.Prose.GetString("YOU_CAN_MODERATE_FORUM"), true, core.Hyperlink.StripSid(thisForum.ModeratorControlPanelUri));
                flagPermissionsBlock = true;
            }

            if (flagPermissionsBlock)
            {
                permissions.Parse("PERMISSION_BLOCK");
            }
        }
예제 #14
0
        public void SendNotification(Core core, ItemKey donotNotify, User actionBy, ItemKey itemOwnerKey, ItemKey itemKey, string verb, string url)
        {
            long userTypeId = ItemType.GetTypeId(core, typeof(User));
            List<ItemKey> receiverKeys = Subscription.GetSubscribers(core, itemKey, 0, 0);

            foreach (ItemKey receiverKey in receiverKeys)
            {
                if (receiverKey.TypeId == userTypeId && (!receiverKey.Equals(donotNotify)))
                {
                    core.LoadUserProfile(receiverKey.Id);
                }
            }

            foreach (ItemKey receiverKey in receiverKeys)
            {
                if (receiverKey.TypeId == userTypeId && (!receiverKey.Equals(donotNotify)))
                {
                    SendNotification(core, actionBy, core.PrimitiveCache[receiverKey.Id], itemOwnerKey, itemKey, verb, url);
                }
            }
        }
예제 #15
0
 public ApplicationDeveloper(Core core, DataRow memberRow)
     : base(core)
 {
     loadItemInfo(typeof(ApplicationDeveloper), memberRow);
     core.LoadUserProfile(userId);
     loadUserFromUser(core.PrimitiveCache[userId]);
 }