public void IsTrashed_New_ReturnsFalse()
        {
            EnsureTestDocumentTypes();
            var node = new CMSNode(testContentType3);

            Assert.IsFalse(node.IsTrashed);
        }
        public static StylesheetProperty MakeNew(string Text, StyleSheet sheet, BusinessLogic.User user)
        {
            CMSNode newNode = CMSNode.MakeNew(sheet.Id, moduleObjectType, user.Id, 2, Text, Guid.NewGuid());

            Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteNonQuery(_ConnString, CommandType.Text, "Insert into cmsStylesheetProperty (nodeId,stylesheetPropertyAlias,stylesheetPropertyValue) values ('" + newNode.Id + "','" + Text + "','')");
            return(new StylesheetProperty(newNode.Id));
        }
        public void CountLeafNodes_Roots_ReturnsCount(string objectTypeId, int parentId, int expected, string description)
        {
            EnsureTestDocumentTypes();
            var actual = CMSNode.CountLeafNodes(parentId, new Guid(objectTypeId));

            Assert.AreEqual(expected, actual, description);
        }
        public void CountLeafNodes_DocumentTypeChild_ReturnsCount()
        {
            EnsureTestDocumentTypes();
            var actual = CMSNode.CountLeafNodes(testContentType1.Id, new Guid(DocumentTypeObjectTypeId));

            Assert.AreEqual(2, actual);
        }
Exemplo n.º 5
0
 public Task(int TaskId)
 {
     using (SqlDataReader dr =
                Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteReader(
                    GlobalSettings.DbDSN,
                    CommandType.Text,
                    "select taskTypeId, nodeId, parentUserId, userId, DateTime, comment from cmsTask where id = @id",
                    new SqlParameter("@id", TaskId)))
     {
         if (dr.Read())
         {
             _id        = TaskId;
             Type       = new TaskType(int.Parse(dr["taskTypeId"].ToString()));
             Node       = new CMSNode(int.Parse(dr["nodeId"].ToString()));
             ParentUser = User.GetUser(int.Parse(dr["parentUserId"].ToString()));
             User       = User.GetUser(int.Parse(dr["userId"].ToString()));
             Date       = dr.GetDateTime(dr.GetOrdinal("DateTime"));
             Comment    = dr["comment"].ToString();
         }
         else
         {
             throw new ArgumentException("Task with id: '" + TaskId + "' not found");
         }
     }
 }
        public void CountByObjectType_ReturnsCount(string objectTypeId, int expected, string description)
        {
            EnsureTestDocumentTypes();
            var actual = CMSNode.CountByObjectType(new Guid(objectTypeId));

            Assert.AreEqual(expected, actual, "There should be {0} of nodeObjectType {1}", expected, description);
        }
        public void MakeNew_PersistsNewUmbracoNodeRow()
        {
            // Testing Document._objectType, since it has exclusive use of GetNewDocumentSortOrder. :)

            int id = 0;

            try
            {
                CreateContext();
                TestCMSNode.MakeNew(-1, 1, "TestContent 1", Document._objectType);
                TestCMSNode.MakeNew(-1, 1, "TestContent 2", Document._objectType);
                var node3          = TestCMSNode.MakeNew(-1, 1, "TestContent 3", Document._objectType);
                var totalDocuments = database.ExecuteScalar <int>(
                    "SELECT COUNT(*) FROM umbracoNode WHERE nodeObjectType = @ObjectTypeId",
                    new { ObjectTypeId = Document._objectType });
                Assert.AreEqual(3, totalDocuments);
                id = node3.Id;
                var loadedNode = new CMSNode(id);
                AssertNonEmptyNode(loadedNode);
                Assert.AreEqual(2, loadedNode.sortOrder);
            }
            finally
            {
                DeleteContent();
            }
        }
        public void TopMostNodeIds_ReturnsUniqueIdsOfRootNodes()
        {
            // Lacks testing of sorting

            // Root
            Assert.IsTrue(
                new[] { new Guid("916724A5-173D-4619-B97E-B9DE133DD6F5") }
                .SequenceEqual(CMSNode.TopMostNodeIds(new Guid(RootObjectTypeId)))
                );

            // Content
            EnsureTestDocumentTypes();
            var nodes = CreateContent();

            try
            {
                Assert.IsTrue(
                    new[] { nodes[0].UniqueId }
                    .SequenceEqual(CMSNode.TopMostNodeIds(Document._objectType))
                    );
            }
            finally
            {
                for (var i = nodes.Count - 1; i >= 0; i--)
                {
                    nodes[i].delete();
                }
                DeleteContent();
            }
        }
Exemplo n.º 9
0
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);


            if (_showpreview)
            {
                if (string.IsNullOrEmpty(ItemIdValue.Value) || !CMSNode.IsNode(int.Parse(ItemIdValue.Value)))
                {
                    PreviewContainer.Style.Add(HtmlTextWriterStyle.Display, "none");
                    ImgViewer.MediaId = -1;
                }
                else
                {
                    ImgViewer.MediaId = int.Parse(ItemIdValue.Value);
                }
            }

            //if (ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
            //{
            //    //renders the media picker JS class
            //    ScriptManager.RegisterStartupScript(this, this.GetType(), "MediaChooser", MediaChooserScripts.MediaPicker, true);
            //    ScriptManager.RegisterStartupScript(this, this.GetType(), this.ClientID + "MediaPicker", strScript, true);

            //}
            //else
            //{
            //    //renders the media picker JS class
            //    Page.ClientScript.RegisterClientScriptBlock(typeof(mediaChooser), "MediaChooser", MediaChooserScripts.MediaPicker, true);
            //    Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID + "MediaPicker", strScript, true);

            //}
        }
