Example #1
0
        public static int CountWords(int DocumentId)
        {
            Document d = new Document(DocumentId);

            int words = CountWordsInString(d.Text);
            foreach (Property p in d.getProperties)
            {
                if (p.Value.GetType() == "".GetType())
                {
                    if (p.Value.ToString().Trim() != "")
                        words += CountWordsInString(p.Value.ToString());
                }
            }

            return words;
        }
Example #2
0
		/// <summary>
		/// Whenever an action is performed upon a document/media/member, this method is executed, ensuring that 
		/// all registered handlers will have an oppotunity to handle the action.
		/// </summary>
		/// <param Name="d">The document being operated on</param>
		/// <param Name="action">The action triggered</param>
		public static void RunActionHandlers(Document d, IAction action)
		{
			foreach(IActionHandler ia in _actionHandlers)
			{
				try
				{
					foreach(IAction a in ia.ReturnActions())
					{
						if(a.Alias == action.Alias)
						{
							// Uncommented for auto publish support
							//								System.Web.HttpContext.Current.Trace.Write("Umbraco.Cms.BusinessLogic.Action.RunActionHandlers", "Running " + ia.HandlerName() + " (matching action: " + a.Alias + ")");
							ia.Execute(d, action);
						}
					}
				}
				catch(Exception iaExp)
				{
					Log.Add(LogTypes.Error, User.GetUser(0), -1, string.Format("Error loading actionhandler '{0}': {1}",
						ia.HandlerName(), iaExp));
				}
			}

			// Run notification
			// Find current user
			User u;
			try
			{
				u = new UmbracoEnsuredPage().ValidatedUser;
			}
			catch
			{
				u = User.GetUser(0);
			}
			Notification.GetNotifications(d, u, action);
		}
Example #3
0
		public static Cms.BusinessLogic.Member.MemberGroup[] GetAccessingGroups(int DocumentId) 
		{
			Cms.BusinessLogic.web.Document d = new Document(DocumentId);

			if (!IsProtected(DocumentId, d.Path))
				return null;
			else 
			{
                XmlNode currentNode = getPage(getProtectedPage(d.Path));
				Cms.BusinessLogic.Member.MemberGroup[] mg = new Umbraco.Cms.BusinessLogic.Member.MemberGroup[currentNode.SelectNodes("./group").Count];
				int count = 0;
				foreach (XmlNode n in currentNode.SelectNodes("./group"))
				{
					mg[count] = new Cms.BusinessLogic.Member.MemberGroup(int.Parse(n.Attributes.GetNamedItem("id").Value));
					count++;
				}
				return mg;
			}

		}
Example #4
0
		public static bool IsProtectedByGroup(int DocumentId, int GroupId) 
		{
			bool isProtected = false;

			Cms.BusinessLogic.web.Document d = new Document(DocumentId);

			if (!IsProtected(DocumentId, d.Path))
				isProtected = false;
			else 
			{
				XmlNode currentNode = getPage(getProtectedPage(d.Path));
				if (currentNode.SelectSingleNode("./group [@id=" + GroupId.ToString() + "]") != null) 
				{
					isProtected = true;
				}
			}

			return isProtected;
		}
