Esempio n. 1
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();
            }
        }
Esempio n. 2
0
        public static bool UnsubscribeFromItem(Core core, ItemKey itemKey)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            core.Db.BeginTransaction();

            SelectQuery query = Subscription.GetSelectQueryStub(core, typeof(Subscription));
            query.AddCondition("subscription_item_id", itemKey.Id);
            query.AddCondition("subscription_item_type_id", itemKey.TypeId);
            query.AddCondition("user_id", core.LoggedInMemberId);

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

            if (subscriptionDataTable.Rows.Count == 1)
            {
                DeleteQuery dQuery = new DeleteQuery(typeof(Subscription));
                dQuery.AddCondition("subscription_item_id", itemKey.Id);
                dQuery.AddCondition("subscription_item_type_id", itemKey.TypeId);
                dQuery.AddCondition("user_id", core.LoggedInMemberId);

                core.Db.Query(dQuery);

                ItemInfo info = new ItemInfo(core, itemKey);
                info.DecrementSubscribers();

                UpdateQuery uQuery = new UpdateQuery(typeof(UserInfo));
                uQuery.AddField("user_subscriptions", new QueryOperation("user_subscriptions", QueryOperations.Subtraction, 1));
                uQuery.AddCondition("user_id", core.LoggedInMemberId);
                core.Db.Query(uQuery);

                return true;
            }

            return false;
        }
Esempio n. 3
0
        public NetworkMember Join(Core core, User member, string networkEmail)
        {
            string activateKey = User.GenerateActivationSecurityToken();

            if (!IsValidNetworkEmail(networkEmail) && networkInfo.RequireConfirmation)
            {
                return null;
            }

            if (IsNetworkMember(member.ItemKey))
            {
                return null;
            }

            int isActive = (networkInfo.RequireConfirmation) ? 0 : 1;

            // delete any existing unactivated e-mails for this user in this network, re-send the invitation
            db.BeginTransaction();

            try
            {
                NetworkMember nm = new NetworkMember(core, this, member);

                if (!nm.IsMemberActive)
                {
                    try
                    {
                        UserEmail uMail = new UserEmail(core, nm.MemberEmail);
                        uMail.Delete();
                    }
                    catch (InvalidUserEmailException)
                    {
                        // Do Nothing
                    }
                    nm.Delete();
                }
            }
            catch (InvalidUserException)
            {
                // Do Nothing
            }

            if (!networkInfo.RequireConfirmation)
            {
                UpdateQuery uQuery = new UpdateQuery(GetTable(typeof(Network)));
                uQuery.AddField("network_members", new QueryOperation("network_members", QueryOperations.Addition, 1));
                uQuery.AddCondition("network_id", networkId);

                db.Query(uQuery);
            }

            InsertQuery iQuery = new InsertQuery(GetTable(typeof(NetworkMember)));
            iQuery.AddField("network_id", this.Id);
            iQuery.AddField("user_id", member.UserId);
            iQuery.AddField("member_join_date_ut", UnixTime.UnixTimeStamp());
            iQuery.AddField("member_join_ip", core.Session.IPAddress.ToString());
            iQuery.AddField("member_email", networkEmail);
            iQuery.AddField("member_active", isActive);
            iQuery.AddField("member_activate_code", activateKey);

            db.Query(iQuery);

            NetworkMember newMember = new NetworkMember(core, this, member);
            string activateUri = string.Format("http://zinzam.com/network/{0}?mode=activate&id={1}&key={2}",
                networkNetwork, member.UserId, activateKey);

            if (networkInfo.RequireConfirmation)
            {
                EmailAddressTypes emailType = EmailAddressTypes.Other;

                switch (networkInfo.NetworkType)
                {
                    case NetworkTypes.School:
                    case NetworkTypes.University:
                        emailType = EmailAddressTypes.Student;
                        break;
                    case NetworkTypes.Workplace:
                        emailType = EmailAddressTypes.Business;
                        break;
                }

                UserEmail registrationEmail = UserEmail.Create(core, newMember, networkEmail, emailType, true);

                Template emailTemplate = new Template(core.Http.TemplateEmailPath, "join_network.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", member.DisplayName);
                emailTemplate.Parse("U_ACTIVATE", activateUri);
                emailTemplate.Parse("S_EMAIL", networkEmail);

                core.Email.SendEmail(networkEmail, core.Settings.SiteTitle + " Network Registration Confirmation", emailTemplate);
            }

            return newMember;
        }
Esempio n. 4
0
 public void SetRead()
 {
     UpdateQuery uquery = new UpdateQuery("notifications");
 }
Esempio n. 5
0
        /// <summary>
        /// Approves a user tag for public display.
        /// </summary>
        /// <param name="core">Core token</param>
        /// <param name="tag">User tag to approve</param>
        /// <returns>True on success</returns>
        public static bool ApproveTag(Core core, UserTag tag)
        {
            UpdateQuery query = new UpdateQuery("user_tags");
            query.AddField("tag_approved", true);
            query.AddCondition("tag_id", tag.TagId);
            query.AddCondition("user_id", core.LoggedInMemberId);

            if (core.Db.Query(query) == 1)
            {
                tag.tagApproved = true; // we can update private members
                NotifyTag(core, tag);
                return true;
            }
            else
            {
                return false;
            }
        }