Exemplo n.º 10
0
        public static MembershipUser GetAccessingMembershipUser(int documentId)
        {
            CMSNode d = new CMSNode(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(Membership.GetUser(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.");
                }
            }
        }
        /// <summary>
        ///   Gets the image property.
        /// </summary>
        /// <returns></returns>
        internal static string GetOriginalUrl(int nodeId, ImageResizerPrevalueEditor imagePrevalueEditor)
        {
            Property imageProperty;
            var node = new CMSNode(nodeId);
            if (node.nodeObjectType == Document._objectType)
            {
                imageProperty = new Document(nodeId).getProperty(imagePrevalueEditor.PropertyAlias);
            }
            else if (node.nodeObjectType == Media._objectType)
            {
                imageProperty = new Media(nodeId).getProperty(imagePrevalueEditor.PropertyAlias);
            }
            else
            {
                if (node.nodeObjectType != Member._objectType)
                {
                    throw new Exception("Unsupported Umbraco Node type for Image Resizer (only Document, Media and Members are supported.");
                }
                imageProperty = new Member(nodeId).getProperty(imagePrevalueEditor.PropertyAlias);
            }

            try
            {
                return imageProperty.Value.ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
        public override void Run(IWorkflowInstance workflowInstance, IWorkflowRuntime runtime)
        {
            base.Run(workflowInstance, runtime);

            var body = Helper.Instance.RenderTemplate(RenderTemplate);
            
            IList<string> files = new List<string>();

            foreach(var nodeId in ((UmbracoWorkflowInstance) workflowInstance).CmsNodes)
            {
                var node = new CMSNode(nodeId);
                if(node.IsMedia())
                {
                    files.Add(IOHelper.MapPath((string) new Media(nodeId).getProperty("umbracoFile").Value));
                }
            }

            var f = new User(From).Email;
            foreach(var r in GetRecipients())
            {
                var mail = new MailMessage(f, r) {Subject = Subject, IsBodyHtml = true, Body = body};

                foreach(var file in files)
                {
                    var attach = new Attachment(file);
                    mail.Attachments.Add(attach);
                }

                var smtpClient = new SmtpClient();
                smtpClient.Send(mail);
            }

            runtime.Transition(workflowInstance, this, "done");
        }
Exemplo n.º 13
0
        private void InsertPermission(int nodeID, IAction permission)
        {
            //create a new CMSNode object but don't initialize (this prevents a db query)
            CMSNode node = new CMSNode(nodeID, false);

            Permission.MakeNew(m_user, node, permission.Letter);
        }
Exemplo n.º 14
0
 public static void MakeNew(User User, CMSNode Node, char ActionLetter)
 {
     Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteNonQuery(GlobalSettings.DbDSN, CommandType.Text,
                                                                "if not exists(select userId from umbracoUser2nodeNotify where userId = @userId and nodeId = @nodeId and action = @action) insert into umbracoUser2nodeNotify (userId, nodeId, action) values (@userId, @nodeId, @action)",
                                                                new SqlParameter("@userId", User.Id), new SqlParameter("@nodeId", Node.Id),
                                                                new SqlParameter("@action", ActionLetter.ToString()));
 }
        private bool ValidAction(char actionLetter)
        {
            CMSNode d             = new CMSNode(int.Parse(helper.Request("id")));
            IAction currentAction = umbraco.BusinessLogic.Actions.Action.GetPermissionAssignable().Where(a => a.Letter == actionLetter).First();

            return(CheckPermissions(d, currentAction, actionLetter));
        }
        public void HasChildren_WhenParent_ReturnsTrue()
        {
            EnsureTestDocumentTypes();
            var parent = new CMSNode(testContentType1);

            Assert.IsTrue(parent.HasChildren);
        }
Exemplo n.º 17
0
        private bool ValidAction(char actionLetter)
        {
            var cmsNode       = new CMSNode(int.Parse(helper.Request("id")));
            var currentAction = BusinessLogic.Actions.Action.GetPermissionAssignable().First(a => a.Letter == actionLetter);

            return(CheckPermissions(cmsNode, currentAction));
        }
        public void HasChildren_WhenLeaf_ReturnsFalse()
        {
            EnsureTestDocumentTypes();
            var leaf = new CMSNode(testContentType3);

            Assert.IsFalse(leaf.HasChildren);
        }
Exemplo n.º 19
0
        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);

            node = new cms.businesslogic.CMSNode(int.Parse(helper.Request("id")));

            ArrayList actionList = BusinessLogic.Actions.Action.GetAll();
            
            foreach (interfaces.IAction a in actionList)
            {
                if (a.ShowInNotifier)
                {
                   
                    CheckBox c = new CheckBox();
                    c.ID = a.Letter.ToString();
                    
                    if (base.getUser().GetNotifications(node.Path).IndexOf(a.Letter) > -1)
                        c.Checked = true;

                    uicontrols.PropertyPanel pp = new umbraco.uicontrols.PropertyPanel();
                    pp.Text = ui.Text("actions", a.Alias);
                    pp.Controls.Add(c);

                    pane_form.Controls.Add(pp);
                    
                    actions.Add(c);
                 
                }
            }
          
        }
Exemplo n.º 20
0
        public static Template[] getAll()
        {
            Guid[] ids = CMSNode.TopMostNodeIds(_objectType);

            SortedList initRetVal = new SortedList();

            for (int i = 0; i < ids.Length; i++)
            {
                Template t = new Template(ids[i]);
                initRetVal.Add(t.Text + t.UniqueId, t);
            }

            Template[] retVal = new Template[ids.Length];

            IDictionaryEnumerator ide = initRetVal.GetEnumerator();

            int count = 0;

            while (ide.MoveNext())
            {
                retVal[count] = (Template)ide.Value;
                count++;
            }

            return(retVal);
        }
        /// <summary>
        ///   Gets the image property.
        /// </summary>
        /// <returns></returns>
        internal static string GetOriginalUrl(int nodeId, ImageResizerPrevalueEditor imagePrevalueEditor)
        {
            Property imageProperty;
            var      node = new CMSNode(nodeId);

            if (node.nodeObjectType == Document._objectType)
            {
                imageProperty = new Document(nodeId).getProperty(imagePrevalueEditor.PropertyAlias);
            }
            else if (node.nodeObjectType == Media._objectType)
            {
                imageProperty = new Media(nodeId).getProperty(imagePrevalueEditor.PropertyAlias);
            }
            else
            {
                if (node.nodeObjectType != Member._objectType)
                {
                    throw new Exception("Unsupported Umbraco Node type for Image Resizer (only Document, Media and Members are supported.");
                }
                imageProperty = new Member(nodeId).getProperty(imagePrevalueEditor.PropertyAlias);
            }

            try
            {
                return(imageProperty.Value.ToString());
            }
            catch
            {
                return(string.Empty);
            }
        }
        public void GetNodesForPreview_NotChildrenOnly_ReturnsItself()
        {
            EnsureTestDocumentTypes();
            var nodes = CreateContent();

            try
            {
                // oh yes, GetNodesForPreview in base returns both draft and not draft as draft
                var expectedNodes = new[] { nodes[0], nodes[0] };
                var result        = new CMSNode(nodes[0].Id).GetNodesForPreview(false);
                Assert.AreEqual(expectedNodes.Length, result.Count);
                for (var i = 0; i < expectedNodes.Length; i++)
                {
                    AssertXmlPreviewNode(expectedNodes, result, i);
                }
            }
            finally
            {
                for (var i = nodes.Count - 1; i >= 0; i--)
                {
                    nodes[i].delete();
                }
                DeleteContent();
            }
        }
        public void Run(IWorkflowInstance workflowInstance, IWorkflowRuntime runtime)
        {
            // Cast to Umbraco worklow instance.
            var umbracoWorkflowInstance = (UmbracoWorkflowInstance)workflowInstance;

            var count       = 0;
            var newCmsNodes = new List <int>();

            foreach (var nodeId in umbracoWorkflowInstance.CmsNodes)
            {
                var n = new CMSNode(nodeId);
                if (!n.IsMedia())
                {
                    continue;
                }

                var d = new Media(nodeId);
                if (!MediaTypes.Contains(d.ContentType.Id))
                {
                    continue;
                }

                newCmsNodes.Add(nodeId);
                count++;
            }

            umbracoWorkflowInstance.CmsNodes = newCmsNodes;

            var transition = (count > 0) ? "contains_media" : "does_not_contain_media";

            runtime.Transition(workflowInstance, this, transition);
        }
Exemplo n.º 24
0
 private int FindTemplateRoot(CMSNode t)
 {
     if (t.ParentId < 0)
         return t.Id;
     else
         return FindTemplateRoot(t.Parent);
 }
        public void GetDescendants_Root_ReturnsNone()
        {
            var root      = new CMSNode(-1);
            var rootDescs = root.GetDescendants().Cast <CMSNode>();

            Assert.AreEqual(0, rootDescs.Count());
        }
Exemplo n.º 26
0
 public static void UpdateCruds(IUserGroup userGroup, CMSNode node, string permissions)
 {
     ApplicationContext.Current.Services.UserService.ReplaceUserGroupPermissions(
         userGroup.Id,
         permissions.ToCharArray(),
         node.Id);
 }
Exemplo n.º 27
0
        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);

            node = new cms.businesslogic.CMSNode(int.Parse(helper.Request("id")));

            ArrayList actionList = BusinessLogic.Actions.Action.GetAll();

            foreach (interfaces.IAction a in actionList)
            {
                if (a.ShowInNotifier)
                {
                    CheckBox c = new CheckBox();
                    c.ID = a.Letter.ToString();

                    if (base.getUser().GetNotifications(node.Path).IndexOf(a.Letter) > -1)
                    {
                        c.Checked = true;
                    }

                    uicontrols.PropertyPanel pp = new umbraco.uicontrols.PropertyPanel();
                    pp.CssClass = "inline";
                    pp.Text     = ui.Text("actions", a.Alias);
                    pp.Controls.Add(c);

                    pane_form.Controls.Add(pp);

                    actions.Add(c);
                }
            }
        }
