Example #1
0
        protected void BeginProfile()
        {
            anAssemblyName = core.Http["an"];

            try
            {
                primitive = new ApplicationEntry(core, anAssemblyName);
            }
            catch (InvalidApplicationException)
            {
                core.Functions.Generate404();
                return;
            }

            core.PagePath = core.PagePath.Substring(AnApplication.ApplicationName.Length + 1 + 12);
            if (core.PagePath.Trim(new char[] { '/' }) == string.Empty)
            {
                core.PagePath = "/profile";
            }

            BoxSocial.Internals.Application.LoadApplications(core, AppPrimitives.Application, core.PagePath, BoxSocial.Internals.Application.GetApplications(core, AnApplication));

            PageTitle = AnApplication.Title;

            core.Template.Parse("PRIMITIVE_THUMB", Owner.Thumbnail);
            core.Template.Parse("PRIMITIVE_ICON", Owner.Icon);
            core.Template.Parse("PRIMITIVE_TILE", Owner.Tile);
            core.Template.Parse("PRIMITIVE_SQUARE", Owner.Square);
            core.Template.Parse("PRIMITIVE_COVER_PHOTO", Owner.CoverPhoto);
            core.Template.Parse("PRIMITIVE_MOBILE_COVER_PHOTO", Owner.MobileCoverPhoto);
        }
        public ApplicationDeveloper(Core core, ApplicationEntry owner, User user)
            : base(core)
        {
            // load the info into a the new object being created
            this.userInfo = user.UserInfo;
            this.userProfile = user.Profile;
            this.userStyle = user.Style;
            this.userId = user.UserId;
            this.userName = user.UserName;
            this.domain = user.UserDomain;
            this.emailAddresses = user.EmailAddresses;

            SelectQuery sQuery = ApplicationDeveloper.GetSelectQueryStub(core, typeof(ApplicationDeveloper));
            sQuery.AddCondition("user_id", user.Id);
            sQuery.AddCondition("application_id", owner.Id);

            try
            {
                System.Data.Common.DbDataReader reader = core.Db.ReaderQuery(sQuery);
                if (reader.HasRows)
                {
                    reader.Read();

                    loadItemInfo(typeof(ApplicationDeveloper), reader);

                    reader.Close();
                    reader.Dispose();
                }
                else
                {
                    reader.Close();
                    reader.Dispose();

                    throw new InvalidApplicationDeveloperException();
                }
            }
            catch (InvalidItemException)
            {
                throw new InvalidApplicationDeveloperException();
            }
        }
Example #3
0
        public static List<ApplicationEntry> GetApplications(Core core, Primitive owner)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            List<ApplicationEntry> applicationsList = new List<ApplicationEntry>();
            Dictionary<long, ApplicationEntry> applicationsDictionary = new Dictionary<long, ApplicationEntry>();

            System.Data.Common.DbDataReader userApplicationsReader = core.Db.ReaderQuery(GetApplicationQuery(core, owner));

            if (userApplicationsReader.HasRows)
            {
                List<long> applicationIds = new List<long>();
                while (userApplicationsReader.Read())
                {
                    ApplicationEntry ae = new ApplicationEntry(core, userApplicationsReader);
                    applicationsList.Add(ae);
                    applicationsDictionary.Add(ae.ApplicationId, ae);

                    applicationIds.Add(ae.ApplicationId);
                }

                userApplicationsReader.Close();
                userApplicationsReader.Dispose();

                /*DataTable applicationSlugsTable = core.db.Query(string.Format(@"SELECT {0}
                    FROM application_slugs al
                    WHERE application_id IN ({1})
                    AND slug_primitives & {2:0}
                    ORDER BY application_id;",
                    ApplicationEntry.APPLICATION_SLUG_FIELDS, applicationIds, (byte)owner.AppPrimitive));*/

                SelectQuery query = Item.GetSelectQueryStub(core, typeof(ApplicationSlug));
                query.AddCondition("application_id", ConditionEquality.In, applicationIds);
                query.AddCondition(new QueryOperation("slug_primitives", QueryOperations.BinaryAnd, (byte)owner.AppPrimitive), ConditionEquality.NotEqual, false);
                query.AddCondition("slug_static", false);
                query.AddSort(SortOrder.Ascending, "application_id");

                System.Data.Common.DbDataReader applicationSlugsReader = core.Db.ReaderQuery(query);

                while(applicationSlugsReader.Read())
                {
                    applicationsDictionary[(long)applicationSlugsReader["application_id"]].LoadSlugEx((string)applicationSlugsReader["slug_slug_ex"]);
                }

                applicationSlugsReader.Close();
                applicationSlugsReader.Dispose();
            }
            else
            {
                userApplicationsReader.Close();
                userApplicationsReader.Dispose();
            }

            return applicationsList;
        }
Example #4
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;
        }
Example #5
0
        private void InitiateApplicationMethod()
        {
            string applicationName = core.Http.Query["global_an"];
            string callName = core.Http.Query["global_call"];

            OAuthApplication oae = null;
            string nonce = null;

            if (AuthoriseRequest("/oauth/" + applicationName + "/" + callName, null, out oae, out nonce))
            {
                if (applicationName == "Internals")
                {
                    core.InvokeApplicationCall(null, callName);
                }
                else
                {
                    try
                    {
                        ApplicationEntry ae = new ApplicationEntry(core, applicationName);

                        core.InvokeApplicationCall(ae, callName);
                    }
                    catch (InvalidApplicationException)
                    {
                    }
                }
            }
            else
            {
                core.Http.StatusCode = 401;

                NameValueCollection response = new NameValueCollection();
                response.Add("error", "unauthorised, access token rejected");

                core.Http.WriteAndEndResponse(response);
                return;
            }
        }
Example #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string profileUserName = core.Http["un"];
            string groupUserName = core.Http["gn"];
            string applicationUserName = core.Http["an"];
            string mode = core.Http["mode"];
            bool retina = core.Http["retina"] == "true";
            User profileOwner = null;
            UserGroup thisGroup = null;
            ApplicationEntry anApplication = null;

            int width = 100;

            if (retina)
            {
                switch (mode)
                {
                    case "icon":
                        width = 100;
                        break;
                    case "tile":
                        width = 200;
                        break;
                    case "square":
                    case "high":
                        width = 400;
                        break;
                    case "tiny":
                        width = 160;
                        break;
                    case "thumb":
                        width = 320;
                        break;
                    case "mobile":
                        width = 640;
                        break;
                    case "display":
                        width = 1280;
                        break;
                    case "full":
                    case "ultra":
                        width = 2560;
                        break;
                }
            }
            else
            {
                switch (mode)
                {
                    case "icon":
                        width = 50;
                        break;
                    case "tile":
                        width = 100;
                        break;
                    case "square":
                        width = 200;
                        break;
                    case "high":
                        width = 400;
                        break;
                    case "tiny":
                        width = 80;
                        break;
                    case "thumb":
                        width = 160;
                        break;
                    case "mobile":
                        width = 320;
                        break;
                    case "display":
                        width = 640;
                        break;
                    case "full":
                        width = 1280;
                        break;
                    case "ultra":
                        width = 2560;
                        break;
                }
            }

            if (!string.IsNullOrEmpty(profileUserName))
            {
                try
                {

                    profileOwner = new User(core, profileUserName);
                }
                catch
                {
                    core.Functions.Generate404();
                    return;
                }

                if (profileOwner != null)
                {
                    if (profileOwner.UserInfo.DisplayPictureId > 0)
                    {
                        httpContext.Response.Redirect(string.Format("/memberpage.aspx?un={0}&path=/images/_{1}/_{0}.png", profileUserName, mode), true);
                        return;
                    }
                }
            }

            if (!string.IsNullOrEmpty(groupUserName))
            {
                try
                {

                    thisGroup = new UserGroup(core, groupUserName);
                }
                catch
                {
                    core.Functions.Generate404();
                    return;
                }

                if (thisGroup != null)
                {
                    if (thisGroup.GroupInfo.DisplayPictureId > 0)
                    {
                        httpContext.Response.Redirect(string.Format("/grouppage.aspx?gn={0}&path=/images/_{1}/_{0}.png", groupUserName, mode), true);
                        return;
                    }
                }
            }

            if (!string.IsNullOrEmpty(applicationUserName))
            {
                try
                {

                    anApplication = new ApplicationEntry(core, applicationUserName);
                }
                catch
                {
                    core.Functions.Generate404();
                    return;
                }

                if (anApplication != null)
                {
                    if (anApplication.GalleryIcon > 0)
                    {
                        httpContext.Response.Redirect(string.Format("/applicationpage.aspx?an={0}&path=/images/_{1}/_{0}.png", applicationUserName, mode), true);
                        return;
                    }
                }
            }

            Response.Cache.SetCacheability(HttpCacheability.Public);
            Response.Cache.SetMaxAge(new TimeSpan(10, 0, 0));
            Response.Cache.SetLastModified(DateTime.Now.Subtract(new TimeSpan(10, 0, 0)));
            Response.ContentType = "image/png";
            Response.Clear();

            Image image = null;

            string imagePath = string.Empty;

            if (!string.IsNullOrEmpty(profileUserName))
            {
                byte[] userBytes = System.Text.Encoding.UTF8.GetBytes(profileUserName);
                MD5 md5 = MD5.Create();
                int hash = BitConverter.ToInt32(md5.ComputeHash(userBytes), 0);

                image = Identicon.CreateIdenticon(hash, width, false);
                if (retina)
                {
                    imagePath = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Server.MapPath("./"), "images"), "user"), "_" + mode), string.Format("{0}@2x.png",
                        profileUserName));
                }
                else
                {
                    imagePath = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Server.MapPath("./"), "images"), "user"), "_" + mode), string.Format("{0}.png",
                        profileUserName));
                }
            }

            if (!string.IsNullOrEmpty(groupUserName))
            {
                byte[] userBytes = System.Text.Encoding.UTF8.GetBytes(groupUserName);
                MD5 md5 = MD5.Create();
                int hash = BitConverter.ToInt32(md5.ComputeHash(userBytes), 0);

                char letter = thisGroup.DisplayName.ToUpper()[0];
                image = CreateIcon(letter, width, false);
                if (retina)
                {
                    imagePath = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Server.MapPath("./"), "images"), "group"), "_" + mode), string.Format("{0}@2x.png",
                        groupUserName));
                }
                else
                {
                    imagePath = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Server.MapPath("./"), "images"), "group"), "_" + mode), string.Format("{0}.png",
                        groupUserName));
                }
            }

            if (!string.IsNullOrEmpty(applicationUserName))
            {
                byte[] userBytes = System.Text.Encoding.UTF8.GetBytes(applicationUserName);
                MD5 md5 = MD5.Create();
                int hash = BitConverter.ToInt32(md5.ComputeHash(userBytes), 0);

                char letter = anApplication.DisplayName.ToUpper()[0];
                image = CreateIcon(letter, width, false);
                if (retina)
                {
                    imagePath = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Server.MapPath("./"), "images"), "application"), "_" + mode), string.Format("{0}@2x.png",
                        applicationUserName));
                }
                else
                {
                    imagePath = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Server.MapPath("./"), "images"), "application"), "_" + mode), string.Format("{0}.png",
                        applicationUserName));
                }
            }

            try
            {
                FileStream newFileStream = new FileStream(imagePath, FileMode.Create);
                image.Save(newFileStream, ImageFormat.Png);
                newFileStream.Close();
            }
            catch { }

            MemoryStream newStream = new MemoryStream();
            image.Save(newStream, ImageFormat.Png);

            core.Http.WriteStream(newStream);

            if (db != null)
            {
                db.CloseConnection();
            }

            core.Prose.Close();
            //core.Dispose();
            //core = null;

            Response.End();
        }
