Пример #1
0
        /// <summary>
        /// Creates a new gallery for the logged in user.
        /// </summary>
        /// <param name="core">Core token</param>
        /// <param name="parent">Parent gallery</param>
        /// <param name="title">Gallery title</param>
        /// <param name="slug">Gallery slug</param>
        /// <param name="description">Gallery description</param>
        /// <param name="permissions">Gallery permission mask</param>
        /// <returns>An instance of the newly created gallery</returns>
        public static Gallery Create(Core core, Primitive owner, Gallery parent, string title, ref string slug, string description)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            GallerySettings settings = null;
            try
            {
                settings = new GallerySettings(core, owner);
            }
            catch (InvalidGallerySettingsException)
            {
                settings = GallerySettings.Create(core, owner);
            }

            string parents = "";
            // ensure we have generated a valid slug
            slug = Gallery.GetSlugFromTitle(title, slug);

            if (!Gallery.CheckGallerySlugValid(slug))
            {
                throw new GallerySlugNotValidException();
            }

            if (!Gallery.CheckGallerySlugUnique(core.Db, parent.owner, parent.FullPath, slug))
            {
                throw new GallerySlugNotUniqueException();
            }

            if (parent != null)
            {
                ParentTree parentTree = new ParentTree();

                if (parent.Parents != null)
                {
                    foreach (ParentTreeNode ptn in parent.Parents.Nodes)
                    {
                        parentTree.Nodes.Add(new ParentTreeNode(ptn.ParentTitle, ptn.ParentSlug, ptn.ParentId));
                    }
                }

                if (parent.Id > 0)
                {
                    parentTree.Nodes.Add(new ParentTreeNode(parent.GalleryTitle, parent.Path, parent.Id));
                }

                XmlSerializer xs = new XmlSerializer(typeof(ParentTree));
                StringBuilder sb = new StringBuilder();
                StringWriter stw = new StringWriter(sb);

                xs.Serialize(stw, parentTree);
                stw.Flush();
                stw.Close();

                parents = sb.ToString();
            }

            InsertQuery iQuery = new InsertQuery("user_galleries");
            iQuery.AddField("gallery_title", title);
            iQuery.AddField("gallery_abstract", description);
            iQuery.AddField("gallery_path", slug);
            iQuery.AddField("gallery_parent_path", parent.FullPath);
            iQuery.AddField("user_id", core.LoggedInMemberId);
            iQuery.AddField("settings_id", settings.Id);
            iQuery.AddField("gallery_item_id", owner.Id);
            iQuery.AddField("gallery_item_type_id", owner.TypeId);
            iQuery.AddField("gallery_parent_id", parent.GalleryId);
            iQuery.AddField("gallery_bytes", 0);
            iQuery.AddField("gallery_items", 0);
            iQuery.AddField("gallery_item_comments", 0);
            iQuery.AddField("gallery_visits", 0);
            iQuery.AddField("gallery_hierarchy", parents);

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

            Gallery gallery = new Gallery(core, owner, galleryId);

            /* LOAD THE DEFAULT ITEM PERMISSIONS */
            Access.CreateAllGrantsForOwner(core, gallery);
            Access.CreateGrantForPrimitive(core, gallery, User.GetEveryoneGroupKey(core), "VIEW");
            Access.CreateGrantForPrimitive(core, gallery, Friend.GetFriendsGroupKey(core), "COMMENT");
            Access.CreateGrantForPrimitive(core, gallery, User.GetEveryoneGroupKey(core), "VIEW_ITEMS");
            Access.CreateGrantForPrimitive(core, gallery, Friend.GetFriendsGroupKey(core), "COMMENT_ITEMS");
            Access.CreateGrantForPrimitive(core, gallery, Friend.GetFriendsGroupKey(core), "RATE_ITEMS");

            return gallery;
        }
Пример #2
0
        /// <summary>
        /// Hook showing gallery items on a network profile.
        /// </summary>
        /// <param name="e">Hook event arguments</param>
        public void ShowNetworkGallery(HookEventArgs e)
        {
            Network theNetwork = (Network)e.Owner;

            Template template = new Template(Assembly.GetExecutingAssembly(), "viewprofilegallery");
            template.Medium = core.Template.Medium;
            template.SetProse(core.Prose);

            Gallery gallery = new Gallery(e.core, theNetwork);

            List<GalleryItem> galleryItems = gallery.GetItems(e.core, 1, 6, 0);

            template.Parse("PHOTOS", theNetwork.GalleryItems.ToString());

            foreach (GalleryItem galleryItem in galleryItems)
            {
                VariableCollection galleryVariableCollection = template.CreateChild("photo_list");

                galleryVariableCollection.Parse("TITLE", galleryItem.ItemTitle);
                galleryVariableCollection.Parse("PHOTO_URI", Gallery.BuildPhotoUri(core, theNetwork, galleryItem.Path));

                string thumbUri = string.Format("/network/{0}/images/_tiny/{1}",
                    theNetwork.NetworkNetwork, galleryItem.Path);
                galleryVariableCollection.Parse("THUMBNAIL", thumbUri);
            }

            template.Parse("U_NETWORK_GALLERY", Gallery.BuildGalleryUri(core, theNetwork));

            e.core.AddMainPanel(template);
        }
Пример #3
0
        void AccountGalleriesUpload_Show(object sender, EventArgs e)
        {
            long galleryId = core.Functions.RequestLong("gallery-id", 0);

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

            if (galleryId == 0)
            {
                // Invalid gallery
                core.Display.ShowMessage("An error occured", "An error occured");
                return;
            }

            try
            {
                Gallery gallery = new Gallery(core, Owner, galleryId);

                if (!gallery.Access.Can("CREATE_ITEMS"))
                {
                    core.Functions.Generate403();
                    return;
                }

                breadCrumbParts.Add(new string[] { "!" + gallery.Uri, gallery.GalleryTitle });

                CheckBox publishToFeedCheckBox = new CheckBox("publish-feed");
                publishToFeedCheckBox.IsChecked = true;

                CheckBox highQualityCheckBox = new CheckBox("high-quality");
                highQualityCheckBox.IsChecked = false;

                core.Display.ParseLicensingBox(template, "S_GALLERY_LICENSE", 0);

                template.Parse("S_PUBLISH_FEED", publishToFeedCheckBox);
                template.Parse("S_HIGH_QUALITY", highQualityCheckBox);
                template.Parse("S_GALLERY_ID", galleryId.ToString());

                core.Display.ParseClassification(template, "S_PHOTO_CLASSIFICATION", Classifications.Everyone);

                breadCrumbParts.Add(new string[] { "upload?gallery-id=" + galleryId.ToString(), core.Prose.GetString("UPLOAD_PHOTO") });

                page.Owner.ParseBreadCrumbs(breadCrumbParts);
            }
            catch (InvalidGalleryException)
            {
                core.Display.ShowMessage("An error occured", "An error occured");
                return;
            }

            if (core.Http.Form["save"] != null)
            {
                AccountGalleriesUpload_Save(sender, e);
            }
        }
Пример #4
0
        void AccountApplicationIcon_Save(object sender, EventArgs e)
        {
            AuthoriseRequestSid();

            if (Owner.GetType() != typeof(ApplicationEntry))
            {
                DisplayGenericError();
                return;
            }

            ApplicationEntry ae = (ApplicationEntry)Owner;

            string meSlug = "application-icons";

            BoxSocial.Applications.Gallery.Gallery profileGallery;
            try
            {
                profileGallery = new BoxSocial.Applications.Gallery.Gallery(core, ae, meSlug);
            }
            catch (InvalidGalleryException)
            {
                BoxSocial.Applications.Gallery.Gallery root = new BoxSocial.Applications.Gallery.Gallery(core, ae);
                profileGallery = BoxSocial.Applications.Gallery.Gallery.Create(core, ae, root, "Application Icons", ref meSlug, "Application Icons");
            }

            if (profileGallery != null)
            {
                string title = "";
                string description = "";
                string slug = "";

                try
                {
                    slug = core.Http.Files["photo-file"].FileName;
                }
                catch
                {
                    DisplayGenericError();
                    return;
                }

                try
                {
                    if (ae.GalleryIcon > 0)
                    {
                        try
                        {
                            GalleryItem gi = new GalleryItem(core, ae.GalleryIcon);
                            gi.Delete();
                        }
                        catch
                        {
                        }
                    }

                    MemoryStream stream = new MemoryStream();
                    core.Http.Files["photo-file"].InputStream.CopyTo(stream);

                    db.BeginTransaction();

                    GalleryItem galleryItem = GalleryItem.Create(core, ae, profileGallery, title, ref slug, core.Http.Files["photo-file"].FileName, core.Http.Files["photo-file"].ContentType, (ulong)core.Http.Files["photo-file"].ContentLength, description, 0, Classifications.Everyone, stream, false);

                    db.UpdateQuery(string.Format("UPDATE applications SET application_gallery_icon = {0} WHERE application_id = {1}",
                        galleryItem.Id, ae.Id));

                    //db.CommitTransaction();
                    stream.Close();

                    SetRedirectUri(BuildUri());
                    core.Display.ShowMessage("Icon uploaded", "You have successfully uploaded a new application icon.");
                    return;
                }
                catch (GalleryItemTooLargeException)
                {
                    SetError("The photo you have attempted to upload is too big, you can upload photos up to 1.2 MiB in size.");
                    return;
                }
                catch (GalleryQuotaExceededException)
                {
                    SetError("You do not have enough quota to upload this photo. Try resizing the image before uploading or deleting images you no-longer need. Smaller images use less quota.");
                    return;
                }
                catch (InvalidGalleryItemTypeException)
                {
                    SetError("You have tried to upload a file type that is not a picture. You are allowed to upload PNG and JPEG images.");
                    return;
                }
                catch (InvalidGalleryFileNameException)
                {
                    core.Display.ShowMessage("Submission failed", "Submission failed, try uploading with a different file name.");
                    return;
                }
            }
            else
            {
                DisplayGenericError();
                return;
            }
        }
Пример #5
0
        public override void ExecuteCall(string callName)
        {
            switch (callName)
            {
                case "list_galleries":
                    {
                        long ownerId = core.Functions.RequestLong("owner_id", core.Session.LoggedInMember.Id);
                        long ownerTypeId = core.Functions.RequestLong("owner_type_id", core.Session.LoggedInMember.ItemKey.TypeId);
                        long galleryId = core.Functions.RequestLong("gallery_id", 0);
                        ItemKey ownerKey = new ItemKey(ownerId, ownerTypeId);

                        Gallery gallery = null;
                        if (galleryId > 0)
                        {
                            gallery = new Gallery(core, galleryId);
                        }
                        else
                        {
                            core.PrimitiveCache.LoadPrimitiveProfile(ownerKey);
                            Primitive owner = core.PrimitiveCache[ownerKey];

                            gallery = new Gallery(core, owner);
                        }

                        if (gallery != null)
                        {
                            if (gallery.Access.Can("VIEW"))
                            {
                                List<Gallery> galleries = gallery.GetGalleries();
                                List<Gallery> responseGalleries = new List<Gallery>();

                                foreach (Gallery g in galleries)
                                {
                                    if (gallery.Access.Can("VIEW"))
                                    {
                                        responseGalleries.Add(g);
                                    }
                                }

                                core.Response.WriteObject(responseGalleries);
                            }
                            else
                            {

                            }
                        }
                    }
                    break;
                case "list_gallery_items":
                    {
                        long galleryId = core.Functions.RequestLong("gallery_id", 0);
                        long offsetId = core.Functions.RequestLong("offset_id", 0);

                        Gallery gallery = null;
                        if (galleryId > 0)
                        {
                            gallery = new Gallery(core, galleryId);
                        }

                        if (gallery != null)
                        {
                            if (gallery.Access.Can("VIEW_ITEMS"))
                            {
                                List<GalleryItem> galleryItems = gallery.GetItems(core, 1, 12, offsetId);

                                core.Response.WriteObject(galleryItems);
                            }
                        }
                    }
                    break;
                case "gallery_item":
                    GalleryItem.Show(core);
                    break;
                case "upload":
                    Gallery.Upload(core);
                    break;
            }
        }
Пример #6
0
        void AccountGalleriesManage_New(object sender, ModuleModeEventArgs e)
        {
            SetTemplate("account_galleries_add");

            long galleryId = core.Functions.RequestLong("id", 0);
            bool edit = false;

            if (e.Mode == "edit")
            {
                edit = true;
            }

            List<string> permissions = new List<string>();
            permissions.Add("Can Read");
            permissions.Add("Can Comment");

            if (!edit)
            {
                if (galleryId > 0)
                {
                    try
                    {
                        Gallery pg = new Gallery(core, Owner, galleryId);

                        Dictionary<string, string> licenses = new Dictionary<string, string>();
                        DataTable licensesTable = db.Query("SELECT license_id, license_title FROM licenses");
                    }
                    catch (InvalidGalleryException)
                    {
                        core.Display.ShowMessage("Invalid", "If you have stumbled onto this page by mistake, click back in your browser.");
                        return;
                    }
                }
                else
                {
                    // New Gallery
                }
            }
            else
            {
                // edit
                template.Parse("EDIT", "TRUE");

                try
                {
                    Gallery ug = new Gallery(core, Owner, galleryId);

                    template.Parse("S_TITLE", ug.GalleryTitle);
                    template.Parse("S_DESCRIPTION", ug.GalleryAbstract);

                    Dictionary<string, string> licenses = new Dictionary<string, string>();
                    DataTable licensesTable = db.Query("SELECT license_id, license_title FROM licenses");
                }
                catch (InvalidGalleryException)
                {
                    core.Display.ShowMessage("Invalid", "If you have stumbled onto this page by mistake, click back in your browser.");
                    return;
                }
            }

            template.Parse("S_GALLERY_ID", galleryId.ToString());

            Save(new EventHandler(AccountGalleriesManage_Save));
        }