Exemplo n.º 28
0
        public static bool HasAccces(int documentId, object memberId)
        {
            bool hasAccess = false;

            cms.businesslogic.CMSNode node = new CMSNode(documentId);

            if (!IsProtected(documentId, node.Path))
            {
                return(true);
            }
            else
            {
                MembershipUser member      = Membership.GetUser(memberId);
                XmlNode        currentNode = getPage(getProtectedPage(node.Path));

                if (member != null)
                {
                    foreach (string role in Roles.GetRolesForUser())
                    {
                        if (currentNode.SelectSingleNode("./group [@id='" + role + "']") != null)
                        {
                            hasAccess = true;
                            break;
                        }
                    }
                }
            }
            return(hasAccess);
        }
Exemplo n.º 29
0
 /// <summary>
 /// Just like GetItemTitle, except returns the full path (breadcrumbs) of the node
 /// </summary>
 protected virtual string GetItemBreadcrumbs()
 {
     if (!string.IsNullOrEmpty(ItemIdValue.Value))
     {
         try
         {
             int nodeId = -1;
             if (int.TryParse(ItemIdValue.Value, out nodeId))
             {
                 CMSNode node      = new CMSNode(nodeId);
                 string  title     = node.Text;
                 string  separator = " > ";
                 while (node != null && node.Level > 1)
                 {
                     node  = node.Parent;
                     title = node.Text + separator + title;
                 }
                 return(title);
             }
             else
             {
                 return(ItemIdValue.Value);
             }
         }
         catch (ArgumentException) { /*the node does not exist! we will ignore*/ }
     }
     return("");
 }
        public static Template MakeNew(string name, BusinessLogic.User u)
        {
            // CMSNode MakeNew(int parentId, Guid objectType, int userId, int level, string text, Guid uniqueID)
            CMSNode n = CMSNode.MakeNew(-1, _objectType, u.Id, 1, name, Guid.NewGuid());

            //ensure unique alias
            name = helpers.Casing.SafeAlias(name);
            if (GetByAlias(name) != null)
            {
                name = EnsureUniqueAlias(name, 1);
            }
            name = name.Replace("/", ".").Replace("\\", "");

            if (name.Length > 100)
            {
                name = name.Substring(0, 95) + "...";
            }


            SqlHelper.ExecuteNonQuery("INSERT INTO cmsTemplate (NodeId, Alias, design, master) VALUES (@nodeId, @alias, @design, @master)",
                                      SqlHelper.CreateParameter("@nodeId", n.Id),
                                      SqlHelper.CreateParameter("@alias", name),
                                      SqlHelper.CreateParameter("@design", ' '),
                                      SqlHelper.CreateParameter("@master", DBNull.Value));

            Template     t = new Template(n.Id);
            NewEventArgs e = new NewEventArgs();

            t.OnNew(e);

            return(t);
        }
Exemplo n.º 31
0
 /// <summary>
 /// Delete notifications by user and node
 /// </summary>
 /// <param name="user"></param>
 /// <param name="node"></param>
 public static void DeleteNotifications(User user, CMSNode node)
 {
     // delete all settings on the node for this user
     SqlHelper.ExecuteNonQuery("delete from umbracoUser2NodeNotify where userId = @userId and nodeId = @nodeId",
                               SqlHelper.CreateParameter("@userId", user.Id),
                               SqlHelper.CreateParameter("@nodeId", node.Id));
 }
Exemplo n.º 32
0
        public virtual string GetAttachmentLinks(IEnumerable <int> attachedNodes)
        {
            var s = new StringBuilder();

            s.Append("<br/><br/>");

            var host = HttpContext.Current.Request.Url.Host;

            if (HttpContext.Current.Request.Url.Port != 80)
            {
                host += ":" + HttpContext.Current.Request.Url.Port;
            }

            foreach (var nodeId in attachedNodes)
            {
                var node = new CMSNode(nodeId);

                if (node.IsDocument())
                {
                    s.Append(string.Format("{2} ({1}): <a href='http://{0}/umbraco/dialogs/preview.aspx?id={1}'>[" + GlobalisationService.Instance.GetString("preview") + "]</a> ", host, nodeId, node.Text) + Environment.NewLine);
                    s.Append(string.Format("<a href='http://{0}/umbraco/actions/editContent.aspx?id={1}'>[" + GlobalisationService.Instance.GetString("edit") + "]</a><br/>", host, nodeId) + Environment.NewLine);
                }
                else if (node.IsMedia())
                {
                    s.Append(string.Format("{2} ({1}): <a href='http://{0}/umbraco/dialogs/preview.aspx?id={1}'>{2}</a> ", host, nodeId, node.Text) + Environment.NewLine);
                }
                else
                {
                    s.Append(node.Text + "<br/>" + Environment.NewLine);
                }
            }

            return(s.ToString());
        }