Example #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            bool isAjax = false;

            if (Request["ajax"] == "true")
            {
                isAjax = true;
            }

            if (!core.Session.SignedIn)
            {
                core.Response.ShowMessage("notSignedIn", "Subscription Error", "You must be logged in to subscribe.");
            }

            string mode = core.Http["mode"];
            long itemId = core.Functions.RequestLong("item", 0);
            long itemTypeId = core.Functions.RequestLong("type", 0);
            ItemKey itemKey = null;

            try
            {
                itemKey = new ItemKey(itemId, itemTypeId);
            }
            catch
            {
                core.Response.ShowMessage("invalidItem", "Invalid Item", "The item you have attempted to subscribe to is invalid.");
                return;
            }

            try
            {
                // This isn't the most elegant fix, but it works
                ApplicationEntry ae = null;
                if (core.IsPrimitiveType(itemTypeId))
                {
                    ae = core.GetApplication("GuestBook");
                }
                else
                {
                    ItemType itemType = new ItemType(core, itemTypeId);
                    if (itemType.ApplicationId == 0)
                    {
                        ae = core.GetApplication("GuestBook");
                    }
                    else
                    {
                        ae = new ApplicationEntry(core, itemType.ApplicationId);
                    }
                }

                BoxSocial.Internals.Application.LoadApplication(core, AppPrimitives.Any, ae);
            }
            catch (InvalidItemTypeException)
            {
                core.Response.ShowMessage("invalidItem", "Invalid Item", "The item you have attempted to subscribe to is invalid.");
                return;
            }
            catch (InvalidApplicationException)
            {
                core.Response.ShowMessage("invalidItem", "Invalid Item", "The item you have attempted to rate is invalid.");
                return;
            }

            bool success = false;
            try
            {
                switch (mode)
                {
                    case "subscribe":
                        success = Subscription.SubscribeToItem(core, itemKey);
                        Core.ItemSubscribed(itemKey, loggedInMember);

                        if (success)
                        {
                            if (isAjax)
                            {
                                core.Response.SendStatus("subscriptionAccepted");
                            }
                            else
                            {
                                core.Display.ShowMessage("Subscribed", "You have successfully subscribed.");
                            }
                        }
                        else
                        {
                            core.Response.ShowMessage("error", "Error", "Subscription unsuccessful.");
                        }
                        break;
                    case "unsubscribe":
                        success = Subscription.UnsubscribeFromItem(core, itemKey);
                        Core.ItemUnsubscribed(itemKey, loggedInMember);

                        if (success)
                        {
                            if (isAjax)
                            {
                                core.Response.SendStatus("unsubscriptionAccepted");
                            }
                            else
                            {
                                core.Display.ShowMessage("Unsubscribed", "You have successfully unsubscribed.");
                            }
                        }
                        else
                        {
                            core.Response.ShowMessage("error", "Error", "Unsubscription unsuccessful.");
                        }
                        break;
                }
            }
            catch (InvalidItemException)
            {
                core.Response.ShowMessage("invalidItem", "Invalid Item", "The item you have attempted to subscribe to is invalid.");
            }
            catch (InvalidSubscriptionException)
            {
                core.Response.ShowMessage("invalidSubscription", "Invalid Subscription", "The subscription is not valid.");
            }
            catch (AlreadySubscribedException)
            {
                core.Response.ShowMessage("alreadySubscribed", "Already Subscribed", "You have already subscribe to this item, you cannot subscribe to it again");
            }
        }
Example #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            bool isAjax = false;

            if (Request["ajax"] == "true")
            {
                isAjax = true;
            }

            int rating = core.Functions.RequestInt("rating", 0);
            long itemId = core.Functions.RequestLong("item", 0);
            long itemTypeId = core.Functions.RequestLong("type", 0);
            ItemKey itemKey = null;

            try
            {
                itemKey = new ItemKey(itemId, itemTypeId);
            }
            catch
            {
                core.Response.ShowMessage("invalidItem", "Invalid Item", "The item you have attempted to rate is invalid.");
                return;
            }

            try
            {
                // This isn't the most elegant fix, but it works
                ApplicationEntry ae = null;
                if (core.IsPrimitiveType(itemTypeId))
                {
                    ae = core.GetApplication("GuestBook");
                }
                else
                {
                    ItemType itemType = new ItemType(core, itemTypeId);
                    if (itemType.ApplicationId == 0)
                    {
                        ae = core.GetApplication("GuestBook");
                    }
                    else
                    {
                        ae = new ApplicationEntry(core, itemType.ApplicationId);
                    }
                }

                BoxSocial.Internals.Application.LoadApplication(core, AppPrimitives.Any, ae);
            }
            catch (InvalidItemTypeException)
            {
                core.Response.ShowMessage("invalidItem", "Invalid Item", "The item you have attempted to rate is invalid.");
                return;
            }
            catch (InvalidApplicationException)
            {
                core.Response.ShowMessage("invalidItem", "Invalid Item", "The item you have attempted to rate is invalid.");
                return;
            }

            try
            {
                Rating.Vote(core, itemKey, rating);

                core.Response.SendStatus("voteAccepted");
            }
            catch (InvalidItemException ex)
            {
                core.Response.ShowMessage("invalidItem", "Invalid Item", "The item you have attempted to rate is invalid.");
            }
            catch (InvalidRatingException)
            {
                core.Response.ShowMessage("invalidRating", "Invalid Rating", "The rating you have attempted to give for this item is invalid.");
            }
            catch (AlreadyRatedException)
            {
                core.Response.ShowMessage("alreadyVoted", "Already Voted", "You have already rated this item, you cannot rate it again");
            }

            //else
            //{
            //    /* TODO permissions */
            //    /* after 7 days release the IP for dynamics ip fairness */
            //    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()));

            //    if (ratingsTable.Rows.Count > 0)
            //    {
            //        //Response.Write("alreadyVoted");
            //        Ajax.ShowMessage(true, "alreadyVoted", "Already Voted", "You have already rated this item, you cannot rate it again");
            //        return;
            //    }
            //    else
            //    {
            //        /* Register a vote */
            //        /* start transaction */
            //        InsertQuery iQuery = new InsertQuery("ratings");
            //        iQuery.AddField("rate_item_id", itemId);
            //        iQuery.AddField("rate_item_type", itemType);
            //        iQuery.AddField("user_id", loggedInMember.UserId);
            //        iQuery.AddField("rate_time_ut", UnixTime.UnixTimeStamp());
            //        iQuery.AddField("rate_rating", rating);
            //        iQuery.AddField("rate_ip", session.IPAddress.ToString());

            //        db.UpdateQuery(iQuery, true);

            //        switch (itemType)
            //        {
            //            case "PHOTO":
            //                db.UpdateQuery(string.Format("UPDATE gallery_items SET gallery_item_rating = (gallery_item_rating * gallery_item_ratings + {0}) / (gallery_item_ratings + 1), gallery_item_ratings = gallery_item_ratings + 1 WHERE gallery_item_id = {1}",
            //                    rating, itemId), false);
            //                break;
            //        }

            //        Ajax.SendStatus("voteAccepted");
            //        return;
            //    }
            //}
        }
