public static UserGroup Create(Core core, string groupTitle, string groupSlug, string groupDescription, long groupCategory, string groupType) { if (core == null) { throw new NullCoreException(); } Mysql db = core.Db; SessionState session = core.Session; if (core.Session.LoggedInMember == null) { return null; } if (!CheckGroupNameUnique(core, groupSlug)) { return null; } switch (groupType) { case "open": groupType = "OPEN"; break; case "request": groupType = "REQUEST"; break; case "closed": groupType = "CLOSED"; break; case "private": groupType = "PRIVATE"; break; default: return null; } db.BeginTransaction(); InsertQuery iQuery = new InsertQuery(UserGroup.GetTable(typeof(UserGroup))); iQuery.AddField("group_name", groupSlug); iQuery.AddField("group_domain", string.Empty); long groupId = db.Query(iQuery); iQuery = new InsertQuery(UserGroupInfo.GetTable(typeof(UserGroupInfo))); iQuery.AddField("group_id", groupId); iQuery.AddField("group_name", groupSlug); iQuery.AddField("group_name_display", groupTitle); iQuery.AddField("group_type", groupType); iQuery.AddField("group_abstract", groupDescription); iQuery.AddField("group_reg_date_ut", UnixTime.UnixTimeStamp()); iQuery.AddField("group_operators", 1); iQuery.AddField("group_officers", 0); iQuery.AddField("group_members", 1); iQuery.AddField("group_category", groupCategory); iQuery.AddField("group_gallery_items", 0); iQuery.AddField("group_home_page", "/profile"); iQuery.AddField("group_style", string.Empty); iQuery.AddField("group_reg_ip", session.IPAddress.ToString()); iQuery.AddField("group_icon", 0); iQuery.AddField("group_bytes", 0); iQuery.AddField("group_views", 0); db.Query(iQuery); if (groupType != "PRIVATE") { db.UpdateQuery(string.Format("UPDATE global_categories SET category_groups = category_groups + 1 WHERE category_id = {0}", groupCategory)); } db.UpdateQuery(string.Format("INSERT INTO group_members (user_id, group_id, group_member_approved, group_member_ip, group_member_date_ut) VALUES ({0}, {1}, 1, '{2}', UNIX_TIMESTAMP())", session.LoggedInMember.UserId, groupId, Mysql.Escape(session.IPAddress.ToString()))); db.UpdateQuery(string.Format("INSERT INTO group_operators (user_id, group_id) VALUES ({0}, {1})", session.LoggedInMember.UserId, groupId)); UserGroup newGroup = new UserGroup(core, groupId); // Install a couple of applications try { ApplicationEntry profileAe = new ApplicationEntry(core, "Profile"); profileAe.Install(core, newGroup); } catch { } try { ApplicationEntry groupsAe = new ApplicationEntry(core, "Groups"); groupsAe.Install(core, newGroup); } catch { } try { ApplicationEntry galleryAe = new ApplicationEntry(core, "Gallery"); galleryAe.Install(core, newGroup); } catch { } try { ApplicationEntry guestbookAe = new ApplicationEntry(core, "GuestBook"); guestbookAe.Install(core, newGroup); } catch { } return newGroup; }
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; }
internal static void Create(Core core, ForumTopic topic) { if (core == null) { throw new NullCoreException(); } if (core.LoggedInMemberId > 0) { InsertQuery iQuery = new InsertQuery(GetTable(typeof(TopicReadStatus))); iQuery.AddField("topic_id", topic.Id); iQuery.AddField("user_id", core.LoggedInMemberId); iQuery.AddField("forum_id", topic.ForumId); iQuery.AddField("read_time_ut", UnixTime.UnixTimeStamp()); // topic.LastPostTimRaw core.Db.Query(iQuery); } }
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; }
/// <summary> /// /// </summary> /// <param name="core">Core token</param> /// <param name="galleryItem"></param> /// <param name="owner"></param> /// <param name="member"></param> /// <param name="location"></param> /// <returns></returns> public static UserTag Create(Core core, GalleryItem galleryItem, User owner, User member, Point location) { if (core == null) { throw new NullCoreException(); } InsertQuery query = new InsertQuery("user_tags"); query.AddField("user_id", owner.UserId); query.AddField("tag_user_id", member.UserId); query.AddField("gallery_item_id", galleryItem.ItemId); query.AddField("tag_x", location.X); query.AddField("tag_y", location.Y); if (owner.UserId != member.UserId) { query.AddField("tag_approved", false); } else { query.AddField("tag_approved", true); } long tagId = core.Db.Query(query); UserTag tag = new UserTag(core, galleryItem, tagId); NotifyTag(core, tag); return tag; }
public static ListItem Create(Core core, List list, string text, ref string normalisedText) { if (core == null) { throw new NullCoreException(); } if (string.IsNullOrEmpty(normalisedText)) { normalisedText = text; } if (!list.Access.Can("APPEND")) { throw new UnauthorisedToCreateItemException(); } NormaliseListItem(text, ref normalisedText); core.Db.BeginTransaction(); ListItemText lit; try { lit = new ListItemText(core, normalisedText); } catch (InvalidListItemTextException) { lit = ListItemText.Create(core, text, ref normalisedText); } InsertQuery iQuery = new InsertQuery(GetTable(typeof(ListItem))); iQuery.AddField("list_id", list.Id); iQuery.AddField("list_item_text_id", lit.Id); long listItemId = core.Db.Query(iQuery); return new ListItem(core, listItemId); }
public static UserEmail Create(Core core, User owner, string email, EmailAddressTypes type, bool isRegistration) { if (core == null) { throw new NullCoreException(); } if (!User.CheckEmailValid(email)) { throw new EmailInvalidException(); } if (!User.CheckEmailUnique(core, email)) { throw new EmailAlreadyRegisteredException(); } string activateKey = User.GenerateActivationSecurityToken(); InsertQuery iquery = new InsertQuery(UserEmail.GetTable(typeof(UserEmail))); iquery.AddField("email_user_id", owner.Id); iquery.AddField("email_email", email); iquery.AddField("email_type", (byte)type); if (!isRegistration) { iquery.AddField("email_verified", false); } else { iquery.AddField("email_verified", true); } iquery.AddField("email_time_ut", UnixTime.UnixTimeStamp()); iquery.AddField("email_activate_code", activateKey); iquery.AddField("email_simple_permissions", true); long emailId = core.Db.Query(iquery); if (!isRegistration) { string activateUri = string.Format(core.Hyperlink.Uri + "register/?mode=activate-email&id={0}&key={1}", emailId, activateKey); Template emailTemplate = new Template(core.Http.TemplateEmailPath, "email_activation.html"); emailTemplate.Parse("TO_NAME", owner.DisplayName); emailTemplate.Parse("U_ACTIVATE", activateUri); emailTemplate.Parse("USERNAME", owner.UserName); core.Email.SendEmail(email, core.Settings.SiteTitle + " email activation", emailTemplate); } UserEmail newEmail = new UserEmail(core, emailId); Access.CreateGrantForPrimitive(core, newEmail, User.GetCreatorKey(core), "VIEW"); if (!isRegistration) { Access.CreateGrantForPrimitive(core, newEmail, Friend.GetFriendsGroupKey(core), "VIEW"); } Access.CreateGrantForPrimitive(core, newEmail, User.GetEveryoneGroupKey(core), "RECIEVE_FROM"); return newEmail; }
public static ApplicationSlug Create(Core core, long applicationId, string slug, string stub, bool isStatic, AppPrimitives primitives, long updatedTime) { if (core == null) { throw new NullCoreException(); } InsertQuery iQuery = new InsertQuery(GetTable(typeof(ApplicationSlug))); iQuery.AddField("slug_stub", stub); iQuery.AddField("slug_slug_ex", slug); iQuery.AddField("application_id", applicationId); iQuery.AddField("slug_primitives", (byte)primitives); iQuery.AddField("slug_static", isStatic); iQuery.AddField("slug_updated_ut", updatedTime); long slugId = core.Db.Query(iQuery); return new ApplicationSlug(core, slugId); }
public static NagivationTab Create(Core core, Page page) { if (core == null) { throw new NullCoreException(); } byte order = 0; SelectQuery query = NagivationTab.GetSelectQueryStub(core, typeof(NagivationTab)); query.AddCondition("tab_item_id", page.Owner.Id); query.AddCondition("tab_item_type_id", page.Owner.TypeId); query.AddSort(SortOrder.Descending, "tab_order"); query.LimitCount = 1; DataTable tabOrderTable = core.Db.Query(query); if (tabOrderTable.Rows.Count == 1) { NagivationTab tab = new NagivationTab(core, tabOrderTable.Rows[0]); order = (byte)(tab.Order + 1); } InsertQuery iQuery = new InsertQuery(NagivationTab.GetTable(typeof(NagivationTab))); iQuery.AddField("tab_page_id", page.Id); iQuery.AddField("tab_item_id", page.Owner.Id); iQuery.AddField("tab_item_type_id", page.Owner.TypeId); iQuery.AddField("tab_order", order); long tabId = core.Db.Query(iQuery); return new NagivationTab(core, tabId); }
public static void LogView(Core core, NumberedItem item) { if (core == null) { throw new NullCoreException(); } if (item.Id < 1) { throw new InvalidItemException(); } if (core.Session.IsBot) { // Do not count page views from robots return; } ItemViewDiscountedReason reason = ItemViewDiscountedReason.None; ItemKey ownerKey = null; if (item is IPermissibleItem) { IPermissibleItem pitem = (IPermissibleItem)item; ownerKey = pitem.OwnerKey; if (core.Session.SignedIn && pitem.OwnerKey == core.LoggedInMemberItemKey) { reason = ItemViewDiscountedReason.ItemOwner; } } if (item is IPermissibleSubItem) { IPermissibleSubItem pitem = (IPermissibleSubItem)item; ownerKey = pitem.OwnerKey; if (core.Session.SignedIn && pitem.OwnerKey == core.LoggedInMemberItemKey) { reason = ItemViewDiscountedReason.ItemOwner; } } long timestamp = UnixTime.UnixTimeStamp(); string urlreferer = core.Http.UrlReferer; if (string.IsNullOrEmpty(urlreferer)) { SelectQuery sQuery = Session.GetSelectQueryStub(core, typeof(Session)); sQuery.AddCondition("session_string", core.Session.SessionId); DataTable sessionTable = core.Db.Query(sQuery); if (sessionTable.Rows.Count == 1) { if (sessionTable.Rows[0]["session_http_referer"] is string) { string session_referer = (string)sessionTable.Rows[0]["session_http_referer"]; if (!string.IsNullOrEmpty(session_referer)) { urlreferer = session_referer; } } } } InsertQuery iQuery = new InsertQuery("item_views"); iQuery.AddField("view_item_id", item.ItemKey.Id); iQuery.AddField("view_item_type_id", item.ItemKey.TypeId); if (ownerKey != null) { iQuery.AddField("view_item_owner_id", ownerKey.Id); iQuery.AddField("view_item_owner_type_id", ownerKey.TypeId); } if (core.Session.SignedIn) { iQuery.AddField("user_id", core.LoggedInMemberId); } iQuery.AddField("view_ip", core.Session.IPAddress.ToString()); iQuery.AddField("view_session_id", core.Session.SessionId); iQuery.AddField("view_time_ut", timestamp); iQuery.AddField("view_timespan", 0); iQuery.AddField("view_update_time_ut", timestamp); iQuery.AddField("view_referral_uri", core.Http["ref"]); iQuery.AddField("view_http_referer", urlreferer); iQuery.AddField("view_http_user_agent", core.Http.UserAgent); iQuery.AddField("view_cookies", core.Session.SessionMethod == SessionMethods.Cookie); iQuery.AddField("view_javascript", core.Http.BrowserIdentifiesJavascript); iQuery.AddField("view_counted", false); iQuery.AddField("view_discounted", false); iQuery.AddField("view_processed", false); iQuery.AddField("view_discounted_reason", (int)reason); iQuery.AddField("view_state", (int)ItemViewState.New); // commit the query long viewId = core.Db.Query(iQuery); core.Template.Parse("ITEM_VIEW_ID", viewId.ToString()); }
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(); }
public static Musician Create(Core core, string title, string slug) { if (core == null) { throw new NullCoreException(); } Mysql db = core.Db; SessionState session = core.Session; if (core.Session.LoggedInMember == null) { return null; } if (!CheckMusicianNameUnique(core, slug)) { return null; } db.BeginTransaction(); InsertQuery iQuery = new InsertQuery(Musician.GetTable(typeof(Musician))); iQuery.AddField("musician_name", title); iQuery.AddField("musician_slug", slug); iQuery.AddField("musician_name_first", title.ToLower()[0]); iQuery.AddField("musician_reg_ip", session.IPAddress.ToString()); iQuery.AddField("musician_reg_date_ut", UnixTime.UnixTimeStamp()); long musicianId = db.Query(iQuery); Musician newMusician = new Musician(core, musicianId); MusicianMember member = MusicianMember.Create(core, newMusician, session.LoggedInMember); try { ApplicationEntry musicianAe = new ApplicationEntry(core, "Musician"); musicianAe.Install(core, newMusician); } catch { } try { ApplicationEntry galleryAe = new ApplicationEntry(core, "Gallery"); galleryAe.Install(core, newMusician); } catch { } try { ApplicationEntry guestbookAe = new ApplicationEntry(core, "GuestBook"); guestbookAe.Install(core, newMusician); } catch { } Access.CreateGrantForPrimitive(core, newMusician, User.GetEveryoneGroupKey(core), "VIEW"); Access.CreateGrantForPrimitive(core, newMusician, User.GetRegisteredUsersGroupKey(core), "COMMENT"); Access.CreateGrantForPrimitive(core, newMusician, User.GetRegisteredUsersGroupKey(core), "COMMENT_GIGS"); return newMusician; }
public override long Query(InsertQuery query) { return UpdateQuery(query); }
/// <summary> /// /// </summary> /// <param name="core"></param> /// <param name="itemType"></param> /// <param name="itemId"></param> /// <remarks>ItemRated should implement a transaction.</remarks> public static void ShareItem(Core core, ItemKey itemKey) { if (core == null) { throw new NullCoreException(); } if (itemKey.Id < 1) { throw new InvalidItemException(); } ItemInfo ii = null; try { ii = new ItemInfo(core, itemKey); } catch (InvalidIteminfoException) { ii = ItemInfo.Create(core, itemKey); } ii.IncrementSharedTimes(); InsertQuery iQuery = new InsertQuery(typeof(Share)); iQuery.AddField("share_item_id", itemKey.Id); iQuery.AddField("share_item_type_id", itemKey.TypeId); iQuery.AddField("user_id", core.LoggedInMemberId); iQuery.AddField("share_time_ut", UnixTime.UnixTimeStamp()); iQuery.AddField("share_ip", core.Session.IPAddress.ToString()); // commit the transaction core.Db.Query(iQuery); return; }
public static UserStyle Create(Core core, User owner, string css) { if (core == null) { throw new NullCoreException(); } if (owner.Id == core.LoggedInMemberId) { InsertQuery iQuery = new InsertQuery(Item.GetTable(typeof(UserStyle))); iQuery.AddField("user_id", owner.Id); iQuery.AddField("style_css", css); core.Db.Query(iQuery); return new UserStyle(core, owner.Id); } else { throw new UnauthorisedToCreateItemException(); } }
/// <summary> /// Create a new TrackBack /// </summary> /// <param name="core">Core token</param> /// <param name="entry">Blog entry to attach trackback to</param> /// <param name="uri">Trackback uri</param> /// <param name="blurb">Trackback blurb</param> /// <returns></returns> public static TrackBack Create(Core core, BlogEntry entry, string uri, string blurb) { if (core == null) { throw new NullCoreException(); } if (entry == null) { throw new InvalidBlogEntryException(); } // TODO: validate uri InsertQuery iquery = new InsertQuery(TrackBack.GetTable(typeof(TrackBack))); iquery.AddField("post_id", entry.PostId); iquery.AddField("trackback_uri", uri); iquery.AddField("trackback_blurb", Functions.TrimStringToWord(blurb, 511)); iquery.AddField("trackback_time_ut", UnixTime.UnixTimeStamp()); iquery.AddField("trackback_ip", core.Session.IPAddress.ToString()); long id = core.Db.Query(iquery); return new TrackBack(core, id); }
/// <summary> /// /// </summary> /// <param name="core"></param> /// <param name="itemType"></param> /// <param name="itemId"></param> /// <param name="rating"></param> /// <remarks>ItemRated should implement a transaction.</remarks> public static void Vote(Core core, ItemKey itemKey, int rating) { if (core == null) { throw new NullCoreException(); } if (itemKey.Id < 1) { throw new InvalidItemException(); } if (rating < 1 || rating > 5) { throw new InvalidRatingException(); } /* after 7 days release the IP for dynamics ip fairness */ SelectQuery query = new SelectQuery("ratings r"); query.AddFields("user_id"); query.AddCondition("rate_item_id", itemKey.Id); query.AddCondition("rate_item_type_id", itemKey.TypeId); QueryCondition qc1 = query.AddCondition("user_id", core.LoggedInMemberId); QueryCondition qc2 = qc1.AddCondition(ConditionRelations.Or, "rate_ip", core.Session.IPAddress.ToString()); qc2.AddCondition("rate_time_ut", ConditionEquality.GreaterThan, UnixTime.UnixTimeStamp() - 60 * 60 * 24 * 7); /*DataTable ratingsTable = db.Query(string.Format("SELECT user_id FROM ratings WHERE rate_item_id = {0} AND rate_item_type = '{1}' AND (user_id = {2} OR (rate_ip = '{3}' AND rate_time_ut > UNIX_TIMESTAMP() - (60 * 60 * 24 * 7)))", itemId, Mysql.Escape(itemType), loggedInMember.UserId, session.IPAddress.ToString()));*/ DataTable ratingsTable = core.Db.Query(query); if (ratingsTable.Rows.Count > 0) { throw new AlreadyRatedException(); } /* Impossible using object query model */ /*UpdateQuery uQuery = new UpdateQuery(typeof(ItemInfo)); uQuery.AddField("rating", new QueryOperation("info_rating", QueryOperations.Division, new QueryOperation(QueryOperations.Addition, new QueryOperation("info_rating", QueryOperations.Multiplication, new DataField(typeof(ItemInfo), "info_ratings")))); uQuery.AddCondition("info_item_id", itemKey.Id); uQuery.AddCondition("info_item_type_id", itemKey.TypeId);*/ core.Db.UpdateQuery(string.Format("UPDATE item_info SET info_rating = (info_rating * info_ratings + {0}) / (info_ratings + 1), info_ratings = info_ratings + 1 WHERE info_item_id = {1} AND info_item_type_id = {2}", rating, itemKey.Id, itemKey.TypeId)); InsertQuery iQuery = new InsertQuery("ratings"); iQuery.AddField("rate_item_id", itemKey.Id); iQuery.AddField("rate_item_type_id", itemKey.TypeId); iQuery.AddField("user_id", core.LoggedInMemberId); iQuery.AddField("rate_time_ut", UnixTime.UnixTimeStamp()); iQuery.AddField("rate_rating", rating); iQuery.AddField("rate_ip", core.Session.IPAddress.ToString()); // commit the transaction core.Db.Query(iQuery); return; }
public static MusicianMember Create(Core core, Musician musician, User member) { if (core == null) { throw new NullCoreException(); } InsertQuery iQuery = new InsertQuery(typeof(MusicianMember)); iQuery.AddField("user_id", member.Id); iQuery.AddField("musician_id", musician.Id); iQuery.AddField("member_date_ut", UnixTime.UnixTimeStamp()); iQuery.AddField("member_lead", false); iQuery.AddField("member_instruments", 0); iQuery.AddField("member_stage_name", string.Empty); iQuery.AddField("member_biography", string.Empty); core.Db.Query(iQuery); MusicianMember newMember = new MusicianMember(core, musician, member); return newMember; }
internal static ListItemText Create(Core core, string text, ref string normalisedText) { if (core == null) { throw new NullCoreException(); } ListItem.NormaliseListItem(text, ref normalisedText); InsertQuery iQuery = new InsertQuery(GetTable(typeof(ListItemText))); iQuery.AddField("list_item_text", text); iQuery.AddField("list_item_text_normalised", normalisedText); long listItemTextId = core.Db.Query(iQuery); return new ListItemText(core, listItemTextId); }
internal static TopicPost Create(Core core, Forum forum, ForumTopic topic, string subject, string text) { if (core == null) { throw new NullCoreException(); } if (forum == null) { if (topic.ForumId == forum.Id) { forum = topic.Forum; } } else { if (topic.ForumId != forum.Id) { forum = topic.Forum; } } if (forum == null) { throw new InvalidForumException(); } if (topic == null) { throw new InvalidTopicException(); } if (!forum.Access.Can("REPLY_TOPICS")) { // todo: throw new exception throw new UnauthorisedToCreateItemException(); } InsertQuery iQuery = new InsertQuery(NumberedItem.GetTable(typeof(TopicPost))); iQuery.AddField("topic_id", topic.Id); iQuery.AddField("forum_id", forum.Id); iQuery.AddField("user_id", core.LoggedInMemberId); iQuery.AddField("post_title", subject); iQuery.AddField("post_text", text); iQuery.AddField("post_time_ut", UnixTime.UnixTimeStamp()); iQuery.AddField("post_modified_ut", UnixTime.UnixTimeStamp()); iQuery.AddField("post_ip", core.Session.IPAddress.ToString()); long postId = core.Db.Query(iQuery); TopicPost newPost = new TopicPost(core, forum, topic, postId); core.Search.Index(newPost, new SearchField("forum_id", forum.Id.ToString())); return newPost; }
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; }
private void RequestOAuthAccessToken() { // Final step in oauth handshake OAuthApplication oae = null; string nonce = null; string verifier = core.Http.Form["oauth_verifier"]; OAuthVerifier oAuthVerifier = null; OAuthToken oauthToken = null; try { oAuthVerifier = new OAuthVerifier(core, verifier); } catch (InvalidOAuthVerifierException) { core.Http.StatusCode = 401; NameValueCollection response = new NameValueCollection(); response.Add("error", "unauthorised, invalid verifier"); core.Http.WriteAndEndResponse(response); return; } if (oAuthVerifier.Expired) { core.Http.StatusCode = 401; NameValueCollection response = new NameValueCollection(); response.Add("error", "unauthorised, verifier expired"); core.Http.WriteAndEndResponse(response); return; } try { oauthToken = new OAuthToken(core, oAuthVerifier.TokenId); } catch (InvalidOAuthTokenException) { core.Http.StatusCode = 401; NameValueCollection response = new NameValueCollection(); response.Add("error", "unauthorised, invalid token"); core.Http.WriteAndEndResponse(response); return; } if (AuthoriseRequest("/oauth/access_token", oauthToken, out oae, out nonce)) { oAuthVerifier.UseVerifier(); // TODO: check application is not already installed SelectQuery query = new SelectQuery(typeof(PrimitiveApplicationInfo)); query.AddCondition("application_id", oauthToken.ApplicationId); query.AddCondition("item_id", oAuthVerifier.UserId); query.AddCondition("item_type_id", ItemKey.GetTypeId(core, typeof(User))); System.Data.Common.DbDataReader appReader = db.ReaderQuery(query); if (!appReader.HasRows) { appReader.Close(); appReader.Dispose(); OAuthToken oauthAuthToken = OAuthToken.Create(core, oae, nonce); InsertQuery iQuery = new InsertQuery("primitive_apps"); iQuery.AddField("application_id", oauthToken.ApplicationId); iQuery.AddField("item_id", oAuthVerifier.UserId); iQuery.AddField("item_type_id", ItemKey.GetTypeId(core, typeof(User))); iQuery.AddField("app_email_notifications", true); iQuery.AddField("app_oauth_access_token", oauthAuthToken.Token); iQuery.AddField("app_oauth_access_token_secret", oauthAuthToken.TokenSecret); if (core.Db.Query(iQuery) > 0) { // successfull } db.CommitTransaction(); NameValueCollection response = new NameValueCollection(); response.Add("oauth_token", oauthAuthToken.Token); response.Add("oauth_token_secret", oauthAuthToken.TokenSecret); core.Http.WriteAndEndResponse(response); } else { appReader.Read(); PrimitiveApplicationInfo pai = new PrimitiveApplicationInfo(core, appReader); appReader.Close(); appReader.Dispose(); NameValueCollection response = new NameValueCollection(); response.Add("oauth_token", pai.OAuthAccessToken); response.Add("oauth_token_secret", pai.OAuthAccessTokenSecret); core.Http.WriteAndEndResponse(response); } } else { // FAIL core.Http.StatusCode = 401; NameValueCollection response = new NameValueCollection(); response.Add("error", "unauthorised, access token rejected"); core.Http.WriteAndEndResponse(response); core.Http.End(); return; } }
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; }
public static List Create(Core core, string title, ref string slug, string listAbstract, short listType) { if (core == null) { throw new NullCoreException(); } Navigation.GenerateSlug(title, ref slug); if (!IsValidListType(core, listType)) { throw new ListTypeNotValidException(); } try { Page listPage; try { listPage = new Page(core, core.Session.LoggedInMember, "lists"); } catch (PageNotFoundException) { string listsSlug = "lists"; try { listPage = Page.Create(core, core.Session.LoggedInMember, "Lists", ref listsSlug, 0, "", PageStatus.PageList, 0, Classifications.None); } catch (PageSlugNotUniqueException) { throw new Exception("Cannot create lists slug."); } } Page page = Page.Create(core, core.Session.LoggedInMember, title, ref slug, listPage.Id, "", PageStatus.PageList, 0, Classifications.None); // Create list InsertQuery iQuery = new InsertQuery(GetTable(typeof(List))); iQuery.AddField("user_id", core.LoggedInMemberId); iQuery.AddField("list_title", title); iQuery.AddField("list_path", slug); iQuery.AddField("list_type", listType); iQuery.AddField("list_abstract", listAbstract); long listId = core.Db.Query(iQuery); List list = new List(core, core.Session.LoggedInMember, listId); /* LOAD THE DEFAULT ITEM PERMISSIONS */ list.Access.CreateAllGrantsForOwner(); list.Access.CreateGrantForPrimitive(User.GetEveryoneGroupKey(core), "VIEW"); //Access.CreateAllGrantsForOwner(core, list); //Access.CreateGrantForPrimitive(core, list, new ItemKey(-2, ItemType.GetTypeId(typeof(User))), "VIEW"); return list; } catch (PageSlugNotUniqueException) { throw new ListSlugNotUniqueException(); } }
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(); } }
public static Confirmation Create(Core core, string session, string code, byte type) { if (core == null) { throw new NullCoreException(); } InsertQuery iQuery = new InsertQuery(GetTable(typeof(Confirmation))); iQuery.AddField("session_id", session); iQuery.AddField("confirm_code", code); iQuery.AddField("confirm_type", type); long confirmId = core.Db.Query(iQuery); return new Confirmation(core, confirmId); }
internal static void Create(Core core, ForumTopic topic, TopicPost lastVisiblePost) { if (core == null) { throw new NullCoreException(); } if (core.LoggedInMemberId > 0) { InsertQuery iQuery = new InsertQuery(GetTable(typeof(TopicReadStatus))); iQuery.AddField("topic_id", topic.Id); iQuery.AddField("user_id", core.LoggedInMemberId); iQuery.AddField("forum_id", topic.ForumId); iQuery.AddField("read_time_ut", lastVisiblePost.TimeCreatedRaw); core.Db.Query(iQuery); } }
public static UserPhoneNumber Create(Core core, string phoneNumber, PhoneNumberTypes phoneType) { if (core == null) { throw new NullCoreException(); } InsertQuery iquery = new InsertQuery(UserPhoneNumber.GetTable(typeof(UserPhoneNumber))); iquery.AddField("phone_user_id", core.Session.LoggedInMember.Id); iquery.AddField("phone_number", phoneNumber); iquery.AddField("phone_type", (byte)phoneType); iquery.AddField("phone_time_ut", UnixTime.UnixTimeStamp()); iquery.AddField("phone_simple_permissions", true); iquery.AddField("phone_validated", false); long phoneId = core.Db.Query(iquery); UserPhoneNumber newPhoneNumber = new UserPhoneNumber(core, phoneId); Access.CreateGrantForPrimitive(core, newPhoneNumber, User.GetCreatorKey(core), "VIEW"); Access.CreateGrantForPrimitive(core, newPhoneNumber, Friend.GetFriendsGroupKey(core), "VIEW"); return newPhoneNumber; }
/// <summary> /// Creates a new blog for the logged in user. /// </summary> /// <param name="core"></param> /// <returns></returns> public static Calendar Create(Core core, Primitive owner) { if (core == null) { throw new NullCoreException(); } InsertQuery iQuery = new InsertQuery(GetTable(typeof(Calendar))); iQuery.AddField("calendar_item_id", owner.Id); iQuery.AddField("calendar_item_type_id", owner.TypeId); iQuery.AddField("calendar_simple_permissions", true); long calendarId = core.Db.Query(iQuery); Calendar newCalendar = new Calendar(core, owner); if (owner is User) { Access.CreateAllGrantsForOwner(core, newCalendar); newCalendar.Access.CreateGrantForPrimitive(Friend.GetFriendsGroupKey(core), "VIEW"); } if (owner is UserGroup) { newCalendar.Access.CreateGrantForPrimitive(UserGroup.GetGroupOperatorsGroupKey(core), "VIEW", "CREATE_EVENTS", "CREATE_TASKS", "ASSIGN_TASKS", "EDIT_EVENTS", "EDIT_TASKS"); newCalendar.Access.CreateGrantForPrimitive(UserGroup.GetGroupOfficersGroupKey(core), "VIEW", "CREATE_EVENTS", "CREATE_TASKS", "ASSIGN_TASKS", "EDIT_EVENTS", "EDIT_TASKS"); newCalendar.Access.CreateGrantForPrimitive(User.GetEveryoneGroupKey(core), "VIEW"); newCalendar.Access.CreateGrantForPrimitive(User.GetCreatorKey(core), "EDIT_EVENTS", "EDIT_TASKS"); } return newCalendar; }
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(); } }