Exemplo n.º 33
0
        private void NodeChildrenCount(CMSNode node, bool countChildren, string[] documentAliasFilters)
        {
            if (documentAliasFilters.Length > 0)
            {
                foreach (var filter in documentAliasFilters)
                {
                    var trimmedFilter = filter.TrimStart(" ".ToCharArray());
                    trimmedFilter = trimmedFilter.TrimEnd(" ".ToCharArray());

                    if ((new Document(node.Id).ContentType.Alias == trimmedFilter || trimmedFilter == string.Empty) && ValidNode(node.Text))
                    {
                        _nodeCount += 1;
                    }
                }
            }
            else
            {
                if (ValidNode(node.Text))
                {
                    _nodeCount += 1;
                }
            }

            if (countChildren)
            {
                //store children array here because iterating over an Array property object is very inneficient.
                var children = node.Children;
                foreach (CMSNode child in children)
                {
                    NodeChildrenCount(child, countChildren, documentAliasFilters);
                }
            }
        }
        public void Run(IWorkflowInstance workflowInstance, IWorkflowRuntime runtime)
        {
            // Cast to Umbraco worklow instance.
            var umbracoWorkflowInstance = (UmbracoWorkflowInstance) workflowInstance;

            var count = 0;
            var newCmsNodes = new List<int>();

            foreach(var nodeId in umbracoWorkflowInstance.CmsNodes)
            {
                var n = new CMSNode(nodeId);
                if(!n.IsDocument()) continue;

                var d = new Document(nodeId);
                if (!DocumentTypes.Contains(d.ContentType.Id)) continue;
                
                newCmsNodes.Add(nodeId);
                count++;
            }

            umbracoWorkflowInstance.CmsNodes = newCmsNodes;

            var transition = (count > 0) ? "contains_docs" : "does_not_contain_docs";
            runtime.Transition(workflowInstance, this, transition);
        }
Exemplo n.º 35
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var id = Convert.ToInt32(Request["id"]);

            _workflowInstance = TheWorkflowInstanceService.GetInstance(id);

            var nodes = ((UmbracoWorkflowInstance)_workflowInstance).CmsNodes;

            if (!Page.IsPostBack)
            {
                var nodeDetails = new List <NodeInfo>();

                foreach (var nodeId in nodes)
                {
                    var node = new CMSNode(nodeId);
                    nodeDetails.Add(new NodeInfo
                    {
                        Id       = nodeId,
                        Name     = node.Text,
                        Url      = umbraco.library.NiceUrl(nodeId),
                        Approved = true,
                        Comment  = string.Empty
                    });
                }

                var json = JsonConvert.SerializeObject(nodeDetails, Formatting.Indented);
                JsonLiteral.Text = json;

                NodeRepeater.DataSource = nodeDetails;
                NodeRepeater.DataBind();
            }
        }
        private void NodeChildrenCount(CMSNode node, bool countChildren, string[] documentAliasFilters)
        {
            if (documentAliasFilters.Length > 0)
            {
                foreach (var filter in documentAliasFilters)
                {
                    var trimmedFilter = filter.TrimStart(" ".ToCharArray());
                    trimmedFilter = trimmedFilter.TrimEnd(" ".ToCharArray());

                    if ((new Document(node.Id).ContentType.Alias == trimmedFilter || trimmedFilter == string.Empty) && ValidNode(node.Text))
                    {
                        _nodeCount += 1;
                    }
                }
            }
            else
            {
                if (ValidNode(node.Text))
                {
                    _nodeCount += 1;
                }
            }

            if (countChildren)
            {
                //store children array here because iterating over an Array property object is very inneficient.
                var children = node.Children;
                foreach (CMSNode child in children)
                {
                    NodeChildrenCount(child, countChildren, documentAliasFilters);
                }
            }

        }