Пример #7
0
        void AccountGalleriesManage_Show(object sender, EventArgs e)
        {
            SetTemplate("account_galleries");

            long parentGalleryId = core.Functions.RequestLong("id", 0);
            string galleryParentPath = "";
            Gallery pg = null;

            if (parentGalleryId > 0)
            {
                try
                {
                    pg = new Gallery(core, Owner, parentGalleryId);

                    template.Parse("U_NEW_GALLERY", BuildUri("galleries", "new", pg.Id));
                    template.Parse("U_UPLOAD_PHOTO", pg.PhotoUploadUri);
                    template.Parse("U_EDIT_PERMISSIONS", core.Hyperlink.AppendAbsoluteSid(string.Format("/api/acl?id={0}&type={1}", pg.Id, ItemType.GetTypeId(core, typeof(Gallery))), true));

                    galleryParentPath = pg.FullPath;
                }
                catch (InvalidGalleryException)
                {
                    DisplayGenericError();
                    return;
                }
            }
            else
            {
                pg = new Gallery(core, Owner);
                template.Parse("U_NEW_GALLERY", BuildUri("galleries", "new", 0));
                template.Parse("U_EDIT_PERMISSIONS", core.Hyperlink.AppendAbsoluteSid(string.Format("/api/acl?id={0}&type={1}", pg.Settings.Id, ItemType.GetTypeId(core, typeof(GallerySettings))), true));
            }

            List<Gallery> ugs = pg.GetGalleries();

            foreach (Gallery ug in ugs)
            {
                VariableCollection galleryVariableCollection = template.CreateChild("gallery_list");

                galleryVariableCollection.Parse("NAME", ug.GalleryTitle);
                galleryVariableCollection.Parse("ITEMS", core.Functions.LargeIntegerToString(ug.Items));

                galleryVariableCollection.Parse("U_MANAGE", BuildUri("galleries", ug.Id));
                galleryVariableCollection.Parse("U_VIEW", ug.Uri);
                galleryVariableCollection.Parse("U_EDIT_PERMISSIONS", ug.AclUri);
                galleryVariableCollection.Parse("U_EDIT", BuildUri("galleries", "edit", ug.Id));
                galleryVariableCollection.Parse("U_DELETE", BuildUri("galleries", "delete", ug.Id));
            }
        }
Пример #8
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="core"></param>
        public static void Upload(Core core)
        {
            Primitive owner = core.Session.LoggedInMember;

            long galleryId = core.Functions.FormLong("gallery-id", 0);
            string title = core.Http.Form["title"];
            string galleryTitle = core.Http.Form["gallery-title"];
            string description = core.Http.Form["description"];
            bool publishToFeed = (core.Http.Form["publish-feed"] != null);
            bool highQualitySave = (core.Http.Form["high-quality"] != null);
            bool submittedTitle = true;

            if (string.IsNullOrEmpty(galleryTitle))
            {
                submittedTitle = false;
                galleryTitle = "Uploaded " + core.Tz.Now.ToString("MMMM dd, yyyy");
            }

            bool newGallery = core.Http.Form["album"] == "create";

            int filesUploaded = 0;
            for (int i = 0; i < core.Http.Files.Count; i++)
            {
                if (core.Http.Files.GetKey(i).StartsWith("photo-file", StringComparison.Ordinal))
                {
                    if (core.Http.Files[i] == null || core.Http.Files[i].ContentLength == 0)
                    {
                        // Ignore error, continue
                        continue;
                    }
                    filesUploaded++;
                }
            }

            if (filesUploaded == 0)
            {
                //core.Ajax.ShowMessage(core.IsAjax, "error", "No files selected", "You need to select some files to upload");
                return;
            }

            try
            {
                Gallery parent = null;

                if (newGallery)
                {
                    Gallery grandParent = null;

                    if (!submittedTitle)
                    {
                        string grandParentSlug = "photos-from-posts";
                        try
                        {
                            grandParent = new Gallery(core, owner, grandParentSlug);
                        }
                        catch (InvalidGalleryException)
                        {
                            Gallery root = new Gallery(core, owner);
                            grandParent = Gallery.Create(core, owner, root, "Photos From Posts", ref grandParentSlug, "All my unsorted uploads");
                        }
                    }
                    else
                    {
                        grandParent = new Gallery(core, owner);
                    }

                    string gallerySlug = string.Empty;

                    if (!submittedTitle)
                    {
                        gallerySlug = "photos-" + UnixTime.UnixTimeStamp().ToString();
                    }
                    else
                    {
                        gallerySlug = Gallery.GetSlugFromTitle(galleryTitle, "");
                    }

                    try
                    {
                        parent = Gallery.Create(core, owner, grandParent, galleryTitle, ref gallerySlug, string.Empty);
                    }
                    catch (GallerySlugNotUniqueException)
                    {
                        core.Response.ShowMessage("error", "Gallery not unique", "Please give a different name to the gallery");
                    }

                    AccessControlLists acl = new AccessControlLists(core, parent);
                    acl.SaveNewItemPermissions();
                }
                else
                {
                    parent = new Gallery(core, owner, galleryId);
                }

                string slug = string.Empty;
                try
                {
                    for (int i = 0; i < core.Http.Files.Count; i++)
                    {
                        if (!core.Http.Files.GetKey(i).StartsWith("photo-file", StringComparison.Ordinal))
                        {
                            continue;
                        }

                        slug = core.Http.Files[i].FileName;

                        MemoryStream stream = new MemoryStream();
                        core.Http.Files[i].InputStream.CopyTo(stream);

                        core.Db.BeginTransaction();

                        GalleryItem newGalleryItem = GalleryItem.Create(core, owner, parent, title, ref slug, core.Http.Files[i].FileName, core.Http.Files[i].ContentType, (ulong)core.Http.Files[i].ContentLength, description, core.Functions.GetLicenseId(), core.Functions.GetClassification(), stream, highQualitySave, core.Session.ApplicationId /*, width, height*/);
                        stream.Close();

                        if (publishToFeed && i < 3)
                        {
                            core.CallingApplication.PublishToFeed(core, core.Session.LoggedInMember, parent, newGalleryItem, Functions.SingleLine(core.Bbcode.Flatten(newGalleryItem.ItemAbstract)));
                        }
                    }
                }
                catch (GalleryItemTooLargeException)
                {
                    core.Db.RollBackTransaction();
                    core.Response.ShowMessage("error", "Photo too big", "The photo you have attempted to upload is too big, you can upload photos up to " + Functions.BytesToString(core.Settings.MaxFileSize) + " in size.");
                    return;
                }
                catch (GalleryQuotaExceededException)
                {
                    core.Db.RollBackTransaction();
                    core.Response.ShowMessage("error", "Not Enough Quota", "You do not have enough quota to upload this photo. Try resizing the image before uploading or deleting images you no-longer need. Smaller images use less quota.");
                    return;
                }
                catch (InvalidGalleryItemTypeException)
                {
                    core.Db.RollBackTransaction();
                    core.Response.ShowMessage("error", "Invalid image uploaded", "You have tried to upload a file type that is not a picture. You are allowed to upload PNG and JPEG images.");
                    return;
                }
                catch (InvalidGalleryFileNameException)
                {
                    core.Db.RollBackTransaction();
                    core.Response.ShowMessage("error", "Submission failed", "Submission failed, try uploading with a different file name.");
                    return;
                }
            }
            catch (InvalidGalleryException)
            {
            }
        }
Пример #9
0
        /// <summary>
        /// Delete all children of a gallery
        /// </summary>
        /// <param name="core">Core token</param>
        /// <param name="gallery">Gallery being deleted</param>
        /// <returns>An array containing the number of gallery photos deleted
        /// (index 0), and the number of bytes consumed by said photos
        /// (index 1).</returns>
        private static long[] galleryDeleteChildren(Core core, Gallery gallery)
        {
            long itemsDeleted = 0; // index 0
            long bytesDeleted = 0; // index 1

            List<Gallery> galleries = gallery.GetGalleries();

            foreach (Gallery galleryGallery in galleries)
            {
                long[] stuffDeleted = galleryDeleteChildren(core, galleryGallery);
                itemsDeleted += stuffDeleted[0];
                bytesDeleted += stuffDeleted[1];
            }

            object objectsDeleted = core.Db.Query(string.Format("SELECT SUM(gallery_item_bytes) AS bytes_deleted FROM gallery_items WHERE user_id = {0} AND gallery_item_parent_path = '{1}';",
                    core.LoggedInMemberId, Mysql.Escape(gallery.FullPath))).Rows[0]["bytes_deleted"];

            if (!(objectsDeleted is DBNull))
            {
                bytesDeleted += (long)(decimal)objectsDeleted;
            }

            core.Db.BeginTransaction();
            itemsDeleted += core.Db.UpdateQuery(string.Format("DELETE FROM gallery_items WHERE user_id = {0} AND gallery_item_parent_path = '{1}'",
                core.Session.LoggedInMember.UserId, Mysql.Escape(gallery.FullPath)));

            core.Db.UpdateQuery(string.Format("DELETE FROM user_galleries WHERE user_id = {0} AND gallery_id = {1}",
                core.Session.LoggedInMember.UserId, gallery.GalleryId));
            return new long[] { itemsDeleted, bytesDeleted };
        }
Пример #10
0
        public static void ShowMore(object sender, ShowPPageEventArgs e)
        {
            char[] trimStartChars = { '.', '/' };

            string galleryPath = e.Slug;

            if (galleryPath != null)
            {
                galleryPath = galleryPath.TrimEnd('/').TrimStart(trimStartChars);
            }
            else
            {
                galleryPath = "";
            }

            Gallery gallery;
            if (galleryPath != "")
            {
                try
                {
                    gallery = new Gallery(e.Core, e.Page.Owner, galleryPath);

                    if (!gallery.Access.Can("VIEW"))
                    {
                        e.Core.Functions.Generate403();
                        return;
                    }
                }
                catch (InvalidGalleryException)
                {
                    return;
                }
            }
            else
            {
                gallery = new Gallery(e.Core, e.Page.Owner);
            }

            Template template = new Template(Assembly.GetExecutingAssembly(), "pane_photo");
            template.Medium = e.Core.Template.Medium;
            template.SetProse(e.Core.Prose);

            bool moreContent = false;
            long lastId = 0;

            List<GalleryItem> galleryItems = gallery.GetItems(e.Core, e.Page.TopLevelPageNumber, 12, e.Page.TopLevelPageOffset);

            int i = 0;
            foreach (GalleryItem galleryItem in galleryItems)
            {
                VariableCollection galleryVariableCollection = template.CreateChild("photo_list");

                galleryVariableCollection.Parse("TITLE", galleryItem.ItemTitle);
                galleryVariableCollection.Parse("PHOTO_URI", Gallery.BuildPhotoUri(e.Core, e.Page.Owner, galleryItem.ParentPath, galleryItem.Path));
                galleryVariableCollection.Parse("COMMENTS", e.Core.Functions.LargeIntegerToString(galleryItem.Comments));
                galleryVariableCollection.Parse("VIEWS", e.Core.Functions.LargeIntegerToString(galleryItem.ItemViews));
                galleryVariableCollection.Parse("INDEX", i.ToString());
                galleryVariableCollection.Parse("ID", galleryItem.Id.ToString());
                galleryVariableCollection.Parse("TYPE_ID", galleryItem.ItemKey.TypeId.ToString());

                galleryVariableCollection.Parse("ICON", galleryItem.IconUri);
                galleryVariableCollection.Parse("TILE", galleryItem.TileUri);
                galleryVariableCollection.Parse("SQUARE", galleryItem.SquareUri);

                galleryVariableCollection.Parse("TINY", galleryItem.TinyUri);
                galleryVariableCollection.Parse("THUMBNAIL", galleryItem.ThumbnailUri);

                Display.RatingBlock(galleryItem.ItemRating, galleryVariableCollection, galleryItem.ItemKey);

                if (galleryItem.Info.Likes > 0)
                {
                    galleryVariableCollection.Parse("LIKES", string.Format(" {0:d}", galleryItem.Info.Likes));
                    galleryVariableCollection.Parse("DISLIKES", string.Format(" {0:d}", galleryItem.Info.Dislikes));
                }

                switch (i % 3)
                {
                    case 0:
                        galleryVariableCollection.Parse("ABC", "a");
                        break;
                    case 1:
                        galleryVariableCollection.Parse("ABC", "b");
                        break;
                    case 2:
                        galleryVariableCollection.Parse("ABC", "c");
                        break;
                }

                switch (i % 4)
                {
                    case 0:
                        galleryVariableCollection.Parse("ABCD", "a");
                        break;
                    case 1:
                        galleryVariableCollection.Parse("ABCD", "b");
                        break;
                    case 2:
                        galleryVariableCollection.Parse("ABCD", "c");
                        break;
                    case 3:
                        galleryVariableCollection.Parse("ABCD", "d");
                        break;
                }

                lastId = galleryItem.Id;
                i++;
            }

            if (e.Core.TopLevelPageNumber * 12 < gallery.Items)
            {
                moreContent = true;
            }

            string loadMoreUri = Gallery.BuildGalleryUri(e.Core, e.Page.Owner, galleryPath) + "?p=" + (e.Core.TopLevelPageNumber + 1) + "&o=" + lastId;
            e.Core.Response.SendRawText(moreContent ? loadMoreUri : "noMoreContent", template.ToString());
        }
Пример #11
0
        /// <summary>
        /// Updates gallery information
        /// </summary>
        /// <param name="db">Database</param>
        /// <param name="owner">Gallery owner</param>
        /// <param name="parent">Parent gallery</param>
        /// <param name="itemId">If greater than 0, the index of new gallery cover photo</param>
        /// <param name="items">Number of items added to the gallery</param>
        /// <param name="bytes">Number of bytes added to the gallery</param>
        public static void UpdateGalleryInfo(Core core, Gallery parent, long itemId, int items, long bytes)
        {
            UpdateQuery uQuery = new UpdateQuery("user_galleries");
            uQuery.AddField("gallery_items", new QueryOperation("gallery_items", QueryOperations.Addition, items));
            uQuery.AddField("gallery_bytes", new QueryOperation("gallery_bytes", QueryOperations.Addition, bytes));
            uQuery.AddCondition("gallery_id", parent.GalleryId);

            core.Db.Query(uQuery);
        }