Example #9
0
        public void InvokeApplicationCall(ApplicationEntry ae, string callName)
        {
            if (ae == null)
            {
                // Internal calls
                switch (callName)
                {
                    case "item_types":
                        this.Functions.ReturnItemTypeIds();
                        break;
                    case "update":

                        break;
                    case "feed":
                        Feed.ShowMore(this, Session.LoggedInMember);
                        break;
                    case "primitive":
                        break;
                    case "permission_groups":
                        this.Functions.ReturnPermissionGroupList(ResponseFormats.Json);
                        break;
                    case "page_list":
                        {
                            long id = Functions.RequestLong("id", 0);
                            long typeId = Functions.RequestLong("type_id", 0);
                            string path = Http["path"];
                            ItemKey ownerKey = new ItemKey(id, typeId);

                            PrimitiveCache.LoadPrimitiveProfile(ownerKey);
                            Primitive owner = PrimitiveCache[ownerKey];

                            if (owner != null)
                            {
                                Page page = null;
                                if (!string.IsNullOrEmpty(path))
                                {
                                    page = new Page(this, owner, path);
                                }

                                List<Page> pages = Display.GetPageList(owner, Session.LoggedInMember, page);

                                Response.WriteObject(pages);
                            }
                        }
                        break;
                    case "comments":
                        {
                            long id = Functions.RequestLong("id", 0);
                            long typeId = Functions.RequestLong("type_id", 0);
                            int page = Math.Max(Functions.RequestInt("page", 1), 1);
                            int perPage = Math.Max(Math.Min(20, Functions.RequestInt("per_page", 10)), 1);
                            SortOrder order = Http["sort_order"] == "DESC" ? SortOrder.Descending : SortOrder.Ascending;

                            ItemKey itemKey = new ItemKey(id, typeId);

                            // Check ACLs
                            ICommentableItem item = (ICommentableItem)NumberedItem.Reflect(this, itemKey);
                            bool canViewComments = true;

                            if (item is IPermissibleItem)
                            {
                                if (!((IPermissibleItem)item).Access.Can("VIEW"))
                                {
                                    canViewComments = false;
                                }
                            }

                            if (canViewComments)
                            {
                                List<Comment> comments = Comment.GetComments(this, itemKey, order, page, perPage, null);

                                Response.WriteObject(comments);
                            }
                        }
                        break;
                    case "comment_post":
                        Comment newComment = Comment.Post(this);

                        Response.WriteObject(newComment);
                        break;
                    case "comment_report":
                        //Comment.Report(this);
                        break;
                    case "comment_delete":
                        try
                        {
                            Comment.Delete(this);
                        }
                        catch (InvalidCommentException)
                        {
                            this.Response.ShowMessage("error", "Error", "An error was encountered while deleting the comment, the comment has not been deleted.");
                        }
                        catch (PermissionDeniedException)
                        {
                            this.Response.ShowMessage("permission-denied", "Permission Denied", "You do not have the permissions to delete this comment.");
                        }
                        break;
                    case "rate":
                        {
                            int rating = Functions.RequestInt("rating", 0);
                            long itemId = Functions.RequestLong("item", 0);
                            long itemTypeId = Functions.RequestLong("type", 0);
                            ItemKey itemKey = null;

                            try
                            {
                                itemKey = new ItemKey(itemId, itemTypeId);
                            }
                            catch
                            {
                            }

                            Rating.Vote(this, itemKey, rating);
                        }
                        break;
                    case "get_rating":
                        {
                            long itemId = Functions.RequestLong("item", 0);
                            long itemTypeId = Functions.RequestLong("type", 0);

                            ItemKey itemKey = null;

                            try
                            {
                                itemKey = new ItemKey(itemId, itemTypeId);
                            }
                            catch
                            {
                            }

                            ItemInfo info = new ItemInfo(this, itemKey);

                            Response.WriteObject(info.Rating);
                        }
                        break;
                    case "like":
                        {
                            long itemId = Functions.RequestLong("item", 0);
                            long itemTypeId = Functions.RequestLong("type", 0);
                            string type = this.Http["like"];
                            ItemKey itemKey = null;

                            try
                            {
                                itemKey = new ItemKey(itemId, itemTypeId);
                            }
                            catch
                            {
                            }

                            try
                            {
                                LikeType like = LikeType.Neutral;
                                switch (type)
                                {
                                    case "like":
                                        like = LikeType.Like;
                                        break;
                                    case "dislike":
                                        like = LikeType.Dislike;
                                        break;
                                }
                                Like.LikeItem(this, itemKey, like);

                                switch (like)
                                {
                                    case LikeType.Like:
                                        //NotificationSubscription.Create(core, loggedInMember, itemKey);
                                        try
                                        {
                                            Subscription.SubscribeToItem(this, itemKey);
                                        }
                                        catch (AlreadySubscribedException)
                                        {
                                            // not a problem
                                        }
                                        break;
                                    case LikeType.Neutral:
                                    case LikeType.Dislike:
                                        //NotificationSubscription.Unsubscribe(core, loggedInMember, itemKey);
                                        Subscription.UnsubscribeFromItem(this, itemKey);
                                        break;
                                }
                            }
                            catch
                            {

                            }
                        }
                        break;
                    case "subscribe":
                        {
                            string mode = this.Http["mode"];
                            long itemId = this.Functions.RequestLong("item_id", 0);
                            long itemTypeId = this.Functions.RequestLong("item_type_id", 0);

                            ItemKey itemKey = null;

                            try
                            {
                                itemKey = new ItemKey(itemId, itemTypeId);
                            }
                            catch
                            {
                                this.Response.ShowMessage("invalidItem", "Invalid Item", "The item you have attempted to subscribe to is invalid.");
                                return;
                            }

                            //Subscription.Register();
                        }
                        break;
                }
            }
            else
            {
                Application callApplication = Application.GetApplication(this, AppPrimitives.Any, ae);

                if (callApplication != null)
                {
                    callApplication.ExecuteCall(callName);
                }
            }
        }
Example #10
0
        public List<ApplicationEntry> GetCronApplications()
        {
            loadAssemblies();

            SelectQuery query = ApplicationEntry.GetSelectQueryStub(this, typeof(ApplicationEntry));
            query.AddCondition("application_cron_enabled", true);
            query.AddCondition("application_cron_frequency", ConditionEquality.GreaterThan, 0);

            DataTable applicationDataTable = Db.Query(query);

            List<ApplicationEntry> aes = new List<ApplicationEntry>();

            foreach (DataRow row in applicationDataTable.Rows)
            {
                ApplicationEntry ae = new ApplicationEntry(this, row);
                aes.Add(ae);

                if (Prose != null && ae.ApplicationType == ApplicationType.Native)
                {
                    Prose.AddApplication(ae.Key);
                }
            }

            return aes;
        }
Example #11
0
        public ApplicationEntry GetApplication(string name)
        {
            loadAssemblies();

            if (loadedAssemblies.ContainsKey(name))
            {
                ItemKey ik = loadedAssemblies[name];
                ItemCache.RequestItem(ik); // Not normally needed, but in-case the persisted NumberedItems cache is purged
                ApplicationEntry ae = (ApplicationEntry)ItemCache[ik];

                if (Prose != null && ae.ApplicationType == ApplicationType.Native)
                {
                    Prose.AddApplication(ae.Key);
                }

                return ae;
            }
            else
            {
                ApplicationEntry ae = new ApplicationEntry(this, name);

                if (loadedAssemblies != null)
                {
                    if (!loadedAssemblies.ContainsKey(name))
                    {
                        loadedAssemblies.Add(name, ae.ItemKey);
                    }

                    Cache.SetCached("Applications", loadedAssemblies, new TimeSpan(1, 0, 0), CacheItemPriority.Default);
                }

                if (Prose != null && ae.ApplicationType == ApplicationType.Native)
                {
                    Prose.AddApplication(ae.Key);
                }

                return ae;
            }
        }