Example #5
0
        // TODO: Include update with html mail notification and document contents
        private static void sendNotification(User performingUser, User mailingUser, Document documentObject,
                                             IAction Action)
        {
            // build summary
            StringBuilder summary = new StringBuilder();
            foreach (Property p in documentObject.getProperties)
            {
                summary.Append("<tr>");
                summary.Append("<th>" + p.PropertyType.Name + "</th>");
                summary.Append("<td>" + p.Value.ToString() + "</td>");
                summary.Append("</tr>");
                summary.Append("<tr><td colspan=\"2\" class=\"splitter\">&nbsp;</td></tr>");
            }
            string[] subjectVars = {
                                       HttpContext.Current.Request.ServerVariables["SERVER_NAME"], ui.Text(Action.Alias)
                                       ,
                                       documentObject.Text
                                   };
            string[] bodyVars = {
                                    mailingUser.Name, ui.Text(Action.Alias), documentObject.Text, performingUser.Name,
                                    HttpContext.Current.Request.ServerVariables["SERVER_NAME"],
                                    documentObject.Id.ToString(), summary.ToString()
                                };

            // create the mail message 
            MailMessage mail = new MailMessage(UmbracoSettings.NotificationEmailSender, mailingUser.Email);

            // populate the message
            mail.Subject = ui.Text("notifications", "mailSubject", subjectVars, mailingUser);
            if (UmbracoSettings.NotificationDisableHtmlEmail)
            {
                mail.IsBodyHtml = false;
                mail.Body = ui.Text("notifications", "mailBody", bodyVars, mailingUser);
            } else
            {
                mail.IsBodyHtml = true;
                mail.Body =
                    @"<html><head><style>
body {
    font-family: Trebuchet MS, arial, sans-serif;
    font-color: black;
}


.buttons {
    margin: 8px 0;
    padding: 8px;
    display: block;
}

.buttons a, .buttons a:visited, .buttons a:active {
    color: white;
}


.buttonPublish {
    color: white;
    font-weight: bold;
    background-color: #66cc66;
    text-decoration : none;
    margin-right: 20px;
    border: 8px solid #66cc66;
    width: 150px;
}

.buttonEdit {
    color: white;
    font-weight: bold;
    background-color: #5372c3;
    text-decoration : none;    
    margin-right: 20px;
    border: 8px solid #5372c3;
    width: 150px;
}

.buttonDelete {
    color: white;
    font-weight: bold;
    background-color: #ca4a4a;
    text-decoration : none;
    border: 8px solid #ca4a4a;
    width: 150px;
}

.updateSummary {
    width: 100%;
}

.splitter {
    border-bottom: 1px solid #CCC;
    font-size: 2px;
}

.updateSummary th {
    text-align: left;
    vertical-align: top;
    width: 25%;
}

.updateSummary td {
    text-align: left;
    vertical-align: top;
}
</style>
</head>
<body>
" +
                    ui.Text("notifications", "mailBodyHtml", bodyVars, mailingUser) + "</body></html>";
            }

            // send it
            SmtpClient sender = new SmtpClient(GlobalSettings.SmtpServer);
            sender.Send(mail);
        }