Пример #12
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void Show(object sender, ShowPPageEventArgs e)
        {
            if (e.Core.ResponseFormat == ResponseFormats.Xml)
            {
                ShowMore(sender, e);
                return;
            }

            e.Template.SetTemplate("Gallery", "viewgallery");

            /*GallerySettings settings;
            try
            {
                settings = new GallerySettings(e.Core, e.Page.Owner);
            }
            catch (InvalidGallerySettingsException)
            {
                GallerySettings.Create(e.Core, e.Page.Owner);
                settings = new GallerySettings(e.Core, e.Page.Owner);
            }*/

            char[] trimStartChars = { '.', '/' };

            string galleryPath = e.Slug;

            if (galleryPath != null)
            {
                galleryPath = galleryPath.TrimEnd('/').TrimStart(trimStartChars);
            }
            else
            {
                galleryPath = "";
            }

            Gallery gallery;
            if (galleryPath != "")
            {
                try
                {
                    gallery = new Gallery(e.Core, e.Page.Owner, galleryPath);

                    try
                    {
                        if (!gallery.Access.Can("VIEW"))
                        {
                            e.Core.Functions.Generate403();
                            return;
                        }
                    }
                    catch (InvalidAccessControlPermissionException)
                    {
                    }

                    try
                    {
                        if (gallery.Access.Can("CREATE_ITEMS"))
                        {
                            e.Template.Parse("U_UPLOAD_PHOTO", gallery.PhotoUploadUri);
                        }
                        if (gallery.Access.Can("CREATE_CHILD"))
                        {
                            e.Template.Parse("U_NEW_GALLERY", gallery.NewGalleryUri);
                        }
                    }
                    catch (InvalidAccessControlPermissionException)
                    {
                    }
                }
                catch (InvalidGalleryException)
                {
                    e.Core.Functions.Generate404();
                    return;
                }
            }
            else
            {
                gallery = new Gallery(e.Core, e.Page.Owner);

                try
                {
                    if (gallery.Settings.AllowItemsAtRoot && gallery.access.Can("CREATE_ITEMS"))
                    {
                        e.Template.Parse("U_UPLOAD_PHOTO", gallery.PhotoUploadUri);
                    }
                    if (gallery.Access.Can("CREATE_CHILD"))
                    {
                        e.Template.Parse("U_NEW_GALLERY", gallery.NewGalleryUri);
                    }
                }
                catch (InvalidAccessControlPermissionException)
                {
                }
            }

            /* pages */
            e.Core.Display.ParsePageList(e.Page.Owner, true);

            if (gallery.Id == 0)
            {
                e.Template.Parse("PAGE_TITLE", gallery.owner.DisplayNameOwnership + " Gallery");
                e.Template.Parse("GALLERY_TITLE", gallery.owner.DisplayNameOwnership + " Gallery");
            }
            else
            {
                e.Template.Parse("PAGE_TITLE", gallery.GalleryTitle);
                e.Template.Parse("GALLERY_TITLE", gallery.GalleryTitle);
            }

            List<string[]> breadCrumbParts = new List<string[]>();

            breadCrumbParts.Add(new string[] { "gallery", e.Core.Prose.GetString("GALLERY") });

            if (gallery.Parents != null)
            {
                foreach (ParentTreeNode ptn in gallery.Parents.Nodes)
                {
                    breadCrumbParts.Add(new string[] { ptn.ParentSlug.ToString(), ptn.ParentTitle });
                }
            }

            if (gallery.Id > 0)
            {
                breadCrumbParts.Add(new string[] { gallery.Path, gallery.GalleryTitle });
            }

            e.Page.Owner.ParseBreadCrumbs(breadCrumbParts);

            List<Gallery> galleries = gallery.GetGalleries();
            List<IPermissibleItem> iPermissibleItems = new List<IPermissibleItem>();

            if (galleries.Count > 0)
            {
                foreach (Gallery galleryGallery in galleries)
                {
                    iPermissibleItems.Add(galleryGallery);
                }
                e.Core.AcessControlCache.CacheGrants(iPermissibleItems);

                e.Template.Parse("GALLERIES", galleries.Count.ToString());

                foreach (Gallery galleryGallery in galleries)
                {
                    if (!galleryGallery.Access.Can("VIEW"))
                    {
                        continue;
                    }
                    VariableCollection galleryVariableCollection = e.Template.CreateChild("gallery_list");

                    galleryVariableCollection.Parse("TITLE", galleryGallery.GalleryTitle);
                    galleryVariableCollection.Parse("URI", Gallery.BuildGalleryUri(e.Core, e.Page.Owner, galleryGallery.FullPath));
                    galleryVariableCollection.Parse("ID", galleryGallery.Id.ToString());
                    galleryVariableCollection.Parse("TYPE_ID", galleryGallery.ItemKey.TypeId.ToString());

                    galleryVariableCollection.Parse("ICON", galleryGallery.IconUri);
                    galleryVariableCollection.Parse("TILE", galleryGallery.TileUri);
                    galleryVariableCollection.Parse("SQUARE", galleryGallery.SquareUri);

                    galleryVariableCollection.Parse("TINY", galleryGallery.TinyUri);
                    galleryVariableCollection.Parse("THUMBNAIL", galleryGallery.ThumbnailUri);

                    //galleryVariableCollection.Parse("U_EDIT", );

                    //e.Core.Display.ParseBbcode(galleryVariableCollection, "ABSTRACT", galleryGallery.GalleryAbstract);

                    if (galleryGallery.Info.Likes > 0)
                    {
                        galleryVariableCollection.Parse("LIKES", string.Format(" {0:d}", galleryGallery.Info.Likes));
                        galleryVariableCollection.Parse("DISLIKES", string.Format(" {0:d}", galleryGallery.Info.Dislikes));
                    }

                    long items = galleryGallery.Items;

                    if (items == 1)
                    {
                        galleryVariableCollection.Parse("ITEMS", string.Format(e.Core.Prose.GetString("_ITEM"), e.Core.Functions.LargeIntegerToString(items)));
                    }
                    else
                    {
                        galleryVariableCollection.Parse("ITEMS", string.Format(e.Core.Prose.GetString("_ITEMS"), e.Core.Functions.LargeIntegerToString(items)));
                    }
                }
            }

            bool moreContent = false;
            long lastId = 0;
            bool first = true;

            long galleryComments = 0;
            if (gallery.Items > 0)
            {
                List<GalleryItem> galleryItems = gallery.GetItems(e.Core, e.Page.TopLevelPageNumber, 12, e.Page.TopLevelPageOffset);

                e.Template.Parse("PHOTOS", galleryItems.Count.ToString());

                int i = 0;
                foreach (GalleryItem galleryItem in galleryItems)
                {
                    if (first)
                    {
                        first = false;
                        e.Template.Parse("NEWEST_ID", galleryItem.Id.ToString());
                    }

                    VariableCollection galleryVariableCollection = e.Template.CreateChild("photo_list");

                    galleryVariableCollection.Parse("TITLE", galleryItem.ItemTitle);
                    galleryVariableCollection.Parse("PHOTO_URI", Gallery.BuildPhotoUri(e.Core, e.Page.Owner, galleryItem.ParentPath, galleryItem.Path));
                    galleryVariableCollection.Parse("COMMENTS", e.Core.Functions.LargeIntegerToString(galleryItem.Comments));
                    galleryVariableCollection.Parse("VIEWS", e.Core.Functions.LargeIntegerToString(galleryItem.ItemViews));
                    galleryVariableCollection.Parse("INDEX", i.ToString());
                    galleryVariableCollection.Parse("ID", galleryItem.Id.ToString());
                    galleryVariableCollection.Parse("TYPE_ID", galleryItem.ItemKey.TypeId.ToString());

                    galleryVariableCollection.Parse("ICON", galleryItem.IconUri);
                    galleryVariableCollection.Parse("TILE", galleryItem.TileUri);
                    galleryVariableCollection.Parse("SQUARE", galleryItem.SquareUri);

                    galleryVariableCollection.Parse("TINY", galleryItem.TinyUri);
                    galleryVariableCollection.Parse("THUMBNAIL", galleryItem.ThumbnailUri);

                    Display.RatingBlock(galleryItem.ItemRating, galleryVariableCollection, galleryItem.ItemKey);

                    if (galleryItem.Info.Likes > 0)
                    {
                        galleryVariableCollection.Parse("LIKES", string.Format(" {0:d}", galleryItem.Info.Likes));
                        galleryVariableCollection.Parse("DISLIKES", string.Format(" {0:d}", galleryItem.Info.Dislikes));
                    }

                    switch (i % 3)
                    {
                        case 0:
                            galleryVariableCollection.Parse("ABC", "a");
                            break;
                        case 1:
                            galleryVariableCollection.Parse("ABC", "b");
                            break;
                        case 2:
                            galleryVariableCollection.Parse("ABC", "c");
                            break;
                    }

                    switch (i % 4)
                    {
                        case 0:
                            galleryVariableCollection.Parse("ABCD", "a");
                            break;
                        case 1:
                            galleryVariableCollection.Parse("ABCD", "b");
                            break;
                        case 2:
                            galleryVariableCollection.Parse("ABCD", "c");
                            break;
                        case 3:
                            galleryVariableCollection.Parse("ABCD", "d");
                            break;
                    }

                    lastId = galleryItem.Id;
                    galleryComments += galleryItem.Comments;
                    i++;
                }

                if (galleryItems.Count > 0)
                {
                    e.Template.Parse("S_RATEBAR", "TRUE");
                }

                e.Core.Display.ParsePagination(Gallery.BuildGalleryUri(e.Core, e.Page.Owner, galleryPath), 0, 12, gallery.Items);

                if (e.Core.TopLevelPageNumber * 12 < gallery.Items)
                {
                    moreContent = true;
                }

                e.Template.Parse("U_NEXT_PAGE", Gallery.BuildGalleryUri(e.Core, e.Page.Owner, galleryPath) + "?p=" + (e.Core.TopLevelPageNumber + 1) + "&o=" + lastId);
            }

            if (gallery.Id > 0)
            {
                e.Template.Parse("ALBUM_COMMENTS", "TRUE");
                if (gallery.Access.Can("COMMENT"))
                {
                    e.Template.Parse("CAN_COMMENT", "TRUE");
                }

                e.Core.Display.DisplayComments(e.Template, e.Page.Owner, e.Page.CommentPageNumber, gallery);

                e.Core.Display.ParsePagination("COMMENT_PAGINATION", Gallery.BuildGalleryUri(e.Core, e.Page.Owner, galleryPath), 1, 10, gallery.Info.Comments);
            }

            e.Template.Parse("COMMENTS", gallery.Comments.ToString());
            e.Template.Parse("L_COMMENTS", string.Format("{0} Comments in gallery", galleryComments));
            e.Template.Parse("U_COMMENTS", e.Core.Hyperlink.BuildGalleryCommentsUri(e.Page.Owner, galleryPath));
        }
Пример #13
0
        public static void NotifyGalleryComment(Core core, Job job)
        {
            Comment comment = new Comment(core, job.ItemId);
            Gallery ev = new Gallery(core, comment.CommentedItemKey.Id);

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

            core.CallingApplication.SendNotification(core, comment.OwnerKey, comment.User, ev.OwnerKey, ev.ItemKey, "_COMMENTED_GALLERY", comment.BuildUri(ev));
        }
Пример #14
0
        /// <summary>
        /// Deletes a gallery
        /// </summary>
        /// <param name="core">Core token</param>
        /// <param name="gallery">Gallery to delete</param>
        public static void Delete(Core core, Gallery gallery)
        {
            long[] stuffDeleted = galleryDeleteChildren(core, gallery);
            long itemsDeleted = stuffDeleted[0];
            long bytesDeleted = stuffDeleted[1];

            // comitt the transaction
            core.Db.UpdateQuery(string.Format("UPDATE user_info SET user_gallery_items = user_gallery_items - {1}, user_bytes = user_bytes - {2} WHERE user_id = {1}",
                core.Session.LoggedInMember.UserId, itemsDeleted, bytesDeleted));
        }
Пример #15
0
        /// <summary>
        /// Delete the gallery item
        /// </summary>
        public override long Delete()
        {
            SelectQuery squery = new SelectQuery("gallery_items gi");
            squery.AddFields("COUNT(*) AS number");
            squery.AddCondition("gallery_item_storage_path", storagePath);

            DataTable results = db.Query(squery);

            /*DeleteQuery dquery = new DeleteQuery("gallery_items");
            dquery.AddCondition("gallery_item_id", itemId);
            dquery.AddCondition("user_id", core.LoggedInMemberId);*/

            long deleted = base.Delete();
            if (deleted > 0)
            {
                // TODO, determine if the gallery icon and act appropriately
                /*if (parentId > 0)
                {

                }*/

                if (owner is User)
                {
                    Gallery parent = new Gallery(core, (User)owner, parentId);
                    Gallery.UpdateGalleryInfo(core, parent, (long)itemId, -1, -ItemBytes);
                }

                UpdateQuery uQuery = new UpdateQuery("user_info");
                uQuery.AddField("user_gallery_items", new QueryOperation("user_gallery_items", QueryOperations.Subtraction, 1));
                uQuery.AddField("user_bytes", new QueryOperation("user_bytes", QueryOperations.Subtraction, ItemBytes));
                uQuery.AddCondition("user_id", userId);

                db.Query(uQuery);

                if ((long)results.Rows[0]["number"] > 1)
                {
                    // do not delete the storage file, still in use
                }
                else
                {
                    // delete the storage file
                    core.Storage.DeleteFile(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, "_storage"), storagePath);
                }

                return deleted;
            }
            else
            {
                //TODO: throw new
                throw new Exception("Unauthorised");
            }
        }
Пример #16
0
 public static GalleryItem Create(Core core, Primitive owner, Gallery parent, string title, ref string slug, string fileName, string contentType, ulong bytes, string description, byte license, Classifications classification, Stream stream, bool highQuality /*int width, int height*/)
 {
     return Create(core, owner, parent, title, ref slug, fileName, contentType, bytes, description, license, classification, stream, highQuality, 0);
 }
        void AccountGalleriesPhotoCover_Show(object sender, EventArgs e)
        {
            AuthoriseRequestSid();

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

            if (pictureId == 0)
            {
                core.Display.ShowMessage("Invalid submission", "You have made an invalid form submission. (0x07)");
                return;
            }

            // check the image exists
            // check the image is owned by the user trying to set it as their display picture
            try
            {
                GalleryItem ugi = new GalleryItem(core, Owner, pictureId);

                string galleryFullPath = ugi.ParentPath;
                int indexOfLastSlash = galleryFullPath.LastIndexOf('/');

                try
                {
                    Gallery gallery = new Gallery(core, Owner, galleryFullPath);

                    gallery.HighlightId = pictureId;
                    gallery.Update();

                    SetRedirectUri(Gallery.BuildGalleryUri(core, Owner, galleryFullPath));
                    core.Display.ShowMessage("Gallery Cover Image Changed", "You have successfully changed the cover image of the gallery.");
                    return;
                }
                catch (InvalidGalleryException)
                {
                    core.Display.ShowMessage("Cannot change gallery cover", "You could not change the gallery cover image to the selected image.");
                    return;
                }
                catch (UnauthorisedToUpdateItemException)
                {
                    core.Display.ShowMessage("Unauthorised", "You are unauthorised to complete this action.");
                    return;
                }
            }
            catch (GalleryItemNotFoundException)
            {
                core.Display.ShowMessage("Cannot change gallery cover", "You could not change the gallery cover image to the selected image.");
                return;
            }
        }
