Ejemplo n.º 1
0
        private void initialize()
        {
            _fileName  = System.IO.Path.GetFileName(_path);
            _length    = _fs.GetSize(_path);
            _extension = System.IO.Path.GetExtension(_path) != null
                ? System.IO.Path.GetExtension(_path).Substring(1).ToLowerInvariant()
                : "";

            _url = _fs.GetUrl(_path);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Render this control to the output parameter specified.
        /// </summary>
        /// <param name="output"> The HTML writer to write out to </param>
        protected override void Render(HtmlTextWriter output)
        {
            //render the validator if it is not valid
            //NOTE: it would be better to have this as a normal composite control but we don't want to
            // break compatibility so we cannot make this inherit from a different class than it already
            // is, so now we have to hack this together.
            if (_customValidator.IsValid == false)
            {
                _customValidator.RenderControl(output);
            }

            if (string.IsNullOrEmpty(Text) == false)
            {
                var relativeFilePath = _fs.GetRelativePath(_text);
                var ext = relativeFilePath.Substring(relativeFilePath.LastIndexOf(".") + 1, relativeFilePath.Length - relativeFilePath.LastIndexOf(".") - 1);
                var relativeThumbFilePath = relativeFilePath.Replace("." + ext, "_thumb.jpg");
                var hasThumb = false;
                try
                {
                    hasThumb = _fs.FileExists(relativeThumbFilePath);
                    // 4.8.0 added support for png thumbnails (but for legacy it might have been jpg - hence the check before)
                    if (hasThumb == false && (ext == "gif" || ext == "png"))
                    {
                        relativeThumbFilePath = relativeFilePath.Replace("." + ext, "_thumb.png");
                        hasThumb = _fs.FileExists(relativeThumbFilePath);
                    }
                }
                catch
                {
                }
                if (hasThumb)
                {
                    var thumb = new Image
                    {
                        ImageUrl    = _fs.GetUrl(relativeThumbFilePath),
                        BorderStyle = BorderStyle.None
                    };

                    output.WriteLine("<a href=\"" + _fs.GetUrl(relativeFilePath) + "\" target=\"_blank\">");
                    thumb.RenderControl(output);
                    output.WriteLine("</a><br/>");
                }
                else
                {
                    output.WriteLine("<a href=\"" + _fs.GetUrl(relativeFilePath) + "\" target=\"_blank\">" +
                                     _fs.GetUrl(relativeFilePath) + "</a><br/>");
                }

                output.WriteLine("<input type=\"checkbox\" id=\"" + ClientID + "clear\" name=\"" + ClientID +
                                 "clear\" value=\"1\"/> <label for=\"" + ClientID + "clear\">" + ui.Text("uploadClear") +
                                 "</label><br/>");
            }
            base.Render(output);
        }
Ejemplo n.º 3
0
        public bool TryFindExistingMedia(int parentNodeId, string fileName, out Media existingMedia)
        {
            var children = parentNodeId == -1 ? Media.GetRootMedias() : new Media(parentNodeId).Children;

            foreach (var childMedia in children)
            {
                if (childMedia.ContentType.Alias == MediaTypeAlias)
                {
                    var prop = childMedia.getProperty("umbracoFile");
                    if (prop != null)
                    {
                        var destFilePath = FileSystem.GetRelativePath(prop.Id, fileName);
                        var destFileUrl  = FileSystem.GetUrl(destFilePath);

                        if (prop.Value.ToString() == destFileUrl)
                        {
                            existingMedia = childMedia;
                            return(true);
                        }
                    }
                }
            }

            existingMedia = null;
            return(false);
        }
Ejemplo n.º 4
0
        public void writeContents(int id, string filename, Byte[] contents, string username, string password)
        {
            Authenticate(username, password);

            filename = filename.Replace("/", global::Umbraco.Core.IO.IOHelper.DirSepChar.ToString());
            filename = filename.Replace(@"\", global::Umbraco.Core.IO.IOHelper.DirSepChar.ToString());
            filename = filename.Substring(filename.LastIndexOf(global::Umbraco.Core.IO.IOHelper.DirSepChar) + 1, filename.Length - filename.LastIndexOf(global::Umbraco.Core.IO.IOHelper.DirSepChar) - 1).ToLower();

            var m = new Media(id);

            var numberedFolder = MediaSubfolderCounter.Current.Increment();
            var path           = _fs.GetRelativePath(numberedFolder.ToString(CultureInfo.InvariantCulture), filename);

            var stream = new MemoryStream();

            stream.Write(contents, 0, contents.Length);
            stream.Seek(0, 0);

            _fs.AddFile(path, stream);

            m.getProperty("umbracoFile").Value      = _fs.GetUrl(path);
            m.getProperty("umbracoExtension").Value = Path.GetExtension(filename).Substring(1);
            m.getProperty("umbracoBytes").Value     = _fs.GetSize(path);

            m.Save();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Render this control to the output parameter specified.
        /// </summary>
        /// <param name="output"> The HTML writer to write out to </param>
        protected override void Render(HtmlTextWriter output)
        {
            if (!string.IsNullOrEmpty(Text))
            {
                var relativeFilePath = _fs.GetRelativePath(_text);
                var ext = relativeFilePath.Substring(relativeFilePath.LastIndexOf(".") + 1, relativeFilePath.Length - relativeFilePath.LastIndexOf(".") - 1);
                var relativeThumbFilePath = relativeFilePath.Replace("." + ext, "_thumb.jpg");
                var hasThumb = false;
                try
                {
                    hasThumb = _fs.FileExists(relativeThumbFilePath);
                    // 4.8.0 added support for png thumbnails (but for legacy it might have been jpg - hence the check before)
                    if (!hasThumb && (ext == "gif" || ext == "png"))
                    {
                        relativeThumbFilePath = relativeFilePath.Replace("." + ext, "_thumb.png");
                        hasThumb = _fs.FileExists(relativeThumbFilePath);
                    }
                }
                catch
                {
                }
                if (hasThumb)
                {
                    var thumb = new Image
                    {
                        ImageUrl    = _fs.GetUrl(relativeThumbFilePath),
                        BorderStyle = BorderStyle.None
                    };

                    output.WriteLine("<a href=\"" + _fs.GetUrl(relativeFilePath) + "\" target=\"_blank\">");
                    thumb.RenderControl(output);
                    output.WriteLine("</a><br/>");
                }
                else
                {
                    output.WriteLine("<a href=\"" + _fs.GetUrl(relativeFilePath) + "\" target=\"_blank\">" +
                                     _fs.GetUrl(relativeFilePath) + "</a><br/>");
                }

                output.WriteLine("<input type=\"checkbox\" id=\"" + ClientID + "clear\" name=\"" + ClientID +
                                 "clear\" value=\"1\"/> <label for=\"" + ClientID + "clear\">" + ui.Text("uploadClear") +
                                 "</label><br/>");
            }
            base.Render(output);
        }
Ejemplo n.º 6
0
        public bool TryFindExistingMedia(int parentNodeId, string fileName, out Media existingMedia)
        {
            var children = parentNodeId == -1 ? Media.GetRootMedias() : new Media(parentNodeId).Children;

            foreach (var childMedia in children)
            {
                if (childMedia.ContentType.Alias == MediaTypeAlias)
                {
                    var prop = childMedia.getProperty(Constants.Conventions.Media.File);
                    if (prop != null && prop.Value != null)
                    {
                        int subfolderId;
                        var currentValue = prop.Value.ToString();

                        var subfolder = UmbracoConfig.For.UmbracoSettings().Content.UploadAllowDirectories
                            ? currentValue.Replace(FileSystem.GetUrl("/"), "").Split('/')[0]
                            : currentValue.Substring(currentValue.LastIndexOf("/", StringComparison.Ordinal) + 1).Split('-')[0];

                        if (int.TryParse(subfolder, out subfolderId))
                        {
                            var destFilePath = GetRelativePath(subfolderId, fileName);
                            var destFileUrl  = FileSystem.GetUrl(destFilePath);

                            if (prop.Value.ToString() == destFileUrl)
                            {
                                existingMedia = childMedia;
                                return(true);
                            }
                        }
                    }
                }
            }

            existingMedia = null;
            return(false);
        }
Ejemplo n.º 7
0
        private static string Resize(MediaFileSystem fileSystem, string path, string extension, int maxWidthHeight, string fileNameAddition)
        {
            var fileNameThumb = DoResize(fileSystem, path, extension, GetDimensions(fileSystem, path).Item1, GetDimensions(fileSystem, path).Item2, maxWidthHeight, fileNameAddition);

            return(fileSystem.GetUrl(fileNameThumb));
        }
Ejemplo n.º 8
0
        private string FormatMedia(string html)
        {
            // root media url
            var rootMediaUrl = _fs.GetUrl("");

            // Find all media images
            var pattern = string.Format("<img [^>]*src=\"(?<mediaString>{0}[^\"]*)\" [^>]*>", rootMediaUrl);

            var tags = Regex.Matches(html, pattern, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

            foreach (Match tag in tags)
            {
                if (tag.Groups.Count <= 0)
                {
                    continue;
                }

                // Replace /> to ensure we're in old-school html mode
                var tempTag = "<img";
                var orgSrc  = tag.Groups["mediaString"].Value;

                // gather all attributes
                // TODO: This should be replaced with a general helper method - but for now we'll wanna leave umbraco.dll alone for this patch
                var ht = new Hashtable();
                var m  = Regex.Matches(tag.Value.Replace(">", " >"),
                                       "(?<attributeName>\\S*)=\"(?<attributeValue>[^\"]*)\"|(?<attributeName>\\S*)=(?<attributeValue>[^\"|\\s]*)\\s",
                                       RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

                //GE: Add ContainsKey check and expand the ifs for readability
                foreach (Match attributeSet in m)
                {
                    if (attributeSet.Groups["attributeName"].Value.ToLower() != "src" && ht.ContainsKey(attributeSet.Groups["attributeName"].Value) == false)
                    {
                        ht.Add(attributeSet.Groups["attributeName"].Value, attributeSet.Groups["attributeValue"].Value);
                    }
                }

                // build the element
                // Build image tag
                var ide = ht.GetEnumerator();
                while (ide.MoveNext())
                {
                    tempTag += string.Format(" {0}=\"{1}\"", ide.Key, ide.Value);
                }

                orgSrc = IOHelper.ResolveUrl(orgSrc.Replace("%20", " "));

                var mediaService = ApplicationContext.Current.Services.MediaService;
                var imageMedia   = mediaService.GetMediaByPath(orgSrc);

                if (imageMedia == null)
                {
                    tempTag = string.Format("{0} src=\"{1}\" />", tempTag, IOHelper.ResolveUrl(orgSrc));
                }
                else
                {
                    // We're doing .Any checks here instead of FirstOrDefault because the default value of Properties
                    // is not null but default(KeyedCollection<string, Property>). This is a bit easier to read.
                    // To clarify: imageMedia.Properties.FirstOrDefault(x => x.Alias == "umbracoWidth") == null; will NOT work.

                    var widthValue = string.Empty;
                    if (imageMedia.Properties.Any(x => x.Alias == "umbracoWidth"))
                    {
                        widthValue = imageMedia.Properties.First(x => x.Alias == "umbracoWidth").Value.ToString();
                    }

                    var heightValue = string.Empty;
                    if (imageMedia.Properties.Any(x => x.Alias == "umbracoHeight"))
                    {
                        heightValue = imageMedia.Properties.First(x => x.Alias == "umbracoHeight").Value.ToString();
                    }

                    // Format the tag
                    if (imageMedia.Properties.Any(x => x.Alias == "umbracoFile"))
                    {
                        var umbracoFileProperty = imageMedia.Properties.First(x => x.Alias == "umbracoFile");
                        tempTag = string.Format("{0} rel=\"{1},{2}\" src=\"{3}\" />", tempTag, widthValue, heightValue, umbracoFileProperty.Value);
                    }
                }

                html = html.Replace(tag.Value, tempTag);
            }

            return(html);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Converts the value received from the editor into the value can be stored in the database.
        /// </summary>
        /// <param name="editorValue">The value received from the editor.</param>
        /// <param name="currentValue">The current value of the property</param>
        /// <returns>The converted value.</returns>
        /// <remarks>
        /// <para>The <paramref name="currentValue"/> is used to re-use the folder, if possible.</para>
        /// <para>The <paramref name="editorValue"/> is value passed in from the editor. We normally don't care what
        /// the editorValue.Value is set to because we are more interested in the files collection associated with it,
        /// however we do care about the value if we are clearing files. By default the editorValue.Value will just
        /// be set to the name of the file - but again, we just ignore this and deal with the file collection in
        /// editorValue.AdditionalData.ContainsKey("files")</para>
        /// <para>We only process ONE file. We understand that the current value may contain more than one file,
        /// and that more than one file may be uploaded, so we take care of them all, but we only store ONE file.
        /// Other places (FileUploadPropertyEditor...) do NOT deal with multiple files, and our logic for reusing
        /// folders would NOT work, etc.</para>
        /// </remarks>
        public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue)
        {
            currentValue = currentValue ?? string.Empty;

            // at that point,
            // currentValue is either empty or "/media/path/to/img.jpg"
            // editorValue.Value is { "clearFiles": true } or { "selectedFiles": "img1.jpg,img2.jpg" }
            // comparing them makes little sense

            // check the editorValue value to see whether we need to clear files
            var editorJsonValue = editorValue.Value as JObject;
            var clears          = editorJsonValue != null && editorJsonValue["clearFiles"] != null && editorJsonValue["clearFiles"].Value <bool>();
            var uploads         = editorValue.AdditionalData.ContainsKey("files") && editorValue.AdditionalData["files"] is IEnumerable <ContentItemFile>;

            // nothing = no changes, return what we have already (leave existing files intact)
            if (clears == false && uploads == false)
            {
                return(currentValue);
            }

            // get the current file paths
            var currentPaths = currentValue.ToString()
                               .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                               .Select(x => _mediaFileSystem.GetRelativePath(x)) // get the fs-relative path
                               .ToArray();

            // if clearing, remove these files and return
            if (clears)
            {
                foreach (var pathToRemove in currentPaths)
                {
                    _mediaFileSystem.DeleteFile(pathToRemove, true);
                }
                return(string.Empty); // no more files
            }

            // ensure we have the required guids
            if (editorValue.AdditionalData.ContainsKey("cuid") == false || // for the content item
                editorValue.AdditionalData.ContainsKey("puid") == false)    // and the property type
            {
                throw new Exception("Missing cuid/puid additional data.");
            }
            var cuido = editorValue.AdditionalData["cuid"];
            var puido = editorValue.AdditionalData["puid"];

            if ((cuido is Guid) == false || (puido is Guid) == false)
            {
                throw new Exception("Invalid cuid/puid additional data.");
            }
            var cuid = (Guid)cuido;
            var puid = (Guid)puido;

            if (cuid == Guid.Empty || puid == Guid.Empty)
            {
                throw new Exception("Invalid cuid/puid additional data.");
            }

            // process the files
            var files = ((IEnumerable <ContentItemFile>)editorValue.AdditionalData["files"]).ToArray();

            var       newPaths  = new List <string>();
            const int maxLength = 1; // we only process ONE file

            for (var i = 0; i < maxLength /*files.Length*/; i++)
            {
                var file = files[i];

                // skip invalid files
                if (UploadFileTypeValidator.ValidateFileExtension(file.FileName) == false)
                {
                    continue;
                }

                // get the filepath
                // in case we are using the old path scheme, try to re-use numbers (bah...)
                var reuse    = i < currentPaths.Length ? currentPaths[i] : null;                // this would be WRONG with many files
                var filepath = _mediaFileSystem.GetMediaPath(file.FileName, reuse, cuid, puid); // fs-relative path

                using (var filestream = File.OpenRead(file.TempFilePath))
                {
                    _mediaFileSystem.AddFile(filepath, filestream, true); // must overwrite!

                    var ext = _mediaFileSystem.GetExtension(filepath);
                    if (_mediaFileSystem.IsImageFile(ext) && ext != ".svg")
                    {
                        var preValues = editorValue.PreValues.FormatAsDictionary();
                        var sizes     = preValues.Any() ? preValues.First().Value.Value : string.Empty;
                        using (var image = Image.FromStream(filestream))
                            _mediaFileSystem.GenerateThumbnails(image, filepath, sizes);
                    }

                    // all related properties (auto-fill) are managed by FileUploadPropertyEditor
                    // when the content is saved (through event handlers)

                    newPaths.Add(filepath);
                }
            }

            // remove all temp files
            foreach (var file in files)
            {
                File.Delete(file.TempFilePath);
            }

            // remove files that are not there anymore
            foreach (var pathToRemove in currentPaths.Except(newPaths))
            {
                _mediaFileSystem.DeleteFile(pathToRemove, true);
            }


            return(string.Join(",", newPaths.Select(x => _mediaFileSystem.GetUrl(x))));
        }
Ejemplo n.º 10
0
        protected UrlData newMediaObjectLogic(
            string blogid,
            string username,
            string password,
            FileData file)
        {
            if (ValidateUser(username, password))
            {
                User    u           = new User(username);
                Channel userChannel = new Channel(username);
                UrlData fileUrl     = new UrlData();
                if (userChannel.ImageSupport)
                {
                    Media rootNode;
                    if (userChannel.MediaFolder > 0)
                    {
                        rootNode = new Media(userChannel.MediaFolder);
                    }
                    else
                    {
                        rootNode = new Media(u.StartMediaId);
                    }

                    // Create new media
                    Media m = Media.MakeNew(file.name, MediaType.GetByAlias(userChannel.MediaTypeAlias), u, rootNode.Id);

                    Property fileObject = m.getProperty(userChannel.MediaTypeFileProperty);

                    var filename         = file.name.Replace("/", "_");
                    var relativeFilePath = UmbracoMediaFactory.GetRelativePath(fileObject.Id, filename);

                    fileObject.Value = _fs.GetUrl(relativeFilePath);
                    fileUrl.url      = fileObject.Value.ToString();

                    if (!fileUrl.url.StartsWith("http"))
                    {
                        var protocol = GlobalSettings.UseSSL ? "https" : "http";
                        fileUrl.url = protocol + "://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + fileUrl.url;
                    }

                    _fs.AddFile(relativeFilePath, new MemoryStream(file.bits));

                    // Try updating standard file values
                    try
                    {
                        string orgExt = "";
                        // Size
                        if (m.getProperty(Constants.Conventions.Media.Bytes) != null)
                        {
                            m.getProperty(Constants.Conventions.Media.Bytes).Value = file.bits.Length;
                        }
                        // Extension
                        if (m.getProperty(Constants.Conventions.Media.Extension) != null)
                        {
                            orgExt =
                                ((string)
                                 file.name.Substring(file.name.LastIndexOf(".") + 1,
                                                     file.name.Length - file.name.LastIndexOf(".") - 1));
                            m.getProperty(Constants.Conventions.Media.Extension).Value = orgExt.ToLower();
                        }
                        // Width and Height
                        // Check if image and then get sizes, make thumb and update database
                        if (m.getProperty(Constants.Conventions.Media.Width) != null && m.getProperty(Constants.Conventions.Media.Height) != null &&
                            ",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + orgExt.ToLower() + ",") > 0)
                        {
                            int fileWidth;
                            int fileHeight;

                            using (var stream = _fs.OpenFile(relativeFilePath))
                            {
                                Image image = Image.FromStream(stream);
                                fileWidth  = image.Width;
                                fileHeight = image.Height;
                                stream.Close();
                                try
                                {
                                    m.getProperty(Constants.Conventions.Media.Width).Value  = fileWidth.ToString();
                                    m.getProperty(Constants.Conventions.Media.Height).Value = fileHeight.ToString();
                                }
                                catch (Exception ex)
                                {
                                    LogHelper.Error <UmbracoMetaWeblogAPI>("An error occurred reading the media stream", ex);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error <UmbracoMetaWeblogAPI>("An error occurred in newMediaObjectLogic", ex);
                    }

                    return(fileUrl);
                }
                else
                {
                    throw new ArgumentException(
                              "Image Support is turned off in this channel. Modify channel settings in umbraco to enable image support.");
                }
            }
            return(new UrlData());
        }
        /// <summary>
        /// Converts the value received from the editor into the value can be stored in the database.
        /// </summary>
        /// <param name="editorValue">The value received from the editor.</param>
        /// <param name="currentValue">The current value of the property</param>
        /// <returns>The converted value.</returns>
        /// <remarks>
        /// <para>The <paramref name="currentValue"/> is used to re-use the folder, if possible.</para>
        /// <para>editorValue.Value is used to figure out editorFile and, if it has been cleared, remove the old file - but
        /// it is editorValue.AdditionalData["files"] that is used to determine the actual file that has been uploaded.</para>
        /// </remarks>
        public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue)
        {
            // get the current path
            var currentPath = string.Empty;

            try
            {
                var svalue      = currentValue as string;
                var currentJson = string.IsNullOrWhiteSpace(svalue) ? null : JObject.Parse(svalue);
                if (currentJson != null && currentJson["src"] != null)
                {
                    currentPath = currentJson["src"].Value <string>();
                }
            }
            catch (Exception ex)
            {
                // for some reason the value is invalid so continue as if there was no value there
                LogHelper.WarnWithException <ImageCropperPropertyValueEditor>("Could not parse current db value to a JObject.", ex);
            }
            if (string.IsNullOrWhiteSpace(currentPath) == false)
            {
                currentPath = _mediaFileSystem.GetRelativePath(currentPath);
            }

            // get the new json and path
            JObject editorJson = null;
            var     editorFile = string.Empty;

            if (editorValue.Value != null)
            {
                editorJson = editorValue.Value as JObject;
                if (editorJson != null && editorJson["src"] != null)
                {
                    editorFile = editorJson["src"].Value <string>();
                }
            }

            // ensure we have the required guids
            if (editorValue.AdditionalData.ContainsKey("cuid") == false || // for the content item
                editorValue.AdditionalData.ContainsKey("puid") == false)    // and the property type
            {
                throw new Exception("Missing cuid/puid additional data.");
            }
            var cuido = editorValue.AdditionalData["cuid"];
            var puido = editorValue.AdditionalData["puid"];

            if ((cuido is Guid) == false || (puido is Guid) == false)
            {
                throw new Exception("Invalid cuid/puid additional data.");
            }
            var cuid = (Guid)cuido;
            var puid = (Guid)puido;

            if (cuid == Guid.Empty || puid == Guid.Empty)
            {
                throw new Exception("Invalid cuid/puid additional data.");
            }

            // editorFile is empty whenever a new file is being uploaded
            // or when the file is cleared (in which case editorJson is null)
            // else editorFile contains the unchanged value

            var uploads = editorValue.AdditionalData.ContainsKey("files") && editorValue.AdditionalData["files"] is IEnumerable <ContentItemFile>;
            var files   = uploads ? ((IEnumerable <ContentItemFile>)editorValue.AdditionalData["files"]).ToArray() : new ContentItemFile[0];
            var file    = uploads ? files.FirstOrDefault() : null;

            if (file == null) // not uploading a file
            {
                // if editorFile is empty then either there was nothing to begin with,
                // or it has been cleared and we need to remove the file - else the
                // value is unchanged.
                if (string.IsNullOrWhiteSpace(editorFile) && string.IsNullOrWhiteSpace(currentPath) == false)
                {
                    _mediaFileSystem.DeleteFile(currentPath, true);
                    return(null); // clear
                }

                return(editorJson == null ? null : editorJson.ToString()); // unchanged
            }

            // process the file
            var filepath = editorJson == null ? null : ProcessFile(editorValue, file, currentPath, cuid, puid);

            // remove all temp files
            foreach (var f in files)
            {
                File.Delete(f.TempFilePath);
            }

            // remove current file if replaced
            if (currentPath != filepath && string.IsNullOrWhiteSpace(currentPath) == false)
            {
                _mediaFileSystem.DeleteFile(currentPath, true);
            }

            // update json and return
            if (editorJson == null)
            {
                return(null);
            }
            editorJson["src"] = filepath == null ? string.Empty : _mediaFileSystem.GetUrl(filepath);
            return(editorJson.ToString());
        }
Ejemplo n.º 12
0
        private string formatMedia(string html)
        {
            // root media url
            var rootMediaUrl = _fs.GetUrl("");

            // Find all media images
            var pattern = String.Format("<img [^>]*src=\"(?<mediaString>{0}[^\"]*)\" [^>]*>", rootMediaUrl);

            MatchCollection tags =
                Regex.Matches(html, pattern, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

            foreach (Match tag in tags)
            {
                if (tag.Groups.Count > 0)
                {
                    // Replace /> to ensure we're in old-school html mode
                    string tempTag = "<img";
                    string orgSrc  = tag.Groups["mediaString"].Value;

                    // gather all attributes
                    // TODO: This should be replaced with a general helper method - but for now we'll wanna leave umbraco.dll alone for this patch
                    Hashtable       ht = new Hashtable();
                    MatchCollection m  =
                        Regex.Matches(tag.Value.Replace(">", " >"),
                                      "(?<attributeName>\\S*)=\"(?<attributeValue>[^\"]*)\"|(?<attributeName>\\S*)=(?<attributeValue>[^\"|\\s]*)\\s",
                                      RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

                    //GE: Add ContainsKey check and expand the ifs for readability
                    foreach (Match attributeSet in m)
                    {
                        if (attributeSet.Groups["attributeName"].Value.ToString().ToLower() != "src")
                        {
                            if (!ht.ContainsKey(attributeSet.Groups["attributeName"].Value.ToString()))
                            {
                                ht.Add(attributeSet.Groups["attributeName"].Value.ToString(), attributeSet.Groups["attributeValue"].Value.ToString());
                            }
                        }
                    }

                    // build the element
                    // Build image tag
                    IDictionaryEnumerator ide = ht.GetEnumerator();
                    while (ide.MoveNext())
                    {
                        tempTag += " " + ide.Key.ToString() + "=\"" + ide.Value.ToString() + "\"";
                    }

                    // Find the original filename, by removing the might added width and height
                    // NH, 4.8.1 - above replaced by loading the right media file from the db later!
                    orgSrc =
                        global::Umbraco.Core.IO.IOHelper.ResolveUrl(orgSrc.Replace("%20", " "));

                    // Check for either id or guid from media
                    string mediaId = getIdFromSource(orgSrc, rootMediaUrl);

                    Media imageMedia = null;

                    try
                    {
                        int      mId = int.Parse(mediaId);
                        Property p   = new Property(mId);
                        imageMedia = new Media(Content.GetContentFromVersion(p.VersionId).Id);
                    }
                    catch
                    {
                        try
                        {
                            imageMedia = new Media(Content.GetContentFromVersion(new Guid(mediaId)).Id);
                        }
                        catch
                        {
                        }
                    }

                    // Check with the database if any media matches this url
                    if (imageMedia != null)
                    {
                        try
                        {
                            // Format the tag
                            tempTag = tempTag + " rel=\"" +
                                      imageMedia.getProperty("umbracoWidth").Value.ToString() + "," +
                                      imageMedia.getProperty("umbracoHeight").Value.ToString() + "\" src=\"" + global::Umbraco.Core.IO.IOHelper.ResolveUrl(imageMedia.getProperty("umbracoFile").Value.ToString()) +
                                      "\"";
                            tempTag += "/>";

                            // Replace the tag
                            html = html.Replace(tag.Value, tempTag);
                        }
                        catch (Exception ee)
                        {
                            Log.Add(LogTypes.Error, User.GetUser(0), -1,
                                    "Error reading size data from media: " + imageMedia.Id.ToString() + ", " +
                                    ee.ToString());
                        }
                    }
                    else
                    {
                        Log.Add(LogTypes.Error, User.GetUser(0), -1,
                                "Error reading size data from media (not found): " + orgSrc);
                    }
                }
            }
            return(html);
        }