Example #6
0
        /// <summary>
        /// Performance tuned method for use in the tree
        /// </summary>
        /// <param Name="NodeId">The parentdocuments id</param>
        /// <returns></returns>
        public static Document[] GetChildrenForTree(int NodeId)
        {
            ArrayList tmp = new ArrayList();
            using (SqlDataReader dr =
                Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteReader(GlobalSettings.DbDSN, CommandType.Text,
                                        @"
create table #temp (contentId int, versionDate datetime)      
insert into #temp
select contentId, max(versionDate) 
from cmsContentVersion 
inner join umbracoNode on umbracoNode.id = cmsContentVersion.contentId and umbracoNode.parentId = @parentId
group by contentId

select 
	count(children.id) as children, umbracoNode.id, umbracoNode.uniqueId, umbracoNode.level, umbracoNode.parentId, cmsDocument.documentUser, umbracoNode.path, umbracoNode.sortOrder, isnull(publishCheck.published,0) as published, umbracoNode.createDate, cmsDocument.text, cmsDocument.updateDate, cmsContentVersion.versionDate, cmsContentType.icon
from umbracoNode 
left join umbracoNode children on children.parentId = umbracoNode.id
inner join cmsContent on cmsContent.nodeId = umbracoNode.id
inner join cmsContentType on cmsContentType.nodeId = cmsContent.contentType
inner join #temp on #temp.contentId = cmsContent.nodeId
inner join cmsContentVersion on cmsContentVersion.contentId = #temp.contentId and cmsContentVersion.versionDate = #temp.versionDate
inner join cmsDocument on cmsDocument.versionId = cmsContentversion.versionId
left join cmsDocument publishCheck on publishCheck.nodeId = cmsContent.nodeID and publishCheck.published = 1
where umbracoNode.parentID = @parentId 
group by umbracoNode.id, umbracoNode.uniqueId, umbracoNode.level, umbracoNode.parentId, cmsDocument.documentUser, umbracoNode.path, umbracoNode.sortOrder, isnull(publishCheck.published,0), umbracoNode.createDate, cmsDocument.text, cmsDocument.updateDate, cmsContentVersion.versionDate, cmsContentType.icon 
order by umbracoNode.sortOrder

drop table #temp


",
                                        new SqlParameter("@parentId", NodeId)))
            {
                while (dr.Read())
                {
                    Document d = new Document(int.Parse(dr["id"].ToString()), true);
                    bool _hc = false;
                    if (int.Parse(dr["children"].ToString()) > 0)
                        _hc = true;
                    d.SetupDocumentForTree(new Guid(dr["uniqueId"].ToString()), int.Parse((dr["level"].ToString())),
                                           int.Parse(dr["parentId"].ToString()),
                                           int.Parse(dr["documentUser"].ToString()),
                                           bool.Parse(dr["published"].ToString()),
                                           dr["path"].ToString(), dr["text"].ToString(),
                                           DateTime.Parse(dr["createDate"].ToString()),
                                           DateTime.Parse(dr["updateDate"].ToString()),
                                           DateTime.Parse(dr["versionDate"].ToString()), dr["icon"].ToString(), _hc);
                    tmp.Add(d);
                }
            }

            Document[] retval = new Document[tmp.Count];

            for (int i = 0; i < tmp.Count; i ++)
                retval[i] = (Document) tmp[i];

            return retval;
        }
Example #7
0
        /// <summary>
        /// Publishing a document
        /// 
        /// A xmlrepresentation of the document and its data are exposed to the runtime data
        /// (an xmlrepresentation is added -or updated if the document previously are published) ,
        /// this will lead to a new version of the document being created, for continuing editing of
        /// the data.
        /// </summary>
        /// <param Name="u">The usercontext under which the action are performed</param>
        public void Publish(User u)
        {
            _published = true;
            string tempVersion = System.Version.ToString();
            Guid newVersion = createNewVersion();

            Log.Add(LogTypes.Publish, u, Id, "");

            Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteNonQuery(_ConnString, CommandType.Text,
                                      "insert into cmsDocument (newest, nodeId, published, documentUser, versionId, Text, TemplateId) values (1," +
                                      Id + ", 0, " + u.Id + ", '" + newVersion + "', N'" + Umbraco.SqlHelper.SafeString(Text) +
                                      "', " + _template + ")");
            Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteNonQuery(_ConnString, CommandType.Text,
                                      "update cmsDocument set published = 0 where nodeId = " + Id +
                                      " update cmsDocument set published = 1, newest = 0 where versionId = '" +
                                      tempVersion + "'");

            // update release and expire dates
            Document newDoc = new Document(Id, newVersion);
            if (ReleaseDate != new DateTime())
                newDoc.ReleaseDate = ReleaseDate;
            if (ExpireDate != new DateTime())
                newDoc.ExpireDate = ExpireDate;

            // Update xml in db using the new document (has correct version date)
            newDoc.XmlGenerate(new XmlDocument());
        }
Example #8
0
 /// <summary>
 /// Deletes all documents of a type, will be invoked if a documenttype is deleted.
 /// 
 /// Note: use with care: this method can result in wast amount of data being deleted.
 /// </summary>
 /// <param Name="dt">The type of which documents should be deleted</param>
 public static void DeleteFromType(DocumentType dt)
 {
     foreach (Content c in getContentOfContentType(dt))
     {
         // due to recursive structure document might already been deleted..
         if (IsNode(c.UniqueId))
         {
             Document tmp = new Document(c.UniqueId);
             tmp.delete();
         }
     }
 }
