示例#1
0
        public static WikiFile Create(string fileName, string extension, Guid node, Guid memberGuid, byte[] file, string filetype, List <UmbracoVersion> versions, string dotNetVersion)
        {
            try
            {
                if (ExtensionNotAllowed(extension))
                {
                    return(null);
                }

                var content = Content.GetContentFromVersion(node);
                var member  = new Member(memberGuid);

                if (content != null)
                {
                    var wikiFile = new WikiFile();

                    if (dotNetVersion != null)
                    {
                        wikiFile.DotNetVersion = dotNetVersion;
                    }

                    wikiFile.Name        = fileName;
                    wikiFile.NodeId      = content.Id;
                    wikiFile.NodeVersion = content.Version;
                    wikiFile.FileType    = filetype;
                    wikiFile.CreatedBy   = member.Id;
                    wikiFile.Downloads   = 0;
                    wikiFile.Archived    = false;
                    wikiFile.Versions    = versions;
                    wikiFile.Version     = versions[0];
                    wikiFile.Verified    = false;

                    var path = string.Format("/media/wiki/{0}", content.Id);

                    if (Directory.Exists(HttpContext.Current.Server.MapPath(path)) == false)
                    {
                        Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));
                    }

                    fileName = fileName.Substring(0, fileName.LastIndexOf('.') + 1);
                    path     = string.Format("{0}/{1}_{2}.{3}", path, DateTime.Now.Ticks, umbraco.cms.helpers.url.FormatUrl(fileName), extension);

                    using (var fileStream = new FileStream(HttpContext.Current.Server.MapPath(path), FileMode.Create))
                        fileStream.Write(file, 0, file.Length);

                    wikiFile.Path = path;
                    wikiFile.SetMinimumUmbracoVersion();
                    wikiFile.Save();

                    return(wikiFile);
                }
            }
            catch (Exception ex)
            {
                Log.Add(LogTypes.Debug, -1, ex.ToString());
            }

            return(null);
        }
示例#2
0
        public static WikiFile Create(string name, Guid node, Guid memberGuid, HttpPostedFile file, string filetype, List <UmbracoVersion> versions, string dotNetVersion)
        {
            try
            {
                var filename  = file.FileName;
                var extension = filename.Substring(filename.LastIndexOf('.') + 1);

                if (ExtensionNotAllowed(extension))
                {
                    return(null);
                }

                var content = Content.GetContentFromVersion(node);

                var member = new Member(memberGuid);

                if (content != null)
                {
                    var wikiFile = new WikiFile
                    {
                        Name          = name,
                        NodeId        = content.Id,
                        NodeVersion   = content.Version,
                        FileType      = filetype,
                        CreatedBy     = member.Id,
                        Downloads     = 0,
                        Archived      = false,
                        Versions      = versions,
                        Version       = versions[0],
                        Verified      = false,
                        DotNetVersion = dotNetVersion
                    };

                    var path = string.Format("/media/wiki/{0}", content.Id);

                    if (Directory.Exists(HttpContext.Current.Server.MapPath(path)) == false)
                    {
                        Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));
                    }

                    path = string.Format("{0}/{1}_{2}.{3}", path, DateTime.Now.Ticks, umbraco.cms.helpers.url.FormatUrl(filename), extension);

                    file.SaveAs(HttpContext.Current.Server.MapPath(path));

                    wikiFile.Path = path;

                    wikiFile.Save();

                    return(wikiFile);
                }
            }
            catch (Exception ex)
            {
                Log.Add(LogTypes.Debug, -1, ex.ToString());
            }

            return(null);
        }
示例#3
0
        protected void DeleteFile(object sender, CommandEventArgs e)
        {
            WikiFile wf = new WikiFile(int.Parse(e.CommandArgument.ToString()));
            //Member mem = Member.GetCurrentMember();

            //if (wf.CreatedBy == mem.Id)
                wf.Delete();

            RebindFiles();
        }
        protected void DeleteFile(object sender, CommandEventArgs e)
        {
            WikiFile wf = new WikiFile( int.Parse(e.CommandArgument.ToString()) );
            Member mem = Member.GetCurrentMember();

            if(wf.CreatedBy == mem.Id || Utils.IsProjectContributor(mem.Id,pageId))
                wf.Delete();

            RebindFiles();
        }