Example #12
0
        public override SearchResult DoSearch(string input, int pageNumber, Primitive filterByOwner, Type filterByType)
        {
            Initialise();

            int perPage = 10;
            int start = (pageNumber - 1) * perPage;

            List<ISearchableItem> results = new List<ISearchableItem>();
            List<ItemKey> itemKeys = new List<ItemKey>();
            List<long> applicationIds = new List<long>();

            QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "item_string", analyzer);

            BooleanQuery query = new BooleanQuery();
            Query bodyQuery = parser.Parse(input);

            query.Add(bodyQuery, Occur.MUST);

            BooleanQuery accessQuery = new BooleanQuery();
            TermQuery accessPublicQuery = new TermQuery(new Term("item_public", "1"));
            accessQuery.Add(accessPublicQuery, Occur.SHOULD);

            if (core.Session.IsLoggedIn)
            {
                List<long> friends = core.Session.LoggedInMember.GetFriendsWithMeIds();

                BooleanQuery accessFriendQuery = new BooleanQuery();
                TermQuery friendQuery = new TermQuery(new Term("item_public", "2"));
                accessFriendQuery.Add(friendQuery, Occur.MUST);

                string userTypeId = ItemType.GetTypeId(core, typeof(User)).ToString();
                foreach (long friendId in friends)
                {
                    BooleanQuery ownerQuery = new BooleanQuery();
                    TermQuery ownerIdQuery = new TermQuery(new Term("owner_id", friendId.ToString()));
                    TermQuery ownerTypeQuery = new TermQuery(new Term("owner_type_id", userTypeId));

                    ownerQuery.Add(ownerIdQuery, Occur.MUST);
                    ownerQuery.Add(ownerTypeQuery, Occur.MUST);

                    accessFriendQuery.Add(ownerQuery, Occur.SHOULD);
                }

                accessQuery.Add(accessFriendQuery, Occur.SHOULD);
            }

            query.Add(accessQuery, Occur.MUST);

            if (filterByType != null)
            {
                TermQuery typeQuery = new TermQuery(new Term("item_type_id", ItemType.GetTypeId(core, filterByType).ToString()));

                query.Add(typeQuery, Occur.MUST);
            }

            if (filterByOwner != null)
            {
                TermQuery ownerIdQuery = new TermQuery(new Term("owner_id", filterByOwner.Id.ToString()));
                TermQuery ownerTypeIdQuery = new TermQuery(new Term("owner_type_id", filterByOwner.TypeId.ToString()));

                query.Add(ownerIdQuery, Occur.MUST);
                query.Add(ownerTypeIdQuery, Occur.MUST);
            }

            NameValueCollection queryString = new NameValueCollection();
            queryString.Add("wt", "json");
            queryString.Add("start", start.ToString());
            queryString.Add("q", query.ToString());

            WebClient wc = new WebClient();
            wc.QueryString = queryString;
            string solrResultString = wc.DownloadString("http://" + server + "/select");

            //HttpContext.Current.Response.Write(solrResultString + "<br />");

            JsonTextReader reader = new JsonTextReader(new StringReader(solrResultString));

            int totalResults = 0;
            List<Dictionary<string, string>> docs = new List<Dictionary<string, string>>();
            bool readingResponse = false;
            bool inDocument = false;
            string lastToken = string.Empty;
            int current = -1;

            while (reader.Read())
            {
                if (readingResponse)
                {
                    if (reader.Value != null)
                    {
                        if (inDocument)
                        {
                            if (reader.TokenType == JsonToken.PropertyName)
                            {
                                lastToken = reader.Value.ToString();
                                //HttpContext.Current.Response.Write(lastToken + "<br />\n");
                            }
                            else
                            {
                                docs[current].Add(lastToken, reader.Value.ToString());
                                lastToken = string.Empty;
                            }
                            /*else if (reader.TokenType == JsonToken.Integer)
                            {
                                docs[docs.Count - 1].Add(lastToken, reader.Value.ToString());
                            }
                            else if (reader.TokenType == JsonToken.Boolean)
                            {
                                docs[docs.Count - 1].Add(lastToken, reader.Value.ToString());
                            }
                            else if (reader.TokenType == JsonToken.Float)
                            {
                                docs[docs.Count - 1].Add(lastToken, reader.Value.ToString());
                            }*/
                        }
                        else
                        {
                            if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "numFound")
                            {
                                lastToken = reader.Value.ToString();
                            }
                            if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "docs")
                            {
                                lastToken = reader.Value.ToString();
                            }
                            if (reader.TokenType == JsonToken.Integer && lastToken == "numFound")
                            {
                                totalResults = int.Parse(reader.Value.ToString());
                                lastToken = string.Empty;
                                //HttpContext.Current.Response.Write(totalResults + " results<br />\n");
                            }
                        }
                    }
                    else
                    {
                        if (reader.TokenType == JsonToken.StartArray && lastToken == "docs")
                        {
                            inDocument = true;
                            lastToken = string.Empty;
                        }
                        if (reader.TokenType == JsonToken.StartObject && inDocument)
                        {
                            docs.Add(new Dictionary<string,string>());
                            current++;
                        }
                        if (reader.TokenType == JsonToken.EndArray && inDocument)
                        {
                            inDocument = false;
                        }
                    }
                }
                else
                {
                    if (reader.Value != null)
                    {
                        if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "response")
                        {
                            readingResponse = true;
                        }
                    }

                }
            }

            for (int i = 0; i < docs.Count; i++)
            {
                long itemId = 0;
                long itemTypeId = 0;
                long applicationId = 0;

                long.TryParse(docs[i]["item_id"], out itemId);
                long.TryParse(docs[i]["item_type_id"], out itemTypeId);
                long.TryParse(docs[i]["application_id"], out applicationId);

                ItemKey key = new ItemKey(itemId, itemTypeId);

                if (!applicationIds.Contains(applicationId))
                {
                    applicationIds.Add(applicationId);
                }

                itemKeys.Add(key);
                //HttpContext.Current.Response.Write("item_id: " + itemId + ", item_type_id:" + itemTypeId + "<br />\n");
            }

            // Force each application with results to load
            for (int i = 0; i < applicationIds.Count; i++)
            {
                if (applicationIds[i] > 0)
                {
                    ApplicationEntry ae = new ApplicationEntry(core, applicationIds[i]);

                    BoxSocial.Internals.Application.LoadApplication(core, AppPrimitives.Any, ae);
                }
            }

            List<IPermissibleItem> tempResults = new List<IPermissibleItem>();

            foreach (ItemKey key in itemKeys)
            {
                core.ItemCache.RequestItem(key);
            }

            core.ItemCache.ExecuteQueue();
            foreach (ItemKey key in itemKeys)
            {
                try
                {
                    if (core.ItemCache.ContainsItem(key))
                    {
                        NumberedItem thisItem = core.ItemCache[key];

                        if (thisItem != null)
                        {
                            if (thisItem is IPermissibleItem)
                            {
                                tempResults.Add((IPermissibleItem)thisItem);
                            }
                            if (thisItem is IPermissibleSubItem)
                            {
                                tempResults.Add(((IPermissibleSubItem)thisItem).PermissiveParent);
                            }
                            results.Add((ISearchableItem)thisItem);
                        }
                    }
                    else
                    {
                        totalResults--;
                    }
                }
                catch (InvalidItemException)
                {
                }
            }

            if (tempResults.Count > 0)
            {
                core.AcessControlCache.CacheGrants(tempResults);
            }

            return new SearchResult(results, totalResults);
        }
Example #13
0
        public static void LoadApplication(Core core, AppPrimitives primitive, ApplicationEntry ae)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            if (!core.LoadedApplication(ae))
            {
                Application newApplication = GetApplication(core, primitive, ae);

                if (newApplication != null)
                {
                    if ((newApplication.GetAppPrimitiveSupport() & primitive) == primitive
                        || primitive == AppPrimitives.Any)
                    {
                        newApplication.Initialise(core);

                        if (core.Template != null)
                        {
                            core.Template.AddPageAssembly(ae.Assembly);

                            if (ae.HasStyleSheet)
                            {
                                VariableCollection styleSheetVariableCollection = core.Template.CreateChild("style_sheet_list");

                                styleSheetVariableCollection.Parse("URI", @"/styles/applications/" + ae.Key + @".css");
                            }

                            if (ae.HasJavascript)
                            {
                                VariableCollection javaScriptVariableCollection = core.Template.CreateChild("javascript_list");

                                javaScriptVariableCollection.Parse("URI", @"/scripts/" + ae.Key + @".js");
                            }
                        }

                        /* Initialise prose class for the application */
                        core.Prose.AddApplication(ae.Key);
                    }
                }
            }
        }
Example #14
0
        public static List<ApplicationEntry> GetStaticApplications(Core core)
        {
            List<ApplicationEntry> applicationsList = new List<ApplicationEntry>();
            Dictionary<long, ApplicationEntry> applicationsDictionary = new Dictionary<long, ApplicationEntry>();

            DataTable userApplicationsTable = GetStaticApplicationRows(core);

            if (userApplicationsTable.Rows.Count > 0)
            {
                List<long> applicationIds = new List<long>();
                foreach (DataRow applicationRow in userApplicationsTable.Rows)
                {
                    ApplicationEntry ae = new ApplicationEntry(core, applicationRow);
                    applicationsList.Add(ae);
                    applicationsDictionary.Add(ae.ApplicationId, ae);

                    applicationIds.Add(ae.ApplicationId);
                }

                /*DataTable applicationSlugsTable = core.db.Query(string.Format(@"SELECT {0}
                    FROM application_slugs al
                    WHERE application_id IN ({1})
                    AND slug_primitives & {2:0}
                    ORDER BY application_id;",
                    ApplicationEntry.APPLICATION_SLUG_FIELDS, applicationIds, (byte)owner.AppPrimitive));*/

                SelectQuery query = Item.GetSelectQueryStub(core, typeof(ApplicationSlug));
                query.AddCondition("application_id", ConditionEquality.In, applicationIds);
                //query.AddCondition(new QueryOperation("slug_primitives", QueryOperations.BinaryAnd, (byte)AppPrimitives.None), ConditionEquality.NotEqual, false);
                // Zero anyway, could be anything
                query.AddCondition("slug_static", true);
                query.AddSort(SortOrder.Ascending, "application_id");

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

                foreach (DataRow slugRow in applicationSlugsTable.Rows)
                {
                    applicationsDictionary[(long)slugRow["application_id"]].LoadSlugEx((string)slugRow["slug_slug_ex"]);
                }
            }

            return applicationsList;
        }
