Exemple #1
0
        /// <summary>
        /// Initialises a new instance of the UserTag class.
        /// </summary>
        /// <param name="core">Core token</param>
        /// <param name="galleryItem">The gallery item tagged</param>
        /// <param name="tagId">Tag Id to retrieve</param>
        public UserTag(Core core, GalleryItem galleryItem, long tagId)
            : base(core)
        {
            ItemLoad += new ItemLoadHandler(UserTag_ItemLoad);

            taggedGalleryItem = galleryItem;

            try
            {
                LoadItem(tagId);
            }
            catch (InvalidItemException)
            {
                throw new InvalidUserTagException();
            }
        }
        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;
            }
        }
        void AccountGalleriesPhotoTag_Save(object sender, EventArgs e)
        {
            AuthoriseRequestSid();

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

                GalleryItem photo = new GalleryItem(core, Owner, photoId);

                long tagCount = core.Functions.FormLong("tags", 0);
                HttpContext.Current.Response.Write(tagCount.ToString());

                List<UserTag> tags = UserTag.GetTags(core, photo);

                List<string> tagInfo = new List<string>();

                List<string> usernames = new List<string>();
                Dictionary<string, long> usersTaggedByName = new Dictionary<string, long>();

                // Load names
                for (int i = 0; i < tagCount; i++)
                {
                    if (!string.IsNullOrEmpty(core.Http.Form["name[" + i + "]"]))
                    {
                        if (!usernames.Contains(core.Http.Form["name[" + i + "]"]))
                        {
                            usernames.Add(core.Http.Form["name[" + i + "]"]);
                            long userId = core.LoadUserProfile(core.Http.Form["name[" + i + "]"]);
                            if (userId > 0)
                            {
                                usersTaggedByName.Add(core.Http.Form["name[" + i + "]"], userId);
                            }
                        }
                    }
                }

                /*
                 * Tag info of the format x,y,title,uid
                 */
                for (int i = 0; i < tagCount; i++)
                {
                    string tag = core.Http.Form["tag[" + i + "]"];
                    string name = core.Http.Form["name[" + i + "]"];
                    if (string.IsNullOrEmpty(name))
                    {
                        tagInfo.Add(tag);
                    }
                    else
                    {
                        if (usersTaggedByName.ContainsKey(name))
                        {
                            tagInfo.Add(tag + "," + name + "," + usersTaggedByName[name].ToString());
                        }
                        else
                        {
                            tagInfo.Add(tag + "," + name + "," + "0");
                        }
                    }
                }

                Dictionary<long, Point> newTags = new Dictionary<long, Point>();

                foreach (string ti in tagInfo)
                {
                    bool tagExists = false;
                    string[] parts = ti.Split(',');

                    if (parts.Length != 4)
                    {
                        continue;
                    }

                    int x, y;
                    string title = parts[2];
                    long uid;

                    if ((!int.TryParse(parts[0], out x)) || (!int.TryParse(parts[1], out y)) || (!long.TryParse(parts[3], out uid)))
                    {
                        continue;
                    }

                    bool flag = true;
                    foreach (UserTag tag in tags)
                    {
                        if (tag.TaggedMember.Id == uid)
                        {
                            flag = false;
                            break;
                        }
                    }

                    if (flag)
                    {
                        core.LoadUserProfile(uid);
                        newTags.Add(uid, new Point(x * 1000, y * 1000));
                    }
                }

                foreach (long uid in newTags.Keys)
                {
                    UserTag ut = UserTag.Create(core, photo, core.Session.LoggedInMember, core.PrimitiveCache[uid], newTags[uid]);
                }
            }
            catch (GalleryItemNotFoundException)
            {
                core.Display.ShowMessage("Invalid submission", "You have made an invalid form submission. (0x0A)");
                return;
            }
        }
        void AccountGalleriesPhotoDelete_Show(object sender, EventArgs e)
        {
            long id = core.Functions.RequestLong("id", 0);

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

            try
            {
                GalleryItem ugi = new GalleryItem(core, Owner, id);

                Dictionary<string, string> hiddenFieldList = new Dictionary<string, string>();
                hiddenFieldList.Add("module", ModuleKey);
                hiddenFieldList.Add("sub", Key);
                hiddenFieldList.Add("mode", "confirm");
                hiddenFieldList.Add("id", ugi.Id.ToString());

                core.Display.ShowConfirmBox(core.Hyperlink.AppendSid(Owner.AccountUriStub, true),
                    "Confirm Delete Photo",
                    string.Format("Are you sure you want to delete the photo `{0}`",
                    ugi.Path), hiddenFieldList);
            }
            catch
            {
                DisplayGenericError();
            }
        }