Exemplo n.º 37
0
        public static void MakeNew(CMSNode Node, User User, User Translator, Language Language, string Comment,
                                   bool IncludeSubpages, bool SendEmail)
        {
            // Create pending task
            Task t = new Task();
            t.Comment = Comment;
            t.Node = Node;
            t.ParentUser = User;
            t.User = Translator;
            t.Type = new TaskType("toTranslate");
            t.Save();

            // Add log entry
            Log.Add(LogTypes.SendToTranslate, User, Node.Id,
                    "Translator: " + Translator.Name + ", Language: " + Language.FriendlyName);

            // send it
            if (SendEmail)
            {
                // Send mail
                string[] subjectVars = {HttpContext.Current.Request.ServerVariables["SERVER_NAME"], Node.Text};
                string[] bodyVars = {
                                        Translator.Name, Node.Text, User.Name,
                                        HttpContext.Current.Request.ServerVariables["SERVER_NAME"], Node.Id.ToString(),
                                        Language.FriendlyName
                                    };

                if (User.Email != "" && User.Email.Contains("@") && Translator.Email != "" &&
                    Translator.Email.Contains("@"))
                {
                    // create the mail message 
                    MailMessage mail = new MailMessage(User.Email, Translator.Email);

                    // populate the message
                    mail.Subject = ui.Text("translation", "mailSubject", subjectVars, Translator);
                    mail.IsBodyHtml = false;
                    mail.Body = ui.Text("translation", "mailBody", bodyVars, Translator);
                    try
                    {
                        SmtpClient sender = new SmtpClient(GlobalSettings.SmtpServer);
                        sender.Send(mail);
                    }
                    catch (Exception ex)
                    {
                        Log.Add(LogTypes.Error, User, Node.Id,
                                string.Format("Error sending translation e-mail:{0}", ex.ToString()));
                    }
                }
                else
                    Log.Add(LogTypes.Error, User, Node.Id,
                            "Could not send translation e-mail because either user or translator lacks e-mail in settings");
            }

            if (IncludeSubpages)
            {
                foreach (CMSNode n in Node.Children)
                    MakeNew(n, User, Translator, Language, Comment, true, false);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            _currentPage = new CMSNode(int.Parse(helper.Request("id")));

            pp_translator.Text = ui.Text("translation","translator", this.getUser());
            pp_language.Text = ui.Text("translation", "translateTo", this.getUser());
            pp_includeSubs.Text = ui.Text("translation","includeSubpages", this.getUser());
            pp_comment.Text = ui.Text("comment", this.getUser());
            pane_form.Text = ui.Text("translation", "sendToTranslate", _currentPage.Text, base.getUser());
            

            if (!IsPostBack)
            {
                // default language
                var selectedLanguage = 0;

                var domains = library.GetCurrentDomains(_currentPage.Id);
                if (domains != null)
                {
                    selectedLanguage = domains[0].Language.id;
                    defaultLanguage.Text = ui.Text("defaultLanguageIs", base.getUser()) + " " + domains[0].Language.FriendlyName;
                }
                else
                {
                    defaultLanguage.Text = ui.Text("defaultLanguageIsNotAssigned", base.getUser());
                }
                
                // languages
                language.Items.Add(new ListItem(ui.Text("general", "choose", base.getUser()), ""));
                foreach (var l in cms.businesslogic.language.Language.getAll)
                {
                    var li = new ListItem();
                    li.Text = l.FriendlyName;
                    li.Value = l.id.ToString();
                    if (selectedLanguage == l.id)
                        li.Selected = true;
                    language.Items.Add(li);
                }

                // Subpages
                if (_currentPage.Children.Length == 0)
                    includeSubpages.Enabled = false;

                // Translators
                foreach (var u in BusinessLogic.User.getAll())
                    if (u.UserType.Alias.ToLower() == "translator")
                        translator.Items.Add(new ListItem(u.Name, u.Id.ToString()));

                if (translator.Items.Count == 0) {
                    feedback.Text = ui.Text("translation", "noTranslators");
                    feedback.type = uicontrols.Feedback.feedbacktype.error;
                    doTranslation.Enabled = false;
                }

                // send button
                doTranslation.Text = ui.Text("general", "ok", base.getUser());
            }
        }
 /// <summary>
 /// Copies all  permissions to related users of the usertype
 /// </summary>
 /// <param name="userType">Type of the user.</param>
 /// <param name="node">The node.</param>
 public static void CopyPermissions(UserType userType, CMSNode node)
 {
     string permissions = userType.GetPermissions(node.Path);
         foreach (User user in userType.GetAllRelatedUsers())
         {
             if (!user.IsAdmin() && !user.Disabled)
             {
                 Permission.UpdateCruds(user, node, permissions);
                 user.initCruds();
             }
         }
 }
Exemplo n.º 40
0
 public static ContentItem MakeNew(string Name, ContentItemType cit, BusinessLogic.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++;
     CMSNode.MakeNew(ParentId,_objectType, u.Id, newLevel,  Name, newId);
     ContentItem tmp = new ContentItem(newId);
     tmp.CreateContent(cit);
     return tmp;
 }
Exemplo n.º 41
0
        private DataTypeItem BuildDataTypeItem(DataTypeDefinition dataTypeDefinition)
        {
            var dataTypeItem = new DataTypeItem();
            dataTypeItem.Id = dataTypeDefinition.DataType.DataTypeDefinitionId;
            dataTypeItem.ControlTypeName = dataTypeDefinition.DataType.GetType().FullName;

            var node = new CMSNode(dataTypeItem.Id);
            dataTypeItem.DataTypeName = node.Text;

            dataTypeItem.PreValueItems = this.BuildPreValues(dataTypeDefinition);
            dataTypeItem.Type = this.DetermineType(dataTypeItem);
            dataTypeItem.ModelType = DetermineModelType(dataTypeItem);
            return dataTypeItem;
        }
Exemplo n.º 42
0
        public NodeInfo GetNodeInfo(int id)
        {
            Authorize();

            var node = new CMSNode(id);
            return new NodeInfo()
            {
                Id = node.Id,
                Path = node.Path,
                PathAsNames = string.Join("->",
                   GetPathNames(node.Path.Split(',')
                                       .Select(x => int.Parse(x))
                                       .ToArray()))
            };
        }
Exemplo n.º 43
0
		public Relation(int Id)
		{
			using (SqlDataReader dr = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteReader(GlobalSettings.DbDSN, CommandType.Text, "select * from umbracoRelation where id = @id", new SqlParameter("@id", Id)))
			{
				if(dr.Read())
				{
					this._id = int.Parse(dr["id"].ToString());
					this._parentNode = new CMSNode(int.Parse(dr["parentId"].ToString()));
					this._childNode = new CMSNode(int.Parse(dr["childId"].ToString()));
					this._relType = RelationType.GetById(int.Parse(dr["relType"].ToString()));
					this._comment = dr["comment"].ToString();
					this._datetime = DateTime.Parse(dr["datetime"].ToString());
				}
			}
		}
Exemplo n.º 44
0
        /// <summary>
        /// Creates a new Media
        /// </summary>
        /// <param name="Name">The name of the media</param>
        /// <param name="dct">The type of the media</param>
        /// <param name="u">The user creating the media</param>
        /// <param name="ParentId">The id of the folder under which the media is created</param>
        /// <returns></returns>
        public static Media MakeNew(string Name, MediaType dct, BusinessLogic.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++;
            CMSNode.MakeNew(ParentId, _objectType, u.Id, newLevel, Name, newId);
            Media tmp = new Media(newId);
            tmp.CreateContent(dct);

            NewEventArgs e = new NewEventArgs();
            tmp.OnNew(e);

            return tmp;
        }
Exemplo n.º 45
0
 /// <summary>
 /// Returns the permissions for a node
 /// </summary>
 /// <param name="user"></param>
 /// <returns></returns>
 public static IEnumerable<Permission> GetNodePermissions(CMSNode node)
 {
     var items = new List<Permission>();
     using (IRecordsReader dr = SqlHelper.ExecuteReader("select * from umbracoUser2NodePermission where nodeId = @nodeId order by nodeId", SqlHelper.CreateParameter("@nodeId", node.Id)))
     {
         while (dr.Read())
         {
             items.Add(new Permission()
             {
                 NodeId = dr.GetInt("nodeId"),
                 PermissionId = Convert.ToChar(dr.GetString("permission")),
                 UserId = dr.GetInt("userId")
             });
         }
     }
     return items;
 }
        public void Run(IWorkflowInstance workflowInstance, IWorkflowRuntime runtime)
        {
            // Cast to Umbraco worklow instance.
            var umbracoWorkflowInstance = (UmbracoWorkflowInstance) workflowInstance;

            foreach(var nodeId in umbracoWorkflowInstance.CmsNodes)
            {
                var n = new CMSNode(nodeId);
                if(!n.IsDocument()) continue;

                var d = new Document(nodeId);
                d.Publish(User.GetUser(0));

                umbraco.library.UpdateDocumentCache(d.Id);
            }

            runtime.Transition(workflowInstance, this, "done");
        }
        public override void ProcessRequest(HttpContext context)
        {
            if (BasePage.ValidateUserContextID(BasePage.umbracoUserContextID) == false)
                throw new Exception("Client authorization failed. User is not logged in");

            //user must be allowed to see content or media
            if (AuthorizeRequest(DefaultApps.content.ToString()) == false && AuthorizeRequest(DefaultApps.media.ToString()) == false)
                return;

            context.Response.ContentType = "text/plain";

            _prefix = context.Request.QueryString["q"];

            var parentNodeId = Convert.ToInt32(context.Request.QueryString["id"]);
            var showGrandChildren = Convert.ToBoolean(context.Request.QueryString["showchildren"]);

            var documentAliasFilter = context.Request.QueryString["filter"];
            var documentAliasFilters = documentAliasFilter.Split(",".ToCharArray());

            var parent = new CMSNode(parentNodeId);

            _nodeCount = 0;

            //store children array here because iterating over an Array property object is very inneficient.
            var children = parent.Children;
            foreach (CMSNode child in children)
            {
                NodeChildrenCount(child, showGrandChildren, documentAliasFilters);
            }

            _output = new string[_nodeCount];
            _counter = 0;
            int level = 1;

            foreach (CMSNode child in children)
            {
                AddNode(child, level, showGrandChildren, documentAliasFilters);
            }

            foreach (var item in _output)
            {
                context.Response.Write(item + Environment.NewLine);
            }
        }
Exemplo n.º 48
0
        /// <summary>
        /// Sends the notifications for the specified user regarding the specified node and action.
        /// </summary>
        /// <param name="Node">The node.</param>
        /// <param name="user">The user.</param>
        /// <param name="Action">The action.</param>
        public static void GetNotifications(CMSNode Node, User user, IAction Action)
        {
            User[] allUsers = User.getAll();
            foreach (User u in allUsers)
            {
                try
                {
                    if (!u.Disabled && u.GetNotifications(Node.Path).IndexOf(Action.Letter.ToString()) > -1)
                    {
                        LogHelper.Debug<Notification>(string.Format("Notification about {0} sent to {1} ({2})", ui.Text(Action.Alias, u), u.Name, u.Email));
                        sendNotification(user, u, (Document)Node, Action);
                    }
                }
                catch (Exception notifyExp)
                {
					LogHelper.Error<Notification>("Error in notification", notifyExp);
                }
            }
        }
Exemplo n.º 49
0
		public Relation(int Id)
		{
			using (IRecordsReader dr = SqlHelper.ExecuteReader("select * from umbracoRelation where id = @id", SqlHelper.CreateParameter("@id", Id)))
			{
                if (dr.Read())
                {
                    this._id = dr.GetInt("id");
                    this._parentNode = new CMSNode(dr.GetInt("parentId"));
                    this._childNode = new CMSNode(dr.GetInt("childId"));
                    this._relType = RelationType.GetById(dr.GetInt("relType"));
                    this._comment = dr.GetString("comment");
                    this._datetime = dr.GetDateTime("datetime");
                }
                else
                {
                    throw new ArgumentException("No relation found for id " + Id.ToString());
                }
			}
		}
Exemplo n.º 50
0
		protected void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			if (helper.Request("nodeId") == "") 
			{
			
				string appType = ui.Text("sections", helper.Request("app")).ToLower();
                pane_chooseNode.Text = ui.Text("create", "chooseNode", appType, this.getUser()) + "?";

                DataBind();
			} 
			else 
			{
                int nodeId = int.Parse(helper.Request("nodeId"));
                //ensure they have access to create under this node!!
                if (helper.Request("app") == Constants.Applications.Media || CheckCreatePermissions(nodeId))
                {
                    //pane_chooseName.Text = ui.Text("create", "updateData", this.getUser());
                    var c = new CMSNode(nodeId);
                    path.Value = c.Path;
                    pane_chooseNode.Visible = false;
                    panel_buttons.Visible = false;
                    pane_chooseName.Visible = true;
                    var createDef = new XmlDocument();
                    var defReader = new XmlTextReader(Server.MapPath(IOHelper.ResolveUrl(SystemDirectories.Umbraco) + "/config/create/UI.xml"));
                    createDef.Load(defReader);
                    defReader.Close();

                    // Find definition for current nodeType
                    XmlNode def = createDef.SelectSingleNode("//nodeType [@alias = '" + Request.QueryString["app"] + "']");
                    phCreate.Controls.Add(new UserControl().LoadControl(IOHelper.ResolveUrl(SystemDirectories.Umbraco) + def.SelectSingleNode("./usercontrol").FirstChild.Value));
                }
                else
                {                    
                    PageNameHolder.type = umbraco.uicontrols.Feedback.feedbacktype.error;
                    PageNameHolder.Text = ui.GetText("rights") + " " + ui.GetText("error");
                    JTree.DataBind();
                }
			}
                        
		}