Example #15
0
        public static List<ApplicationEntry> GetModuleApplications(Core core, Primitive owner)
        {
            List<ApplicationEntry> applicationsList = new List<ApplicationEntry>();
            Dictionary<long, ApplicationEntry> applicationsDictionary = new Dictionary<long, ApplicationEntry>();

            System.Data.Common.DbDataReader userApplicationsReader = core.Db.ReaderQuery(GetApplicationQuery(core, owner));

            if (userApplicationsReader.HasRows)
            {
                List<long> applicationIds = new List<long>();
                while (userApplicationsReader.Read())
                {
                    ApplicationEntry ae = new ApplicationEntry(core, userApplicationsReader);
                    applicationsList.Add(ae);
                    applicationsDictionary.Add(ae.ApplicationId, ae);

                    applicationIds.Add(ae.Id);
                }

                userApplicationsReader.Close();
                userApplicationsReader.Dispose();

                SelectQuery query = ControlPanelModuleRegister.GetSelectQueryStub(core, typeof(ControlPanelModuleRegister));
                query.AddCondition("application_id", ConditionEquality.In, applicationIds);
                query.AddSort(SortOrder.Ascending, "application_id");

                System.Data.Common.DbDataReader modulesReader = core.Db.ReaderQuery(query);

                while(modulesReader.Read())
                {
                    applicationsDictionary[(int)modulesReader["application_id"]].AddModule((string)modulesReader["module_module"]);
                }

                modulesReader.Close();
                modulesReader.Dispose();
            }
            else
            {
                userApplicationsReader.Close();
                userApplicationsReader.Dispose();
            }

            return applicationsList;
        }
        public void ApplicationInstall(object sender, EventArgs e)
        {
            AuthoriseRequestSid();

            int id;

            try
            {
                id = int.Parse(core.Http.Query["id"]);
            }
            catch
            {
                core.Display.ShowMessage("Error", "Error!");
                return;
            }

            /*try
            {*/
            ApplicationEntry ae = new ApplicationEntry(core, id);
            bool success = ae.Install(core, core.Session.LoggedInMember, Owner);
            /*}
            catch
            {
            }*/

            if (success)
            {
                SetRedirectUri(BuildUri());
                core.Display.ShowMessage("Application Installed", "The application has been installed to your profile.");
            }
            else
            {
                SetRedirectUri(BuildUri());
                core.Display.ShowMessage("Application Not Installed", "The application has not been installed to your profile.");
            }
        }
Example #17
0
        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;
        }
Example #18
0
 internal bool LoadedApplication(ApplicationEntry ae)
 {
     if (loadedApplicationIds.Contains(ae.Id))
     {
         return true;
     }
     else
     {
         loadedApplicationIds.Add(ae.Id);
         return false;
     }
 }
Example #19
0
        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;
        }
Example #20
0
        private void loadAssemblies()
        {
            if (loadedAssemblies == null)
            {
                object o = Cache.GetCached("Applications");

                if (o != null && o is Dictionary<string, ItemKey>)
                {
                    loadedAssemblies = (Dictionary<string, ItemKey>)o;
                }
                else
                {
                    loadedAssemblies = new Dictionary<string, ItemKey>(16, StringComparer.Ordinal);
                }

                AssemblyName[] assemblies = Assembly.Load(new AssemblyName("BoxSocial.FrontEnd")).GetReferencedAssemblies();
                List<string> applicationNames = new List<string>();

                foreach (AssemblyName an in assemblies)
                {
                    if (!loadedAssemblies.ContainsKey(an.Name))
                    {
                        applicationNames.Add(an.Name);
                    }
                }

                SelectQuery query = Item.GetSelectQueryStub(this, typeof(ApplicationEntry));
                query.AddCondition("application_assembly_name", ConditionEquality.In, applicationNames);

                System.Data.Common.DbDataReader applicationReader = db.ReaderQuery(query);

                ItemCache.RegisterType(typeof(ApplicationEntry));

                while (applicationReader.Read())
                {
                    ApplicationEntry ae = new ApplicationEntry(this, applicationReader);
                    ItemCache.RegisterItem(ae);
                    loadedAssemblies.Add(ae.AssemblyName, ae.ItemKey);

                    if (Prose != null)
                    {
                        Prose.AddApplication(ae.Key);
                    }
                }

                applicationReader.Close();
                applicationReader.Dispose();

                if (loadedAssemblies != null)
                {
                    Cache.SetCached("Applications", loadedAssemblies, new TimeSpan(1, 0, 0), CacheItemPriority.Default);
                }
            }
        }
Example #21
0
 public static string Uri(Core core, ApplicationEntry anApplication)
 {
     return core.Hyperlink.AppendSid(string.Format("{0}comments",
         anApplication.UriStub));
 }
Example #22
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="db"></param>
        /// <param name="userName"></param>
        /// <param name="eMail"></param>
        /// <param name="password"></param>
        /// <param name="passwordConfirm"></param>
        /// <returns>Null if registration failed</returns>
        public static User Register(Core core, string userName, string eMail, string password, string passwordConfirm)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            Mysql db = core.Db;
            SessionState session = core.Session;

            string passwordClearText = password;

            if (!CheckUserNameUnique(db, userName))
            {
                return null;
            }

            if (!CheckUserNameValid(userName))
            {
                return null;
            }

            password = VerifyPasswordMatch(password, passwordConfirm);

            if (password == "")
            {
                return null;
            }

            string activateKey = User.GenerateActivationSecurityToken();

            InsertQuery query = new InsertQuery("user_keys");
            query.AddField("user_name", userName);
            query.AddField("user_name_lower", userName.ToLower());
            query.AddField("user_domain", "");
            query.AddField("user_name_first", userName[0].ToString().ToLower());

            db.BeginTransaction();
            long userId = db.Query(query);

            if (userId < 0)
            {
                db.RollBackTransaction();
                throw new InvalidUserException();
            }

            query = new InsertQuery("user_info");
            query.AddField("user_id", userId);
            query.AddField("user_name", userName);
            query.AddField("user_alternate_email", eMail);
            query.AddField("user_password", password);
            query.AddField("user_reg_date_ut", UnixTime.UnixTimeStamp());
            query.AddField("user_activate_code", activateKey);
            query.AddField("user_reg_ip", session.IPAddress.ToString());
            query.AddField("user_home_page", "/profile");
            query.AddField("user_bytes", 0);
            query.AddField("user_status_messages", 0);
            query.AddField("user_show_bbcode", 0x07);
            query.AddField("user_show_custom_styles", true);
            query.AddField("user_email_notifications", true);
            query.AddField("user_new_password", "");
            query.AddField("user_last_visit_ut", -30610224000L);
            query.AddField("user_language", "en");

            if (db.Query(query) < 0)
            {
                throw new InvalidUserException();
            }

            query = new InsertQuery("user_profile");
            query.AddField("user_id", userId);
            query.AddField("profile_date_of_birth_ut", -30610224000L);
            // TODO: ACLs

            db.Query(query);

            User newUser = new User(core, userId);
            UserEmail registrationEmail = UserEmail.Create(core, newUser, eMail, EmailAddressTypes.Personal, true);

            // Install a couple of applications
            try
            {
                ApplicationEntry profileAe = new ApplicationEntry(core, "Profile");
                profileAe.Install(core, newUser);
            }
            catch
            {
            }

            try
            {
                ApplicationEntry mailAe = new ApplicationEntry(core, "Mail");
                mailAe.Install(core, newUser);
            }
            catch
            {
            }

            try
            {
                ApplicationEntry galleryAe = new ApplicationEntry(core, "Gallery");
                galleryAe.Install(core, newUser);
            }
            catch
            {
            }

            try
            {
                ApplicationEntry guestbookAe = new ApplicationEntry(core, "GuestBook");
                guestbookAe.Install(core, newUser);
            }
            catch
            {
            }

            try
            {
                ApplicationEntry groupsAe = new ApplicationEntry(core, "Groups");
                groupsAe.Install(core, newUser);
            }
            catch
            {
            }

            try
            {
                ApplicationEntry networksAe = new ApplicationEntry(core, "Networks");
                networksAe.Install(core, newUser);
            }
            catch
            {
            }

            try
            {
                ApplicationEntry calendarAe = new ApplicationEntry(core, "Calendar");
                calendarAe.Install(core, newUser);
            }
            catch
            {
            }

            string activateUri = string.Format("{0}register/?mode=activate&id={1}&key={2}",
                core.Hyperlink.Uri, userId, activateKey);

            Template emailTemplate = new Template(core.Http.TemplateEmailPath, "registration_welcome.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", userName);
            emailTemplate.Parse("U_ACTIVATE", activateUri);
            emailTemplate.Parse("USERNAME", userName);
            emailTemplate.Parse("PASSWORD", passwordClearText);

            core.Email.SendEmail(eMail, "Activate your account. Welcome to " + core.Settings.SiteTitle, emailTemplate);

            Access.CreateAllGrantsForOwner(core, newUser);
            Access.CreateGrantForPrimitive(core, newUser, User.GetEveryoneGroupKey(core), "VIEW");
            Access.CreateGrantForPrimitive(core, newUser, User.GetEveryoneGroupKey(core), "VIEW_STATUS");
            Access.CreateGrantForPrimitive(core, newUser, Friend.GetFriendsGroupKey(core), "COMMENT");
            Access.CreateGrantForPrimitive(core, newUser, Friend.GetFriendsGroupKey(core), "VIEW_FRIENDS");
            Access.CreateGrantForPrimitive(core, newUser, Friend.GetFamilyGroupKey(core), "VIEW_FAMILY");

            core.Search.Index(newUser);

            return newUser;
        }