Пример #18
0
        /// <summary>
        /// Creates a new gallery item
        /// </summary>
        /// <param name="core">Core token</param>
        /// <param name="owner">Owner</param>
        /// <param name="parent">Gallery</param>
        /// <param name="title">Title</param>
        /// <param name="slug">Slug</param>
        /// <param name="fileName">File name</param>
        /// <param name="storageName">Storage name</param>
        /// <param name="contentType">Content type</param>
        /// <param name="bytes">Bytes</param>
        /// <param name="description">Description</param>
        /// <param name="permissions">Permissions mask</param>
        /// <param name="license">License</param>
        /// <param name="classification">Classification</param>
        /// <remarks>Slug is a reference</remarks>
        /// <returns>New gallery item</returns>
        public static GalleryItem Create(Core core, Primitive owner, Gallery parent, string title, ref string slug, string fileName, string contentType, ulong bytes, string description, byte license, Classifications classification, Stream stream, bool highQuality, long applicationId /*int width, int height*/)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            if (stream == null)
            {
                throw new Exception("The image stream is empty!");
            }

            int width, height;
            stream = OrientImage(stream, out width, out height);

            string storageName = Storage.HashFile(stream);

            /*
             * scale and save
             */
            string storageFilePath = string.Empty;

            if (highQuality || (width <= (int)PictureScale.Ultra && height <= (int)PictureScale.Ultra))
            {
                core.Storage.SaveFile(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, "_storage"), storageName, stream, contentType);
            }
            else
            {
                int originalWidth = width;
                int originalHeight = height;

                Size newSize = GalleryItem.GetSize(new Size(width, height), new Size((int)PictureScale.Ultra, (int)PictureScale.Ultra));
                width = newSize.Width;
                height = newSize.Height;

                if (Core.IsUnix && WebConfigurationManager.AppSettings["image-method"] == "imagemagick")
                {
                    storageFilePath = System.IO.Path.Combine(core.Settings.ImagemagickTempPath, "_storage", storageName);

                    if (stream is MemoryStream)
                    {
                        MemoryStream ms = (MemoryStream)stream;
                        FileStream ds = new FileStream(storageFilePath, FileMode.Create);
                        ms.WriteTo(ds);
                        ds.Close();
                    }
                    else
                    {
                        stream.Position = 0;
                        byte[] b = new byte[stream.Length];
                        stream.Read(b, 0, (int)stream.Length);
                        FileStream ds = new FileStream(storageFilePath, FileMode.Create);
                        ds.Write(b, 0, b.Length);
                        ds.Close();
                    }
                }

                CreateScaleWithRatioPreserved(core, contentType, stream, storageName, "_storage", (int)PictureScale.Ultra, (int)PictureScale.Ultra);
            }

            /*
             * create thumbnails
             */
            bool tinyExists = false;
            bool thumbExists = false;
            bool mobileExists = false;
            bool displayExists = false;
            bool fullExists = false;
            bool ultraExists = false;

            switch (core.Medium)
            {
                case Forms.DisplayMedium.Desktop:
                    if (width > (int)PictureScale.Display || height > (int)PictureScale.Display)
                    {
                        displayExists = CreateScaleWithRatioPreserved(core, contentType, stream, storageName, DisplayPrefix, (int)PictureScale.Display, (int)PictureScale.Display);
                    }
                    else
                    {
                        // This strips all uploaded images of EXIF data
                        displayExists = CreateScaleWithRatioPreserved(core, contentType, stream, storageName, DisplayPrefix, width, height);
                    }
                    break;
                case Forms.DisplayMedium.Mobile:
                    if (width > (int)PictureScale.Mobile || height > (int)PictureScale.Mobile)
                    {
                        mobileExists = CreateScaleWithRatioPreserved(core, contentType, stream, storageName, MobilePrefix, (int)PictureScale.Mobile, (int)PictureScale.Mobile);
                    }
                    break;
            }

            if (!string.IsNullOrEmpty(storageFilePath))
            {
                if (File.Exists(storageFilePath))
                {
                    try
                    {
                        File.Delete(storageFilePath);
                    }
                    catch (FileNotFoundException)
                    {
                    }
                }
            }

            /*
             * save the image
             */

            Mysql db = core.Db;

            if (owner is User)
            {
                if (owner.Id != core.LoggedInMemberId)
                {
                    throw new Exception("Error, user IDs don't match");
                }
            }

            if (bytes > (ulong)core.Settings.MaxFileSize)
            {
                throw new GalleryItemTooLargeException();
            }

            if (core.Session.LoggedInMember.UserInfo.BytesUsed + bytes > (ulong)core.Settings.MaxUserStorage)
            {
                throw new GalleryQuotaExceededException();
            }

            switch (contentType)
            {
                case "image/png":
                case "image/jpeg":
                case "image/pjpeg":
                case "image/gif":
                    break;
                default:
                    throw new InvalidGalleryItemTypeException();
            }

            title = Functions.TrimStringToWord(title);

            slug = GalleryItem.GetSlugFromFileName(fileName, slug);
            slug = Functions.TrimStringWithExtension(slug);

            if (slug != "image.jpg")
            {
                GalleryItem.EnsureGallerySlugUnique(core, parent, owner, ref slug);
            }

            InsertQuery iQuery = new InsertQuery("gallery_items");
            iQuery.AddField("gallery_item_uri", slug);
            iQuery.AddField("gallery_item_title", title);
            iQuery.AddField("gallery_item_abstract", description);
            iQuery.AddField("gallery_item_date_ut", UnixTime.UnixTimeStamp());
            iQuery.AddField("gallery_item_storage_path", storageName);
            iQuery.AddField("gallery_item_parent_path", parent.FullPath);
            iQuery.AddField("gallery_item_content_type", contentType);
            iQuery.AddField("user_id", core.LoggedInMemberId);
            iQuery.AddField("gallery_item_bytes", bytes);
            iQuery.AddField("gallery_item_license", license);
            iQuery.AddField("gallery_id", parent.GalleryId);
            iQuery.AddField("gallery_item_item_id", owner.Id);
            iQuery.AddField("gallery_item_item_type_id", owner.TypeId);
            iQuery.AddField("gallery_item_classification", (byte)classification);
            iQuery.AddField("gallery_item_icon_exists", false);
            iQuery.AddField("gallery_item_tile_exists", false);
            iQuery.AddField("gallery_item_square_exists", false);
            iQuery.AddField("gallery_item_high_exists", false);
            iQuery.AddField("gallery_item_tiny_exists", tinyExists);
            iQuery.AddField("gallery_item_thumb_exists", thumbExists);
            iQuery.AddField("gallery_item_mobile_exists", mobileExists);
            iQuery.AddField("gallery_item_display_exists", displayExists);
            iQuery.AddField("gallery_item_full_exists", fullExists);
            iQuery.AddField("gallery_item_ultra_exists", ultraExists);
            iQuery.AddField("gallery_item_cover_exists", false);
            iQuery.AddField("gallery_item_mobile_cover_exists", false);
            iQuery.AddField("gallery_item_width", width);
            iQuery.AddField("gallery_item_height", height);
            iQuery.AddField("gallery_item_vcrop", 0);
            iQuery.AddField("gallery_item_hcrop", 0);
            iQuery.AddField("gallery_item_application_id", applicationId);

            // we want to use transactions
            long itemId = db.Query(iQuery);

            if (itemId >= 0)
            {
                // ios uploads anonymously
                if (slug == "image.jpg")
                {
                    slug = string.Format("image-{0}.jpg", itemId);
                    UpdateQuery iosQuery = new UpdateQuery("gallery_items");
                    iosQuery.AddField("gallery_item_uri", slug);
                    iosQuery.AddCondition("gallery_item_id", itemId);

                    db.Query(iosQuery);
                }

                //owner.UpdateGalleryInfo(parent, itemId, 1, (long)bytes);
                //if (owner is User)
                {
                    Gallery.UpdateGalleryInfo(core, parent, itemId, 1, (long)bytes);
                }
                /*parent.Bytes += (long)bytes;
                parent.Items += 1;
                parent.Update();*/

                UpdateQuery uQuery = new UpdateQuery("user_info");
                uQuery.AddField("user_gallery_items", new QueryOperation("user_gallery_items", QueryOperations.Addition, 1));
                uQuery.AddField("user_bytes", new QueryOperation("user_bytes", QueryOperations.Addition, bytes));
                uQuery.AddCondition("user_id", core.LoggedInMemberId);

                if (db.Query(uQuery) < 0)
                {
                    throw new Exception("Transaction failed, panic!");
                }

                GalleryItem newGalleryItem = new GalleryItem(core, owner, itemId);
                core.Db.CommitTransaction();

                core.Search.Index(newGalleryItem);

                if (core.Queue != null)
                {
                    core.Queue.PushJob(new Job(core.Settings.QueueDefaultPriority, core.CallingApplication.Id, core.LoggedInMemberId, newGalleryItem.ItemKey.TypeId, newGalleryItem.ItemKey.Id, "create_ultra"));
                    core.Queue.PushJob(new Job(core.Settings.QueueDefaultPriority, core.CallingApplication.Id, core.LoggedInMemberId, newGalleryItem.ItemKey.TypeId, newGalleryItem.ItemKey.Id, "create_full"));
                    switch (core.Medium)
                    {
                        case Forms.DisplayMedium.Desktop:
                            core.Queue.PushJob(new Job(core.Settings.QueueDefaultPriority, core.CallingApplication.Id, core.LoggedInMemberId, newGalleryItem.ItemKey.TypeId, newGalleryItem.ItemKey.Id, "create_mobile"));
                            break;
                        case Forms.DisplayMedium.Mobile:
                            core.Queue.PushJob(new Job(core.Settings.QueueDefaultPriority, core.CallingApplication.Id, core.LoggedInMemberId, newGalleryItem.ItemKey.TypeId, newGalleryItem.ItemKey.Id, "create_display"));
                            break;
                    }
                    core.Queue.PushJob(new Job(core.Settings.QueueDefaultPriority, core.CallingApplication.Id, core.LoggedInMemberId, newGalleryItem.ItemKey.TypeId, newGalleryItem.ItemKey.Id, "create_thumb"));
                    core.Queue.PushJob(new Job(core.Settings.QueueDefaultPriority, core.CallingApplication.Id, core.LoggedInMemberId, newGalleryItem.ItemKey.TypeId, newGalleryItem.ItemKey.Id, "create_tiny"));

                    core.Queue.PushJob(new Job(core.Settings.QueueDefaultPriority, core.CallingApplication.Id, core.LoggedInMemberId, newGalleryItem.ItemKey.TypeId, newGalleryItem.ItemKey.Id, "create_high"));
                    core.Queue.PushJob(new Job(core.Settings.QueueDefaultPriority, core.CallingApplication.Id, core.LoggedInMemberId, newGalleryItem.ItemKey.TypeId, newGalleryItem.ItemKey.Id, "create_square"));
                    core.Queue.PushJob(new Job(core.Settings.QueueDefaultPriority, core.CallingApplication.Id, core.LoggedInMemberId, newGalleryItem.ItemKey.TypeId, newGalleryItem.ItemKey.Id, "create_tile"));
                    core.Queue.PushJob(new Job(core.Settings.QueueDefaultPriority, core.CallingApplication.Id, core.LoggedInMemberId, newGalleryItem.ItemKey.TypeId, newGalleryItem.ItemKey.Id, "create_icon"));
                }

                return newGalleryItem;
                //return itemId;
            }

            throw new Exception("Transaction failed, panic!");
        }
Пример #19
0
        void AccountGalleriesManage_Save(object sender, EventArgs e)
        {
            long galleryId = 0;
            string title = "";
            string description = "";
            bool edit = false;

            try
            {
                galleryId = long.Parse(core.Http.Form["id"]);
                title = core.Http.Form["title"];
                description = core.Http.Form["description"];
            }
            catch
            {
                core.Display.ShowMessage("Invalid submission", "You have made an invalid form submission. (0x01)");
                return;
            }

            if (core.Http.Form["mode"] == "edit")
            {
                edit = true;
            }

            string slug = Gallery.GetSlugFromTitle(title, "");

            if (!edit)
            {
                try
                {
                    Gallery parent;
                    if (galleryId > 0)
                    {
                        parent = new Gallery(core, Owner, galleryId);
                    }
                    else
                    {
                        parent = new Gallery(core, Owner);
                    }

                    if (parent.FullPath.Length + slug.Length + 1 < 192)
                    {
                        if (Gallery.Create(core, Owner, parent, title, ref slug, description) != null)
                        {
                            SetRedirectUri(BuildUri("galleries", parent.GalleryId));
                            core.Display.ShowMessage("Gallery Created", "You have successfully created a new gallery.");
                            return;
                        }
                        else
                        {
                            core.Display.ShowMessage("Invalid submission", "You have made an invalid form submission. (0x02)");
                            return;
                        }
                    }
                    else
                    {
                        SetError("The gallery path you have given is too long. Try using a shorter name or less nesting.");
                        //Display.ShowMessage("Gallery Path Too Long", "The gallery path you have given is too long. Try using a shorter name or less nesting.");
                        return;
                    }
                }
                catch (GallerySlugNotUniqueException)
                {
                    SetError("You have tried to create a gallery with the same name of one that already exits. Please give the gallery a unique name.");
                    //Display.ShowMessage("Gallery with same name already exists", "You have tried to create a gallery with the same name of one that already exits. Go back and give the gallery a unique name.");
                    return;
                }
                catch (GallerySlugNotValidException)
                {
                    SetError("The name of the gallery you have created is invalid, please choose another name.");
                    //Display.ShowMessage("Gallery name invalid", "The name of the gallery you have created is invalid, please choose another name.");
                    return;
                }
                catch (Exception ex)
                {
                    core.Display.ShowMessage("Invalid submission", "You have made an invalid form submission. (0x03) " + ex.ToString());
                    return;
                }
            }
            else
            {
                // save edit
                try
                {
                    Gallery gallery = new Gallery(core, Owner, galleryId);

                    try
                    {
                        if (gallery.ParentPath.Length + slug.Length + 1 < 192)
                        {
                            gallery.Update(core, title, slug, description);

                            SetRedirectUri(BuildUri("galleries", gallery.ParentId));
                            core.Display.ShowMessage("Gallery Edit Saved", "You have saved the edits to the gallery.");
                            return;
                        }
                        else
                        {
                            core.Display.ShowMessage("Gallery Path Too Long", "The gallery path you have given is too long. Try using a shorter name or less nesting.");
                            return;
                        }
                    }
                    catch (GallerySlugNotUniqueException)
                    {
                        core.Display.ShowMessage("Gallery with same name already exists", "You have tried to create a gallery with the same name of one that already exits. Go back and give the gallery a unique name.");
                        return;
                    }
                    catch (GallerySlugNotValidException)
                    {
                        core.Display.ShowMessage("Gallery name invalid", "The name of the gallery you have created is invalid, please choose another name.");
                        return;
                    }
                    catch (Exception ex)
                    {
                        core.Display.ShowMessage("Invalid submission", "You have made an invalid form submission. (0x04) " + ex.ToString());
                        return;
                    }
                }
                catch
                {
                    core.Display.ShowMessage("Invalid submission", "You have made an invalid form submission. (0x05)");
                    return;
                }
            }
        }