Esempio n. 6
0
        public static ForumTopic Create(Core core, Forum forum, string subject, string text, TopicStates status)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            if (forum == null)
            {
                throw new InvalidForumException();
            }

            core.Db.BeginTransaction();

            if (!forum.Access.Can("CREATE_TOPICS"))
            {
                // todo: throw new exception
                throw new UnauthorisedToCreateItemException();
            }

            if ((status == TopicStates.Announcement || status == TopicStates.Global) && (!forum.Access.Can("CREATE_ANNOUNCEMENTS")))
            {
                throw new UnauthorisedToCreateItemException();
            }

            if (status == TopicStates.Sticky && (!forum.Access.Can("CREATE_STICKY")))
            {
                throw new UnauthorisedToCreateItemException();
            }

            if (forum.Owner is UserGroup)
            {
                ForumSettings settings = new ForumSettings(core, (UserGroup)forum.Owner);

                if (forum.Id == 0 && (!settings.AllowTopicsAtRoot))
                {
                    throw new UnauthorisedToCreateItemException();
                }

                if (!((UserGroup)forum.Owner).IsGroupOperator(core.Session.LoggedInMember.ItemKey))
                {
                    status = TopicStates.Normal;
                }
            }

            InsertQuery iquery = new InsertQuery(ForumTopic.GetTable(typeof(ForumTopic)));
            iquery.AddField("forum_id", forum.Id);
            iquery.AddField("topic_title", subject);
            iquery.AddField("user_id", core.LoggedInMemberId);
            iquery.AddField("topic_posts", 0);
            iquery.AddField("topic_views", 0);
            iquery.AddField("topic_time_ut", UnixTime.UnixTimeStamp());
            iquery.AddField("topic_modified_ut", UnixTime.UnixTimeStamp());
            iquery.AddField("topic_last_post_time_ut", UnixTime.UnixTimeStamp());
            iquery.AddField("topic_status", (byte)status);
            iquery.AddField("topic_locked", false);
            iquery.AddField("topic_last_post_id", 0);
            iquery.AddField("topic_first_post_id", 0);
            iquery.AddField("topic_item_id", forum.Owner.Id);
            iquery.AddField("topic_item_type_id", forum.Owner.TypeId);

            long topicId = core.Db.Query(iquery);

            ForumTopic topic = new ForumTopic(core, forum, topicId);

            TopicPost post = TopicPost.Create(core, forum, topic, subject, text);

            UpdateQuery uQuery = new UpdateQuery(ForumTopic.GetTable(typeof(ForumTopic)));
            uQuery.AddField("topic_first_post_id", post.Id);
            uQuery.AddField("topic_last_post_id", post.Id);
            uQuery.AddField("topic_last_post_time_ut", post.TimeCreatedRaw);
            uQuery.AddCondition("topic_id", topic.Id);

            long rowsUpdated = core.Db.Query(uQuery);

            topic.firstPostId = post.Id;
            topic.lastPostId = post.Id;
            topic.lastPostTimeRaw = post.TimeCreatedRaw;

            if (rowsUpdated != 1)
            {
                core.Db.RollBackTransaction();
                core.Display.ShowMessage("ERROR", "Error, rolling back transaction");
            }

            if (forum.Id > 0)
            {
                List<long> parentForumIds = new List<long>();
                parentForumIds.Add(forum.Id);

                if (forum.Parents != null)
                {
                    foreach (ParentTreeNode ptn in forum.Parents.Nodes)
                    {
                        parentForumIds.Add(ptn.ParentId);
                    }
                }

                uQuery = new UpdateQuery(Forum.GetTable(typeof(Forum)));
                uQuery.AddField("forum_posts", new QueryOperation("forum_posts", QueryOperations.Addition, 1));
                uQuery.AddField("forum_topics", new QueryOperation("forum_topics", QueryOperations.Addition, 1));
                uQuery.AddField("forum_last_post_id", post.Id);
                uQuery.AddField("forum_last_post_time_ut", post.TimeCreatedRaw);
                uQuery.AddCondition("forum_id", ConditionEquality.In, parentForumIds);

                rowsUpdated = core.Db.Query(uQuery);

                if (rowsUpdated < 1)
                {
                    core.Db.RollBackTransaction();
                    core.Display.ShowMessage("ERROR", "Error, rolling back transaction");
                }

                uQuery = new UpdateQuery(Forum.GetTable(typeof(Forum)));
                uQuery.AddField("forum_topics", new QueryOperation("forum_topics_paged", QueryOperations.Addition, 1));
                uQuery.AddCondition("forum_id", forum.Id);

                rowsUpdated = core.Db.Query(uQuery);

                if (rowsUpdated < 1)
                {
                    core.Db.RollBackTransaction();
                    core.Display.ShowMessage("ERROR", "Error, rolling back transaction");
                }
            }

            uQuery = new UpdateQuery(ForumSettings.GetTable(typeof(ForumSettings)));
            uQuery.AddField("forum_posts", new QueryOperation("forum_posts", QueryOperations.Addition, 1));
            uQuery.AddField("forum_topics", new QueryOperation("forum_topics", QueryOperations.Addition, 1));
            uQuery.AddCondition("forum_item_id", forum.Owner.Id);
            uQuery.AddCondition("forum_item_type_id", forum.Owner.TypeId);

            rowsUpdated = core.Db.Query(uQuery);

            if (rowsUpdated != 1)
            {
                core.Db.RollBackTransaction();
                core.Display.ShowMessage("ERROR", "Error, rolling back transaction");
            }

            /*uQuery = new UpdateQuery(ForumMember.GetTable(typeof(ForumMember)));
            uQuery.AddField("posts", new QueryOperation("posts", QueryOperations.Addition, 1));
            uQuery.AddCondition("user_id", core.session.LoggedInMember.Id);
            uQuery.AddCondition("item_id", forum.Owner.Id);
            uQuery.AddCondition("item_type_id", forum.Owner.TypeId);

            rowsUpdated = core.db.Query(uQuery);

            if (rowsUpdated == 0)
            {
                ForumMember fm = ForumMember.Create(core, forum.Owner, core.session.LoggedInMember, true);

                uQuery = new UpdateQuery(ForumMember.GetTable(typeof(ForumMember)));
                uQuery.AddField("posts", new QueryOperation("posts", QueryOperations.Addition, 1));
                uQuery.AddCondition("user_id", core.session.LoggedInMember.Id);
                uQuery.AddCondition("item_id", forum.Owner.Id);
                uQuery.AddCondition("item_type_id", forum.Owner.TypeId);

                core.db.Query(uQuery);
            }*/

            ForumMember fm = null;

            try
            {
                fm = new ForumMember(core, forum.Owner, core.Session.LoggedInMember);
            }
            catch (InvalidForumMemberException)
            {
                fm = ForumMember.Create(core, forum.Owner, core.Session.LoggedInMember, true);
            }

            fm.ForumPosts += 1;

            /*Dictionary<long, ForumMemberRank> ranks = ForumMemberRank.GetRanks(core, forum.Owner);

            if (!(ranks.ContainsKey(fm.ForumRankId) && ranks[fm.ForumRankId].RankSpecial))
            {
                int rankLastMin = 0;
                foreach (ForumMemberRank rank in ranks.Values)
                {
                    if ((!rank.RankSpecial) && fm.ForumPosts >= rank.RankPosts && rank.RankPosts > rankLastMin)
                    {
                        fm.ForumRankId = rank.Id;
                        rankLastMin = rank.RankPosts;
                    }
                }
            }*/

            fm.Update(typeof(ForumMember));

            return topic;
        }
Esempio n. 7
0
        public static Notification Create(Core core, ApplicationEntry application, User receiver, ItemKey itemKey, string subject, string body)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            int applicationId = 0;

            if (application != null)
            {
                // TODO: ensure only internals can call a null application
                applicationId = (int)application.Id;
            }

            InsertQuery iQuery = new InsertQuery("notifications");
            iQuery.AddField("notification_primitive_id", receiver.Id);
            iQuery.AddField("notification_primitive_type_id", ItemKey.GetTypeId(core, typeof(User)));
            if (itemKey != null)
            {
                iQuery.AddField("notification_item_id", itemKey.Id);
                iQuery.AddField("notification_item_type_id", itemKey.TypeId);
            }
            iQuery.AddField("notification_title", subject);
            iQuery.AddField("notification_body", body);
            iQuery.AddField("notification_time_ut", UnixTime.UnixTimeStamp());
            iQuery.AddField("notification_read", false);
            iQuery.AddField("notification_seen", false);
            iQuery.AddField("notification_application", applicationId);

            long notificationId = core.Db.Query(iQuery);

            UpdateQuery query = new UpdateQuery(typeof(UserInfo));
            query.AddField("user_unread_notifications", new QueryOperation("user_unread_notifications", QueryOperations.Addition, 1));
            query.AddCondition("user_id", receiver.Id);

            core.Db.Query(query);

            Notification notification = new Notification(core, receiver, notificationId, subject, body, UnixTime.UnixTimeStamp(), applicationId);

            return notification;
        }
Esempio n. 8
0
        public void MoveUp()
        {
            this.AuthenticateAction(ItemChangeAction.Edit);

            if (order != 0)
            {
                UpdateQuery uQuery = new UpdateQuery(Item.GetTable(typeof(NagivationTab)));
                uQuery.AddField("tab_order", new QueryOperation("tab_order", QueryOperations.Addition, 1));
                uQuery.AddCondition("tab_item_id", ownerKey.Id);
                uQuery.AddCondition("tab_item_type_id", ownerKey.TypeId);
                uQuery.AddCondition("tab_order", ConditionEquality.Equal, order - 1);

                db.Query(uQuery);

                SetProperty("order", (byte)(order - 1));

                Update();
            }
        }
Esempio n. 9
0
        public static void Remove(Core core, ListItem item)
        {
            core.Db.BeginTransaction();

            item.Delete();

            UpdateQuery uQuery = new UpdateQuery(GetTable(typeof(List)));
            uQuery.AddField("list_items", new QueryOperation("list_items", QueryOperations.Subtraction, 1));
            uQuery.AddCondition("list_id", item.ListId);

            core.Db.Query(uQuery);
        }