Example #23
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string comment;
            long itemId;
            long itemTypeId;
            ItemKey itemKey = null;
            ICommentableItem thisItem = null;
            long commentId = -1;
            bool isAjax = false;
            ApplicationEntry ae = null;

            if (Request["ajax"] == "true")
            {
                isAjax = true;
            }

            string mode = Request.QueryString["mode"];

            if (mode == "quote")
            {
                template.SetTemplate("posting.comment.html");

                try
                {
                    itemId = long.Parse((string)Request.QueryString["item"]);
                }
                catch
                {
                    core.Response.SendRawText("errorFetchingComment", "");
                    return;
                }

                DataTable commentsTable = db.Query(string.Format("SELECT ui.user_name, c.comment_text FROM comments c LEFT JOIN user_info ui ON c.user_id = ui.user_id WHERE comment_id = {0}",
                    itemId));

                if (commentsTable.Rows.Count == 1)
                {
                    string quotedComment = string.Format("\n\n[quote=\"{0}\"]{1}[/quote]",
                        (string)commentsTable.Rows[0]["user_name"], (string)commentsTable.Rows[0]["comment_text"]);

                    template.Parse("COMMENT_TEXT", quotedComment);
                }
                else
                {
                    core.Response.SendRawText("errorFetchingComment", "");
                }

                return;
            }

            if (mode == "fetch")
            {
                try
                {
                    itemId = long.Parse((string)Request.QueryString["item"]);
                }
                catch
                {
                    core.Response.SendRawText("errorFetchingComment", "");
                    return;
                }

                DataTable commentsTable = db.Query(string.Format("SELECT ui.user_name, c.comment_text FROM comments c LEFT JOIN user_info ui ON c.user_id = ui.user_id WHERE comment_id = {0}",
                    itemId));

                if (commentsTable.Rows.Count == 1)
                {
                    core.Response.SendRawText("commentFetched", (string.Format("\n\n[quote=\"{0}\"]{1}[/quote]",
                        (string)commentsTable.Rows[0]["user_name"], (string)commentsTable.Rows[0]["comment_text"])));
                }
                else
                {
                    core.Response.SendRawText("errorFetchingComment", "");
                }

                return;
            }

            if (mode == "load")
            {
                try
                {
                    itemId = long.Parse((string)core.Http.Query["item"]);
                    itemTypeId = long.Parse((string)core.Http.Query["type"]);
                }
                catch
                {
                    core.Response.SendRawText("errorFetchingComment", "");
                    return;
                }

                try
                {
                    // This isn't the most elegant fix, but it works
                    if (core.IsPrimitiveType(itemTypeId))
                    {
                        ae = core.GetApplication("GuestBook");
                    }
                    else
                    {
                        ItemType itemType = new ItemType(core, itemTypeId);
                        if (itemType.ApplicationId == 0)
                        {
                            ae = core.GetApplication("GuestBook");
                        }
                        else
                        {
                            ae = new ApplicationEntry(core, itemType.ApplicationId);
                        }
                    }

                    BoxSocial.Internals.Application.LoadApplication(core, AppPrimitives.Any, ae);
                }
                catch (InvalidApplicationException)
                {
                    core.Response.ShowMessage("invalidComment", "Invalid Comment", "The comments you have attempted to fetch are invalid. (0x01)");
                    return;
                }

                try
                {
                    thisItem = (ICommentableItem)NumberedItem.Reflect(core, new ItemKey(itemId, itemTypeId));
                }
                catch (Exception ex)
                {
                    // Only catch genuine InvalidItemException throws
                    if ((ex.GetType() == typeof(TargetInvocationException) && ex.InnerException.GetType().IsSubclassOf(typeof(InvalidItemException))) || ex.GetType().IsSubclassOf(typeof(InvalidItemException)))
                    {
                        core.Response.ShowMessage("invalidItem", "Item no longer exists", "Cannot load the comments as the item no longer exists.");
                    }
                    throw ex;
                }

                Template template = new Template("pane.comments.html");
                template.Medium = core.Template.Medium;
                template.SetProse(core.Prose);

                template.Parse("U_SIGNIN", Core.Hyperlink.BuildLoginUri());

                if (thisItem is IPermissibleItem)
                {
                    if (!((IPermissibleItem)thisItem).Access.Can("VIEW"))
                    {
                        core.Response.ShowMessage("accessDenied", "Access Denied", "The you do not have access to these comments");
                        return;
                    }

                    if (((IPermissibleItem)thisItem).Access.Can("COMMENT"))
                    {
                        template.Parse("CAN_COMMENT", "TRUE");
                    }
                }

                if (thisItem is IPermissibleSubItem)
                {
                    if (!((IPermissibleSubItem)thisItem).PermissiveParent.Access.Can("VIEW"))
                    {
                        core.Response.ShowMessage("accessDenied", "Access Denied", "The you do not have access to these comments");
                        return;
                    }

                    if (((IPermissibleSubItem)thisItem).PermissiveParent.Access.Can("COMMENT"))
                    {
                        template.Parse("CAN_COMMENT", "TRUE");
                    }
                }

                if (thisItem is ICommentableItem)
                {
                    core.Display.DisplayComments(template, ((ICommentableItem)thisItem).Owner, 1, (ICommentableItem)thisItem);
                    //List<Comment> comments = Comment.GetComments(core, new ItemKey(itemId, itemTypeId), SortOrder.Ascending, 1, 10, null);

                    core.Response.SendRawText("fetchSuccess", template.ToString());
                }
                else
                {
                    core.Response.ShowMessage("invalidComment", "Invalid Comment", "The comments you have attempted to fetch are invalid. (0x07)");
                }
                return;
            }

            if (mode == "report")
            {
                try
                {
                    itemId = long.Parse((string)Request.QueryString["item"]);
                }
                catch
                {
                    core.Response.ShowMessage("errorReportingComment", "Error", "The comment you have reported is invalid.");
                    return;
                }

                // only logged in members can report comment spam
                if (session.IsLoggedIn)
                {
                    // has the user reported the comment before?
                    DataTable reportsTable = db.Query(string.Format("SELECT report_id FROM spam_reports WHERE comment_id = {0} AND user_id = {1};",
                        itemId, loggedInMember.UserId));

                    if (reportsTable.Rows.Count == 0)
                    {
                        db.BeginTransaction();
                        db.UpdateQuery(string.Format("UPDATE comments SET comment_spam_score = comment_spam_score + 2 WHERE comment_id = {0}",
                            itemId));

                        // add a log entry that the user reported this comment
                        db.UpdateQuery(string.Format("INSERT INTO spam_reports (comment_id, user_id, report_time_ut) VALUES ({0}, {1}, UNIX_TIMESTAMP());",
                            itemId, loggedInMember.UserId));
                    }
                    else
                    {
                        core.Response.ShowMessage("alreadyReported", "Already Reported", "You have already reported this comment as SPAM.");
                    }
                }
                core.Response.ShowMessage("commentReported", "Reported Comment", "You have successfully reported a comment.");
                return;
            }

            if (mode == "delete")
            {
                // select the comment
                try
                {
                    Comment.Delete(core);
                }
                catch (InvalidCommentException)
                {
                    core.Response.ShowMessage("errorDeletingComment", "Error", "An error was encountered while deleting the comment, the comment has not been deleted.");
                }
                catch (PermissionDeniedException)
                {
                    core.Response.ShowMessage("permissionDenied", "Permission Denied", "You do not have the permissions to delete this comment.");
                }

                if (core.ResponseFormat == ResponseFormats.Xml)
                {
                    core.Response.SendRawText("commentDeleted", "You have successfully deleted the comment.");
                }
                else
                {
                    core.Response.ShowMessage("commentDeleted", "Comment Deleted", "You have successfully deleted the comment");
                }
                return;
            }

            // else we post a comment
            {
                try
                {
                    comment = (string)Request.Form["comment"];
                    itemId = core.Functions.RequestLong("item_id", 0);
                    itemTypeId = core.Functions.RequestLong("item_type_id", 0);
                    itemKey = new ItemKey(itemId, itemTypeId);
                }
                catch
                {
                    core.Response.ShowMessage("invalidComment", "Invalid Comment", "The comment you have attempted to post is invalid. (0x02)");
                    return;
                }

                if (itemId == 0 || itemTypeId == 0)
                {
                    core.Response.ShowMessage("invalidComment", "Invalid Comment", "The comment you have attempted to post is invalid. (0x08)");
                    return;
                }

                try
                {
                    // This isn't the most elegant fix, but it works
                    if (core.IsPrimitiveType(itemTypeId))
                    {
                        ae = core.GetApplication("GuestBook");
                    }
                    else
                    {
                        ItemType itemType = new ItemType(core, itemTypeId);
                        if (itemType.ApplicationId == 0)
                        {
                            ae = core.GetApplication("GuestBook");
                        }
                        else
                        {
                            ae = new ApplicationEntry(core, itemType.ApplicationId);
                        }
                    }

                    BoxSocial.Internals.Application.LoadApplication(core, AppPrimitives.Any, ae);
                }
                catch (InvalidApplicationException)
                {
                    core.Response.ShowMessage("invalidComment", "Invalid Comment", "The comment you have attempted to post is invalid. (0x03)");
                    return;
                }

                /* save comment in the database */

                NumberedItem item = null;
                try
                {
                    item = NumberedItem.Reflect(core, new ItemKey(itemId, itemTypeId));
                    if (item is ICommentableItem)
                    {
                        thisItem = (ICommentableItem)item;

                        IPermissibleItem pItem = null;
                        if (item is IPermissibleItem)
                        {
                            pItem = (IPermissibleItem)item;
                        }
                        else if (item is IPermissibleSubItem)
                        {
                            pItem = ((IPermissibleSubItem)item).PermissiveParent;
                        }
                        else
                        {
                            pItem = thisItem.Owner;
                        }

                        if (!pItem.Access.Can("COMMENT"))
                        {
                            core.Response.ShowMessage("notLoggedIn", "Permission Denied", "You do not have the permissions to post a comment to this item.");
                        }
                    }
                    else
                    {
                        core.Response.ShowMessage("invalidComment", "Invalid Item", "The comment you have attempted to post is invalid. (0x07)");
                    }
                }
                catch (InvalidItemException)
                {
                    core.Response.ShowMessage("invalidComment", "Invalid Comment", "The comment you have attempted to post is invalid. (0x04)");
                }

                Comment commentObject = null;
                try
                {
                    commentObject = Comment.Create(Core, itemKey, comment);
                    commentId = commentObject.CommentId;

                    if (item != null)
                    {
                        if (item is IActionableItem || item is IActionableSubItem)
                        {
                            //ae.TouchFeed(core.Session.LoggedInMember, item);
                        }
                        else
                        {
                            ae.PublishToFeed(core, core.Session.LoggedInMember, commentObject, item, Functions.SingleLine(core.Bbcode.Flatten(commentObject.Body)));
                        }
                        ICommentableItem citem = (ICommentableItem)item;

                        citem.CommentPosted(new CommentPostedEventArgs(commentObject, core.Session.LoggedInMember, new ItemKey(itemId, itemTypeId)));
                    }

                    Comment.Commented(core, itemKey);

                    // Notify everyone who comments on the item by default, track this so people can unsubscribe later
                    //NotificationSubscription.Create(core, loggedInMember, itemKey);
                    try
                    {
                        Subscription.SubscribeToItem(core, itemKey);
                    }
                    catch (AlreadySubscribedException)
                    {
                        // not a problem
                    }

                }
                catch (NotLoggedInException)
                {
                    core.Response.ShowMessage("notLoggedIn", "Not Logged In", "You must be logged in to post a comment.");
                }
                catch (CommentFloodException)
                {
                    core.Response.ShowMessage("rejectedByFloodControl", "Posting Too Fast", "You are posting too fast. Please wait a minute and try again.");
                }
                catch (CommentTooLongException)
                {
                    core.Response.ShowMessage("commentTooLong", "Comment Too Long", "The comment you have attempted to post is too long, maximum size is 511 characters.");
                }
                catch (CommentTooShortException)
                {
                    core.Response.ShowMessage("commentTooShort", "Comment Too Short", "The comment you have attempted to post is too short, must be longer than two characters.");
                }
                catch (InvalidCommentException)
                {
                    core.Response.ShowMessage("invalidComment", "Invalid Comment", "The comment you have attempted to post is invalid. (0x05)");
                }
                catch (Exception ex)
                {
                    core.Response.ShowMessage("invalidComment", "Invalid Comment", "The comment you have attempted to post is invalid. (0x06) " + ex.ToString());
                }

                if (core.ResponseFormat == ResponseFormats.Xml)
                {
                    Template ct = new Template(Server.MapPath("./templates"), "pane.comment.html");
                    template.Medium = core.Template.Medium;
                    ct.SetProse(core.Prose);

                    if (core.Session.IsLoggedIn && loggedInMember != null)
                    {
                        ct.Parse("LOGGED_IN", "TRUE");
                        ct.Parse("USER_DISPLAY_NAME", core.Session.LoggedInMember.DisplayName);
                        ct.Parse("USER_TILE", core.Session.LoggedInMember.Tile);
                        ct.Parse("USER_ICON", core.Session.LoggedInMember.Icon);
                    }

                    if (item != null)
                    {
                        template.Parse("ITEM_ID", item.Id.ToString());
                        template.Parse("ITEM_TYPE", item.ItemKey.TypeId.ToString());
                    }

                    VariableCollection commentsVariableCollection = ct.CreateChild("comment-list");

                    //commentsVariableCollection.ParseRaw("COMMENT", Bbcode.Parse(HttpUtility.HtmlEncode(comment), core.session.LoggedInMember));
                    core.Display.ParseBbcode(commentsVariableCollection, "COMMENT", comment);
                    // TODO: finish comments this
                    commentsVariableCollection.Parse("ID", commentId.ToString());
                    commentsVariableCollection.Parse("TYPE_ID", ItemKey.GetTypeId(core, typeof(Comment)));
                    commentsVariableCollection.Parse("USERNAME", loggedInMember.DisplayName);
                    commentsVariableCollection.Parse("USER_ID", loggedInMember.Id.ToString());
                    commentsVariableCollection.Parse("U_PROFILE", loggedInMember.ProfileUri);
                    commentsVariableCollection.Parse("U_QUOTE", core.Hyperlink.BuildCommentQuoteUri(commentId));
                    commentsVariableCollection.Parse("U_REPORT", core.Hyperlink.BuildCommentReportUri(commentId));
                    commentsVariableCollection.Parse("U_DELETE", core.Hyperlink.BuildCommentDeleteUri(commentId));
                    commentsVariableCollection.Parse("TIME", tz.DateTimeToString(tz.Now));
                    commentsVariableCollection.Parse("USER_TILE", loggedInMember.Tile);
                    commentsVariableCollection.Parse("USER_ICON", loggedInMember.Icon);

                    try
                    {
                        if (core.Session.IsLoggedIn)
                        {
                            if (thisItem.Owner.CanModerateComments(loggedInMember))
                            {
                                commentsVariableCollection.Parse("MODERATE", "TRUE");
                            }

                            if (thisItem.Owner.IsItemOwner(loggedInMember))
                            {
                                commentsVariableCollection.Parse("OWNER", "TRUE");
                                commentsVariableCollection.Parse("NORMAL", "FALSE");
                            }
                            else
                            {
                                commentsVariableCollection.Parse("OWNER", "FALSE");
                                commentsVariableCollection.Parse("NORMAL", "TRUE");
                            }
                        }
                        else
                        {
                            commentsVariableCollection.Parse("OWNER", "FALSE");
                            commentsVariableCollection.Parse("NORMAL", "TRUE");
                        }
                    }
                    catch (Exception ex)
                    {
                        commentsVariableCollection.Parse("NORMAL", "FALSE");
                    }

                    core.Response.SendRawText("comment", ct.ToString());

                    if (db != null)
                    {
                        db.CloseConnection();
                    }
                    Response.End();
                    return;
                }
                else
                {
                    string redirect = Request["redirect"];
                    if (!string.IsNullOrEmpty(redirect))
                    {
                        template.Parse("REDIRECT_URI", redirect);
                    }
                    core.Display.ShowMessage("Comment Posted", "Your comment has been successfully posted.");
                }
            }
        }