Example #9
0
        /// <summary>
        /// Creates a new document
        /// </summary>
        /// <param Name="Name">The Name (.Text property) of the document</param>
        /// <param Name="dct">The documenttype</param>
        /// <param Name="u">The usercontext under which the action are performed</param>
        /// <param Name="ParentId">The id of the parent to the document</param>
        /// <returns>The newly created document</returns>
        public static Document MakeNew(string Name, DocumentType dct, User u, int ParentId)
        {
            Guid newId = Guid.NewGuid();
            // Updated to match level from base node
            CMSNode n = new CMSNode(ParentId);
            int newLevel = n.Level;
            newLevel++;
            MakeNew(ParentId, _objectType, u.Id, newLevel, Name, newId);
            Document tmp = new Document(newId, true);
            tmp.CreateContent(dct);
            Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteNonQuery(_ConnString, CommandType.Text,
                                      "insert into cmsDocument (newest, nodeId, published, documentUser, versionId, Text) values (1, " +
                                      tmp.Id + ", 0, " +
                                      u.Id + ", '" + tmp.Version + "', N'" + SqlHelper.SafeString(tmp.Text) + "')");

            // Update the sortOrder if the parent was the root!
            if (ParentId == -1)
            {
                CMSNode c = new CMSNode(newId);
                c.sortOrder = GetRootDocuments().Length + 1;
            }

            Document d = new Document(newId);

            // Log
            Log.Add(LogTypes.New, u, d.Id, "");

            // Run Handler				
            Action.RunActionHandlers(d, new ActionNew());

            // Index
            try
            {
                Indexer.IndexNode(_objectType, d.Id, d.Text, d.User.Name, d.CreateDateTime, null, true);
            }
            catch (Exception ee)
            {
                Log.Add(LogTypes.Error, d.User, d.Id,
                        string.Format("Error indexing document: {0}", ee));
            }

            return d;
        }
Example #10
0
 /// <summary>
 /// 
 /// </summary>
 /// <returns>Returns a breadcrumlike path for the document like: /ancestorname/ancestorname</returns>
 public string GetTextPath()
 {
     string tempPath = "";
     string[] splitPath = Path.Split(".".ToCharArray());
     for (int i = 1; i < Level; i++)
     {
         tempPath += new Document(int.Parse(splitPath[i])).Text + "/";
     }
     if (tempPath.Length > 0)
         tempPath = tempPath.Substring(0, tempPath.Length - 1);
     return tempPath;
 }
Example #11
0
        /// <summary>
        /// Rollbacks a document to a previous version, this will create a new version of the document and copy
        /// all of the old documents data.
        /// </summary>
        /// <param Name="u">The usercontext under which the action are performed</param>
        /// <param Name="VersionId">The unique Id of the version to roll back to</param>
        public void RollBack(Guid VersionId, User u)
        {
            Guid newVersion = createNewVersion();
            Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteNonQuery(_ConnString, CommandType.Text,
                                      "insert into cmsDocument (nodeId, published, documentUser, versionId, Text, TemplateId) values (" +
                                      Id +
                                      ", 0, " + u.Id + ", '" + newVersion + "', N'" + Umbraco.SqlHelper.SafeString(Text) + "', " +
                                      _template + ")");

            // Get new version
            Document dNew = new Document(Id, newVersion);

            // Old version
            Document dOld = new Document(Id, VersionId);

            // Revert title
            dNew.Text = dOld.Text;

            // Revert all properties
            foreach (Property p in dOld.getProperties)
                try
                {
                    dNew.getProperty(p.PropertyType).Value = p.Value;
                }
                catch
                {
                    // property doesn't exists
                }
        }