Exemple #5
0
        public override bool ExecuteJob(Job job)
        {
            if (job.ItemId == 0)
            {
                return true;
            }

            switch (job.Function)
            {
                case "notifyGalleryComment":
                    Gallery.NotifyGalleryComment(core, job);
                    return true;
                case "notifyGalleryItemComment":
                    GalleryItem.NotifyGalleryItemComment(core, job);
                    return true;
                case "create_ultra":
                    try
                    {
                        GalleryItem gi = new GalleryItem(core, job.ItemId);

                        if (gi.UltraExists) return true;

                        if (gi.ItemWidth > (int)PictureScale.Ultra || gi.ItemHeight > (int)PictureScale.Ultra)
                        {
                            if (GalleryItem.CreateScaleWithRatioPreserved(core, gi, gi.StoragePath, GalleryItem.UltraPrefix, (int)PictureScale.Ultra, (int)PictureScale.Ultra))
                            {
                                gi.UltraExists = true;
                                gi.Update();
                            }
                        }
                    }
                    catch (GalleryItemNotFoundException)
                    {
                        return true; // no big deal if this job fails
                    }
                    return true;
                case "create_full":
                    try
                    {
                        GalleryItem gi = new GalleryItem(core, job.ItemId);

                        if (gi.FullExists) return true;

                        if (gi.ItemWidth > (int)PictureScale.Full || gi.ItemHeight > (int)PictureScale.Full)
                        {
                            if (GalleryItem.CreateScaleWithRatioPreserved(core, gi, gi.StoragePath, GalleryItem.FullPrefix, (int)PictureScale.Full, (int)PictureScale.Full))
                            {
                                gi.FullExists = true;
                                gi.Update();
                            }
                        }
                    }
                    catch (GalleryItemNotFoundException)
                    {
                        return true; // no big deal if this job fails
                    }
                    return true;
                case "create_display":
                    try
                    {
                        GalleryItem gi = new GalleryItem(core, job.ItemId);

                        if (gi.DisplayExists) return true;

                        if (gi.ItemWidth > (int)PictureScale.Display || gi.ItemHeight > (int)PictureScale.Display)
                        {
                            if (GalleryItem.CreateScaleWithRatioPreserved(core, gi, gi.StoragePath, GalleryItem.DisplayPrefix, (int)PictureScale.Display, (int)PictureScale.Display))
                            {
                                gi.DisplayExists = true;
                                gi.Update();
                            }
                        }
                        else
                        {
                            // This strips all uploaded images of EXIF data
                            if (GalleryItem.CreateScaleWithRatioPreserved(core, gi, gi.StoragePath, GalleryItem.DisplayPrefix, gi.ItemWidth, gi.ItemHeight))
                            {
                                gi.DisplayExists = true;
                                gi.Update();
                            }
                        }
                    }
                    catch (GalleryItemNotFoundException)
                    {
                        return true; // no big deal if this job fails
                    }
                    return true;
                case "create_mobile":
                    try
                    {
                        GalleryItem gi = new GalleryItem(core, job.ItemId);

                        if (gi.MobileExists) return true;

                        if (gi.ItemWidth > (int)PictureScale.Mobile || gi.ItemHeight > (int)PictureScale.Mobile)
                        {
                            if (GalleryItem.CreateScaleWithRatioPreserved(core, gi, gi.StoragePath, GalleryItem.MobilePrefix, (int)PictureScale.Mobile, (int)PictureScale.Mobile))
                            {
                                gi.MobileExists = true;
                                gi.Update();
                            }
                        }
                    }
                    catch (GalleryItemNotFoundException)
                    {
                        return true; // no big deal if this job fails
                    }
                    return true;
                case "create_thumb":
                    try
                    {
                        GalleryItem gi = new GalleryItem(core, job.ItemId);

                        if (gi.ThumbnailExists) return true;

                        if (gi.ItemWidth > (int)PictureScale.Thumbnail || gi.ItemHeight > (int)PictureScale.Thumbnail)
                        {
                            if (GalleryItem.CreateScaleWithRatioPreserved(core, gi, gi.StoragePath, GalleryItem.ThumbnailPrefix, (int)PictureScale.Thumbnail, (int)PictureScale.Thumbnail))
                            {
                                gi.ThumbnailExists = true;
                                gi.Update();
                            }
                        }
                    }
                    catch (GalleryItemNotFoundException)
                    {
                        return true; // no big deal if this job fails
                    }
                    return true;
                case "create_tiny":
                    try
                    {
                        GalleryItem gi = new GalleryItem(core, job.ItemId);

                        if (gi.TinyExists) return true;

                        if (gi.ItemWidth > (int)PictureScale.Tiny || gi.ItemHeight > (int)PictureScale.Tiny)
                        {
                            if (GalleryItem.CreateScaleWithRatioPreserved(core, gi, gi.StoragePath, GalleryItem.TinyPrefix, (int)PictureScale.Tiny, (int)PictureScale.Tiny))
                            {
                                gi.TinyExists = true;
                                gi.Update();
                            }
                        }
                    }
                    catch (GalleryItemNotFoundException)
                    {
                        return true; // no big deal if this job fails
                    }
                    return true;
                case "create_high":
                    try
                    {
                        GalleryItem gi = new GalleryItem(core, job.ItemId);

                        if (gi.TinyExists) return true;

                        if (GalleryItem.CreateScaleWithSquareRatio(core, gi, gi.StoragePath, GalleryItem.HighPrefix, (int)PictureScale.High, (int)PictureScale.High))
                        {
                            gi.TinyExists = true;
                            gi.Update();
                        }
                    }
                    catch (GalleryItemNotFoundException)
                    {
                        return true; // no big deal if this job fails
                    }
                    return true;
                case "create_square":
                    try
                    {
                        GalleryItem gi = new GalleryItem(core, job.ItemId);

                        if (gi.SquareExists) return true;

                        if (GalleryItem.CreateScaleWithSquareRatio(core, gi, gi.StoragePath, GalleryItem.SquarePrefix, (int)PictureScale.Square, (int)PictureScale.Square))
                        {
                            gi.SquareExists = true;
                            gi.Update();
                        }
                    }
                    catch (GalleryItemNotFoundException)
                    {
                        return true; // no big deal if this job fails
                    }
                    return true;
                case "create_tile":
                    try
                    {
                        GalleryItem gi = new GalleryItem(core, job.ItemId);

                        if (gi.TileExists) return true;

                        if (GalleryItem.CreateScaleWithSquareRatio(core, gi, gi.StoragePath, GalleryItem.TilePrefix, (int)PictureScale.Tile, (int)PictureScale.Tile))
                        {
                            gi.TileExists = true;
                            gi.Update();
                        }
                    }
                    catch (GalleryItemNotFoundException)
                    {
                        return true; // no big deal if this job fails
                    }
                    return true;
                case "create_icon":
                    try
                    {
                        GalleryItem gi = new GalleryItem(core, job.ItemId);

                        if (gi.IconExists) return true;

                        if (GalleryItem.CreateScaleWithSquareRatio(core, gi, gi.StoragePath, GalleryItem.IconPrefix, (int)PictureScale.Icon, (int)PictureScale.Icon))
                        {
                            gi.IconExists = true;
                            gi.Update();
                        }
                    }
                    catch (GalleryItemNotFoundException)
                    {
                        return true; // no big deal if this job fails
                    }
                    return true;
            }

            return false;
        }