示例#5
0
        /// <summary>
        /// Gets all wiki files for all nodes
        /// </summary>
        /// <returns></returns>
        public static Dictionary <int, IEnumerable <WikiFile> > CurrentFiles(IEnumerable <int> nodeIds)
        {
            var wikiFiles = new Dictionary <int, List <WikiFile> >();

            //we can only have 2000 (actually 2100) SQL parameters used at once, so we need to group them
            var nodeBatches = nodeIds.InGroupsOf(2000);

            foreach (var nodeBatch in nodeBatches)
            {
                foreach (var result in ApplicationContext.Current.DatabaseContext.Database.Query <dynamic>("SELECT * FROM wikiFiles WHERE nodeId IN (@nodeIds)", new { nodeIds = nodeBatch }))
                {
                    var file = new WikiFile
                    {
                        Id                   = result.id,
                        Path                 = result.path,
                        Name                 = result.name,
                        FileType             = result.type,
                        RemovedBy            = result.removedBy,
                        CreatedBy            = result.createdBy,
                        NodeVersion          = result.version,
                        NodeId               = result.nodeId,
                        CreateDate           = result.createDate,
                        DotNetVersion        = result.dotNetVersion,
                        Downloads            = result.downloads,
                        Archived             = result.archived,
                        Verified             = result.verified,
                        Versions             = GetVersionsFromString(result.umbracoVersion),
                        MinimumVersionStrict = result.minimumVersionStrict
                    };

                    file.Version = file.Versions.Any()
                        ? GetVersionsFromString(result.umbracoVersion)[0]
                        : UmbracoVersion.DefaultVersion();

                    if (wikiFiles.ContainsKey(result.nodeId))
                    {
                        var list = wikiFiles[result.nodeId];
                        list.Add(file);
                    }
                    else
                    {
                        wikiFiles.Add(result.nodeId, new List <WikiFile>(new[] { file }));
                    }
                }
            }

            return(wikiFiles.ToDictionary(x => x.Key, x => (IEnumerable <WikiFile>)x.Value));
        }
        protected void ArchiveFile(object sender, CommandEventArgs e)
        {
            WikiFile wf = new WikiFile(int.Parse(e.CommandArgument.ToString()));

            if (e.CommandName == "Unarchive")
            {
                wf.Archived = false;
            }
            else
            {
                wf.Archived = true;
            }

            wf.Save();
            RebindFiles();
        }
示例#7
0
        /// <summary>
        /// Gets all wiki files for all nodes
        /// </summary>
        /// <returns></returns>
        public static Dictionary<int, IEnumerable<WikiFile>> CurrentFiles(IEnumerable<int> nodeIds)
        {
            var wikiFiles = new Dictionary<int, List<WikiFile>>();

            //we can only have 2000 (actually 2100) SQL parameters used at once, so we need to group them
            var nodeBatches = nodeIds.InGroupsOf(2000);

            foreach (var nodeBatch in nodeBatches)
            {
                foreach (var result in ApplicationContext.Current.DatabaseContext.Database.Query<dynamic>("SELECT * FROM wikiFiles WHERE nodeId IN (@nodeIds)", new { nodeIds = nodeBatch }))
                {
                    var file = new WikiFile
                    {
                        Id = result.id,
                        Path = result.path,
                        Name = result.name,
                        FileType = result.type,
                        RemovedBy = result.removedBy,
                        CreatedBy = result.createdBy,
                        NodeVersion = result.version,
                        NodeId = result.nodeId,
                        CreateDate = result.createDate,
                        DotNetVersion = result.dotNetVersion,
                        Downloads = result.downloads,
                        Archived = result.archived,
                        Verified = result.verified,
                        Versions = GetVersionsFromString(result.umbracoVersion)
                    };

                    file.Version = file.Versions.Any()
                        ? GetVersionsFromString(result.umbracoVersion)[0]
                        : UmbracoVersion.DefaultVersion();

                    if (wikiFiles.ContainsKey(result.nodeId))
                    {
                        var list = wikiFiles[result.nodeId];
                        list.Add(file);
                    }
                    else
                    {
                        wikiFiles.Add(result.nodeId, new List<WikiFile>(new[] { file }));
                    }
                }
            }

            return wikiFiles.ToDictionary(x => x.Key, x => (IEnumerable<WikiFile>)x.Value);
        }