Example #24
0
        public static OAuthApplication Create(Core core, string title, string slug, string description)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            core.Db.BeginTransaction();

            InsertQuery iQuery = new InsertQuery(typeof(ApplicationEntry));
            iQuery.AddField("application_name", slug);
            iQuery.AddField("user_id", core.LoggedInMemberId);
            iQuery.AddField("application_date_ut", UnixTime.UnixTimeStamp());
            iQuery.AddField("application_title", title);
            iQuery.AddField("application_description", description);
            iQuery.AddField("application_primitive", false);
            iQuery.AddField("application_primitives", (byte)AppPrimitives.None);
            iQuery.AddField("application_comment", false);
            iQuery.AddField("application_rating", false);
            iQuery.AddField("application_style", false);
            iQuery.AddField("application_script", false);
            iQuery.AddField("application_type", (byte)ApplicationType.OAuth);
            iQuery.AddField("application_cron_enabled", false);
            iQuery.AddField("application_cron_frequency", 0);

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

            ApplicationEntry newApplication = new ApplicationEntry(core, applicationId);

            iQuery = new InsertQuery(typeof(OAuthApplication));
            iQuery.AddField("application_id", applicationId);
            iQuery.AddField("application_website", string.Empty);
            iQuery.AddField("application_api_key", OAuth.GeneratePublic());
            iQuery.AddField("application_api_secret", OAuth.GenerateSecret());
            iQuery.AddField("application_api_callback", string.Empty);

            core.Db.Query(iQuery);

            OAuthApplication newApp = new OAuthApplication(core, newApplication);

            ApplicationDeveloper developer = ApplicationDeveloper.Create(core, newApplication, core.Session.LoggedInMember);

            try
            {
                ApplicationEntry profileAe = core.GetApplication("Profile");
                profileAe.Install(core, newApplication);
            }
            catch
            {
            }

            try
            {
                ApplicationEntry guestbookAe = core.GetApplication("GuestBook");
                guestbookAe.Install(core, newApplication);
            }
            catch
            {
            }

            try
            {
                ApplicationEntry galleryAe = core.GetApplication("Gallery");
                galleryAe.Install(core, newApplication);
            }
            catch
            {
            }

            return newApp;
        }
Example #25
0
        public static ItemType Create(Core core, Type type, ApplicationEntry ae)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            string ns = Item.GetNamespace(type);

            ItemType it = (ItemType)Item.Create(core, typeof(ItemType),
                                      new FieldValuePair("type_namespace", ns),
                                      new FieldValuePair("type_application_id", ae.Id.ToString()),
                                      new FieldValuePair("type_commentable", (typeof(ICommentableItem).IsAssignableFrom(type))),
                                      new FieldValuePair("type_likeable", (typeof(ILikeableItem).IsAssignableFrom(type))),
                                      new FieldValuePair("type_rateable", (typeof(IRateableItem).IsAssignableFrom(type))),
                                      new FieldValuePair("type_subscribeable", (typeof(ISubscribeableItem).IsAssignableFrom(type))),
                                      new FieldValuePair("type_viewable", (typeof(IViewableItem).IsAssignableFrom(type))),
                                      new FieldValuePair("type_shareable", (typeof(IShareableItem).IsAssignableFrom(type))),
                                      new FieldValuePair("type_notifiable", (typeof(INotifiableItem).IsAssignableFrom(type))),
                                      new FieldValuePair("type_embeddable", (typeof(IEmbeddableItem).IsAssignableFrom(type))),
                                      new FieldValuePair("type_primitive", type.IsSubclassOf(typeof(Primitive))));

            return it;
        }