Exemple #6
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="core">Core token</param>
        /// <param name="galleryItem"></param>
        /// <param name="owner"></param>
        /// <param name="member"></param>
        /// <param name="location"></param>
        /// <returns></returns>
        public static UserTag Create(Core core, GalleryItem galleryItem, User owner, User member, Point location)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            InsertQuery query = new InsertQuery("user_tags");
            query.AddField("user_id", owner.UserId);
            query.AddField("tag_user_id", member.UserId);
            query.AddField("gallery_item_id", galleryItem.ItemId);
            query.AddField("tag_x", location.X);
            query.AddField("tag_y", location.Y);
            if (owner.UserId != member.UserId)
            {
                query.AddField("tag_approved", false);
            }
            else
            {
                query.AddField("tag_approved", true);
            }

            long tagId = core.Db.Query(query);

            UserTag tag = new UserTag(core, galleryItem, tagId);
            NotifyTag(core, tag);

            return tag;
        }
Exemple #7
0
        /// <summary>
        /// Thumbnail size fits into a x * y display area. Icons are trimmed to an exact x * y pixel display size.
        /// </summary>
        /// <param name="core"></param>
        /// <param name="fileName"></param>
        public static bool CreateScaleWithSquareRatio(Core core, GalleryItem gi, string fileName, string bin, int width, int height)
        {
            // Imagemagick is only supported under mono which doesn't have very good implementation of GDI for image resizing
            if (Core.IsUnix && WebConfigurationManager.AppSettings["image-method"] == "imagemagick")
            {
                Stream fs = core.Storage.RetrieveFile(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, "_storage"), fileName);

                string storageFilePath = System.IO.Path.Combine(core.Settings.ImagemagickTempPath, "_storage", fileName);
                string tempFilePath = System.IO.Path.Combine(core.Settings.ImagemagickTempPath, bin, fileName);

                try
                {
                    if (fs is MemoryStream)
                    {
                        MemoryStream ms = (MemoryStream)fs;
                        FileStream ds = new FileStream(storageFilePath, FileMode.Create);
                        ms.WriteTo(ds);
                        ds.Close();
                        fs.Close();
                    }
                    else
                    {
                        fs.Position = 0;
                        byte[] bytes = new byte[fs.Length];
                        fs.Read(bytes, 0, (int)fs.Length);
                        FileStream ds = new FileStream(storageFilePath, FileMode.Create);
                        ds.Write(bytes, 0, bytes.Length);
                        ds.Close();
                        fs.Close();
                    }
                }
                catch (IOException)
                {
                    return false;
                }

                Process p1 = new Process();
                p1.StartInfo.FileName = "convert";
                p1.StartInfo.Arguments = string.Format("\"{3}\" -strip -auto-orient -interlace Plane -quality 80 -thumbnail {1}x{2}^ -gravity center -extent {1}x{2} \"{0}\"", tempFilePath, width, height, storageFilePath);
                p1.StartInfo.UseShellExecute = false;
                p1.Start();

                p1.WaitForExit();

                FileStream stream = new FileStream(tempFilePath, FileMode.Open);
                core.Storage.SaveFileWithReducedRedundancy(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, bin), fileName, stream, gi.ContentType);
                stream.Close();
                fs.Close();

                File.Delete(storageFilePath);
                File.Delete(tempFilePath);
            }
            else
            {
                Stream fs = core.Storage.RetrieveFile(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, "_storage"), fileName);
                Image image = Image.FromStream(fs);
                Bitmap displayImage;

                displayImage = new Bitmap(width, height, image.PixelFormat);
                displayImage.Palette = image.Palette;

                Graphics g = Graphics.FromImage(displayImage);
                g.Clear(Color.Transparent);
                g.CompositingMode = CompositingMode.SourceOver;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                int square = Math.Min(image.Width, image.Height);
                g.DrawImage(image, new Rectangle(0, 0, width, height), new Rectangle((image.Width - square) / 2, (image.Height - square) / 2, square, square), GraphicsUnit.Pixel);

                MemoryStream stream = new MemoryStream();
                if (image.RawFormat == ImageFormat.Jpeg)
                {
                    ImageCodecInfo codecInfo = GetEncoderInfo(ImageFormat.Jpeg);
                    System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;
                    EncoderParameters myEncoderParameters = new EncoderParameters(2);
                    EncoderParameter myEncoderParameter = new EncoderParameter(encoder, 90L);
                    myEncoderParameters.Param[0] = myEncoderParameter;
                    myEncoderParameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.RenderMethod, (int)EncoderValue.RenderProgressive);

                    displayImage.Save(stream, codecInfo, myEncoderParameters);
                }
                else
                {
                    displayImage.Save(stream, image.RawFormat);
                }
                core.Storage.SaveFileWithReducedRedundancy(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, bin), fileName, stream, gi.ContentType);
                stream.Close();
                fs.Close();
            }

            return true;
        }
        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;
                }
            }
        }