示例#8
0
        public static WikiFile Create(string fileName, string extension, Guid node, Guid memberGuid, byte[] file, string filetype, List<UmbracoVersion> versions)
        {
            try
            {
                if (ExtensionNotAllowed(extension))
                    return null;

                var content = Content.GetContentFromVersion(node);
                var member = new Member(memberGuid);

                if (content != null)
                {
                    var wikiFile = new WikiFile
                                   {
                                       Name = fileName,
                                       NodeId = content.Id,
                                       NodeVersion = content.Version,
                                       FileType = filetype,
                                       CreatedBy = member.Id,
                                       Downloads = 0,
                                       Archived = false,
                                       Versions = versions,
                                       Version = versions[0],
                                       Verified = false
                                   };

                    var path = string.Format("/media/wiki/{0}", content.Id);

                    if (Directory.Exists(HttpContext.Current.Server.MapPath(path)) == false)
                        Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));

                    fileName = fileName.Substring(0, fileName.LastIndexOf('.') + 1);
                    path = string.Format("{0}/{1}_{2}.{3}", path, DateTime.Now.Ticks, umbraco.cms.helpers.url.FormatUrl(fileName), extension);

                    using (var fileStream = new FileStream(HttpContext.Current.Server.MapPath(path), FileMode.Create))
                        fileStream.Write(file, 0, file.Length);

                    wikiFile.Path = path;
                    wikiFile.Save();

                    return wikiFile;
                }
            }
            catch (Exception ex)
            {
                Log.Add(LogTypes.Debug, -1, ex.ToString());
            }

            return null;
        }
示例#9
0
        public string VerifyFile(int fileId)
        {
            if (Xslt.IsMemberInGroup("admin", Members.GetCurrentMember().Id))
            {
                var wikiFile = new WikiFile(fileId) { Verified = true };
                wikiFile.Save();
            }

            return "";
        }
示例#10
0
 public void Remove(WikiFile file)
 {
     file.Delete();
 }
示例#11
0
 /// <summary>
 /// Save or update a media file back to the database.
 /// </summary>
 /// <param name="file"></param>
 public void SaveOrUpdate(WikiFile file)
 {
     var wf = file;
     wf.Save();
 }
示例#12
0
        internal static WikiFile PackageFileByGuid(Guid pack)
        {
            XPathNodeIterator xpn = umbraco.library.GetXmlNodeByXPath("descendant::* [@isDoc and translate(packageGuid,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') = translate('" + pack.ToString() + "','ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')]");

            if (xpn.MoveNext())
            {
                if (xpn.Current is IHasXmlNode)
                {
                    Node node = new Node(((IHasXmlNode)xpn.Current).GetNode());
                    string fileId = safeProperty(node, "file");
                    int _id;

                    if (int.TryParse(fileId, out _id))
                    {
                        string cookieName = "ProjectFileDownload" + fileId;

                        //we clear the cookie on the server just to be sure the download is accounted for
                        if (HttpContext.Current.Request.Cookies[cookieName] != null)
                        {
                            HttpCookie myCookie = new HttpCookie(cookieName);
                            myCookie.Expires = DateTime.Now.AddDays(-1d);
                            HttpContext.Current.Response.Cookies.Add(myCookie);
                        }

                        WikiFile wf = new WikiFile(_id);
                        wf.UpdateDownloadCounter(true,true);

                        return wf;
                    }
                }
            }

            return null;
        }