Exemplo n.º 51
0
 public static void GetNotifications(CMSNode Node, User user, IAction Action)
 {
     User[] allUsers = User.GetAll();
     foreach (User u in allUsers)
     {
         try
         {
             if (!u.Disabled && u.GetNotifications(Node.Path).IndexOf(Action.Letter.ToString()) > -1)
             {
                 Log.Add(LogTypes.Notify, User.GetUser(0), Node.Id,
                         "Notification about " + ui.Text(Action.Alias, u) + " sent to " + u.Name + " (" + u.Email +
                         ")");
                 sendNotification(user, u, (Document) Node, Action);
             }
         }
         catch (Exception notifyExp)
         {
             Log.Add(LogTypes.Error, u, Node.Id, "Error in notification: " + notifyExp);
         }
     }
 }
Exemplo n.º 52
0
        private DataTypeItem BuildDataTypeItem(DataTypeDefinition dataTypeDefinition)
        {
            try
            {
                var dataTypeItem = new DataTypeItem();
                dataTypeItem.Id = dataTypeDefinition.DataType.DataTypeDefinitionId;
                dataTypeItem.ControlTypeName = dataTypeDefinition.DataType.GetType().FullName;

                var node = new CMSNode(dataTypeItem.Id);
                dataTypeItem.DataTypeName = node.Text;

                dataTypeItem.PreValueItems = this.BuildPreValues(dataTypeDefinition);
                dataTypeItem.Type = this.DetermineType(dataTypeItem);
                dataTypeItem.ModelType = DetermineModelType(dataTypeItem);
                return dataTypeItem;

            }
            catch (Exception ex)
            {
                throw new DataTypeException(string.Format("Data type {0} '{1}' could not be loaded.", dataTypeDefinition.Id.ToString(), dataTypeDefinition.Text));
            }
        }