Exemple #9
0
        /// <summary>
        /// Thumbnail size fits into a x * y display area. Icons are trimmed to an exact x * y pixel display size.
        /// </summary>
        /// <param name="core"></param>
        /// <param name="fileName"></param>
        public static void CreateCoverPhoto(Core core, GalleryItem gi, string fileName, bool isMobile)
        {
            string bin = "_cover";
            int width = 960;
            int height = 200;

            if (isMobile)
            {
                bin = "_mcover";
                width = 480;
                height = 100;
            }

            int crop = gi.CropPositionVertical;
            // Imagemagick is only supported under mono which doesn't have very good implementation of GDI for image resizing
            if (Core.IsUnix && WebConfigurationManager.AppSettings["image-method"] == "imagemagick")
            {
                Stream fs = core.Storage.RetrieveFile(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, "_storage"), fileName);
                string storageFilePath = System.IO.Path.Combine(core.Settings.ImagemagickTempPath, "_storage", fileName);
                string tempFilePath = System.IO.Path.Combine(core.Settings.ImagemagickTempPath, bin, fileName);

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

                Size imageSize = new Size(gi.ItemWidth, gi.ItemHeight);
                double scale = (double)width / imageSize.Width;
                int newHeight = (int)(imageSize.Height * scale);
                int cropY = (int)(crop * scale);

                Process p1 = new Process();
                p1.StartInfo.FileName = "convert";
                p1.StartInfo.Arguments = string.Format("\"{3}\" -strip -auto-orient -interlace Plane -quality 80 -resize {1}x{1} -extent {1}x{2}+0+{4} \"{0}\"", tempFilePath, width, height, storageFilePath, cropY);
                p1.StartInfo.UseShellExecute = false;
                p1.Start();

                p1.WaitForExit();

                FileStream stream = new FileStream(tempFilePath, FileMode.Open);
                core.Storage.SaveFileWithReducedRedundancy(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, bin), fileName, stream, gi.ContentType);
                stream.Close();
                fs.Close();

                File.Delete(storageFilePath);
                File.Delete(tempFilePath);
            }
            else
            {
                Stream fs = core.Storage.RetrieveFile(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, "_storage"), fileName);
                Image image = Image.FromStream(fs);
                Bitmap displayImage;

                displayImage = new Bitmap(width, height, image.PixelFormat);
                displayImage.Palette = image.Palette;

                Graphics g = Graphics.FromImage(displayImage);
                g.Clear(Color.Transparent);
                g.CompositingMode = CompositingMode.SourceOver;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                double scale = (double)width / image.Width;
                int newHeight = (int)(image.Height * scale);
                int oldHeight = (int)(height / scale);

                g.DrawImage(image, new Rectangle(0, 0, width, height), new Rectangle(0, crop, image.Width, oldHeight), GraphicsUnit.Pixel);

                MemoryStream stream = new MemoryStream();
                if (image.RawFormat == ImageFormat.Jpeg)
                {
                    ImageCodecInfo codecInfo = GetEncoderInfo(ImageFormat.Jpeg);
                    System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;
                    EncoderParameters myEncoderParameters = new EncoderParameters(2);
                    EncoderParameter myEncoderParameter = new EncoderParameter(encoder, 90L);
                    myEncoderParameters.Param[0] = myEncoderParameter;
                    myEncoderParameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.RenderMethod, (int)EncoderValue.RenderProgressive);

                    displayImage.Save(stream, codecInfo, myEncoderParameters);
                }
                else
                {
                    displayImage.Save(stream, image.RawFormat);
                }
                core.Storage.SaveFileWithReducedRedundancy(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, bin), fileName, stream, gi.ContentType);
                stream.Close();
                fs.Close();
            }
        }