Example #26
0
        public OAuthApplication(Core core, ApplicationEntry ae)
            : base(core, false)
        {
            this.db = db;

            SelectQuery query = GetSelectQueryStub(core);
            query.AddCondition(new DataField(typeof(OAuthApplication), "application_id"), ae.Id);

            System.Data.Common.DbDataReader applicationReader = db.ReaderQuery(query);

            if (applicationReader.HasRows)
            {
                applicationReader.Read();

                loadItemInfo(applicationReader);
                loadApplication(applicationReader);

                applicationReader.Close();
                applicationReader.Dispose();
            }
            else
            {
                applicationReader.Close();
                applicationReader.Dispose();

                throw new InvalidApplicationException();
            }
        }
Example #27
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;
        }
        public void ApplicationSettings(object sender, EventArgs e)
        {
            template.SetTemplate("account_primitive_application_settings.html");

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

            if (id == 0)
            {
                core.Display.ShowMessage("Error", "Error!");
                return;
            }

            SelectQuery query = new SelectQuery("primitive_apps");
            query.AddFields(ApplicationEntry.GetFieldsPrefixed(core, typeof(ApplicationEntry)));
            query.AddFields(PrimitiveApplicationInfo.GetFieldsPrefixed(core, typeof(PrimitiveApplicationInfo)));
            query.AddJoin(JoinTypes.Inner, new DataField("primitive_apps", "application_id"), new DataField("applications", "application_id"));
            query.AddCondition("primitive_apps.application_id", id);
            query.AddCondition("item_id", Owner.Id);
            query.AddCondition("item_type_id", Owner.TypeId);

            DataTable applicationTable = db.Query(query);

            if (applicationTable.Rows.Count == 1)
            {
                ApplicationEntry ae = new ApplicationEntry(core, applicationTable.Rows[0]);

                //List<string> applicationPermissions = new List<string>();
                //applicationPermissions.Add("Can Access");

                template.Parse("APPLICATION_NAME", ae.Title);
                //core.Display.ParsePermissionsBox(template, "S_GAPPLICATION_PERMS", ae.Permissions, applicationPermissions);
                template.Parse("S_APPLICATION_ID", ae.ApplicationId.ToString());

                string radioChecked = " checked=\"checked\"";

                if (Owner is User)
                {
                    template.Parse("S_USER", true);

                    PrimitiveApplicationInfo ownerInfo = new PrimitiveApplicationInfo(core, Owner, ae.Id);
                    if (ownerInfo.EmailNotifications)
                    {
                        template.Parse("S_EMAIL_NOTIFICATIONS_YES", radioChecked);
                    }
                    else
                    {
                        template.Parse("S_EMAIL_NOTIFICATIONS_NO", radioChecked);
                    }
                }
            }
            else
            {
                core.Display.ShowMessage("Error", "Error!");
            }
        }
Example #29
0
        public override SearchResult DoSearch(string input, int pageNumber, Primitive filterByOwner, Type filterByType)
        {
            Initialise();

            int perPage = 10;
            int start = (pageNumber - 1) * perPage;

            List<ISearchableItem> results = new List<ISearchableItem>();
            List<ItemKey> itemKeys = new List<ItemKey>();
            List<long> applicationIds = new List<long>();

            IndexSearcher searcher = new IndexSearcher(directory);

            QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "item_string", analyzer);

            BooleanQuery query = new BooleanQuery();
            Query bodyQuery = parser.Parse(input);

            query.Add(bodyQuery, Occur.MUST);

            BooleanQuery accessQuery = new BooleanQuery();
            TermQuery accessPublicQuery = new TermQuery(new Term("item_public", "1"));
            accessQuery.Add(accessPublicQuery, Occur.SHOULD);

            if (core.Session.IsLoggedIn)
            {
                List<long> friends = core.Session.LoggedInMember.GetFriendsWithMeIds();

                BooleanQuery accessFriendQuery = new BooleanQuery();
                TermQuery friendQuery = new TermQuery(new Term("item_public", "2"));
                accessFriendQuery.Add(friendQuery, Occur.MUST);

                string userTypeId =  ItemType.GetTypeId(core, typeof(User)).ToString();
                foreach (long friendId in friends)
                {
                    BooleanQuery ownerQuery = new BooleanQuery();
                    TermQuery ownerIdQuery = new TermQuery(new Term("owner_id", friendId.ToString()));
                    TermQuery ownerTypeQuery = new TermQuery(new Term("owner_type_id", userTypeId));

                    ownerQuery.Add(ownerIdQuery, Occur.MUST);
                    ownerQuery.Add(ownerTypeQuery, Occur.MUST);

                    accessFriendQuery.Add(ownerQuery, Occur.SHOULD);
                }

                accessQuery.Add(accessFriendQuery, Occur.SHOULD);
            }

            query.Add(accessQuery, Occur.MUST);

            if (filterByType != null)
            {
                TermQuery typeQuery = new TermQuery(new Term("item_type_id", ItemType.GetTypeId(core, filterByType).ToString()));

                query.Add(typeQuery, Occur.MUST);
            }

            if (filterByOwner != null)
            {
                TermQuery ownerIdQuery = new TermQuery(new Term("owner_id", filterByOwner.Id.ToString()));
                TermQuery ownerTypeIdQuery = new TermQuery(new Term("owner_type_id", filterByOwner.TypeId.ToString()));

                query.Add(ownerIdQuery, Occur.MUST);
                query.Add(ownerTypeIdQuery, Occur.MUST);
            }

            TopScoreDocCollector collector = TopScoreDocCollector.Create(start + perPage, true);

            searcher.Search(query, collector);

            ScoreDoc[] hits = collector.TopDocs().ScoreDocs;

            int totalResults = collector.TotalHits;
            int returnResults = hits.Length;

            int end = Math.Min(hits.Length, start + perPage);

            for (int i = start; i < end; i++)
            {
                Document doc = searcher.Doc(hits[i].Doc);

                long itemId = 0;
                long itemTypeId = 0;
                long applicationId = 0;

                long.TryParse(doc.GetField("item_id").StringValue, out itemId);
                long.TryParse(doc.GetField("item_type_id").StringValue, out itemTypeId);
                long.TryParse(doc.GetField("application_id").StringValue, out applicationId);

                ItemKey key = new ItemKey(itemId, itemTypeId);

                if (!applicationIds.Contains(applicationId))
                {
                    applicationIds.Add(applicationId);
                }

                itemKeys.Add(key);
            }

            // Force each application with results to load
            for (int i = 0; i < applicationIds.Count; i++)
            {
                if (applicationIds[i] > 0)
                {
                    ApplicationEntry ae = new ApplicationEntry(core, applicationIds[i]);

                    BoxSocial.Internals.Application.LoadApplication(core, AppPrimitives.Any, ae);
                }
            }

            List<IPermissibleItem> tempResults = new List<IPermissibleItem>();

            foreach (ItemKey key in itemKeys)
            {
                core.ItemCache.RequestItem(key);
            }

            foreach (ItemKey key in itemKeys)
            {
                try
                {
                    NumberedItem thisItem = core.ItemCache[key];

                    if (thisItem != null)
                    {
                        if (thisItem is IPermissibleItem)
                        {
                            tempResults.Add((IPermissibleItem)thisItem);
                        }
                        if (thisItem is IPermissibleSubItem)
                        {
                            tempResults.Add(((IPermissibleSubItem)thisItem).PermissiveParent);
                        }
                        results.Add((ISearchableItem)thisItem);
                    }
                }
                catch (InvalidItemException)
                {
                }
            }

            if (tempResults.Count > 0)
            {
                core.AcessControlCache.CacheGrants(tempResults);
            }

            return new SearchResult(results, totalResults);
        }
        public void ApplicationUninstall(object sender, EventArgs e)
        {
            AuthoriseRequestSid();

            int id;

            try
            {
                id = int.Parse(core.Http.Query["id"]);
            }
            catch
            {
                core.Display.ShowMessage("Error", "Error!");
                return;
            }

            try
            {
                ApplicationEntry ae = new ApplicationEntry(core, id);

                bool uninstalled = false;
                switch (ae.AssemblyName)
                {
                    case "Profile":
                    case "Mail":
                    case "Gallery":
                    case "GuestBook":
                        break;
                    default:
                        if (!ae.IsPrimitive)
                        {
                            switch (ae.ApplicationType)
                            {
                                case ApplicationType.Native:
                                    ae.Uninstall(core, core.Session.LoggedInMember, Owner);
                                    uninstalled = true;
                                    break;
                                case ApplicationType.OAuth:
                                    ae.Deauthorise(core, core.Session.LoggedInMember, Owner);
                                    uninstalled = true;
                                    break;
                            }
                        }
                        break;
                }

                if (!uninstalled)
                {
                    SetRedirectUri(BuildUri());
                    core.Display.ShowMessage("Application cannot be uninstalled", "This application cannot be uninstalled from your profile.");
                }
            }
            catch
            {
            }

            SetRedirectUri(BuildUri());
            core.Display.ShowMessage("Application Uninstalled", "The application has been uninstalled from your profile.");
        }