Esempio n. 10
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="core"></param>
        public static void UpdateView(Core core, bool response)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            long viewId = core.Functions.FormLong("vid", core.Functions.RequestLong("vid", 0));
            string mode = core.Http.Form["view-mode"]; // tick, background, foreground, unload
            if (string.IsNullOrEmpty(mode))
            {
                mode = core.Http["view-mode"];
            }
            long timestamp = UnixTime.UnixTimeStamp();

            if (viewId > 0)
            {
                ItemView view = new ItemView(core, viewId);

                if (view.viewSessionId == core.Session.SessionId)
                {
                    switch (mode.ToLower())
                    {
                        case "tick":
                            if (view.viewState != (int)ItemViewState.Exited && view.viewState != (int)ItemViewState.Inactive)
                            {
                                if (timestamp - view.viewUpdateTimeRaw < 120) // ticks happen every 60 seconds with a 60 second page timeout
                                {
                                    UpdateQuery uQuery = new UpdateQuery(typeof(ItemView));
                                    uQuery.AddField("view_timespan", new QueryOperation("view_timespan", QueryOperations.Addition, timestamp - view.viewUpdateTimeRaw));
                                    uQuery.AddField("view_update_time_ut", timestamp);
                                    uQuery.AddField("view_cookies", core.Session.SessionMethod == SessionMethods.Cookie);
                                    uQuery.AddField("view_javascript", true);
                                    uQuery.AddField("view_state", (int)ItemViewState.Foreground);
                                    uQuery.AddCondition("view_id", viewId);

                                    core.Db.Query(uQuery);
                                }
                                else
                                {
                                    UpdateQuery uQuery = new UpdateQuery(typeof(ItemView));
                                    uQuery.AddField("view_update_time_ut", timestamp);
                                    uQuery.AddField("view_state", (int)ItemViewState.Foreground);
                                    uQuery.AddCondition("view_id", viewId);

                                    core.Db.Query(uQuery);
                                }
                            }
                            break;
                        case "background":
                        case "unload":
                        case "inactive":
                            {
                                UpdateQuery uQuery = new UpdateQuery(typeof(ItemView));
                                uQuery.AddField("view_javascript", true);
                                if (timestamp - view.viewUpdateTimeRaw < 120)
                                {
                                    uQuery.AddField("view_timespan", new QueryOperation("view_timespan", QueryOperations.Addition, timestamp - view.viewUpdateTimeRaw));
                                }
                                uQuery.AddField("view_update_time_ut", timestamp);
                                if (mode.ToLower() == "unload")
                                {
                                    uQuery.AddField("view_state", (int)ItemViewState.Exited);
                                }
                                else if (mode.ToLower() == "inactive")
                                {
                                    uQuery.AddField("view_state", (int)ItemViewState.Inactive);
                                }
                                else
                                {
                                    uQuery.AddField("view_state", (int)ItemViewState.Background);
                                }
                                uQuery.AddCondition("view_id", viewId);

                                core.Db.Query(uQuery);
                            }
                            break;
                        case "foreground":
                            {
                                UpdateQuery uQuery = new UpdateQuery(typeof(ItemView));
                                uQuery.AddField("view_update_time_ut", timestamp);
                                uQuery.AddField("view_state", (int)ItemViewState.Foreground);
                                uQuery.AddCondition("view_id", viewId);

                                core.Db.Query(uQuery);
                            }
                            break;
                        case "active":
                            {
                                UpdateQuery uQuery = new UpdateQuery(typeof(ItemView));
                                uQuery.AddField("view_update_time_ut", timestamp);
                                uQuery.AddField("view_state", (int)ItemViewState.Active);
                                uQuery.AddCondition("view_id", viewId);

                                core.Db.Query(uQuery);
                            }
                            break;
                    }
                }
                else
                {
                    // probably a view bot
                    UpdateQuery uQuery = new UpdateQuery(typeof(ItemView));
                    uQuery.AddField("view_discounted", true);
                    uQuery.AddField("view_processed", true);
                    uQuery.SetBitField("view_discounted_reason", (int)ItemViewDiscountedReason.InvalidSession);
                    uQuery.AddCondition("view_id", viewId);

                    core.Db.Query(uQuery);
                }
            }

            if (response)
            {
                core.Response.SendStatus("viewLogged");
            }
        }
Esempio n. 11
0
        public void MoveDown()
        {
            this.AuthenticateAction(ItemChangeAction.Edit);

            byte maxOrder = 0;

            SelectQuery query = GetSelectQueryStub(core, typeof(NagivationTab), false);
            query.AddCondition("tab_item_id", ownerKey.Id);
            query.AddCondition("tab_item_type_id", ownerKey.TypeId);
            query.AddSort(SortOrder.Descending, "tab_order");
            query.LimitCount = 1;

            DataTable tabTable = db.Query(query);

            if (tabTable.Rows.Count == 1)
            {
                maxOrder = (byte)tabTable.Rows[0]["tab_order"];
            }

            if (order < maxOrder)
            {
                UpdateQuery uQuery = new UpdateQuery(Item.GetTable(typeof(NagivationTab)));
                uQuery.AddField("tab_order", new QueryOperation("tab_order", QueryOperations.Subtraction, 1));
                uQuery.AddCondition("tab_item_id", ownerKey.Id);
                uQuery.AddCondition("tab_item_type_id", ownerKey.TypeId);
                uQuery.AddCondition("tab_order", ConditionEquality.Equal, order + 1);

                db.Query(uQuery);

                SetProperty("order", (byte)(order + 1));

                Update();
            }
        }