Exemple #10
0
        /// <summary>
        /// Thumbnail size fits into a x * y display area. The aspect ratio is preserved.
        /// </summary>
        /// <param name="core"></param>
        /// <param name="fileName"></param>
        public static bool CreateScaleWithRatioPreserved(Core core, GalleryItem gi, string fileName, string bin, int width, int height)
        {
            // Imagemagick is only supported under mono which doesn't have very good implementation of GDI for image resizing
            if (Core.IsUnix && WebConfigurationManager.AppSettings["image-method"] == "imagemagick")
            {
                Stream fs = core.Storage.RetrieveFile(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, "_storage"), fileName);

                string storageFilePath = System.IO.Path.Combine(core.Settings.ImagemagickTempPath, "_storage", fileName);
                string tempFilePath = System.IO.Path.Combine(core.Settings.ImagemagickTempPath, bin, fileName);

                try
                {
                    if (fs is MemoryStream)
                    {
                        MemoryStream ms = (MemoryStream)fs;
                        FileStream ds = new FileStream(storageFilePath, FileMode.Create);
                        ms.WriteTo(ds);
                        ds.Close();
                        fs.Close();
                    }
                    else
                    {
                        fs.Position = 0;
                        byte[] bytes = new byte[fs.Length];
                        fs.Read(bytes, 0, (int)fs.Length);
                        FileStream ds = new FileStream(storageFilePath, FileMode.Create);
                        ds.Write(bytes, 0, bytes.Length);
                        ds.Close();
                        fs.Close();
                    }
                }
                catch (IOException)
                {
                    return false;
                }

                Process p1 = new Process();
                p1.StartInfo.FileName = "convert";
                p1.StartInfo.Arguments = string.Format("\"{3}\" -strip -auto-orient -interlace Plane -quality 80 -thumbnail {1}x{2} \"{0}\"", tempFilePath, width, height, storageFilePath);
                p1.StartInfo.UseShellExecute = false;
                p1.Start();

                p1.WaitForExit();

                FileStream stream = new FileStream(tempFilePath, FileMode.Open);
                core.Storage.SaveFileWithReducedRedundancy(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, bin), fileName, stream, gi.ContentType);
                stream.Close();
                fs.Close();

                File.Delete(storageFilePath);
                File.Delete(tempFilePath);
            }
            else
            {
                Stream fs = core.Storage.RetrieveFile(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, "_storage"), fileName);
                Image image = Image.FromStream(fs);
                Image thumbImage;

                if (image.Width > width || image.Height > height)
                {
                    Size newSize = GetSize(image.Size, new Size(width, height));

                    thumbImage = new Bitmap(newSize.Width, newSize.Height, image.PixelFormat);
                    thumbImage.Palette = image.Palette;
                    Graphics g = Graphics.FromImage(thumbImage);
                    g.Clear(Color.Transparent);
                    g.CompositingMode = CompositingMode.SourceOver;
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    g.DrawImage(image, new Rectangle(0, 0, newSize.Width, newSize.Height), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);

                    MemoryStream stream = new MemoryStream();
                    thumbImage.Save(stream, image.RawFormat);
                    core.Storage.SaveFileWithReducedRedundancy(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, bin), fileName, stream, gi.ContentType);
                    stream.Close();
                    fs.Close();
                }
                else
                {
                    fs.Close();
                    core.Storage.CopyFile(core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, "_storage"), core.Storage.PathCombine(core.Settings.StorageBinUserFilesPrefix, bin), fileName);
                }
            }

            return true;
        }