Пример #20
0
        /// <summary>
        /// Checks the slug for uniqueness, and updates it to maintain
        /// uniqueness if necessary
        /// </summary>
        /// <param name="core">Core token</param>
        /// <param name="gallery">Parent gallery</param>
        /// <param name="owner">Gallery owner</param>
        /// <param name="slug">Slug</param>
        /// <remarks>Slug is a reference argument</remarks>
        public static void EnsureGallerySlugUnique(Core core, Gallery gallery, Primitive owner, ref string slug)
        {
            int nameCount = 1;
            bool copyFound = false;

            string originalSlug = slug;

            // keep going until we find a name that does not already exist in the database
            do
            {
                DataTable galleryItemTable = core.Db.Query(string.Format("SELECT gallery_item_uri FROM gallery_items WHERE gallery_item_uri = '{0}' AND gallery_id = {1} AND gallery_item_item_id = {2} AND gallery_item_item_type_id = {3};",
                    Mysql.Escape(slug), gallery.GalleryId, owner.Id, owner.TypeId));

                if (galleryItemTable.Rows.Count > 0)
                {
                    nameCount++;
                    slug = originalSlug;
                    int pointIndex = slug.LastIndexOf('.');
                    copyFound = true;
                    slug = slug.Remove(pointIndex) + "--" + nameCount.ToString() + slug.Substring(pointIndex);
                }
                else
                {
                    copyFound = false;
                }

                // limit the number of tries to stop abuse, very very very unlikely
                // this allows for 6 files with the same name in the same gallery
                if (nameCount > 5)
                {
                    throw new InvalidGalleryFileNameException();
                }
            }
            while (copyFound);
        }
Пример #21
0
        void AccountGalleriesManage_Delete(object sender, EventArgs e)
        {
            AuthoriseRequestSid();

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

            if (galleryId == 0)
            {
                core.Display.ShowMessage("Cannot Delete Gallery", "No gallery specified to delete. Please go back and try again.");
                return;
            }

            try
            {
                Gallery gallery = new Gallery(core, Owner, galleryId);
                //Gallery.Delete(core, gallery);
                gallery.Delete();

                SetRedirectUri(BuildUri("galleries", "galleries"));
                core.Display.ShowMessage("Gallery Deleted", "You have successfully deleted a gallery.");
            }
            catch
            {
                core.Display.ShowMessage("Cannot Delete Gallery", "An Error occured while trying to delete the gallery.");
                return;
            }
        }
Пример #22
0
        public static void Show(Core core)
        {
            long itemId = core.Functions.RequestLong("item_id", 0);
            long itemTypeId = core.Functions.RequestLong("item_type_id", 0);
            string path = core.Http.Query["path"];
            long ownerId = core.Functions.RequestLong("owner_id", 0);
            long ownerTypeId = core.Functions.RequestLong("owner_type_id", 0);
            ItemKey ownerKey = new ItemKey(ownerId, ownerTypeId);

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

                GalleryItem galleryItem = null;
                if (itemId != 0)
                {
                    galleryItem = new GalleryItem(core, itemId);
                }
                else
                {
                    galleryItem = new GalleryItem(core, owner, path);
                }

                Gallery gallery = null;

                if (galleryItem.parentId > 0)
                {
                    gallery = new Gallery(core, galleryItem.parentId);
                }
                else
                {
                    gallery = new Gallery(core, owner);
                }

                if (!gallery.Access.Can("VIEW_ITEMS"))
                {
                    core.Functions.Generate403();
                    return;
                }

                JsonSerializer js;
                StringWriter jstw;
                JsonTextWriter jtw;

                js = new JsonSerializer();
                jstw = new StringWriter();
                jtw = new JsonTextWriter(jstw);

                js.NullValueHandling = NullValueHandling.Ignore;

                core.Http.WriteJson(js, galleryItem);
            }
            catch
            {
            }
        }
Пример #23
0
        void AccountDisplayPic_Save(object sender, EventArgs e)
        {
            AuthoriseRequestSid();

            if (core.Http.Files["photo-file"].ContentLength == 0)
            {
                int vcrop = core.Functions.FormInt("vcrop", 0);

                if (LoggedInMember.UserInfo.CoverPhotoId > 0)
                {
                    GalleryItem coverItem = new GalleryItem(core, LoggedInMember.UserInfo.CoverPhotoId);
                    coverItem.CropPositionVertical = vcrop;
                    coverItem.Update();

                    SetRedirectUri(BuildUri());
                    core.Display.ShowMessage("Cover photo set", "You have successfully uploaded a new cover photo.");
                    return;
                }
            }
            else
            {
                string meSlug = "cover-photos";

                BoxSocial.Applications.Gallery.Gallery profileGallery;
                try
                {
                    profileGallery = new BoxSocial.Applications.Gallery.Gallery(core, LoggedInMember, meSlug);
                }
                catch (InvalidGalleryException)
                {
                    BoxSocial.Applications.Gallery.Gallery root = new BoxSocial.Applications.Gallery.Gallery(core, LoggedInMember);
                    profileGallery = BoxSocial.Applications.Gallery.Gallery.Create(core, LoggedInMember, root, "Cover Photos", ref meSlug, "All my uploaded cover photos");
                }

                if (profileGallery != null)
                {
                    string title = "";
                    string description = "";
                    string slug = "";

                    try
                    {
                        slug = core.Http.Files["photo-file"].FileName;
                    }
                    catch
                    {
                        DisplayGenericError();
                        return;
                    }

                    try
                    {
                        MemoryStream stream = new MemoryStream();
                        core.Http.Files["photo-file"].InputStream.CopyTo(stream);

                        db.BeginTransaction();

                        GalleryItem galleryItem = GalleryItem.Create(core, LoggedInMember, profileGallery, title, ref slug, core.Http.Files["photo-file"].FileName, core.Http.Files["photo-file"].ContentType, (ulong)core.Http.Files["photo-file"].ContentLength, description, 0, Classifications.Everyone, stream, false);

                        db.UpdateQuery(string.Format("UPDATE user_info SET user_cover = {0} WHERE user_id = {1}",
                            galleryItem.Id, LoggedInMember.UserId));

                        //db.CommitTransaction();
                        stream.Close();

                        SetRedirectUri(BuildUri());
                        core.Display.ShowMessage("Cover photo set", "You have successfully uploaded a new cover photo.");
                        return;
                    }
                    catch (GalleryItemTooLargeException)
                    {
                        SetError("The photo you have attempted to upload is too big, you can upload photos up to 1.2 MiB in size.");
                        return;
                    }
                    catch (GalleryQuotaExceededException)
                    {
                        SetError("You do not have enough quota to upload this photo. Try resizing the image before uploading or deleting images you no-longer need. Smaller images use less quota.");
                        return;
                    }
                    catch (InvalidGalleryItemTypeException)
                    {
                        SetError("You have tried to upload a file type that is not a picture. You are allowed to upload PNG and JPEG images.");
                        return;
                    }
                    catch (InvalidGalleryFileNameException)
                    {
                        core.Display.ShowMessage("Submission failed", "Submission failed, try uploading with a different file name.");
                        return;
                    }
                }
                else
                {
                    DisplayGenericError();
                    return;
                }
            }
        }
Пример #24
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void Show(object sender, ShowPPageEventArgs e)
        {
            e.Template.SetTemplate("Gallery", "viewphoto");

            char[] trimStartChars = { '.', '/' };

            try
            {
                GalleryItem galleryItem = new GalleryItem(e.Core, e.Page.Owner, e.Slug);
                Gallery gallery = null;

                if (galleryItem.parentId > 0)
                {
                    gallery = new Gallery(e.Core, galleryItem.parentId);
                }
                else
                {
                    gallery = new Gallery(e.Core, e.Page.Owner);
                }

                if (!gallery.Access.Can("VIEW_ITEMS"))
                {
                    e.Core.Functions.Generate403();
                    return;
                }

                if (gallery.Access.Can("EDIT_ITEMS"))
                {
                    e.Template.Parse("S_CAN_EDIT", "TRUE");
                }

                if (gallery.Access.Can("DELETE_ITEMS"))
                {
                    e.Template.Parse("S_CAN_DELETE", "TRUE");
                }

                /* pages */
                e.Core.Display.ParsePageList(e.Page.Owner, true);

                galleryItem.Viewed(e.Core.Session.LoggedInMember);
                ItemView.LogView(e.Core, galleryItem);

                /* check gallery item has width and height information saved */

                if (galleryItem.ItemWidth <= 0 || galleryItem.ItemHeight <= 0)
                {
                    Stream fs = e.Core.Storage.RetrieveFile(e.Core.Storage.PathCombine(e.Core.Settings.StorageBinUserFilesPrefix, "_storage"), galleryItem.StoragePath);
                    Image image = Image.FromStream(fs);
                    int width = image.Width;
                    int height = image.Height;

                    galleryItem.ItemWidth = width;
                    galleryItem.ItemHeight = height;
                    galleryItem.Update();
                }

                Size hdSize = galleryItem.GetSize(new Size(1920, 1080));

                e.Core.Meta.Add("og:site_name", e.Core.Settings.SiteTitle);
                e.Core.Meta.Add("twitter:card", "photo");
                if (!string.IsNullOrEmpty(e.Core.Settings.TwitterName))
                {
                    e.Core.Meta.Add("twitter:site", e.Core.Settings.TwitterName);
                }
                if (galleryItem.Owner is User && !string.IsNullOrEmpty(((User)galleryItem.Owner).UserInfo.TwitterUserName))
                {
                    e.Core.Meta.Add("twitter:creator", ((User)galleryItem.Owner).UserInfo.TwitterUserName);
                }
                e.Core.Meta.Add("twitter:image:src", e.Core.Hyperlink.StripSid(e.Core.Hyperlink.AppendCurrentSid(galleryItem.DisplayUri)));
                if (!string.IsNullOrEmpty(galleryItem.ItemTitle))
                {
                    e.Core.Meta.Add("twitter:title", galleryItem.ItemTitle);
                    e.Core.Meta.Add("og:title", galleryItem.ItemTitle);
                }
                else
                {
                    e.Core.Meta.Add("og:title", galleryItem.Path);
                }
                e.Core.Meta.Add("og:type", "boxsocialapp:photo");
                e.Core.Meta.Add("og:url", e.Core.Hyperlink.StripSid(e.Core.Hyperlink.AppendCurrentSid(galleryItem.Uri)));
                e.Core.Meta.Add("og:image", e.Core.Hyperlink.StripSid(e.Core.Hyperlink.AppendCurrentSid(galleryItem.DisplayUri)));

                e.Page.CanonicalUri = galleryItem.Uri;

                e.Template.Parse("PAGE_TITLE", galleryItem.ItemTitle);
                e.Template.Parse("PHOTO_TITLE", galleryItem.ItemTitle);
                e.Template.Parse("PHOTO_ID", galleryItem.ItemId.ToString());
                e.Core.Display.ParseBbcode("PHOTO_DESCRIPTION", e.Core.Bbcode.FromStatusCode(galleryItem.ItemAbstract));
                e.Template.Parse("HD_WIDTH", hdSize.Width);
                e.Template.Parse("HD_HEIGHT", hdSize.Height);
                e.Template.Parse("PHOTO_COMMENTS", e.Core.Functions.LargeIntegerToString(galleryItem.Comments));
                e.Template.Parse("U_MARK_DISPLAY_PIC", galleryItem.MakeDisplayPicUri);
                e.Template.Parse("U_MARK_GALLERY_COVER", galleryItem.SetGalleryCoverUri);
                e.Template.Parse("U_ROTATE_LEFT", galleryItem.RotateLeftUri);
                e.Template.Parse("U_ROTATE_RIGHT", galleryItem.RotateRightUri);
                e.Template.Parse("U_TAG", galleryItem.TagUri);

                e.Template.Parse("PHOTO_MOBILE", galleryItem.MobileUri);
                e.Template.Parse("PHOTO_DISPLAY", galleryItem.DisplayUri);
                e.Template.Parse("PHOTO_FULL", galleryItem.FullUri);
                e.Template.Parse("PHOTO_ULTRA", galleryItem.UltraUri);

                if (gallery.Access.Can("EDIT_ITEMS"))
                {
                    e.Template.Parse("U_EDIT", galleryItem.EditUri);
                }

                if (gallery.Access.Can("DELETE_ITEMS"))
                {
                    e.Template.Parse("U_DELETE", galleryItem.DeleteUri);
                }

                if (gallery.Access.Can("CREATE_ITEMS"))
                {
                    e.Template.Parse("U_UPLOAD_PHOTO", gallery.PhotoUploadUri);
                }

                if (gallery.Access.Can("DOWNLOAD_ORIGINAL"))
                {
                    e.Template.Parse("U_VIEW_FULL", galleryItem.OriginalUri);
                }

                switch (galleryItem.Classification)
                {
                    case Classifications.Everyone:
                        e.Template.Parse("PAGE_CLASSIFICATION", "Suitable for Everyone");
                        e.Template.Parse("I_PAGE_CLASSIFICATION", "rating_e.png");
                        break;
                    case Classifications.Mature:
                        e.Template.Parse("PAGE_CLASSIFICATION", "Suitable for Mature Audiences 15+");
                        e.Template.Parse("I_PAGE_CLASSIFICATION", "rating_15.png");
                        break;
                    case Classifications.Restricted:
                        e.Template.Parse("PAGE_CLASSIFICATION", "Retricted to Audiences 18+");
                        e.Template.Parse("I_PAGE_CLASSIFICATION", "rating_18.png");
                        break;
                }

                if (galleryItem.License != null)
                {
                    if (!string.IsNullOrEmpty(galleryItem.License.Title))
                    {
                        e.Template.Parse("PAGE_LICENSE", galleryItem.License.Title);
                    }
                    if (!string.IsNullOrEmpty(galleryItem.License.Icon))
                    {
                        e.Template.Parse("I_PAGE_LICENSE", galleryItem.License.Icon);
                    }
                    if (!string.IsNullOrEmpty(galleryItem.License.Link))
                    {
                        e.Template.Parse("U_PAGE_LICENSE", galleryItem.License.Link);
                    }
                }

                Display.RatingBlock(galleryItem.ItemRating, e.Template, galleryItem.ItemKey);

                e.Template.Parse("ID", galleryItem.ItemId.ToString());
                e.Template.Parse("TYPEID", galleryItem.ItemKey.TypeId.ToString());
                //template.Parse("U_EDIT", ZzUri.BuildPhotoEditUri((long)photoTable.Rows[0]["gallery_item_id"])));

                if (gallery.Access.IsPublic())
                {
                    e.Template.Parse("IS_PUBLIC", "TRUE");

                    if (galleryItem.Info.SharedTimes > 0)
                    {
                        e.Template.Parse("SHARES", string.Format(" {0:d}", galleryItem.Info.SharedTimes));
                    }
                }
                else
                {
                    e.Template.Parse("IS_PUBLIC", "FALSE");
                }

                if (gallery.Access.Can("COMMENT_ITEMS"))
                {
                    e.Template.Parse("CAN_COMMENT", "TRUE");
                }

                e.Core.Display.DisplayComments(e.Template, e.Page.Owner, galleryItem);

                string pageUri = string.Format("{0}gallery/{1}",
                    HttpUtility.HtmlEncode(e.Page.Owner.UriStub), e.Slug);
                e.Core.Display.ParsePagination("COMMENT_PAGINATION", pageUri, 10, galleryItem.Comments);

                List<string[]> breadCrumbParts = new List<string[]>();

                breadCrumbParts.Add(new string[] { "gallery", e.Core.Prose.GetString("GALLERY") });
                if (gallery.Parents != null)
                {
                    foreach (ParentTreeNode node in gallery.Parents.Nodes)
                    {
                        breadCrumbParts.Add(new string[] { node.ParentSlug, node.ParentTitle });
                    }
                }
                breadCrumbParts.Add(new string[] { gallery.Path, gallery.GalleryTitle });
                if (!string.IsNullOrEmpty(galleryItem.ItemTitle))
                {
                    breadCrumbParts.Add(new string[] { galleryItem.Path, galleryItem.ItemTitle });
                }
                else
                {
                    breadCrumbParts.Add(new string[] { galleryItem.Path, galleryItem.Path });
                }

                e.Page.Owner.ParseBreadCrumbs(breadCrumbParts);

                List<UserTag> tags = UserTag.GetTags(e.Core, galleryItem);

                if (tags.Count > 0)
                {
                    e.Template.Parse("HAS_USER_TAGS", "TRUE");
                }

                e.Template.Parse("TAG_COUNT", tags.Count.ToString());

                int i = 0;

                foreach (UserTag tag in tags)
                {
                    VariableCollection tagsVariableCollection = e.Template.CreateChild("user_tags");

                    tagsVariableCollection.Parse("INDEX", i.ToString());
                    tagsVariableCollection.Parse("TAG_ID", tag.TagId);
                    tagsVariableCollection.Parse("TAG_X", (tag.TagLocation.X / 1000 - 50).ToString());
                    tagsVariableCollection.Parse("TAG_Y", (tag.TagLocation.Y / 1000 - 50).ToString());
                    tagsVariableCollection.Parse("DISPLAY_NAME", tag.TaggedMember.DisplayName);
                    tagsVariableCollection.Parse("U_MEMBER", tag.TaggedMember.Uri);
                    tagsVariableCollection.Parse("TAG_USER_ID", tag.TaggedMember.Id.ToString());
                }

                if (galleryItem.NextItem != null)
                {
                    e.Template.Parse("U_NEXT_PHOTO", galleryItem.NextItem.Uri);
                }

                if (galleryItem.PreviousItem != null)
                {
                    e.Template.Parse("U_PREVIOUS_PHOTO", galleryItem.PreviousItem.Uri);
                }

                /*string path1 = TPage.GetStorageFilePath(galleryItem.StoragePath);
                string path2 = e.Core.Storage.RetrieveFilePath(string.Empty, galleryItem.StoragePath);
                string path3 = e.Core.Storage.RetrieveFilePath("_thumb", galleryItem.StoragePath);

                HttpContext.Current.Response.Write(path1 + "<br />" + path2 + "<br />" + path3);*/

            }
            catch (GalleryItemNotFoundException)
            {
                e.Core.Functions.Generate404();
                return;
            }
        }