Esempio n. 12
0
        public static void ProcessViews(Core core)
        {
            Dictionary<ItemKey, long> adjustment = new Dictionary<ItemKey, long>();

            SelectQuery query = ItemView.GetSelectQueryStub(core, typeof(ItemView));
            query.AddCondition("view_time_ut", ConditionEquality.LessThan, UnixTime.UnixTimeStamp() - 60 * 60 * 24);
            query.AddCondition("view_processed", false);
            query.LimitCount = 30;

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

            List<ItemView> views = new List<ItemView>();

            foreach (DataRow row in viewsDataTable.Rows)
            {
                views.Add(new ItemView(core, row));
            }

            core.Db.BeginTransaction();

            foreach (ItemView view in views)
            {
                ItemInfo info = null;
                try
                {
                    info = new ItemInfo(core, view.ViewKey);
                }
                catch (InvalidIteminfoException)
                {
                    info = ItemInfo.Create(core, view.ViewKey);
                }

                if (info == null)
                {
                    continue;
                }

                if (!adjustment.ContainsKey(view.ViewKey))
                {
                    adjustment.Add(view.ViewKey, 0);
                }

                // If the view unique enough to be counted?
                ItemViewDiscountedReason viewUniqueReason = VerifyView(core, view);
                long increment = 0;

                UpdateQuery uQuery = new UpdateQuery(typeof(ItemView));
                uQuery.AddCondition("view_id", view.viewId);

                if (!view.Processed)
                {
                    if (viewUniqueReason == ItemViewDiscountedReason.None)
                    {
                        uQuery.AddField("view_counted", true);
                        uQuery.AddField("view_discounted", false);

                        adjustment[view.ViewKey]++;
                        increment++;
                    }
                    else
                    {
                        uQuery.AddField("view_counted", false);
                        uQuery.AddField("view_discounted", true);
                    }
                }
                else
                {
                    if (viewUniqueReason == ItemViewDiscountedReason.None)
                    {
                        uQuery.AddField("view_counted", true);
                        uQuery.AddField("view_discounted", false);

                        if (view.viewDiscounted)
                        {
                            adjustment[view.ViewKey]++;
                            increment++;
                        }
                    }
                    else
                    {
                        uQuery.AddField("view_counted", false);
                        uQuery.AddField("view_discounted", true);

                        if (view.viewCounted)
                        {
                            adjustment[view.ViewKey]--;
                            increment--;
                        }
                    }
                }
                uQuery.AddField("view_processed", true);
                uQuery.AddField("view_discounted_reason", (int)viewUniqueReason);

                core.Db.Query(uQuery);

                if (increment != 0 || (viewUniqueReason == ItemViewDiscountedReason.RateLimited && view.viewTimespan > 0))
                {
                    uQuery = new UpdateQuery(typeof(ItemViewCountByHour));
                    uQuery.AddField("view_hourly_count", new QueryOperation("view_hourly_count", QueryOperations.Addition, increment));
                    uQuery.AddField("view_hourly_time", new QueryOperation("view_hourly_time", QueryOperations.Addition, Math.Sign(increment) * Math.Min(view.viewTimespan, 20 * 60))); // attention span is 20 minutes
                    uQuery.AddCondition("view_hourly_time_ut", (view.viewTimeRaw / 60 / 60) * 60 * 60);
                    uQuery.AddCondition("view_hourly_item_id", view.ViewKey.Id);
                    uQuery.AddCondition("view_hourly_item_type_id", view.ViewKey.TypeId);

                    if (core.Db.Query(uQuery) == 0)
                    {
                        InsertQuery iQuery = new InsertQuery(typeof(ItemViewCountByHour));
                        iQuery.AddField("view_hourly_count", increment);
                        iQuery.AddField("view_hourly_time", Math.Sign(increment) * Math.Min(view.viewTimespan, 20 * 60)); // attention span is 20 minutes
                        iQuery.AddField("view_hourly_time_ut", (view.viewTimeRaw / 60 / 60) * 60 * 60);
                        iQuery.AddField("view_hourly_item_id", view.ViewKey.Id);
                        iQuery.AddField("view_hourly_item_type_id", view.ViewKey.TypeId);
                        if (view.ownerKey.Id > 0 && view.ownerKey.TypeId > 0)
                        {
                            iQuery.AddField("view_hourly_item_owner_id", view.ownerKey.Id);
                            iQuery.AddField("view_hourly_item_owner_type_id", view.ownerKey.TypeId);
                        }
                        else
                        {
                            NumberedItem item = NumberedItem.Reflect(core, view.ViewKey);
                            ItemKey ownerKey = null;

                            if (item is IPermissibleItem)
                            {
                                IPermissibleItem pitem = (IPermissibleItem)item;

                                ownerKey = pitem.OwnerKey;
                            }

                            if (item is IPermissibleSubItem)
                            {
                                IPermissibleSubItem pitem = (IPermissibleSubItem)item;

                                ownerKey = pitem.OwnerKey;
                            }

                            if (ownerKey != null)
                            {
                                iQuery.AddField("view_hourly_item_owner_id", ownerKey.Id);
                                iQuery.AddField("view_hourly_item_owner_type_id", ownerKey.TypeId);
                            }
                        }

                        core.Db.Query(iQuery);
                    }
                }
            }

            foreach (ItemKey itemKey in adjustment.Keys)
            {
                if (adjustment[itemKey] != 0)
                {
                    UpdateQuery uQuery = new UpdateQuery(typeof(ItemInfo));
                    uQuery.AddField("info_viewed_times", new QueryOperation("info_viewed_times", QueryOperations.Addition, adjustment[itemKey]));
                    uQuery.AddCondition("info_item_id", itemKey.Id);
                    uQuery.AddCondition("info_item_type_id", itemKey.TypeId);
                    core.Db.Query(uQuery);
                }
            }

            core.Db.CommitTransaction();
        }
Esempio n. 13
0
 public override long Query(UpdateQuery query)
 {
     return UpdateQuery(query);
 }
Esempio n. 14
0
        public void MarkRead()
        {
            UpdateQuery uquery = new UpdateQuery(typeof(MessageRecipient));
            uquery.AddField("is_read", true);
            uquery.AddField("recipient_read_time_ut", UnixTime.UnixTimeStamp());
            uquery.AddCondition("message_id", messageId);
            uquery.AddCondition("user_id", userId);

            db.Query(uquery);
        }
Esempio n. 15
0
        void AccountPassword_Save(object sender, EventArgs e)
        {
            AuthoriseRequestSid();

            string password = core.Http.Form["old-password"];

            password = User.HashPassword(password);

            SelectQuery query = new SelectQuery(User.GetTable(typeof(User)));
            query.AddFields(User.GetFieldsPrefixed(core, typeof(User)));
            query.AddJoin(JoinTypes.Inner, new DataField(typeof(User), "user_id"), new DataField("user_info", "user_id"));
            query.AddCondition("user_keys.user_id", core.LoggedInMemberId);
            query.AddCondition("user_password", password);

            DataTable userTable = db.Query(query);
            if (userTable.Rows.Count != 1)
            {
                SetError("The old password you entered does not match your old password, make sure you have entered your old password correctly.");
                return;
            }
            else if (core.Http.Form["new-password"] != core.Http.Form["confirm-password"])
            {
                SetError("The passwords you entered do not match, make sure you have entered your desired password correctly.");
                return;
            }
            else if (((string)core.Http.Form["new-password"]).Length < 6)
            {
                SetError("The password you entered is too short. Please choose a strong password of 6 characters or more.");
                return;
            }

            UpdateQuery uquery = new UpdateQuery("user_info");
            uquery.AddField("user_password", User.HashPassword(core.Http.Form["new-password"]));
            uquery.AddCondition("user_id", core.LoggedInMemberId);

            long rowsChanged = db.Query(uquery);

            if (rowsChanged == 1)
            {
                SetInformation("You have successfully changed your password. Keep your password safe and do not share it with anyone.");
                //SetRedirectUri(BuildUri());
                //Display.ShowMessage("Changed Password", "You have successfully changed your password. Keep your password safe and do not share it with anyone.");
            }
            else
            {
                DisplayGenericError();
                return;
            }
        }
Esempio n. 16
0
        public ListItem AddNew(string text, ref string normalisedText)
        {
            ListItem item = ListItem.Create(core, this, text, ref normalisedText);

            UpdateQuery uQuery = new UpdateQuery(GetTable(typeof(List)));
            uQuery.AddField("list_items", new QueryOperation("list_items", QueryOperations.Addition, 1));
            uQuery.AddCondition("list_id", listId);

            core.Db.Query(uQuery);

            return item;
        }
Esempio n. 17
0
        public void Read(TopicPost lastVisiblePost)
        {
            //db.BeginTransaction();

            UpdateQuery uQuery = new UpdateQuery(ForumTopic.GetTable(typeof(ForumTopic)));
            uQuery.AddField("topic_views", new QueryOperation("topic_views", QueryOperations.Addition, 1));
            uQuery.AddCondition("topic_id", topicId);

            db.Query(uQuery);

            if ((!IsRead) && core.LoggedInMemberId > 0)
            {
                if (readStatus != null)
                {
                    if (readStatus.ReadTimeRaw < lastVisiblePost.TimeCreatedRaw)
                    {
                        UpdateQuery uQuery2 = new UpdateQuery(TopicReadStatus.GetTable(typeof(TopicReadStatus)));
                        uQuery2.AddField("read_time_ut", lastVisiblePost.TimeCreatedRaw);
                        uQuery2.AddCondition("topic_id", topicId);
                        uQuery2.AddCondition("user_id", core.LoggedInMemberId);

                        db.Query(uQuery2);
                    }
                }
                else
                {
                    TopicReadStatus.Create(core, this, lastVisiblePost);
                }
            }
        }