示例#13
0
        private string GetMinimumUmbracoVersion(WikiFile mediaFile)
        {
            var extractor = new PackageExtraction();
            var filePath = IOHelper.MapPath(mediaFile.Path);
            var packageXml = extractor.ReadTextFileFromArchive(filePath, Constants.Packaging.PackageXmlFileName);
            if (string.IsNullOrWhiteSpace(packageXml))
            {
                return null;
            }

            var packageXmlDoc = XDocument.Parse(packageXml);
            if (packageXmlDoc == null)
            {
                return null;
            }

            // The XPath query will detect if the 'requirements' element has the attribute that we're looking for,
            // and if the child elements also exist. [LK:2016-06-12@CGRT16]
            var requirements = packageXmlDoc.XPathSelectElement("/umbPackage/info/package/requirements[@type='strict' and major and minor and patch]");
            if (requirements == null)
            {
                return null;
            }

            var major = requirements.Element("major").Value;
            var minor = requirements.Element("minor").Value;
            var patch = requirements.Element("patch").Value;

            return string.Join(".", new[] { major, minor, patch });
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["id"] != null)
            {
                var fileId = int.Parse(Request["id"]);

                var wikiFile = new WikiFile(fileId);

                wikiFile.UpdateDownloadCounter(false, wikiFile.FileType == "package");

                var path = BL.Application.SqlHelper.ExecuteScalar<string>(
                        "Select path from wikiFiles where id = @id;",
                        BL.Application.SqlHelper.CreateParameter("@id", fileId));

                var file = BL.Application.SqlHelper.ExecuteScalar<string>(
                   "Select name from wikiFiles where id = @id;",
                   BL.Application.SqlHelper.CreateParameter("@id", fileId));

                var fileinfo = new System.IO.FileInfo(Server.MapPath(path));

                var extension = System.IO.Path.GetExtension(Server.MapPath(path));
                var type = "";
                // set known types based on file extension
                if (extension != null)
                {
                    switch (extension.ToLower())
                    {
                        case ".tif":
                        case ".tiff":
                            type = "image/tiff";
                            break;
                        case ".jpg":
                        case ".jpeg":
                            type = "image/jpeg";
                            break;
                        case ".gif":
                            type = "image/gif";
                            break;
                        case ".docx":
                        case ".doc":
                        case ".rtf":
                            type = "Application/msword";
                            break;
                        case ".pdf":
                            type = "Application/pdf";
                            break;
                        case ".png":
                            type = "image/png";
                            break;
                        case ".bmp":
                            type = "image/bmp";
                            break;
                        default:
                            type = "application/octet-stream";
                            break;
                    }
                }

                Response.Clear();

                Response.AddHeader("Content-Disposition", "attachment; filename= " + MakeSafeFileName(file));
                Response.AddHeader("Content-Length", fileinfo.Length.ToString());
                Response.ContentType = type;
                Response.WriteFile(path);
            }
        }