Exemple #11
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!");
        }
Exemple #12
0
 protected void loadGalleryIcon(System.Data.Common.DbDataReader galleryRow)
 {
     if (!(galleryRow["gallery_item_parent_path"] is DBNull))
     {
         highlightItem = new GalleryItem(core, galleryRow);
     }
     if (!(galleryRow["gallery_item_uri"] is DBNull))
     {
         highlightUri = (string)galleryRow["gallery_item_uri"];
     }
     else
     {
         highlightUri = null;
     }
 }
Exemple #13
0
        public string GetActionBody(List<ItemKey> subItems)
        {
            string returnValue = string.Empty;

            if (subItems.Count > 0)
            {

                long galleryItemTypeId = ItemType.GetTypeId(core, typeof(GalleryItem));
                List<long> itemIds = new List<long>();

                foreach (ItemKey il in subItems)
                {
                    if (il.TypeId == galleryItemTypeId)
                    {
                        itemIds.Add(il.Id);
                    }
                }

                SelectQuery query = GalleryItem.GetSelectQueryStub(core, typeof(GalleryItem));
                query.AddCondition("gallery_item_id", ConditionEquality.In, itemIds);
                query.AddCondition("gallery_id", Id);

                DataTable itemDataTable = db.Query(query);

                if (itemDataTable.Rows.Count == 1)
                {
                    GalleryItem item = new GalleryItem(core, Owner, itemDataTable.Rows[0]);

                    if (!string.IsNullOrEmpty(item.ItemAbstract))
                    {
                        returnValue += item.ItemAbstract + "\r\n\r\n";
                    }

                    returnValue += string.Format("[iurl=\"{0}#hd\"][inline cdn-object=\"{2}\" width=\"{3}\" height=\"{4}\"]{1}[/inline][/iurl]",
                            item.Uri, item.FullPath, item.StoragePath, item.ItemWidth, item.ItemHeight);
                }
                else
                {
                    foreach (DataRow row in itemDataTable.Rows)
                    {
                        GalleryItem item = new GalleryItem(core, Owner, row);

                        returnValue += string.Format("[iurl=\"{0}#hd\"][thumb cdn-object=\"{2}\" width=\"{3}\" height=\"{4}\"]{1}[/thumb][/iurl]",
                                item.Uri, item.FullPath, item.StoragePath, item.ItemWidth, item.ItemHeight);
                    }
                }
            }

            return returnValue;
        }
        void AccountGalleriesPhotoDisplayPic_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, LoggedInMember, pictureId);

                // check for public view permissions on the image
                if (ugi.PermissiveParent.Access.IsPublic())
                {

                    LoggedInMember.UserInfo.DisplayPictureId = pictureId;
                    LoggedInMember.UserInfo.Update();

                    core.Display.ShowMessage("Display Picture Changed", "You have successfully changed your display picture.");
                    return;
                }
                else
                {
                    core.Display.ShowMessage("Cannot set as display picture", "You must use a photo with public view permissions as your display picture.");
                    return;
                }
            }
            catch (GalleryItemNotFoundException)
            {
                core.Display.ShowMessage("Cannot change display picture", "You could not change your display picture to the selected image.");
                return;
            }
        }