Esempio n. 18
0
        public void Remove(long listItemId)
        {
            ListItem item = new ListItem(core, listItemId);

            db.BeginTransaction();

            item.Delete();

            UpdateQuery uQuery = new UpdateQuery(GetTable(typeof(List)));
            uQuery.AddField("list_items", new QueryOperation("list_items", QueryOperations.Subtraction, 1));
            uQuery.AddCondition("list_id", listId);

            db.Query(uQuery);
        }
Esempio n. 19
0
        public TopicPost AddReply(Core core, Forum forum, string subject, string text)
        {
            db.BeginTransaction();

            TopicPost post = TopicPost.Create(core, forum, this, subject, text);

            topicPosts++;

            UpdateQuery uQuery = new UpdateQuery(ForumTopic.GetTable(typeof(ForumTopic)));
            uQuery.AddField("topic_posts", new QueryOperation("topic_posts", QueryOperations.Addition, 1));
            uQuery.AddField("topic_last_post_id", post.Id);
            uQuery.AddField("topic_last_post_time_ut", post.TimeCreatedRaw);
            uQuery.AddCondition("topic_id", post.TopicId);

            long rowsUpdated = db.Query(uQuery);

            if (rowsUpdated != 1)
            {
                db.RollBackTransaction();
                core.Display.ShowMessage("ERROR", "Error, rolling back transaction");
            }

            if (forumId > 0)
            {
                List<long> parentForumIds = new List<long>();
                parentForumIds.Add(Forum.Id);

                if (Forum.Parents != null)
                {
                    foreach (ParentTreeNode ptn in Forum.Parents.Nodes)
                    {
                        parentForumIds.Add(ptn.ParentId);
                    }
                }

                uQuery = new UpdateQuery(Forum.GetTable(typeof(Forum)));
                uQuery.AddField("forum_posts", new QueryOperation("forum_posts", QueryOperations.Addition, 1));
                uQuery.AddField("forum_last_post_id", post.Id);
                uQuery.AddField("forum_last_post_time_ut", post.TimeCreatedRaw);
                uQuery.AddCondition("forum_id", ConditionEquality.In, parentForumIds);

                rowsUpdated = db.Query(uQuery);

                if (rowsUpdated < 1)
                {
                    db.RollBackTransaction();
                    core.Display.ShowMessage("ERROR", "Error, rolling back transaction");
                }
            }

            uQuery = new UpdateQuery(ForumSettings.GetTable(typeof(ForumSettings)));
            uQuery.AddField("forum_posts", new QueryOperation("forum_posts", QueryOperations.Addition, 1));
            uQuery.AddCondition("forum_item_id", Forum.Owner.Id);
            uQuery.AddCondition("forum_item_type_id", Forum.Owner.TypeId);

            rowsUpdated = db.Query(uQuery);

            if (rowsUpdated != 1)
            {
                db.RollBackTransaction();
                core.Display.ShowMessage("ERROR", "Error, rolling back transaction");
            }

            /*uQuery = new UpdateQuery(ForumMember.GetTable(typeof(ForumMember)));
            uQuery.AddField("posts", new QueryOperation("posts", QueryOperations.Addition, 1));
            uQuery.AddCondition("user_id", core.session.LoggedInMember.Id);
            uQuery.AddCondition("item_id", Forum.Owner.Id);
            uQuery.AddCondition("item_type_id", Forum.Owner.TypeId);

            rowsUpdated = db.Query(uQuery);

            if (rowsUpdated == 0)
            {
                ForumMember fm = ForumMember.Create(core, Forum.Owner, core.session.LoggedInMember, true);

                uQuery = new UpdateQuery(ForumMember.GetTable(typeof(ForumMember)));
                uQuery.AddField("posts", new QueryOperation("posts", QueryOperations.Addition, 1));
                uQuery.AddCondition("user_id", core.session.LoggedInMember.Id);
                uQuery.AddCondition("item_id", Forum.Owner.Id);
                uQuery.AddCondition("item_type_id", Forum.Owner.TypeId);

                db.Query(uQuery);
            }*/

            ForumMember fm = null;

            try
            {
                fm = new ForumMember(core, Forum.Owner, core.Session.LoggedInMember);
            }
            catch (InvalidForumMemberException)
            {
                fm = ForumMember.Create(core, Forum.Owner, core.Session.LoggedInMember, true);
            }

            fm.ForumPosts += 1;

            /*Dictionary<long, ForumMemberRank> ranks = ForumMemberRank.GetRanks(core, Forum.Owner);

            if (!(ranks.ContainsKey(fm.ForumRankId) && ranks[fm.ForumRankId].RankSpecial))
            {
                int rankLastMin = 0;
                foreach (ForumMemberRank rank in ranks.Values)
                {
                    if ((!rank.RankSpecial) && fm.ForumPosts >= rank.RankPosts && rank.RankPosts > rankLastMin)
                    {
                        fm.ForumRankId = rank.Id;
                        rankLastMin = rank.RankPosts;
                    }
                }
            }*/

            fm.Update(typeof(ForumMember));

            return post;
        }
Esempio n. 20
0
        public override long Delete(bool parentDeleted)
        {
            long returnValue = 0;
            if (parentDeleted)
            {
                returnValue = base.Delete();
            }
            else
            {
                db.BeginTransaction();
                UpdateQuery uQuery = new UpdateQuery(typeof(Comment));
                uQuery.AddField("comment_deleted", true);
                uQuery.AddCondition("comment_id", Id);

                returnValue = db.Query(uQuery);
            }

            CommentDeleted(core, CommentedItemKey);
            return returnValue;
        }
Esempio n. 21
0
        public static Notification Create(Core core, ApplicationEntry application, User actionBy, User receiver, ItemKey itemOwnerKey, ItemKey itemKey, string verb, string url, string action)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            int applicationId = 0;

            if (application != null)
            {
                // TODO: ensure only internals can call a null application
                applicationId = (int)application.Id;
            }

            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] randomNumber = new byte[16];
            rng.GetBytes(randomNumber);

            string rand = SessionState.HexRNG(randomNumber);
            string verificationString = SessionState.SessionMd5(rand + "bsseed" + DateTime.Now.Ticks.ToString() + core.Session.IPAddress.ToString()).ToLower();

            InsertQuery iQuery = new InsertQuery("notifications");
            iQuery.AddField("notification_primitive_id", receiver.Id);
            iQuery.AddField("notification_primitive_type_id", ItemKey.GetTypeId(core, typeof(User)));
            if (itemKey != null)
            {
                iQuery.AddField("notification_item_id", itemKey.Id);
                iQuery.AddField("notification_item_type_id", itemKey.TypeId);
            }
            if (itemOwnerKey != null)
            {
                iQuery.AddField("notification_item_owner_id", itemOwnerKey.Id);
                iQuery.AddField("notification_item_owner_type_id", itemOwnerKey.TypeId);
            }
            iQuery.AddField("notification_user_id", actionBy.Id);
            iQuery.AddField("notification_user_count", 1);
            iQuery.AddField("notification_verb", verb);
            iQuery.AddField("notification_action", action);
            iQuery.AddField("notification_url", url);
            iQuery.AddField("notification_time_ut", UnixTime.UnixTimeStamp());
            iQuery.AddField("notification_read", false);
            iQuery.AddField("notification_seen", false);
            iQuery.AddField("notification_application", applicationId);
            iQuery.AddField("notification_verification_string", verificationString);

            long notificationId = core.Db.Query(iQuery);

            core.Db.BeginTransaction();
            UpdateQuery query = new UpdateQuery(typeof(UserInfo));
            query.AddField("user_unread_notifications", new QueryOperation("user_unread_notifications", QueryOperations.Addition, 1));
            query.AddCondition("user_id", receiver.Id);

            core.Db.Query(query);

            Notification notification = new Notification(core, receiver, notificationId, string.Empty, string.Empty, UnixTime.UnixTimeStamp(), applicationId);
            // this is not elegant
            // TODO: write appropriate constructor
            notification.userId = actionBy.Id;
            notification.verb = verb;
            notification.action = action;
            notification.url = url;
            notification.itemKey = itemKey;
            notification.itemOwnerKey = itemOwnerKey;
            notification.verificationString = verificationString;

            return notification;
        }