示例#15
0
        public static WikiFile Create(string name, Guid node, Guid memberGuid, HttpPostedFile file, string filetype, List<UmbracoVersion> versions, string dotNetVersion)
        {
            try
            {
                var filename = file.FileName;
                var extension = filename.Substring(filename.LastIndexOf('.') + 1);

                if (ExtensionNotAllowed(extension))
                    return null;

                var content = Content.GetContentFromVersion(node);

                var member = new Member(memberGuid);

                if (content != null)
                {
                    var wikiFile = new WikiFile
                    {
                        Name = name,
                        NodeId = content.Id,
                        NodeVersion = content.Version,
                        FileType = filetype,
                        CreatedBy = member.Id,
                        Downloads = 0,
                        Archived = false,
                        Versions = versions,
                        Version = versions[0],
                        Verified = false,
                        DotNetVersion = dotNetVersion
                    };

                    var path = string.Format("/media/wiki/{0}", content.Id);

                    if (Directory.Exists(HttpContext.Current.Server.MapPath(path)) == false)
                        Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));

                    path = string.Format("{0}/{1}_{2}.{3}", path, DateTime.Now.Ticks, umbraco.cms.helpers.url.FormatUrl(filename), extension);

                    file.SaveAs(HttpContext.Current.Server.MapPath(path));

                    wikiFile.Path = path;

                    // Note: make sure to do this AFTER setting the path, else it will fail
                    wikiFile.SetMinimumUmbracoVersion();

                    wikiFile.Save();

                    return wikiFile;
                }

            }
            catch (Exception ex)
            {
                Log.Add(LogTypes.Debug, -1, ex.ToString());
            }

            return null;
        }
        public SimpleDataSet MapProjectToSimpleDataIndexItem(IPublishedContent project, SimpleDataSet simpleDataSet, string indexType,
            int projectVotes, WikiFile[] files, int downloads, IEnumerable<string> compatVersions)
        {
            var isLive = project.GetPropertyValue<bool>("projectLive");
            var isApproved = project.GetPropertyValue<bool>("approved");

            var minimumVersionStrict = string.Empty;
            var currentFileId = project.GetPropertyValue<int>("file");
            if (currentFileId > 0)
            {
                var currentFile = files.FirstOrDefault(x => x.Id == currentFileId);
                if (currentFile != null)
                    minimumVersionStrict = currentFile.MinimumVersionStrict;
            }

            simpleDataSet.NodeDefinition.NodeId = project.Id;
            simpleDataSet.NodeDefinition.Type = indexType;

            simpleDataSet.RowData.Add("body", project.GetPropertyValue<string>("description"));
            simpleDataSet.RowData.Add("nodeName", project.Name);
            simpleDataSet.RowData.Add("categoryFolder", project.Parent.Name.ToLowerInvariant().Trim());
            simpleDataSet.RowData.Add("updateDate", project.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"));
            simpleDataSet.RowData.Add("createDate", project.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"));
            simpleDataSet.RowData.Add("nodeTypeAlias", "project");
            simpleDataSet.RowData.Add("url", project.Url);
            simpleDataSet.RowData.Add("uniqueId", project.GetPropertyValue<string>("packageGuid"));
            simpleDataSet.RowData.Add("worksOnUaaS", project.GetPropertyValue<string>("worksOnUaaS"));
            simpleDataSet.RowData.Add("minimumVersionStrict", minimumVersionStrict);

            var imageFile = string.Empty;
            if (project.HasValue("defaultScreenshotPath"))
            {
                imageFile = project.GetPropertyValue<string>("defaultScreenshotPath");
            }
            if (string.IsNullOrWhiteSpace(imageFile))
            {
                var image = files.FirstOrDefault(x => x.FileType == "screenshot");
                if (image != null)
                    imageFile = image.Path;
            }

            //Clean up version data before its included in the index, the reason we have to do this
            // is due to the way the version data is stored, you can see it in uVersion.config - it's super strange
            // because of the 3 digit nature but when it doesn't end with a '0' it's actually just the major/minor version
            // so we have to do all of this parsing.
            var version = project.GetPropertyValue<string>("compatibleVersions") ?? string.Empty;
            var cleanedVersions = version.ToLower()
                .Replace("nan", "")
                .Replace("saved", "")
                .Replace("v", "")
                .Trim(',')
                .Split(',')
                //it's stored as an int like 721 (for version 7.2.1)
                .Where(x => x.Length <= 3 && x.Length > 0)
                //pad it out to 3 digits
                .Select(x => x.PadRight(3, '0'))
                .Select(x =>
                {
                    int o;
                    if (int.TryParse(x, out o))
                    {
                        //if it ends with '0', that means it's a X.X.X version
                        // if it does not end with '0', that means that the last 2 digits are the
                        // Minor part of the version
                        return x.EndsWith("0")
                            ? string.Format("{0}.{1}.{2}", x[0], x[1], 0)
                            : string.Format("{0}.{1}.{2}", x[0], x.Substring(1), 0);
                    }
                    return null;
                })
                .Where(x => x != null);

            var cleanedCompatVersions = compatVersions.Select(x => x.Replace("nan", "")
                .Replace("saved", "")
                .Replace("nan", "")
                .Replace("v", "")
                .Replace(".x", "")
                .Trim(','));

            //popularity for sorting number = downloads + karma * 100;
            //TODO: Change score so that we take into account:
            // - recently updated
            // - works on latest umbraco versions
            // - works on uaas
            // - has a forum
            // - has source code link
            // - open for collab / has collaborators
            // - download count in a recent timeframe - since old downloads should count for less

            var pop = downloads + (projectVotes * 100);

            simpleDataSet.RowData.Add("popularity", pop.ToString());
            simpleDataSet.RowData.Add("karma", projectVotes.ToString());
            simpleDataSet.RowData.Add("downloads", downloads.ToString());
            simpleDataSet.RowData.Add("image", imageFile);

            var packageFiles = files.Count(x => x.FileType == "package");
            simpleDataSet.RowData.Add("packageFiles", packageFiles.ToString());

            simpleDataSet.RowData.Add("projectLive", isLive ? "1" : "0");
            simpleDataSet.RowData.Add("approved", isApproved ? "1" : "0");

            //now we need to add the versions and compat versions
            // first, this is the versions that the project has files tagged against
            simpleDataSet.RowData.Add("versions", string.Join(",", cleanedVersions));
            //then we index the versions that the project has actually been flagged as compatible against
            simpleDataSet.RowData.Add("compatVersions", string.Join(",", cleanedCompatVersions));

            return simpleDataSet;
        }