Exemple #15
0
        public static void NotifyGalleryItemComment(Core core, Job job)
        {
            try {
                Comment comment = new Comment(core, job.ItemId);
                GalleryItem ev = new GalleryItem(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_ITEM", comment.BuildUri(ev));
                }

                core.CallingApplication.SendNotification(core, comment.OwnerKey, comment.User, ev.OwnerKey, ev.ItemKey, "_COMMENTED_GALLERY_ITEM", comment.BuildUri(ev));
            }
            catch (InvalidCommentException)
            {
            }
            catch (GalleryItemNotFoundException)
            {

            }
        }
        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;
            }
        }
Exemple #17
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
            {
            }
        }
        void AccountCoverPhoto_Show(object sender, EventArgs e)
        {
            SetTemplate("account_cover_photo");

            LoggedInMember.LoadProfileInfo();

            if (LoggedInMember.UserInfo.CoverPhotoId > 0)
            {
                GalleryItem gi = new GalleryItem(core, LoggedInMember.UserInfo.CoverPhotoId);
                template.Parse("I_COVER_PHOTO", gi.DisplayUri);

                Size newSize = GalleryItem.GetSize(new Size(gi.ItemWidth, gi.ItemHeight), new Size(640,640));

                double scale = (double)newSize.Width / gi.ItemWidth;
                int crop = (int)(gi.CropPositionVertical * scale);

                double scale2 = newSize.Width / 960F;

                int cropS = (int)(200 * scale2);
                int cropB = newSize.Height - crop - cropS;

                template.Parse("CROP_T", crop);
                template.Parse("CROP_S", cropS);
                template.Parse("CROP_B", cropB);
                template.Parse("WIDTH", newSize.Width);
                template.Parse("HEIGHT", newSize.Height);
                template.Parse("CROP", gi.CropPositionVertical);
                template.Parse("SCALE", scale);

            }

            Save(new EventHandler(AccountDisplayPic_Save));
        }
Exemple #19
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;
            }
        }
Exemple #20
0
        /// <summary>
        /// Initialises a new instance of the UserTag class.
        /// </summary>
        /// <param name="core">Core token</param>
        /// <param name="galleryItem">Gallery item</param>
        /// <param name="tagRow">Raw data row of user tag</param>
        private UserTag(Core core, GalleryItem galleryItem, DataRow tagRow)
            : base(core)
        {
            ItemLoad += new ItemLoadHandler(UserTag_ItemLoad);

            taggedGalleryItem = galleryItem;

            loadItemInfo(tagRow);
        }
Exemple #21
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();
        }