Пример #25
0
        /// <summary>
        /// Hook showing gallery items on a group profile.
        /// </summary>
        /// <param name="e">Hook event arguments</param>
        public void ShowGroupGallery(HookEventArgs e)
        {
            UserGroup thisGroup = (UserGroup)e.Owner;

            if (!(!thisGroup.IsGroupMember(e.core.LoggedInMemberItemKey) && thisGroup.GroupType == "CLOSED"))
            {
                Template template = new Template(Assembly.GetExecutingAssembly(), "viewprofilegallery");
                template.Medium = core.Template.Medium;
                template.SetProse(core.Prose);

                // show recent photographs in the gallery
                Gallery gallery = new Gallery(e.core, thisGroup);

                List<GalleryItem> galleryItems = gallery.GetItems(e.core, 1, 6, 0);

                template.Parse("PHOTOS", thisGroup.GalleryItems.ToString());

                foreach (GalleryItem galleryItem in galleryItems)
                {
                    VariableCollection galleryVariableCollection = template.CreateChild("photo_list");

                    galleryVariableCollection.Parse("TITLE", galleryItem.ItemTitle);
                    galleryVariableCollection.Parse("PHOTO_URI", galleryItem.Uri);

                    galleryVariableCollection.Parse("THUMBNAIL", galleryItem.ThumbnailUri);
                }

                template.Parse("U_GROUP_GALLERY", Gallery.BuildGalleryUri(core, thisGroup));

                e.core.AddMainPanel(template);
            }
        }