Esempio n. 22
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override bool ExecuteCron()
        {
            // In this cron we will find any queued unpublished blog posts
            // ready to publish and publish them

            SelectQuery query = BlogEntry.GetSelectQueryStub(core, typeof(BlogEntry));
            query.AddCondition("post_status", (byte)PublishStatuses.Queued);
            query.AddCondition("post_published_ut", ConditionEquality.LessThanEqual, UnixTime.UnixTimeStamp());

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

            foreach (DataRow row in blogPosts.Rows)
            {
                BlogEntry be = new BlogEntry(core, row);

                core.LoadUserProfile(be.OwnerId);
                core.CreateNewSession(core.PrimitiveCache[be.OwnerId]);

                UpdateQuery uQuery = new UpdateQuery(typeof(Blog));
                uQuery.AddField("blog_entries", new QueryOperation("blog_entries", QueryOperations.Addition, 1));
                uQuery.AddField("blog_queued_entries", new QueryOperation("blog_queued_entries", QueryOperations.Subtraction, 1));
                uQuery.AddCondition("user_id", be.OwnerId);

                core.Db.Query(uQuery);

                uQuery = new UpdateQuery(typeof(BlogEntry));
                uQuery.AddField("post_status", (byte)PublishStatuses.Published);
                uQuery.AddCondition("post_id", be.Id);

                core.Db.Query(uQuery);

                core.Search.Index(be);
                core.CallingApplication.PublishToFeed(core, be.Author, be, be.Title);
            }

            return true;
        }
        void AccountCalendarEventInvite_StatusChanged(object sender, ModuleModeEventArgs e)
        {
            AuthoriseRequestSid();

            long eventId = core.Functions.RequestLong("id", 0);

            if (eventId > 0)
            {
                Event calendarEvent = new Event(core, eventId);
                EventInvite invite = new EventInvite(core, eventId, LoggedInMember);

                UpdateQuery uQuery = new UpdateQuery(typeof(EventInvite));

                UpdateQuery uEventQuery = new UpdateQuery(typeof(Event));
                uEventQuery.AddCondition("event_id", eventId);

                switch (e.Mode)
                {
                    case "accept":
                        uQuery.AddField("invite_accepted", true);
                        uQuery.AddField("invite_status", (byte)EventAttendance.Yes);

                        switch (invite.InviteStatus)
                        {
                            case EventAttendance.Yes:
                                break;
                            case EventAttendance.Maybe:
                                uEventQuery.AddField("event_maybes", new QueryOperation("event_maybes", QueryOperations.Subtraction, 1));
                                break;
                            default:
                                break;
                        }
                        if (invite.InviteStatus != EventAttendance.Yes)
                        {
                            uEventQuery.AddField("event_attendees", new QueryOperation("event_attendees", QueryOperations.Addition, 1));
                        }
                        break;
                    case "reject":
                        uQuery.AddField("invite_accepted", false);
                        uQuery.AddField("invite_status", (byte)EventAttendance.No);

                        switch (invite.InviteStatus)
                        {
                            case EventAttendance.Yes:
                                uEventQuery.AddField("event_attendees", new QueryOperation("event_attendees", QueryOperations.Subtraction, 1));
                                break;
                            case EventAttendance.Maybe:
                                uEventQuery.AddField("event_maybes", new QueryOperation("event_maybes", QueryOperations.Subtraction, 1));
                                break;
                            default:
                                break;
                        }
                        break;
                    case "maybe":
                        uQuery.AddField("invite_accepted", false);
                        uQuery.AddField("invite_status", (byte)EventAttendance.Maybe);

                        switch (invite.InviteStatus)
                        {
                            case EventAttendance.Yes:
                                uEventQuery.AddField("event_attendees", new QueryOperation("event_attendees", QueryOperations.Subtraction, 1));
                                break;
                            default:
                                break;
                        }
                        if (invite.InviteStatus != EventAttendance.Maybe)
                        {
                            uEventQuery.AddField("event_maybes", new QueryOperation("event_maybes", QueryOperations.Addition, 1));
                        }
                        break;
                    default:
                        DisplayGenericError();
                        return;
                }

                // TODO: look into this
                uQuery.AddCondition("event_id", eventId);
                uQuery.AddCondition("item_id", LoggedInMember.Id);
                uQuery.AddCondition("item_type_id", LoggedInMember.TypeId);

                db.BeginTransaction();
                db.Query(uQuery);
                db.Query(uEventQuery);

                SetRedirectUri(calendarEvent.Uri);
                switch (e.Mode)
                {
                    case "accept":
                        core.Display.ShowMessage("Invitation Accepted", "You have accepted the invitation to this event.");
                        break;
                    case "maybe":
                        core.Display.ShowMessage("Invitation Acknowledged", "You have indicated you may go to this event.");
                        break;
                    case "reject":
                        core.Display.ShowMessage("Invitation Rejected", "You have rejected the invitation to this event.");
                        break;
                }
                return;
            }
            else
            {
                core.Display.ShowMessage("Invalid submission", "You have made an invalid form submission.");
                return;
            }
        }
Esempio n. 24
0
        void AccountContactManage_VerifyEmail(object sender, ModuleModeEventArgs e)
        {
            AuthoriseRequestSid();

            UserEmail email = new UserEmail(core, core.Functions.RequestLong("id", 0));

            if (email.UserId == LoggedInMember.Id)
            {
                if (!email.IsActivated)
                {
                    string activateKey = User.GenerateActivationSecurityToken();

                    string activateUri = string.Format("http://" + Hyperlink.Domain + "/register/?mode=activate-email&id={0}&key={1}",
                        email.Id, activateKey);

                    UpdateQuery query = new UpdateQuery(typeof(UserEmail));
                    query.AddField("email_activate_code", activateKey);
                    query.AddCondition("email_id", email.Id);

                    core.Db.Query(query);

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

                    emailTemplate.Parse("TO_NAME", Owner.DisplayName);
                    emailTemplate.Parse("U_ACTIVATE", activateUri);
                    emailTemplate.Parse("USERNAME", ((User)Owner).UserName);

                    core.Email.SendEmail(email.Email, core.Settings.SiteTitle + " email activation", emailTemplate);

                    SetRedirectUri(BuildUri());
                    core.Display.ShowMessage("Verification e-mail send", "A verification code has been sent to the e-mail address along with verification instructions.");
                }
                else
                {
                    SetRedirectUri(BuildUri());
                    core.Display.ShowMessage("Already verified", "You have already verified your email address.");
                }
            }
            else
            {
                SetRedirectUri(BuildUri());
                core.Display.ShowMessage("Error", "An error has occured.");
            }
        }