Exemplo n.º 53
0
        protected override void OnInit(EventArgs e)
        {
            this.ID = "ImageCropper";
            //base.OnInit(e);

            int propertyId = ((umbraco.cms.businesslogic.datatype.DefaultData)data).PropertyId;

            int currentDocumentId = ((umbraco.cms.businesslogic.datatype.DefaultData)data).NodeId;
            Property uploadProperty;

            // we need this ugly code because there's no way to use a base class
            CMSNode node = new CMSNode(currentDocumentId);
            if (node.nodeObjectType == Document._objectType)
            {
                uploadProperty = new Document(currentDocumentId).getProperty(config.UploadPropertyAlias);
            }
            else if (node.nodeObjectType == umbraco.cms.businesslogic.media.Media._objectType)
            {
                uploadProperty = new Media(currentDocumentId).getProperty(config.UploadPropertyAlias);
            }
            else if (node.nodeObjectType == Member._objectType)
            {
                uploadProperty = new Member(currentDocumentId).getProperty(config.UploadPropertyAlias);
            }
            else
            {
                throw new Exception("Unsupported Umbraco Node type for Image Cropper (only Document, Media and Members are supported.");
            }

            // upload property could be null here if the property wasn't found
            if (uploadProperty != null)
            {
                string relativeImagePath = uploadProperty.Value.ToString();

                ImageInfo imageInfo = new ImageInfo(relativeImagePath);

                imgImage.ImageUrl = relativeImagePath;
                imgImage.ID = String.Format("cropBox_{0}", propertyId);

                StringBuilder sbJson = new StringBuilder();
                StringBuilder sbRaw = new StringBuilder();

                try
                {
                    _xml = new XmlDocument();
                    _xml.LoadXml(data.Value.ToString());
                }
                catch
                {
                    _xml = createBaseXmlDocument();
                }

                sbJson.Append("{ \"current\": 0, \"crops\": [");

                for (int i = 0; i < config.presets.Count; i++)
                {
                    Preset preset = (Preset)config.presets[i];
                    Crop crop;

                    sbJson.Append("{\"name\":'" + preset.Name + "'");

                    sbJson.Append(",\"config\":{" +
                                  String.Format("\"targetWidth\":{0},\"targetHeight\":{1},\"keepAspect\":{2}",
                                                preset.TargetWidth, preset.TargetHeight,
                                                (preset.KeepAspect ? "true" : "false") + "}"));

                    if (imageInfo.Exists)
                    {
                        crop = preset.Fit(imageInfo);
                    }
                    else
                    {
                        crop.X = 0;
                        crop.Y = 0;
                        crop.X2 = preset.TargetWidth;
                        crop.Y2 = preset.TargetHeight;
                    }

                    // stored
                    if (_xml.DocumentElement != null && _xml.DocumentElement.ChildNodes.Count == config.presets.Count)
                    {
                        XmlNode xmlNode = _xml.DocumentElement.ChildNodes[i];

                        int xml_x = Convert.ToInt32(xmlNode.Attributes["x"].Value);
                        int xml_y = Convert.ToInt32(xmlNode.Attributes["y"].Value);
                        int xml_x2 = Convert.ToInt32(xmlNode.Attributes["x2"].Value);
                        int xml_y2 = Convert.ToInt32(xmlNode.Attributes["y2"].Value);

                        // only use xml values if image is the same and different from defaults (document is stored inbetween image upload and cropping)
                        //if (xml_x2 - xml_x != preset.TargetWidth || xml_y2 - xml_y != preset.TargetHeight)
                        //fileDate == imageInfo.DateStamp && (

                        if (crop.X != xml_x || crop.X2 != xml_x2 || crop.Y != xml_y || crop.Y2 != xml_y2)
                        {
                            crop.X = xml_x;
                            crop.Y = xml_y;
                            crop.X2 = xml_x2;
                            crop.Y2 = xml_y2;
                        }
                    }

                    sbJson.Append(",\"value\":{" + String.Format("\"x\":{0},\"y\":{1},\"x2\":{2},\"y2\":{3}", crop.X, crop.Y, crop.X2, crop.Y2) + "}}");
                    sbRaw.Append(String.Format("{0},{1},{2},{3}", crop.X, crop.Y, crop.X2, crop.Y2));

                    if (i < config.presets.Count - 1)
                    {
                        sbJson.Append(",");
                        sbRaw.Append(";");
                    }
                }

                sbJson.Append("]}");

                hdnJson.Value = sbJson.ToString();
                //hdnJson.ID = String.Format("json_{0}", propertyId);
                hdnRaw.Value = sbRaw.ToString();
                //hdnRaw.ID = String.Format("raw_{0}", propertyId);

                Controls.Add(imgImage);

                Controls.Add(hdnJson);
                Controls.Add(hdnRaw);

                string imageCropperInitScript =
                    "initImageCropper('" +
                    imgImage.ClientID + "', '" +
                    hdnJson.ClientID + "', '" +
                    hdnRaw.ClientID +
                    "');";

                Page.ClientScript.RegisterStartupScript(GetType(), ClientID + "_imageCropper", imageCropperInitScript, true);
                Page.ClientScript.RegisterClientScriptBlock(Resources.json2Script.GetType(), "json2Script", Resources.json2Script, true);
                Page.ClientScript.RegisterClientScriptBlock(Resources.jCropCSS.GetType(), "jCropCSS", Resources.jCropCSS);
                Page.ClientScript.RegisterClientScriptBlock(Resources.jCropScript.GetType(), "jCropScript", Resources.jCropScript, true);
                Page.ClientScript.RegisterClientScriptBlock(Resources.imageCropperScript.GetType(), "imageCropperScript", Resources.imageCropperScript, true);

            }

            base.OnInit(e);
        }
Exemplo n.º 54
0
 /// <summary>
 /// Delete notifications by user and node
 /// </summary>
 /// <param name="user"></param>
 /// <param name="node"></param>
 public static void DeleteNotifications(User user, CMSNode node)
 {
     // delete all settings on the node for this user
     SqlHelper.ExecuteNonQuery("delete from umbracoUser2NodeNotify where userId = @userId and nodeId = @nodeId",
                               SqlHelper.CreateParameter("@userId", user.Id),
                               SqlHelper.CreateParameter("@nodeId", node.Id));
 }