Пример #26
0
        /// <summary>
        /// Shows an image
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Event arguments</param>
        public static void ShowImage(object sender, ShowPPageEventArgs e)
        {
            Stopwatch timer;
            timer = new Stopwatch();
            timer.Start();

            string photoName = e.Slug;
            string cdnDomain = e.Core.Settings.CdnStorageBucketDomain;

            // Square
            bool iconRequest = false; // 50
            bool tileRequest = false; // 100
            bool squareRequest = false; // 200
            bool highRequest = false; // 400

            // Ratio
            bool tinyRequest = false; // 80
            bool thumbnailRequest = false; // 160
            bool mobileRequest = false; // 320
            bool displayRequest = false; // 640
            bool fullRequest = false; // 1280
            bool ultraRequest = false; // 2560

            // Cover
            bool coverRequest = false; // 960
            bool mobileCoverRequest = false; // 480

            bool originalRequest = false;

            bool retinaModifier = false;
            string storagePrefix = string.Empty;
            PictureScale scale = PictureScale.Original;

            int extensionIndex = photoName.LastIndexOf('.');

            //HttpContext.Current.Response.Write("Here " + photoName.Substring(extensionIndex - 3, 3));
            //HttpContext.Current.Response.End();
            if (photoName.Substring(extensionIndex - 3, 3).Equals("@2x"))
            {
                retinaModifier = true;
                photoName = photoName.Remove(extensionIndex - 3, 3);
            }

            //photoName.

            if (photoName.StartsWith(IconPrefix, StringComparison.Ordinal))
            {
                photoName = photoName.Remove(0, 6);
                if (!retinaModifier)
                {
                    iconRequest = true;
                    storagePrefix = IconPrefix;
                    scale = PictureScale.Icon;
                }
                else
                {
                    tileRequest = true;
                    storagePrefix = TilePrefix;
                    scale = PictureScale.Tile;
                }
            }
            else if (photoName.StartsWith(TilePrefix, StringComparison.Ordinal))
            {
                photoName = photoName.Remove(0, 6);
                if (!retinaModifier)
                {
                    tileRequest = true;
                    storagePrefix = TilePrefix;
                    scale = PictureScale.Tile;
                }
                else
                {
                    squareRequest = true;
                    storagePrefix = SquarePrefix;
                    scale = PictureScale.Square;
                }
            }
            else if (photoName.StartsWith(SquarePrefix, StringComparison.Ordinal))
            {
                photoName = photoName.Remove(0, 8);
                if (!retinaModifier)
                {
                    squareRequest = true;
                    storagePrefix = SquarePrefix;
                    scale = PictureScale.Square;
                }
                else
                {
                    highRequest = true;
                    storagePrefix = HighPrefix;
                    scale = PictureScale.High;
                }
            }
            else if (photoName.StartsWith(HighPrefix, StringComparison.Ordinal))
            {
                photoName = photoName.Remove(0, 6);
                highRequest = true;
                storagePrefix = HighPrefix;
                scale = PictureScale.High;
                // There is no retina version of high, it is the retina version
            }
            else if (photoName.StartsWith(TinyPrefix, StringComparison.Ordinal))
            {
                photoName = photoName.Remove(0, 6);
                if (!retinaModifier)
                {
                    tinyRequest = true;
                    storagePrefix = TinyPrefix;
                    scale = PictureScale.Tiny;
                }
                else
                {
                    thumbnailRequest = true;
                    storagePrefix = ThumbnailPrefix;
                    scale = PictureScale.Thumbnail;
                }
            }
            else if (photoName.StartsWith(ThumbnailPrefix, StringComparison.Ordinal))
            {
                photoName = photoName.Remove(0, 7);
                if (!retinaModifier)
                {
                    thumbnailRequest = true;
                    storagePrefix = ThumbnailPrefix;
                    scale = PictureScale.Thumbnail;
                }
                else
                {
                    mobileRequest = true;
                    storagePrefix = MobilePrefix;
                    scale = PictureScale.Mobile;
                }
            }
            else if (photoName.StartsWith(MobilePrefix, StringComparison.Ordinal))
            {
                photoName = photoName.Remove(0, 8);
                if (!retinaModifier)
                {
                    mobileRequest = true;
                    storagePrefix = MobilePrefix;
                    scale = PictureScale.Mobile;
                }
                else
                {
                    displayRequest = true;
                    storagePrefix = DisplayPrefix;
                    scale = PictureScale.Display;
                }
            }
            else if (photoName.StartsWith(DisplayPrefix, StringComparison.Ordinal))
            {
                photoName = photoName.Remove(0, 9);
                if (!retinaModifier)
                {
                    displayRequest = true;
                    storagePrefix = DisplayPrefix;
                    scale = PictureScale.Display;
                }
                else
                {
                    fullRequest = true;
                    storagePrefix = FullPrefix;
                    scale = PictureScale.Full;
                }
            }
            else if (photoName.StartsWith(FullPrefix, StringComparison.Ordinal))
            {
                photoName = photoName.Remove(0, 6);
                if (!retinaModifier)
                {
                    fullRequest = true;
                    storagePrefix = FullPrefix;
                    scale = PictureScale.Full;
                }
                else
                {
                    ultraRequest = true;
                    storagePrefix = UltraPrefix;
                    scale = PictureScale.Ultra;
                }
            }
            else if (photoName.StartsWith(UltraPrefix, StringComparison.Ordinal))
            {
                photoName = photoName.Remove(0, 7);
                ultraRequest = true;
                storagePrefix = UltraPrefix;
                scale = PictureScale.Ultra;
            }
            else if (photoName.StartsWith(CoverPrefix, StringComparison.Ordinal))
            {
                photoName = photoName.Remove(0, 7);
                coverRequest = true;
                storagePrefix = CoverPrefix;
                scale = PictureScale.Cover;
            }
            else if (photoName.StartsWith(MobileCoverPrefix, StringComparison.Ordinal))
            {
                photoName = photoName.Remove(0, 8);
                if (!retinaModifier)
                {
                    mobileCoverRequest = true;
                    storagePrefix = MobileCoverPrefix;
                    scale = PictureScale.MobileCover;
                }
                else
                {
                    coverRequest = true;
                    storagePrefix = CoverPrefix;
                    scale = PictureScale.Cover;
                }
            }
            else
            {
                originalRequest = true;
                scale = PictureScale.Original;
            }

            string[] paths = photoName.Split('/');

            try
            {
                GalleryItem galleryItem;

                if (Gallery.GetNameFromPath(photoName) == "_" + e.Page.Owner.Key + ".png" && e.Page.Owner is User)
                {
                    galleryItem = new GalleryItem(e.Core, e.Page.Owner, ((User)e.Page.Owner).UserInfo.DisplayPictureId);
                }
                else if (Gallery.GetNameFromPath(photoName) == "_" + e.Page.Owner.Key + ".png" && e.Page.Owner is UserGroup)
                {
                    galleryItem = new GalleryItem(e.Core, e.Page.Owner, ((UserGroup)e.Page.Owner).GroupInfo.DisplayPictureId);
                }
                else if (Gallery.GetNameFromPath(photoName) == "_" + e.Page.Owner.Key + ".png" && e.Page.Owner is ApplicationEntry)
                {
                    galleryItem = new GalleryItem(e.Core, e.Page.Owner, ((ApplicationEntry)e.Page.Owner).GalleryIcon);
                }
                else
                {
                    galleryItem = new GalleryItem(e.Core, e.Page.Owner, photoName);
                }
                Gallery gallery = null;

                if (galleryItem.ParentId > 0)
                {
                    gallery = new Gallery(e.Core, e.Page.Owner, galleryItem.ParentId);
                }
                else
                {
                    gallery = new Gallery(e.Core, e.Page.Owner);
                }

                // Do not bother with extra queries when it's a public CDN request
                if ((!e.Core.Settings.UseCdn) || originalRequest)
                {
                    if (!gallery.Access.Can("VIEW_ITEMS"))
                    {
                        e.Core.Functions.Generate403();
                        return;
                    }

                    if (originalRequest)
                    {
                        if (!gallery.Access.Can("DOWNLOAD_ORIGINAL"))
                        {
                            e.Core.Functions.Generate403();
                            return;
                        }
                    }
                }

                e.Core.Http.SetToImageResponse(galleryItem.ContentType, galleryItem.GetCreatedDate(new UnixTime(e.Core, UnixTime.UTC_CODE)));

                /* we assume exists */

                /* process */

                if (!e.Core.Storage.IsCloudStorage)
                {
                    FileInfo fi = new FileInfo(e.Core.Storage.RetrieveFilePath(e.Core.Storage.PathCombine(e.Core.Settings.StorageBinUserFilesPrefix, "_storage"), galleryItem.StoragePath));

                    e.Core.Http.SetToImageResponse(galleryItem.ContentType, fi.LastWriteTimeUtc);
                }

                bool scaleExists = false;

                if (scale != PictureScale.Original)
                {
                    switch (scale)
                    {
                        case PictureScale.Icon:
                            scaleExists = galleryItem.IconExists;
                            cdnDomain = e.Core.Settings.CdnIconBucketDomain;
                            break;
                        case PictureScale.Tile:
                            scaleExists = galleryItem.TileExists;
                            cdnDomain = e.Core.Settings.CdnTileBucketDomain;
                            break;
                        case PictureScale.Square:
                            scaleExists = galleryItem.SquareExists;
                            cdnDomain = e.Core.Settings.CdnSquareBucketDomain;
                            break;
                        case PictureScale.High:
                            scaleExists = galleryItem.HighExists;
                            cdnDomain = e.Core.Settings.CdnHighBucketDomain;
                            break;
                        case PictureScale.Tiny:
                            scaleExists = galleryItem.TinyExists;
                            cdnDomain = e.Core.Settings.CdnTinyBucketDomain;
                            break;
                        case PictureScale.Thumbnail:
                            scaleExists = galleryItem.ThumbnailExists;
                            cdnDomain = e.Core.Settings.CdnThumbBucketDomain;
                            break;
                        case PictureScale.Mobile:
                            scaleExists = galleryItem.MobileExists;
                            cdnDomain = e.Core.Settings.CdnMobileBucketDomain;
                            break;
                        case PictureScale.Display:
                            scaleExists = galleryItem.DisplayExists;
                            cdnDomain = e.Core.Settings.CdnDisplayBucketDomain;
                            break;
                        case PictureScale.Full:
                            scaleExists = galleryItem.FullExists;
                            cdnDomain = e.Core.Settings.CdnFullBucketDomain;
                            break;
                        case PictureScale.Ultra:
                            scaleExists = galleryItem.UltraExists;
                            cdnDomain = e.Core.Settings.CdnUltraBucketDomain;
                            break;
                        case PictureScale.Cover:
                            scaleExists = galleryItem.CoverExists;
                            cdnDomain = e.Core.Settings.CdnCoverBucketDomain;
                            break;
                        case PictureScale.MobileCover:
                            scaleExists = galleryItem.MobileCoverExists;
                            cdnDomain = e.Core.Settings.CdnMobileCoverBucketDomain;
                            break;
                    }

                    if (!scaleExists)
                    {
                        if (scale == PictureScale.MobileCover && e.Core.Storage.IsCloudStorage && !e.Core.Settings.UseCdn)
                        {
                            //HttpContext.Current.Response.Write("Checking for scale: " + timer.ElapsedMilliseconds.ToString() + "\n");
                        }
                        scaleExists = e.Core.Storage.FileExists(e.Core.Storage.PathCombine(e.Core.Settings.StorageBinUserFilesPrefix, storagePrefix), galleryItem.StoragePath);

                        if (scaleExists)
                        {
                            switch (scale)
                            {
                                case PictureScale.Icon:
                                    galleryItem.IconExists = true;
                                    break;
                                case PictureScale.Tile:
                                    galleryItem.TileExists = true;
                                    break;
                                case PictureScale.Square:
                                    galleryItem.SquareExists = true;
                                    break;
                                case PictureScale.High:
                                    galleryItem.HighExists = true;
                                    break;
                                case PictureScale.Tiny:
                                    galleryItem.TinyExists = true;
                                    break;
                                case PictureScale.Thumbnail:
                                    galleryItem.ThumbnailExists = true;
                                    break;
                                case PictureScale.Mobile:
                                    galleryItem.MobileExists = true;
                                    break;
                                case PictureScale.Display:
                                    galleryItem.DisplayExists = true;
                                    break;
                                case PictureScale.Full:
                                    galleryItem.FullExists = true;
                                    break;
                                case PictureScale.Ultra:
                                    galleryItem.UltraExists = true;
                                    break;
                                case PictureScale.Cover:
                                    galleryItem.CoverExists = true;
                                    break;
                                case PictureScale.MobileCover:
                                    galleryItem.MobileCoverExists = true;
                                    break;
                            }

                            galleryItem.Update();
                        }
                    }

                    if (!scaleExists)
                    {
                        bool flag;

                        if (scale == PictureScale.MobileCover && e.Core.Storage.IsCloudStorage && !e.Core.Settings.UseCdn)
                        {
                            //HttpContext.Current.Response.Write("Scale not found: " + timer.ElapsedMilliseconds.ToString() + "\n");
                        }
                        switch (scale)
                        {
                            case PictureScale.Icon:
                            case PictureScale.Tile:
                            case PictureScale.Square:
                            case PictureScale.High:
                                flag = CreateScaleWithSquareRatio(e.Core, galleryItem, galleryItem.StoragePath, storagePrefix, (int)scale, (int)scale);

                                if (flag)
                                {
                                    switch (scale)
                                    {
                                        case PictureScale.Icon:
                                            galleryItem.IconExists = true;
                                            break;
                                        case PictureScale.Tile:
                                            galleryItem.TileExists = true;
                                            break;
                                        case PictureScale.Square:
                                            galleryItem.SquareExists = true;
                                            break;
                                        case PictureScale.High:
                                            galleryItem.HighExists = true;
                                            break;
                                    }
                                }
                                break;
                            case PictureScale.Tiny:
                            case PictureScale.Thumbnail:
                            case PictureScale.Mobile:
                            case PictureScale.Display:
                            case PictureScale.Full:
                            case PictureScale.Ultra:
                                flag = CreateScaleWithRatioPreserved(e.Core, galleryItem, galleryItem.StoragePath, storagePrefix, (int)scale, (int)scale);

                                if (flag)
                                {
                                    switch (scale)
                                    {
                                        case PictureScale.Tiny:
                                            galleryItem.TinyExists = true;
                                            break;
                                        case PictureScale.Thumbnail:
                                            galleryItem.ThumbnailExists = true;
                                            break;
                                        case PictureScale.Mobile:
                                            galleryItem.MobileExists = true;
                                            break;
                                        case PictureScale.Display:
                                            galleryItem.DisplayExists = true;
                                            break;
                                        case PictureScale.Full:
                                            galleryItem.FullExists = true;
                                            break;
                                        case PictureScale.Ultra:
                                            galleryItem.UltraExists = true;
                                            break;
                                    }
                                }
                                break;
                            case PictureScale.Cover:
                                CreateCoverPhoto(e.Core, galleryItem, galleryItem.StoragePath, false);
                                galleryItem.CoverExists = true;
                                break;
                            case PictureScale.MobileCover:
                                if (e.Core.Storage.IsCloudStorage && !e.Core.Settings.UseCdn)
                                {
                                    //HttpContext.Current.Response.Write("About to create cover photo: " + timer.ElapsedMilliseconds.ToString() + "\n");
                                }
                                CreateCoverPhoto(e.Core, galleryItem, galleryItem.StoragePath, true);
                                galleryItem.MobileCoverExists = true;
                                break;
                        }

                        galleryItem.Update();
                    }

                    if (e.Core.Storage.IsCloudStorage)
                    {
                        if (e.Core.Settings.UseCdn)
                        {
                            string imageUri = e.Core.Http.DefaultProtocol + cdnDomain + "/" + galleryItem.StoragePath;
                            e.Core.Http.Redirect(imageUri);
                        }
                        else
                        {
                            if (scale == PictureScale.MobileCover)
                            {
                                //HttpContext.Current.Response.Write("About to get file uri: " + timer.ElapsedMilliseconds.ToString() + "\n");
                            }
                            string imageUri = e.Core.Storage.RetrieveFileUri(e.Core.Storage.PathCombine(e.Core.Settings.StorageBinUserFilesPrefix, storagePrefix), galleryItem.storagePath, galleryItem.ContentType, "picture" + GetFileExtension(galleryItem.ContentType));
                            //if (scale != PictureScale.MobileCover)
                            {
                                e.Core.Http.Redirect(imageUri);
                            }
                            /*else
                            {
                                HttpContext.Current.Response.ContentType = "text/plain";
                                HttpContext.Current.Response.Write("End: " + timer.ElapsedMilliseconds.ToString() + "\n");
                                HttpContext.Current.Response.Write("I made it here\n");
                            }*/
                        }
                    }
                    else
                    {
                        if (galleryItem.ContentType == "image/png")
                        {
                            MemoryStream newStream = new MemoryStream();

                            Stream image = e.Core.Storage.RetrieveFile(e.Core.Storage.PathCombine(e.Core.Settings.StorageBinUserFilesPrefix, storagePrefix), galleryItem.StoragePath);
                            Image hoi = Image.FromStream(image);

                            hoi.Save(newStream, hoi.RawFormat);

                            e.Core.Http.WriteStream(newStream);
                        }
                        else
                        {
                            string imagePath = e.Core.Storage.RetrieveFilePath(e.Core.Storage.PathCombine(e.Core.Settings.StorageBinUserFilesPrefix, storagePrefix), galleryItem.storagePath);
                            e.Core.Http.TransmitFile(imagePath);
                        }
                    }
                }
                else
                {
                    if (e.Core.Storage.IsCloudStorage)
                    {
                        /*if (e.Core.Settings.UseCdn)
                        {
                            string imageUri = "http://" + e.Core.Settings.CdnStorageBucketDomain + "/" + galleryItem.StoragePath;
                            e.Core.Http.Redirect(imageUri);
                        }
                        else
                        {*/
                            string imageUri = e.Core.Storage.RetrieveFileUri(e.Core.Storage.PathCombine(e.Core.Settings.StorageBinUserFilesPrefix, "_storage"), galleryItem.storagePath, galleryItem.ContentType, "picture" + GetFileExtension(galleryItem.ContentType));
                            e.Core.Http.Redirect(imageUri);
                        //}
                    }
                    else
                    {
                        if (galleryItem.ContentType == "image/png")
                        {
                            MemoryStream newStream = new MemoryStream();

                            Stream image = e.Core.Storage.RetrieveFile(e.Core.Storage.PathCombine(e.Core.Settings.StorageBinUserFilesPrefix, "_storage"), galleryItem.StoragePath);
                            Image hoi = Image.FromStream(image);

                            hoi.Save(newStream, hoi.RawFormat);

                            e.Core.Http.WriteStream(newStream);
                        }
                        else
                        {
                            string imagePath = e.Core.Storage.RetrieveFilePath(e.Core.Storage.PathCombine(e.Core.Settings.StorageBinUserFilesPrefix, "_storage"), galleryItem.storagePath);
                            e.Core.Http.TransmitFile(imagePath);
                        }
                    }
                }
            }
            catch (GalleryItemNotFoundException)
            {
                e.Core.Functions.Generate404();
                return;
            }

            if (e.Db != null)
            {
                e.Db.CloseConnection();
            }
            e.Core.Http.End();
        }
Пример #27
0
        void PostContent(HookEventArgs e)
        {
            VariableCollection styleSheetVariableCollection = core.Template.CreateChild("javascript_list");
            styleSheetVariableCollection.Parse("URI", @"/scripts/load-image.min.js");
            styleSheetVariableCollection = core.Template.CreateChild("javascript_list");
            styleSheetVariableCollection.Parse("URI", @"/scripts/canvas-to-blob.min.js");

            styleSheetVariableCollection = core.Template.CreateChild("javascript_list");
            styleSheetVariableCollection.Parse("URI", @"/scripts/jquery.iframe-transport.js");
            styleSheetVariableCollection = core.Template.CreateChild("javascript_list");
            styleSheetVariableCollection.Parse("URI", @"/scripts/jquery.fileupload.js");
            styleSheetVariableCollection = core.Template.CreateChild("javascript_list");
            styleSheetVariableCollection.Parse("URI", @"/scripts/jquery.fileupload-process.js");
            styleSheetVariableCollection = core.Template.CreateChild("javascript_list");
            styleSheetVariableCollection.Parse("URI", @"/scripts/jquery.fileupload-image.js");

            if (e.core.IsMobile)
            {
                return;
            }

            Template template = new Template(Assembly.GetExecutingAssembly(), "postphoto");
            template.Medium = core.Template.Medium;
            template.SetProse(core.Prose);

            string formSubmitUri = core.Hyperlink.AppendSid(e.Owner.AccountUriStub, true);
            template.Parse("U_ACCOUNT", formSubmitUri);
            template.Parse("S_ACCOUNT", formSubmitUri);

            template.Parse("USER_DISPLAY_NAME", e.Owner.DisplayName);

            CheckBox publishToFeedCheckBox = new CheckBox("publish-feed");
            publishToFeedCheckBox.IsChecked = true;

            CheckBox highQualityCheckBox = new CheckBox("high-quality");
            highQualityCheckBox.IsChecked = false;

            core.Display.ParseLicensingBox(template, "S_GALLERY_LICENSE", 0);

            template.Parse("S_PUBLISH_FEED", publishToFeedCheckBox);
            template.Parse("S_HIGH_QUALITY", highQualityCheckBox);

            core.Display.ParseClassification(template, "S_PHOTO_CLASSIFICATION", Classifications.Everyone);

            PermissionGroupSelectBox permissionSelectBox = new PermissionGroupSelectBox(core, "permissions", e.Owner.ItemKey);
            HiddenField aclModeField = new HiddenField("aclmode");
            aclModeField.Value = "simple";

            template.Parse("S_PERMISSIONS", permissionSelectBox);
            template.Parse("S_ACLMODE", aclModeField);

            //GallerySettings settings = new GallerySettings(core, e.Owner);
            Gallery rootGallery = new Gallery(core, e.Owner);
            List<Gallery> galleries = rootGallery.GetGalleries();

            SelectBox galleriesSelectBox = new SelectBox("gallery-id");

            foreach (Gallery gallery in galleries)
            {
                galleriesSelectBox.Add(new SelectBoxItem(gallery.Id.ToString(), gallery.GalleryTitle));
            }

            template.Parse("S_GALLERIES", galleriesSelectBox);

            /* Title TextBox */
            TextBox galleryTitleTextBox = new TextBox("gallery-title");
            galleryTitleTextBox.MaxLength = 127;

            template.Parse("S_GALLERY_TITLE", galleryTitleTextBox);

            CheckBoxArray shareCheckBoxArray = new CheckBoxArray("share-radio");
            shareCheckBoxArray.Layout = Layout.Horizontal;
            CheckBox twitterSyndicateCheckBox = null;
            CheckBox tumblrSyndicateCheckBox = null;
            CheckBox facebookSyndicateCheckBox = null;

            if (e.Owner is User)
            {
                User user = (User)e.Owner;

                if (user.UserInfo.TwitterAuthenticated)
                {
                    twitterSyndicateCheckBox = new CheckBox("photo-share-twitter");
                    twitterSyndicateCheckBox.Caption = "Twitter";
                    twitterSyndicateCheckBox.Icon = "https://g.twimg.com/twitter-bird-16x16.png";
                    twitterSyndicateCheckBox.IsChecked = user.UserInfo.TwitterSyndicate;
                    twitterSyndicateCheckBox.Width.Length = 0;

                    shareCheckBoxArray.Add(twitterSyndicateCheckBox);
                }

                if (user.UserInfo.TumblrAuthenticated)
                {
                    tumblrSyndicateCheckBox = new CheckBox("photo-share-tumblr");
                    tumblrSyndicateCheckBox.Caption = "Tumblr";
                    tumblrSyndicateCheckBox.Icon = "https://platform.tumblr.com/v1/share_4.png";
                    tumblrSyndicateCheckBox.IsChecked = user.UserInfo.TumblrSyndicate;
                    tumblrSyndicateCheckBox.Width.Length = 0;

                    shareCheckBoxArray.Add(tumblrSyndicateCheckBox);
                }

                if (user.UserInfo.FacebookAuthenticated)
                {
                    facebookSyndicateCheckBox = new CheckBox("photo-share-facebook");
                    facebookSyndicateCheckBox.Caption = "Facebook";
                    facebookSyndicateCheckBox.Icon = "https://fbstatic-a.akamaihd.net/rsrc.php/v2/yU/r/fWK1wxX-qQn.png";
                    facebookSyndicateCheckBox.IsChecked = user.UserInfo.FacebookSyndicate;
                    facebookSyndicateCheckBox.Width.Length = 0;

                    shareCheckBoxArray.Add(facebookSyndicateCheckBox);
                }

            }

            if (shareCheckBoxArray.Count > 0)
            {
                template.Parse("S_SHARE", "TRUE");
            }
            if (twitterSyndicateCheckBox != null)
            {
                template.Parse("S_SHARE_TWITTER", twitterSyndicateCheckBox);
            }
            if (tumblrSyndicateCheckBox != null)
            {
                template.Parse("S_SHARE_TUMBLR", tumblrSyndicateCheckBox);
            }
            if (facebookSyndicateCheckBox != null)
            {
                template.Parse("S_SHARE_FACEBOOK", facebookSyndicateCheckBox);
            }

            e.core.AddPostPanel(e.core.Prose.GetString("PHOTO"), template);
        }