Esempio n. 25
0
        public static bool SubscribeToItem(Core core, ItemKey itemKey)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            core.Db.BeginTransaction();

            SelectQuery query = Subscription.GetSelectQueryStub(core, typeof(Subscription));
            query.AddCondition("subscription_item_id", itemKey.Id);
            query.AddCondition("subscription_item_type_id", itemKey.TypeId);
            query.AddCondition("user_id", core.LoggedInMemberId);

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

            if (subscriptionDataTable.Rows.Count == 0)
            {
                InsertQuery iQuery = new InsertQuery(typeof(Subscription));
                iQuery.AddField("subscription_item_id", itemKey.Id);
                iQuery.AddField("subscription_item_type_id", itemKey.TypeId);
                iQuery.AddField("user_id", core.LoggedInMemberId);
                iQuery.AddField("subscription_time_ut", UnixTime.UnixTimeStamp());
                iQuery.AddField("subscription_ip", core.Session.IPAddress.ToString());

                core.Db.Query(iQuery);

                ItemInfo info = new ItemInfo(core, itemKey);
                info.IncrementSubscribers();

                UpdateQuery uQuery = new UpdateQuery(typeof(UserInfo));
                uQuery.AddField("user_subscriptions", new QueryOperation("user_subscriptions", QueryOperations.Addition, 1));
                uQuery.AddCondition("user_id", core.LoggedInMemberId);
                core.Db.Query(uQuery);

                return true;
            }
            else
            {
                throw new AlreadySubscribedException();
            }
        }
Esempio n. 26
0
        void AccountContactManage_VerifyPhone(object sender, ModuleModeEventArgs e)
        {
            AuthoriseRequestSid();
            SetTemplate("account_phone_verify");

            UserPhoneNumber phoneNumber = new UserPhoneNumber(core, core.Functions.RequestLong("id", 0));

            if (phoneNumber.UserId == LoggedInMember.Id)
            {
                if (!phoneNumber.Validated)
                {
                    string activateKey = User.GeneratePhoneActivationToken();

                    UpdateQuery query = new UpdateQuery(typeof(UserPhoneNumber));
                    query.AddField("phone_activate_code", activateKey);
                    query.AddCondition("phone_id", phoneNumber.Id);

                    core.Db.Query(query);

                    core.Sms.SendSms(phoneNumber.PhoneNumber, string.Format("Your {0} security code is {1}.", core.Settings.SiteTitle, activateKey));

                    TextBox verifyTextBox = new TextBox("verify-code");
                    verifyTextBox.Type = InputType.Telephone;

                    template.Parse("S_ID", phoneNumber.Id.ToString());
                    template.Parse("PHONE_NUMBER", phoneNumber.PhoneNumber);
                    template.Parse("S_VERIFY_CODE", verifyTextBox);
                }
                else
                {
                    SetRedirectUri(BuildUri());
                    core.Display.ShowMessage("Already verified", "You have already verified your phone number.");
                }
            }
            else
            {
                SetRedirectUri(BuildUri());
                core.Display.ShowMessage("Error", "An error has occured.");
            }
        }
Esempio n. 27
0
        public static Gig Create(Core core, Musician owner, Tour tour, long time, ushort timezone, string city, string venue, string gigAbstract, bool allAges)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            // TODO: fix this
            Item item = Item.Create(core, typeof(Gig), new FieldValuePair("musician_id", owner.Id),
                new FieldValuePair("tour_id", ((tour != null) ? tour.Id : 0)),
                new FieldValuePair("gig_time_ut", time),
                new FieldValuePair("gig_time_zone", timezone),
                new FieldValuePair("gig_city", city),
                new FieldValuePair("gig_venue", venue),
                new FieldValuePair("gig_abstract", gigAbstract),
                new FieldValuePair("gig_all_ages", allAges));

            Gig gig = (Gig)item;

            if (gig.TourId > 0)
            {
                UpdateQuery uQuery = new UpdateQuery(typeof(Tour));
                uQuery.AddField("tour_gigs", new QueryOperation("tour_gigs", QueryOperations.Addition, "1"));
                uQuery.AddCondition("tour_id", gig.TourId);
            }

            return gig;
        }