Exemplo n.º 55
0
        /// <summary>
        /// Gets the related nodes, of the node with the specified Id, as XML.
        /// </summary>
        /// <param name="NodeId">The node id.</param>
        /// <returns>The related nodes as a XpathNodeIterator in the format:
        ///     <code>
        ///         <relations>
        ///             <relation typeId="[typeId]" typeName="[typeName]" createDate="[createDate]" parentId="[parentId]" childId="[childId]"><node>[standard umbraco node Xml]</node></relation>
        ///         </relations>
        ///     </code>
        /// </returns>
        public static XPathNodeIterator GetRelatedNodesAsXml(int NodeId)
        {
            XmlDocument xd = new XmlDocument();
            xd.LoadXml("<relations/>");
            var rels = new CMSNode(NodeId).Relations;
            foreach (Relation r in rels)
            {
                XmlElement n = xd.CreateElement("relation");
                n.AppendChild(xmlHelper.addCDataNode(xd, "comment", r.Comment));
                n.Attributes.Append(xmlHelper.addAttribute(xd, "typeId", r.RelType.Id.ToString()));
                n.Attributes.Append(xmlHelper.addAttribute(xd, "typeName", r.RelType.Name));
                n.Attributes.Append(xmlHelper.addAttribute(xd, "createDate", r.CreateDate.ToString()));
                n.Attributes.Append(xmlHelper.addAttribute(xd, "parentId", r.Parent.Id.ToString()));
                n.Attributes.Append(xmlHelper.addAttribute(xd, "childId", r.Child.Id.ToString()));

                // Append the node that isn't the one we're getting the related nodes from
                if (NodeId == r.Child.Id)
                    n.AppendChild(r.Parent.ToXml(xd, false));
                else
                    n.AppendChild(r.Child.ToXml(xd, false));
                xd.DocumentElement.AppendChild(n);
            }
            XPathNavigator xp = xd.CreateNavigator();
            return xp.Select(".");
        }
        public virtual string GetAttachmentLinks(IEnumerable<int> attachedNodes)
        {
            var s = new StringBuilder();
            s.Append("<br/><br/>");

            var host = HttpContext.Current.Request.Url.Host;
            if (HttpContext.Current.Request.Url.Port != 80) host += ":" + HttpContext.Current.Request.Url.Port;

            foreach(var nodeId in attachedNodes)
            {
                var node = new CMSNode(nodeId);

                if(node.IsDocument())
                {
                    s.Append(string.Format("{2} ({1}): <a href='http://{0}/umbraco/dialogs/preview.aspx?id={1}'>[" + GlobalisationService.Instance.GetString("preview") + "]</a> ", host, nodeId, node.Text) + Environment.NewLine);
                    s.Append(string.Format("<a href='http://{0}/umbraco/actions/editContent.aspx?id={1}'>[" + GlobalisationService.Instance.GetString("edit") + "]</a><br/>", host, nodeId) + Environment.NewLine);

                } else if(node.IsMedia())
                {
                    s.Append(string.Format("{2} ({1}): <a href='http://{0}/umbraco/dialogs/preview.aspx?id={1}'>{2}</a> ", host, nodeId, node.Text) + Environment.NewLine);
                    
                } else
                {
                    s.Append(node.Text + "<br/>" + Environment.NewLine);
                }
            }
            
            return s.ToString();
        }
        protected IEnumerable<string> GetRecipients()
        {
            var recipients = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            var i = User.GetUser(Instantiator);
            
            if(MailInstantiator && !i.Disabled) recipients.Add(i.Email);

            if(MailNodeOwners)
            {
                foreach(var nodeId in CmsNodes)
                {
                    var e = new CMSNode(nodeId);
                    
                    var u = e.User;

                    if(!u.Disabled)
                        recipients.Add(u.Email);
                }
            }

            if (Users != null)
            {
                foreach (var user in Users)
                {
                    var u = User.GetUser(user);

                    if(!u.Disabled)
                        recipients.Add(u.Email);
                }
            }

            if (UserTypes != null)
            {
                foreach (var userTypeId in UserTypes)
                {
                    foreach (var user in User.getAll().Where(u => u.UserType.Id == userTypeId))
                    {
                        if(!user.Disabled)
                            recipients.Add(user.Email);
                    }
                }
            }
            return recipients;
        }
Exemplo n.º 58
0
        /// <summary>
        /// Sets up the autocomplete functionality
        /// </summary>
        private void setupAutoComplete(int parentNodeId)
        {
            ClientDependencyLoader.Instance.RegisterDependency("Application/JQuery/jquery.autocomplete.js", "UmbracoClient", ClientDependencyType.Javascript);
            ClientDependencyLoader.Instance.RegisterDependency("css/umbracoGui.css", "UmbracoRoot", ClientDependencyType.Css);

            
            childtxt = new TextBox();
            childtxt.ID = "ultimatePickerBox" + base.ID;
            childtxt.AutoCompleteType = AutoCompleteType.Disabled;
            childtxt.CssClass = "umbEditorTextField";

            if (_data.Value.ToString().Length > 3)
            {
                try
                {
                    CMSNode firstSaved = new CMSNode(Convert.ToInt32(_data.Value.ToString().Substring(0, 4)));
                    childtxt.Text = firstSaved.Text;
                }
                catch
                {

                }
            }

            base.ContentTemplateContainer.Controls.Add(childtxt);


            string autoCompleteScript =
                 "jQuery(\"#"
                 + childtxt.ClientID + "\").autocomplete(\""
                 + umbraco.IO.IOHelper.ResolveUrl(umbraco.IO.SystemDirectories.Umbraco)
                 + "/webservices/UltimatePickerAutoCompleteHandler.ashx\",{minChars: 2,max: 100, extraParams:{id:\"" + parentNodeId.ToString() + "\",showchildren:\"" + config[3] + "\",filter:\"" + config[2] + "\",rnd:\"" + DateTime.Now.Ticks + "\"}});";


            string autoCompleteInitScript =
                "jQuery(document).ready(function(){"
                + autoCompleteScript
                + "});";

            Page.ClientScript.RegisterStartupScript(GetType(), ClientID + "_ultimatepickerinit", autoCompleteInitScript, true);

            if (Page.IsPostBack)
            {
                ScriptManager.RegisterClientScriptBlock(this, GetType(), ClientID + "_ultimatepicker", autoCompleteScript, true);

            }

        }
Exemplo n.º 59
0
        public static void MakeNew(User User, CMSNode Node, char ActionLetter)
        {
            var parameters = new[]
                                 {
                                     SqlHelper.CreateParameter("@userId", User.Id),
                                     SqlHelper.CreateParameter("@nodeId", Node.Id),
                                     SqlHelper.CreateParameter("@action", ActionLetter.ToString())
                                 };

            // Method is synchronized so exists remains consistent (avoiding race condition)
            bool exists = SqlHelper.ExecuteScalar<int>(
                "SELECT COUNT(userId) FROM umbracoUser2nodeNotify WHERE userId = @userId AND nodeId = @nodeId AND action = @action",
                parameters) > 0;
            if (!exists)
                SqlHelper.ExecuteNonQuery(
                    "INSERT INTO umbracoUser2nodeNotify (userId, nodeId, action) VALUES (@userId, @nodeId, @action)",
                    parameters);
        }
Exemplo n.º 60
0
        public static void UpdateNotifications(User User, CMSNode Node, string Notifications)
        {
            // delete all settings on the node for this user
            DeleteNotifications(User, Node);

            // Loop through the permissions and create them
            foreach (char c in Notifications)
                MakeNew(User, Node, c);
        }