Пример #28
0
        /// <summary>
        /// Initialises a new instance of the GalleryItem class.
        /// </summary>
        /// <param name="core">Core token</param>
        /// <param name="owner">Gallery item owner</param>
        /// <param name="parent">Gallery item parent</param>
        /// <param name="path">Gallery item path</param>
        public GalleryItem(Core core, User owner, Gallery parent, string path)
            : base(core)
        {
            this.owner = owner;

            ItemLoad += new ItemLoadHandler(GalleryItem_ItemLoad);

            SelectQuery query = GalleryItem.GetSelectQueryStub(core, typeof(GalleryItem));
            query.AddCondition("gallery_item_parent_path", Gallery.GetParentPath(path));
            query.AddCondition("gallery_item_uri", Gallery.GetNameFromPath(path));
            query.AddCondition("gallery_item_item_id", owner.Id);
            query.AddCondition("gallery_item_item_type_id", owner.TypeId);

            DataTable galleryItemTable = db.Query(query);

            if (galleryItemTable.Rows.Count == 1)
            {
                loadItemInfo(galleryItemTable.Rows[0]);
                /*try
                {
                    licenseInfo = new ContentLicense(core, galleryItemTable.Rows[0]);
                }
                catch (InvalidLicenseException)
                {
                }*/
            }
            else
            {
                throw new GalleryItemNotFoundException();
            }
        }
Пример #29
0
        void AccountGalleriesUpload_Save(object sender, EventArgs e)
        {
            ControlPanelSubModule.AuthoriseRequestSid(core);

            long galleryId = core.Functions.FormLong("gallery-id", 0);
            string title = core.Http.Form["title"];
            string galleryTitle = core.Http.Form["gallery-title"];
            string description = core.Http.Form["description"];
            bool publishToFeed = (core.Http.Form["publish-feed"] != null);
            bool highQualitySave = (core.Http.Form["high-quality"] != null);
            bool submittedTitle = true;

            if (string.IsNullOrEmpty(galleryTitle))
            {
                submittedTitle = false;
                galleryTitle = "Uploaded " + core.Tz.Now.ToString("MMMM dd, yyyy");
            }

            bool newGallery = core.Http.Form["album"] == "create";

            int filesUploaded = 0;
            for (int i = 0; i < core.Http.Files.Count; i++)
            {
                if (core.Http.Files.GetKey(i).StartsWith("photo-file", StringComparison.Ordinal))
                {
                    filesUploaded++;
                    if (core.Http.Files[i] == null || core.Http.Files[i].ContentLength == 0)
                    {
                        core.Response.ShowMessage("error", "No files selected", "You need to select some files to upload");
                    }
                }
            }

            if (filesUploaded == 0)
            {
                core.Response.ShowMessage("error", "No files selected", "You need to select some files to upload");
                return;
            }

            try
            {
                Gallery parent = null;

                if (newGallery)
                {
                    Gallery grandParent = null;

                    if (!submittedTitle)
                    {
                        string grandParentSlug = "photos-from-posts";
                        try
                        {
                            grandParent = new Gallery(core, Owner, grandParentSlug);
                        }
                        catch (InvalidGalleryException)
                        {
                            Gallery root = new Gallery(core, Owner);
                            grandParent = Gallery.Create(core, Owner, root, "Photos From Posts", ref grandParentSlug, "All my unsorted uploads");
                        }
                    }
                    else
                    {
                        grandParent = new Gallery(core, Owner);
                    }

                    string gallerySlug = string.Empty;

                    if (!submittedTitle)
                    {
                        gallerySlug = "photos-" + UnixTime.UnixTimeStamp().ToString();
                    }
                    else
                    {
                        gallerySlug = Gallery.GetSlugFromTitle(galleryTitle, "");
                    }

                    try
                    {
                        parent = Gallery.Create(core, LoggedInMember, grandParent, galleryTitle, ref gallerySlug, string.Empty);
                    }
                    catch (GallerySlugNotUniqueException)
                    {
                        core.Response.ShowMessage("error", "Gallery not unique", "Please give a different name to the gallery");
                    }

                    AccessControlLists acl = new AccessControlLists(core, parent);
                    acl.SaveNewItemPermissions();
                }
                else
                {
                    parent = new Gallery(core, Owner, galleryId);
                }

                string slug = string.Empty;
                try
                {
                    for (int i = 0; i < core.Http.Files.Count; i++)
                    {
                        if (!core.Http.Files.GetKey(i).StartsWith("photo-file", StringComparison.Ordinal))
                        {
                            continue;
                        }

                        slug = core.Http.Files[i].FileName;

                        MemoryStream stream = new MemoryStream();
                        core.Http.Files[i].InputStream.CopyTo(stream);

                        db.BeginTransaction();

                        GalleryItem newGalleryItem = GalleryItem.Create(core, Owner, parent, title, ref slug, core.Http.Files[i].FileName, core.Http.Files[i].ContentType, (ulong)core.Http.Files[i].ContentLength, description, core.Functions.GetLicenseId(), core.Functions.GetClassification(), stream, highQualitySave /*, width, height*/);
                        stream.Close();

                        if (publishToFeed && i < 3)
                        {
                            core.CallingApplication.PublishToFeed(core, LoggedInMember, parent, newGalleryItem, Functions.SingleLine(core.Bbcode.Flatten(newGalleryItem.ItemAbstract)));
                        }
                    }

                    //db.CommitTransaction();

                    if (core.ResponseFormat == ResponseFormats.Xml)
                    {
                        long newestId = core.Functions.FormLong("newest-id", 0);
                        long newerId = 0;

                        List<BoxSocial.Internals.Action> feedActions = Feed.GetNewerItems(core, LoggedInMember, newestId);

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

                        foreach (BoxSocial.Internals.Action feedAction in feedActions)
                        {
                            VariableCollection feedItemVariableCollection = template.CreateChild("feed_days_list.feed_item");

                            if (feedAction.Id > newerId)
                            {
                                newerId = feedAction.Id;
                            }

                            core.Display.ParseBbcode(feedItemVariableCollection, "TITLE", feedAction.FormattedTitle);
                            core.Display.ParseBbcode(feedItemVariableCollection, "TEXT", feedAction.Body, core.PrimitiveCache[feedAction.OwnerId], true, string.Empty, string.Empty);

                            feedItemVariableCollection.Parse("USER_DISPLAY_NAME", feedAction.Owner.DisplayName);

                            feedItemVariableCollection.Parse("ID", feedAction.ActionItemKey.Id);
                            feedItemVariableCollection.Parse("TYPE_ID", feedAction.ActionItemKey.TypeId);

                            if (feedAction.ActionItemKey.GetType(core).Likeable)
                            {
                                feedItemVariableCollection.Parse("LIKEABLE", "TRUE");

                                if (feedAction.Info.Likes > 0)
                                {
                                    feedItemVariableCollection.Parse("LIKES", string.Format(" {0:d}", feedAction.Info.Likes));
                                    feedItemVariableCollection.Parse("DISLIKES", string.Format(" {0:d}", feedAction.Info.Dislikes));
                                }
                            }

                            if (feedAction.ActionItemKey.GetType(core).Commentable)
                            {
                                feedItemVariableCollection.Parse("COMMENTABLE", "TRUE");

                                if (feedAction.Info.Comments > 0)
                                {
                                    feedItemVariableCollection.Parse("COMMENTS", string.Format(" ({0:d})", feedAction.Info.Comments));
                                }
                            }

                            //Access access = new Access(core, feedAction.ActionItemKey, true);
                            if (feedAction.PermissiveParent.Access.IsPublic())
                            {
                                feedItemVariableCollection.Parse("IS_PUBLIC", "TRUE");
                                if (feedAction.ActionItemKey.GetType(core).Shareable)
                                {
                                    feedItemVariableCollection.Parse("SHAREABLE", "TRUE");
                                    //feedItemVariableCollection.Parse("U_SHARE", feedAction.ShareUri);

                                    if (feedAction.Info.SharedTimes > 0)
                                    {
                                        feedItemVariableCollection.Parse("SHARES", string.Format(" {0:d}", feedAction.Info.SharedTimes));
                                    }
                                }
                            }

                            if (feedAction.Owner is User)
                            {
                                feedItemVariableCollection.Parse("USER_TILE", ((User)feedAction.Owner).Tile);
                                feedItemVariableCollection.Parse("USER_ICON", ((User)feedAction.Owner).Icon);
                            }
                        }

                        // Check for new messages and upload
                        Dictionary<string, string> returnValues = new Dictionary<string, string>();

                        returnValues.Add("update", "true");
                        returnValues.Add("message", description);
                        returnValues.Add("template", template.ToString());
                        returnValues.Add("newest-id", newerId.ToString());

                        core.Response.SendDictionary("statusPosted", returnValues);
                    }
                    else
                    {
                        if (filesUploaded == 1)
                        {
                            template.Parse("REDIRECT_URI", Gallery.BuildPhotoUri(core, Owner, parent.FullPath, slug));
                        }
                        else
                        {
                            template.Parse("REDIRECT_URI", parent.Uri);
                        }
                        core.Display.ShowMessage("Photo Uploaded", "You have successfully uploaded a photo.");
                    }

                    return;
                }
                catch (GalleryItemTooLargeException)
                {
                    db.RollBackTransaction();
                    core.Response.ShowMessage("error", "Photo too big", "The photo you have attempted to upload is too big, you can upload photos up to " + Functions.BytesToString(core.Settings.MaxFileSize) + " in size.");
                    return;
                }
                catch (GalleryQuotaExceededException)
                {
                    db.RollBackTransaction();
                    core.Response.ShowMessage("error", "Not Enough Quota", "You do not have enough quota to upload this photo. Try resizing the image before uploading or deleting images you no-longer need. Smaller images use less quota.");
                    return;
                }
                catch (InvalidGalleryItemTypeException)
                {
                    db.RollBackTransaction();
                    core.Response.ShowMessage("error", "Invalid image uploaded", "You have tried to upload a file type that is not a picture. You are allowed to upload PNG and JPEG images.");
                    return;
                }
                catch (InvalidGalleryFileNameException)
                {
                    db.RollBackTransaction();
                    core.Response.ShowMessage("error", "Submission failed", "Submission failed, try uploading with a different file name.");
                    return;
                }
            }
            catch (InvalidGalleryException)
            {
                db.RollBackTransaction();
                core.Response.ShowMessage("error", "Submission failed", "Submission failed, Invalid Gallery.");
                return;

            }
        }
Пример #30
0
        /// <summary>
        /// Default show procedure for account sub module.
        /// </summary>
        /// <param name="sender">Object calling load event</param>
        /// <param name="e">Load EventArgs</param>
        void AccountGalleriesUpload_Show(object sender, EventArgs e)
        {
            SetTemplate("account_galleries_upload");

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

            if (galleryId == 0)
            {
                // Invalid gallery
                DisplayGenericError();
                return;
            }

            try
            {
                Gallery gallery = new Gallery(core, Owner, galleryId);

                CheckBox publishToFeedCheckBox = new CheckBox("publish-feed");
                publishToFeedCheckBox.IsChecked = true;

                CheckBox highQualityCheckBox = new CheckBox("high-quality");
                highQualityCheckBox.IsChecked = false;

                core.Display.ParseLicensingBox(template, "S_GALLERY_LICENSE", 0);

                template.Parse("S_PUBLISH_FEED", publishToFeedCheckBox);
                template.Parse("S_HIGH_QUALITY", highQualityCheckBox);
                template.Parse("S_GALLERY_ID", galleryId.ToString());

                core.Display.ParseClassification(template, "S_PHOTO_CLASSIFICATION", Classifications.Everyone);
            }
            catch (InvalidGalleryException)
            {
                DisplayGenericError();
                return;
            }

            Save(new EventHandler(AccountGalleriesUpload_Save));
        }