Esempio n. 28
0
        void AccountContactManage_VerifyPhone_Save(object sender, EventArgs e)
        {
            AuthoriseRequestSid();

            UserPhoneNumber phoneNumber = new UserPhoneNumber(core, core.Functions.FormLong("id", 0));

            if (phoneNumber.UserId == LoggedInMember.Id)
            {
                if (!phoneNumber.Validated)
                {
                    if (phoneNumber.ActivateKey == core.Http.Form["verify-code"])
                    {
                        UpdateQuery query = new UpdateQuery(typeof(UserPhoneNumber));
                        query.AddField("phone_validated", true);
                        query.AddField("phone_validated_time_ut", UnixTime.UnixTimeStamp());
                        query.AddCondition("phone_id", phoneNumber.Id);

                        db.Query(query);

                        SetRedirectUri(BuildUri());
                        core.Display.ShowMessage("Phone number verified", "Your phone number has been verified");
                    }
                }
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Save procedure for a blog entry.
        /// </summary>
        /// <param name="sender">Object calling load event</param>
        /// <param name="e">Load EventArgs</param>
        void AccountBlogWrite_Save(object sender, EventArgs e)
        {
            string title = core.Http.Form["title"];
            //string tags = core.Http.Form["tags"];
            string postBody = core.Http.Form["post"];
            bool publishToFeed = (core.Http.Form["publish-feed"] != null);

            byte license = 0;
            short category = 1;
            long postId = 0;
            PublishStatuses publishStatus = PublishStatuses.Published;
            string postGuid = "";
            long currentTimestamp = UnixTime.UnixTimeStamp();

            /*
             * Create a blog if they do not already have one
             */
            Blog myBlog = null;
            try
            {
                myBlog = new Blog(core, LoggedInMember);
            }
            catch (InvalidBlogException)
            {
                myBlog = Blog.Create(core);
            }

            bool postEditTimestamp = false;
            int postYear, postMonth, postDay, postHour, postMinute;
            DateTime postTime = core.Tz.DateTimeFromMysql(currentTimestamp);

            if (core.Http.Form["publish"] != null)
            {
                publishStatus = PublishStatuses.Published;
            }

            if (core.Http.Form["save"] != null)
            {
                publishStatus = PublishStatuses.Draft;
            }

            postId = core.Functions.FormLong("id", 0);
            license = core.Functions.FormByte("license", license);
            category = core.Functions.FormShort("category", category);

            try
            {
                postYear = core.Functions.FormInt("post-year", 0);
                postMonth = core.Functions.FormInt("post-month", 0);
                postDay = core.Functions.FormInt("post-day", 0);

                postHour = core.Functions.FormInt("post-hour", 0);
                postMinute = core.Functions.FormInt("post-minute", 0);

                postEditTimestamp = !string.IsNullOrEmpty(core.Http.Form["edit-timestamp"]);

                postTime = new DateTime(postYear, postMonth, postDay, postHour, postMinute, 0);
            }
            catch
            {
            }

            if (string.IsNullOrEmpty(title))
            {
                SetError("You must give the blog post a title.");
                return;
            }

            if (string.IsNullOrEmpty(postBody))
            {
                SetError("You cannot save an empty blog post. You must post some content.");
                return;
            }

            string sqlPostTime = "";

            // update, must happen before save new because it populates postId
            if (postId > 0)
            {
                db.BeginTransaction();

                BlogEntry myBlogEntry = new BlogEntry(core, postId);

                long postTimeRaw;
                bool doPublish = false;
                if (postEditTimestamp)
                {
                    postTimeRaw = tz.GetUnixTimeStamp(postTime);

                    if (postTimeRaw > UnixTime.UnixTimeStamp())
                    {
                        publishStatus = PublishStatuses.Queued;
                    }
                }

                if (publishStatus != myBlogEntry.Status)
                {
                    switch (publishStatus)
                    {
                        case PublishStatuses.Published:
                            UpdateQuery uQuery = new UpdateQuery(typeof(Blog));
                            uQuery.AddField("blog_entries", new QueryOperation("blog_entries", QueryOperations.Addition, 1));
                            switch (myBlogEntry.Status)
                            {
                                case PublishStatuses.Draft:
                                    uQuery.AddField("blog_drafts", new QueryOperation("blog_drafts", QueryOperations.Subtraction, 1));
                                    break;
                                case PublishStatuses.Queued:
                                    uQuery.AddField("blog_queued_entries", new QueryOperation("blog_queued_entries", QueryOperations.Subtraction, 1));
                                    break;
                            }
                            uQuery.AddCondition("user_id", Owner.Id);

                            db.Query(uQuery);

                            doPublish = true;
                            break;
                        case PublishStatuses.Draft:
                            uQuery = new UpdateQuery(typeof(Blog));
                            uQuery.AddField("blog_drafts", new QueryOperation("blog_drafts", QueryOperations.Addition, 1));
                            switch (myBlogEntry.Status)
                            {
                                case PublishStatuses.Published:
                                    uQuery.AddField("blog_entries", new QueryOperation("blog_entries", QueryOperations.Subtraction, 1));
                                    break;
                                case PublishStatuses.Queued:
                                    uQuery.AddField("blog_queued_entries", new QueryOperation("blog_queued_entries", QueryOperations.Subtraction, 1));
                                    break;
                            }
                            uQuery.AddCondition("user_id", Owner.Id);

                            db.Query(uQuery);
                            break;
                        case PublishStatuses.Queued:
                            uQuery = new UpdateQuery(typeof(Blog));
                            uQuery.AddField("blog_queued_entries", new QueryOperation("blog_queued_entries", QueryOperations.Addition, 1));
                            switch (myBlogEntry.Status)
                            {
                                case PublishStatuses.Published:
                                    uQuery.AddField("blog_entries", new QueryOperation("blog_entries", QueryOperations.Subtraction, 1));
                                    break;
                                case PublishStatuses.Draft:
                                    uQuery.AddField("blog_drafts", new QueryOperation("blog_drafts", QueryOperations.Subtraction, 1));
                                    break;
                            }
                            uQuery.AddCondition("user_id", Owner.Id);

                            db.Query(uQuery);
                            break;
                    }
                }

                // Save image attachments
                {
                    postBody = core.Bbcode.ExtractAndSaveImageData(postBody, myBlogEntry, saveImage);
                }

                myBlogEntry.Title = title;
                myBlogEntry.BodyCache = string.Empty;
                myBlogEntry.Body = postBody;
                myBlogEntry.License = license;
                myBlogEntry.Category = category;
                myBlogEntry.ModifiedDateRaw = currentTimestamp;
                if (postEditTimestamp)
                {
                    myBlogEntry.PublishedDateRaw = tz.GetUnixTimeStamp(postTime);
                }
                myBlogEntry.Status = publishStatus;

                myBlogEntry.Update();

                if (publishToFeed && publishStatus == PublishStatuses.Published && doPublish)
                {
                    core.Search.Index(myBlogEntry);
                    core.CallingApplication.PublishToFeed(core, LoggedInMember, myBlogEntry, myBlogEntry.Title);
                }

                Tag.LoadTagsIntoItem(core, myBlogEntry, TagSelectBox.FormTags(core, "tags"));
            }
            else if (postId == 0) // else if to make sure only one triggers
            {
                long postTimeRaw;
                // save new
                if (postEditTimestamp)
                {
                    postTimeRaw = tz.GetUnixTimeStamp(postTime);
                }
                else
                {
                    postTimeRaw = currentTimestamp;
                }

                if (postTimeRaw > UnixTime.UnixTimeStamp())
                {
                    publishStatus = PublishStatuses.Queued;
                }

                db.BeginTransaction();

                BlogEntry myBlogEntry = BlogEntry.Create(core, AccessControlLists.GetNewItemPermissionsToken(core), myBlog, title, postBody, license, publishStatus, category, postTimeRaw);

                /*AccessControlLists acl = new AccessControlLists(core, myBlogEntry);
                acl.SaveNewItemPermissions();*/

                postGuid = core.Hyperlink.StripSid(string.Format("{0}blog/{1:0000}/{2:00}/{3}",
                    LoggedInMember.UriStubAbsolute, DateTime.Now.Year, DateTime.Now.Month, postId));

                myBlogEntry.Guid = postGuid;
                long updated = myBlogEntry.Update();

                if (updated > 0)
                {

                }

                switch (publishStatus)
                {
                    case PublishStatuses.Published:
                        UpdateQuery uQuery = new UpdateQuery(typeof(Blog));
                        uQuery.AddField("blog_entries", new QueryOperation("blog_entries", QueryOperations.Addition, 1));
                        uQuery.AddCondition("user_id", Owner.Id);

                        db.Query(uQuery);
                        break;
                    case PublishStatuses.Draft:
                        uQuery = new UpdateQuery(typeof(Blog));
                        uQuery.AddField("blog_drafts", new QueryOperation("blog_drafts", QueryOperations.Addition, 1));
                        uQuery.AddCondition("user_id", Owner.Id);

                        db.Query(uQuery);
                        break;
                    case PublishStatuses.Queued:
                        uQuery = new UpdateQuery(typeof(Blog));
                        uQuery.AddField("blog_queued_entries", new QueryOperation("blog_queued_entries", QueryOperations.Addition, 1));
                        uQuery.AddCondition("user_id", Owner.Id);

                        db.Query(uQuery);
                        break;
                }

                Tag.LoadTagsIntoItem(core, myBlogEntry, TagSelectBox.FormTags(core, "tags"), true);

                // Save image attachments
                {
                    postBody = core.Bbcode.ExtractAndSaveImageData(postBody, myBlogEntry, saveImage);

                    myBlogEntry.BodyCache = string.Empty;
                    myBlogEntry.Body = postBody;
                    myBlogEntry.Update(); // only triggers if postBody has been updated
                }

                if (publishToFeed && publishStatus == PublishStatuses.Published)
                {
                    core.Search.Index(myBlogEntry);
                    core.CallingApplication.PublishToFeed(core, LoggedInMember, myBlogEntry, myBlogEntry.Title);
                }

            }

            switch (publishStatus)
            {
                case PublishStatuses.Draft:
                    SetRedirectUri(BuildUri("drafts"));
                    core.Display.ShowMessage("Draft Saved", "Your draft has been saved.");
                    break;
                case PublishStatuses.Published:
                    SetRedirectUri(BuildUri("manage"));
                    core.Display.ShowMessage("Blog Post Published", "Your blog post has been published.");
                    break;
                case PublishStatuses.Queued:
                    SetRedirectUri(BuildUri("queue"));
                    core.Display.ShowMessage("Blog Post Queued", "Your blog post has been placed in the publish queue.");
                    break;
            }
        }
        private void ApplicationSettingsSave(object sender, EventArgs e)
        {
            AuthoriseRequestSid();

            long id = core.Functions.FormLong("id", 0);

            if (id == 0)
            {
                DisplayGenericError();
                return;
            }

            bool emailNotifications = true;

            try
            {
                if (Owner is User)
                {
                    emailNotifications = (int.Parse(core.Http.Form["email-notifications"]) == 1);
                }
            }
            catch
            {
            }

            UpdateQuery uquery = new UpdateQuery("primitive_apps");
            uquery.AddCondition("item_id", Owner.Id);
            uquery.AddCondition("item_type_id", Owner.TypeId);
            uquery.AddCondition("application_id", id);
            uquery.AddField("app_email_notifications", emailNotifications);

            db.Query(uquery);

            SetRedirectUri(BuildUri());
            core.Display.ShowMessage("Settings updated", "The settings for this application have been successfully updated.");
        }