Example #12
0
        /// <summary>
        /// Retrieve a list of documents with with releasedate greater than today
        /// </summary>
        /// <returns>Retrieve a list of documents with with releasedate greater than today</returns>
        public static Document[] GetDocumentsForRelease()
        {
            ArrayList docs = new ArrayList();
            SqlDataReader dr =
                Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteReader(GlobalSettings.DbDSN, CommandType.Text,
                                        "select distinct nodeId, level, sortOrder from cmsDocument inner join umbracoNode on umbracoNode.id = cmsDocument.nodeId where newest = 1 and not releaseDate is null and releaseDate <= getdate() order by [level], sortOrder");
            while (dr.Read())
                docs.Add(dr.GetInt32(dr.GetOrdinal("nodeId")));
            dr.Close();

            Document[] retval = new Document[docs.Count];
            for (int i = 0; i < docs.Count; i++) retval[i] = new Document((int) docs[i]);
            return retval;
        }
Example #13
0
        /// <summary>
        /// Retrieve a list of documents with an expirationdate greater than today
        /// </summary>
        /// <returns>A list of documents with expirationdates than today</returns>
        public static Document[] GetDocumentsForExpiration()
        {
            ArrayList docs = new ArrayList();
            SqlDataReader dr =
                Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteReader(GlobalSettings.DbDSN, CommandType.Text,
                                        "select distinct nodeId from cmsDocument where newest = 1 and not expireDate is null and expireDate <= getdate()");
            while (dr.Read())
                docs.Add(dr.GetInt32(dr.GetOrdinal("nodeId")));
            dr.Close();

            Document[] retval = new Document[docs.Count];
            for (int i = 0; i < docs.Count; i++) retval[i] = new Document((int) docs[i]);
            return retval;
        }
Example #14
0
 public bool Execute(Document documentObject, IAction action)
 {
     foreach (Domain d in Domain.GetDomainsById(documentObject.Id))
     {
         d.Delete();
     }
     // TODO:  Add DomainDeleteHandler.Execute implementation
     return true;
 }
Example #15
0
		public static Cms.BusinessLogic.Member.Member GetAccessingMember(int DocumentId) 
		{
			Cms.BusinessLogic.web.Document d = new Document(DocumentId);

			if (!IsProtected(DocumentId, d.Path))
				return null;
			else if (GetProtectionType(DocumentId) != ProtectionType.Simple)
				throw new Exception("Document isn't protected using Simple mechanism. Use GetAccessingMemberGroups instead");
			else 
			{
				XmlNode currentNode = getPage(getProtectedPage(d.Path));
				if (currentNode.Attributes.GetNamedItem("memberId") != null)
					return new Cms.BusinessLogic.Member.Member(int.Parse(
						currentNode.Attributes.GetNamedItem("memberId").Value));
				else
					throw new Exception("Document doesn't contain a memberId. This might be caused if document is protected using Umbraco RC1 or older.");

			}

		}
Example #16
0
		public static bool HasAccess(int DocumentId, Cms.BusinessLogic.Member.Member Member) 
		{
			bool hasAccess = false;

			Cms.BusinessLogic.web.Document d = new Document(DocumentId);

			if (!IsProtected(DocumentId, d.Path))
				hasAccess = true;
			else 
			{
				XmlNode currentNode = getPage(getProtectedPage(d.Path));
				if (Member != null) 
				{
					IDictionaryEnumerator ide = Member.Groups.GetEnumerator();
					while(ide.MoveNext())
					{
						Cms.BusinessLogic.Member.MemberGroup mg = (Cms.BusinessLogic.Member.MemberGroup) ide.Value;
						if (currentNode.SelectSingleNode("./group [@id=" + mg.Id.ToString() + "]") != null) 
						{
							hasAccess = true;
							break;
						}
					}
				}
			}

			return hasAccess;
		}
Example #17
0
        /// <summary>
        /// Used to get the firstlevel/root documents of the hierachy
        /// </summary>
        /// <returns>Root documents</returns>
        public static Document[] GetRootDocuments()
        {
            Guid[] topNodeIds = TopMostNodeIds(_objectType);

            Document[] retval = new Document[topNodeIds.Length];
            for (int i = 0; i < topNodeIds.Length; i++)
            {
                Document d = new Document(topNodeIds[i]);
                retval[i] = d;
            }
            return retval;
        }