Exemple #22
0
        /// <summary>
        /// Retrieves a list of user tags for a given photo.
        /// </summary>
        /// <param name="core">Core token</param>
        /// <param name="galleryItem">Gallery item to retrieve user tags of</param>
        /// <returns>A list of user tags</returns>
        public static List<UserTag> GetTags(Core core, GalleryItem galleryItem)
        {
            List<UserTag> tags = new List<UserTag>();

            SelectQuery query = UserTag.GetSelectQueryStub(core, typeof(UserTag));
            query.AddCondition("gallery_item_id", galleryItem.ItemId);

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

            List<long> userIds = new List<long>();
            foreach (DataRow dr in tagDataTable.Rows)
            {
                userIds.Add((long)dr["tag_user_id"]);
            }

            core.LoadUserProfiles(userIds);

            foreach (DataRow dr in tagDataTable.Rows)
            {
                tags.Add(new UserTag(core, galleryItem, dr));
            }

            return tags;
        }
        void AccountGalleriesPhotoTag_Show(object sender, EventArgs e)
        {
            Save(new EventHandler(AccountGalleriesPhotoTag_Save));

            AuthoriseRequestSid();

            SetTemplate("account_galleries_photo_tag");

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

                GalleryItem photo = new GalleryItem(core, LoggedInMember, photoId);

                template.Parse("S_PHOTO_TITLE", photo.ItemTitle);
                template.Parse("S_PHOTO_DISPLAY", photo.DisplayUri);
                template.Parse("S_PHOTO_ID", photo.Id.ToString());

                List<UserTag> tags = UserTag.GetTags(core, photo);

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

                template.Parse("TAG_COUNT", tags.Count.ToString());

                int i = 0;
                foreach (UserTag tag in tags)
                {
                    VariableCollection tagsVariableCollection = template.CreateChild("user_tags");

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

                    i++;
                }
            }
            catch (GalleryItemNotFoundException)
            {
                core.Display.ShowMessage("Invalid", "If you have stumbled onto this page by mistake, click back in your browser.");
                return;
            }
        }
        void AccountGalleriesPhotoRotate_Show(object sender, EventArgs e)
        {
            AuthoriseRequestSid();

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

            if (photoId > 0)
            {
                try
                {
                    GalleryItem photo = new GalleryItem(core, Owner, photoId);

                    System.Drawing.RotateFlipType rotation = System.Drawing.RotateFlipType.RotateNoneFlipNone;

                    switch (core.Http.Query["rotation"])
                    {
                        case "right":
                        case "90": // right 90
                            rotation = System.Drawing.RotateFlipType.Rotate90FlipNone;
                            break;
                        case "180": // 180
                            rotation = System.Drawing.RotateFlipType.Rotate180FlipNone;
                            break;
                        case "left":
                        case "270": // left 90
                            rotation = System.Drawing.RotateFlipType.Rotate270FlipNone;
                            break;
                    }

                    photo.Rotate(core, rotation);

                    SetRedirectUri(Gallery.BuildPhotoUri(core, Owner, photo.ParentPath, photo.Path, true));
                    core.Display.ShowMessage("Image rotated", "You have successfully rotated the image.");
                    return;
                }
                catch (GalleryItemNotFoundException)
                {
                    core.Display.ShowMessage("Error", "An error has occured, go back.");
                    return;
                }
            }
            else
            {
                core.Display.ShowMessage("Error", "An error has occured, go back.");
                return;
            }
        }
        void AccountGalleriesPhotoDelete_Save(object sender, EventArgs e)
        {
            AuthoriseRequestSid();

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

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

            if (core.Display.GetConfirmBoxResult() == ConfirmBoxResult.Yes)
            {
                try
                {
                    GalleryItem photo = new GalleryItem(core, Owner, id);

                    try
                    {
                        photo.Delete();

                        SetRedirectUri(BuildUri("galleries", "galleries"));
                        core.Display.ShowMessage("Photo Deleted", "You have successfully deleted the photo from the gallery.");
                    }
                    // TODO: not photo owner exception
                    /*catch (Invalid)
                    {
                        Display.ShowMessage("Unauthorised", "You are unauthorised to delete this photo.");
                        return;
                    }*/
                    catch (Exception ex)
                    {
                        SetRedirectUri(photo.Uri);
                        core.Display.ShowMessage("Cannot Delete Photo", "An Error occured while trying to delete the photo, you may not be authorised to delete it." + ex.ToString());
                        return;
                    }
                }
                catch (InvalidGalleryItemTypeException)
                {
                    core.Display.ShowMessage("Cannot Delete Photo", "An Error occured while trying to delete the photo, you may not be authorised to delete it.");
                    return;
                }
            }
            else
            {
            }
        }