示例#1
0
        private Sitecore6xItem CopyItemTo(IItem CopyFrom)
        {
            Sitecore6xItem returnItem = null;

            Util.SetStatus("Copying from: " + CopyFrom.Path, "Copying to: " + _sPath);

            // *** Create templates ***
            string sTemplatePath = null;

            // Don't create templates if we are using names instead of id's
            if (this.Options.CopyOperation == CopyOperations.UseNames)
            {
                sTemplatePath = CopyFrom.Templates[0].Path;
            }
            else
            {
                if (CREATE_NEW_BASE_TEMPLATE)
                {
                    // Check to see if Template import folder has been created
                    Sitecore6xItem templateFolder = GetSitecore61Item(TEMPLATE_IMPORT_FOLDER);
                    if (templateFolder == null)
                    {
                        CreateTemplate(TEMPLATE_IMPORT_FOLDER.Remove(TEMPLATE_IMPORT_FOLDER.LastIndexOf("/")),
                                        "/sitecore/templates/common/folder",
                                        TEMPLATE_IMPORT_FOLDER.Remove(0, TEMPLATE_IMPORT_FOLDER.LastIndexOf("/") + 1));
                    }
                    else
                        AddItemToCache(templateFolder);
                }

                // *** Find and create base template from current item ***
                string sBaseTemplatePath = "";
                if (CopyFrom.BaseTemplate != null)
                {
                    Sitecore6xItem baseTemplateItem = null;
                    if (CREATE_NEW_BASE_TEMPLATE)
                    {
                        // Get alternate base template from name, because we don't want to use the "normal" standard template
                        sBaseTemplatePath = TEMPLATE_IMPORT_FOLDER + "/" + CopyFrom.BaseTemplate.Name;
                        baseTemplateItem = GetSitecore61Item(sBaseTemplatePath);
                    }
                    else
                    {
                        // Get normal standard template
                        baseTemplateItem = GetSitecore61Item(CopyFrom.BaseTemplate.ID);
                        if (baseTemplateItem != null)
                            sBaseTemplatePath = baseTemplateItem.ID;
                    }

                    if (baseTemplateItem != null)
                        AddItemToCache(baseTemplateItem);
                }

                // *** Create Template from current item ***
                string sInheritedTemplateIDs = "";
                // Create the templates inherited templates
                RecursivelyCreateTemplates(CopyFrom, out sInheritedTemplateIDs, sBaseTemplatePath);

                // Finally create the items template
                sTemplatePath = CopyFrom.Templates[0].ID;
                //            sTemplatePath = CreateTemplate(CopyFrom.Templates[0], Util.GuidToSitecoreID(CopyFrom.Templates[0].ID), sInheritedTemplateIDs);

                // Normal items only has one template, sTemplatePath will point to the right template.
                // The current item must be a template item because there is more than one template, so the
                // "standard template" is used as "base template" for this template item.
                if (CopyFrom.Templates.Length > 1)
                {
                    sTemplatePath = CopyFrom.BaseTemplate.ID;
                }
            }

            // *** Create Item ***
            string sItemVersion = "1";
            string sNewItemID = "";
            Sitecore6xItem templateItem = null;
            if (this.Options.CopyOperation == CopyOperations.Overwrite)
            {
                // Find existing item
                returnItem = GetSitecore61Item(CopyFrom.ID, this);
                if ((returnItem == null) && (!Util.IsTemplateOnIgnoreList(CopyFrom.Templates)))
                {
                    // No item was found, create new using existing item id's
                    CreateTemplateItemWithSpecificID(this.ID, sTemplatePath, CopyFrom.ID, CopyFrom.Name);
                }
                sNewItemID = CopyFrom.ID;
            }
            // Generate new items id's
            else if (this.Options.CopyOperation == CopyOperations.GenerateNewItemIDs)
            {
                sNewItemID = "";
                CreateTemplateItemWithSpecificID(this.ID, sTemplatePath, ref sNewItemID, CopyFrom.Name);
            }
            // Skip existing items id's
            else if (this.Options.CopyOperation == CopyOperations.SkipExisting)
            {
                returnItem = GetSitecore61Item(CopyFrom.ID, this);
                if (returnItem == null)
                {
                    // Use existing item id's
                    CreateTemplateItemWithSpecificID(this.ID, sTemplatePath, CopyFrom.ID, CopyFrom.Name);
                    sNewItemID = CopyFrom.ID;
                }
            }
            // Use names to identify items, instead of ID's
            else if (this.Options.CopyOperation == CopyOperations.UseNames)
            {
                // If the template cannot be found then skip this item
                templateItem = GetSitecore61Item(sTemplatePath);
                if (templateItem == null)
                    returnItem = null;
                else
                {
                    // Find existing item
                    returnItem = GetSitecore61Item(this.Path + "/" + CopyFrom.Name, this);
                    if (returnItem != null)
                        sNewItemID = returnItem.ID;
                    else
                    {
                        sNewItemID = "";
                        CreateTemplateItemWithSpecificID(this.ID, sTemplatePath, ref sNewItemID, CopyFrom.Name);
                    }
                }
            }

            // If we are skipping existing then do nothing here
            if ((returnItem != null) &&
                ((this.Options.CopyOperation == CopyOperations.SkipExisting) /* ||
                 (this.Options.CopyOperation == CopyOperations.UseNames) */))
            { }
            else if ((templateItem == null) &&
                (this.Options.CopyOperation == CopyOperations.UseNames))
            {
                returnItem = GetSitecore61Item(this.Path + "/" + CopyFrom.Name);
            }
            else if (Util.IsTemplateOnIgnoreList(CopyFrom.Templates))
            {
                // skip this
            }
            // Otherwise populate data fields
            else
            {
                XmlNode contentItem = GetItemXml(sNewItemID);

                // Set language
                XmlNodeList versionNodes = contentItem.SelectNodes("//item/version[@language = '" + this.Options.Language + "']");
                if ((versionNodes == null) || (versionNodes.Count == 0))
                {
                    // If language version is missing, we create it
                    CheckSitecoreReturnValue(_sitecoreApi.AddVersion(sNewItemID, this.Options.Language, Util.CurrentDatabase, _credentials));
                    contentItem = GetItemXml(sNewItemID);
                }
                else
                {
                    sItemVersion = GetItemVersion(contentItem);
                }

                // Save item by creating a new or overwrite existing
                if (returnItem == null)
                {
                    // Update existing fields
                    foreach (IField field in CopyFrom.Fields)
                    {
                        contentItem = ModifyItemField(contentItem, field.TemplateFieldID, field.Key, field.Type, field.Content);
                    }

                    CheckSitecoreReturnValue(_sitecoreApi.InsertXML(this.ID, contentItem.OuterXml, false, Util.CurrentDatabase, _credentials));

                    // Should get returnItem even though it already existed, the fields might have been updated
                    if (this.Options.CopyOperation == CopyOperations.UseNames)
                        returnItem = GetSitecore61Item(sNewItemID, this, true);
                    else
                        returnItem = GetSitecore61Item(sNewItemID, this);
                }

                // Create "Sortorder" field (actually stored on item as an attribute)
                AddFieldFromTemplate(returnItem, "/sitecore/templates/System/Templates/Sections/Appearance/Appearance/__Sortorder", CopyFrom.SortOrder);
                returnItem.SortOrder = CopyFrom.SortOrder;

                // Copy all the fields
                foreach (IField fromField in CopyFrom.Fields)
                {
                    // Fetch field using Key this is neccesary because the field constructor only reads the key, not the name
                    IField toField = Util.GetFieldByName(fromField.Key, returnItem.Fields);
                    if (toField == null)
                    {
                        Sitecore6xField field = new Sitecore6xField(fromField.Name, fromField.Key,
                                    fromField.Type, new Guid(fromField.TemplateFieldID), fromField.Content, fromField.SortOrder, fromField.Section);
                        returnItem._fields.Add(field);
                        toField = field;
                    }
                    toField.Content = ConvertFieldContent(CopyFrom, fromField);
                }

                // Call plugins and update user interface
                if (this.Options.CopyItem != null)
                {
                    this.Options.CopyItem(CopyFrom, this, returnItem);
                }

                // Save item by overwriting existing, neccessary if any returnItem fields have been changed
                returnItem.Save();

                // Copy security rights - if they exist
                if ((this.Options.CopySecuritySettings) && (CopyFrom.Roles != null))
                {
                    try
                    {
                        ExtendedSitecoreAPI.Credentials credential = new ExtendedSitecoreAPI.Credentials();
                        credential.UserName = _credentials.UserName;
                        credential.Password = _credentials.Password;

                        if ((!this.Options.UsersCopied) && (CopyFrom.Users != null))
                        {
                            for (int t = 0; t < CopyFrom.Users.Count(); t++)
                            {
                                bool bIsAdmin = false;
                                if (CopyFrom.Users[t].UserSettings["IsAdmin"].ToLower() == "true")
                                    bIsAdmin = true;
                                ExtendedWebService.CreateUser(
                                            CopyFrom.Users[t].Name,
                                            CopyFrom.Users[t].UserSettings["PassWord"],
                                            CopyFrom.Users[t].UserSettings["Email"],
                                            CopyFrom.Users[t].UserSettings["FullName"],
                                            CopyFrom.Users[t].UserSettings["Roles"],
                                            bIsAdmin,
                                            credential);

                            }
                            this.Options.UsersCopied = true;
                        }

                        for (int t = 0; t < CopyFrom.Roles.Count(); t++)
                        {
                            string sRole = CopyFrom.Roles[t].Name;
                            sRole = Util.MakeValidRoleName(sRole);

                            //                            if (sRole == "__Everyone")
                            //                                sRole = "Everyone";

                            // Add domain name to role, if it isn't already a part of a domain
                            if ((sRole.IndexOf("\\") == -1) && (this.Options.DefaultSecurityDomain != ""))
                                sRole = this.Options.DefaultSecurityDomain + "\\" + sRole;

                            // Allow
                            string sRight = "";
                            if ((CopyFrom.Roles[t].AccessRight & AccessRights.Read) == AccessRights.Read)
                                sRight += "item:read|";

                            if ((CopyFrom.Roles[t].AccessRight & AccessRights.Write) == AccessRights.Write)
                                sRight += "item:write|";

                            if ((CopyFrom.Roles[t].AccessRight & AccessRights.Create) == AccessRights.Create)
                                sRight += "item:create|";

                            if ((CopyFrom.Roles[t].AccessRight & AccessRights.Delete) == AccessRights.Delete)
                                sRight += "item:delete|";

                            if ((CopyFrom.Roles[t].AccessRight & AccessRights.Rename) == AccessRights.Rename)
                                sRight += "item:rename|";

                            if ((CopyFrom.Roles[t].AccessRight & AccessRights.Administer) == AccessRights.Administer)
                                sRight += "item:admin|";

                            // Deny
                            string sDenyRight = "";
                            if ((CopyFrom.Roles[t].AccessRight & AccessRights.DenyRead) == AccessRights.DenyRead)
                                sDenyRight += "item:read|";

                            if ((CopyFrom.Roles[t].AccessRight & AccessRights.DenyWrite) == AccessRights.DenyWrite)
                                sDenyRight += "item:write|";

                            if ((CopyFrom.Roles[t].AccessRight & AccessRights.DenyCreate) == AccessRights.DenyCreate)
                                sDenyRight += "item:create|";

                            if ((CopyFrom.Roles[t].AccessRight & AccessRights.DenyDelete) == AccessRights.DenyDelete)
                                sDenyRight += "item:delete|";

                            if ((CopyFrom.Roles[t].AccessRight & AccessRights.DenyRename) == AccessRights.DenyRename)
                                sDenyRight += "item:rename|";

                            if ((CopyFrom.Roles[t].AccessRight & AccessRights.DenyAdminister) == AccessRights.DenyAdminister)
                                sDenyRight += "item:admin|";

                            // Get existing rights and subtract them from the ones we want to set
                            if (! this.Options.SetItemRightsExplicitly)
                            {
                                string sExistingRights = ExtendedWebService.GetRight(Util.CurrentDatabase, returnItem.ID, CopyFrom.Roles[t].Name,
                                                            CMSConverter.Core.ExtendedSitecoreAPI.SecurityPermission.AllowAccess, credential);
                                sRight = Util.SubtractRights(sExistingRights, sRight);

                                string sExistingDenyRights = ExtendedWebService.GetRight(Util.CurrentDatabase, returnItem.ID, CopyFrom.Roles[t].Name,
                                                            CMSConverter.Core.ExtendedSitecoreAPI.SecurityPermission.DenyAccess, credential);
                                sDenyRight = Util.SubtractRights(sExistingDenyRights, sDenyRight);
                            }

                            // This is a user
                            if (CopyFrom.Roles[t].UserSettings.Count > 0)
                            {
                                bool bIsAdmin = false;
                                if (CopyFrom.Roles[t].UserSettings["IsAdmin"].ToLower() == "true")
                                    bIsAdmin = true;

                                ExtendedWebService.CreateUser(
                                            CopyFrom.Roles[t].Name,
                                            CopyFrom.Roles[t].UserSettings["PassWord"],
                                            CopyFrom.Roles[t].UserSettings["Email"],
                                            CopyFrom.Roles[t].UserSettings["FullName"],
                                            CopyFrom.Roles[t].UserSettings["Roles"],
                                            bIsAdmin,
                                            credential);
                            }
                            // This is a role
                            else
                            {
                                ExtendedWebService.CreateRole(sRole, credential);
                                // This role should inherit from another rootrole
                                if ((!_roleNames.ContainsKey(sRole)) && (this.Options.RootRole != ""))
                                {
                                    string sRootRole = this.Options.RootRole;
                                    if (this.Options.DefaultSecurityDomain != "")
                                        sRootRole = this.Options.DefaultSecurityDomain + "\\" + sRootRole;
                                    ExtendedWebService.AddRoleToRole(sRole, sRootRole, credential);

                                    _roleNames.Add(sRole, sRole);
                                }
                            }

                            // We also need to set rights
                            if (sRight != "")
                            {
                                ExtendedWebService.SetRight(Util.CurrentDatabase,
                                            returnItem.ID, sRole, sRight,
                                            CMSConverter.Core.ExtendedSitecoreAPI.AccessPermission.Allow,
                                            CMSConverter.Core.ExtendedSitecoreAPI.PropagationType.Any,
                                            credential);
                            }
                            if (sDenyRight != "")
                            {
                                ExtendedWebService.SetRight(Util.CurrentDatabase,
                                            returnItem.ID, sRole, sDenyRight,
                                            CMSConverter.Core.ExtendedSitecoreAPI.AccessPermission.Deny,
                                            CMSConverter.Core.ExtendedSitecoreAPI.PropagationType.Any,
                                            credential);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        this.Options.CopySecuritySettings = false;
                        Util.AddWarning("An exception occured while transferring security settings, copying security is now disabled.");
                        Util.AddWarning("The security exception was: " + ex.Message + "\n" + ex.StackTrace);
                    }
                }
            }
            return returnItem;
        }
示例#2
0
        private Sitecore6xItem(XmlNode itemNode, Sitecore6xItem parent, Sitecore61.VisualSitecoreService sitecoreApi, Sitecore61.Credentials credentials, ConverterOptions Options, bool bAllFields = false)
        {
            _Parent = parent;
            _sitecoreApi = sitecoreApi;
            _credentials = credentials;
            _Options = Options;

            _ID = new Guid(itemNode.Attributes["id"].Value);
            _sName = itemNode.Attributes["name"].Value;
            _sKey = itemNode.Attributes["key"].Value;
            _TemplateID = new Guid(itemNode.Attributes["tid"].Value);
            _sTemplateName = itemNode.Attributes["template"].Value;
            // If basetemplate isn't defined use _TemplateID otherwise extract list of inherited templates
            XmlNode baseTemplateNode = itemNode.SelectSingleNode("//field[@key='__base template']/content");
            if (baseTemplateNode == null)
            {
                _sTemplateIDs = new string[1];
                _sTemplateIDs[0] = Util.GuidToSitecoreID(_TemplateID);
            }
            else
                _sTemplateIDs = baseTemplateNode.InnerText.Split('|');

            // _sParentID = itemNode.Attributes["parentid"].Value;
            _sSortOrder = itemNode.Attributes["sortorder"].Value;
            if ((itemNode.Attributes["haschildren"] != null) && (itemNode.Attributes["haschildren"].Value == "1"))
                _bHasChildren = true;

            _sPath = "";
            string sItemVersion = GetItemVersion(itemNode);
            XmlNode contentNode = _sitecoreApi.GetItemFields(Util.GuidToSitecoreID(_ID), this.Options.Language, sItemVersion, bAllFields, Util.CurrentDatabase, _credentials);
            XmlNodeList paths = contentNode.SelectNodes("/path/item");
            foreach (XmlNode path in paths)
            {
                if (_sPath == "")
                    _sPath = "/" + path.Attributes["name"].Value;
                else
                    _sPath = "/" + path.Attributes["name"].Value + _sPath;
            }

            if (bAllFields)
            {
                foreach (XmlNode node in contentNode.SelectNodes("field"))
                {
                    Sitecore6xField field = new Sitecore6xField(node);
                    _fields.Add(field);
                }
            }

            // Add missing fields from other language versions, this is nessesary because new templates
            // are created from an items fields.
            // The program always assumes that all fields exists, so the fieldvalues could be empty in
            // order to prevent copying to another language.
            XmlNodeList fieldList = itemNode.SelectNodes("version[@language='" + this.Options.Language + "']/fields/field");
            foreach (XmlNode node in fieldList)
            {
                Sitecore6xField field = new Sitecore6xField(node);
                var existingfields = from f in _fields
                                     where f.TemplateFieldID == field.TemplateFieldID
                                     select f;
                if (existingfields.Count() == 0)
                {
                    if ((field.Name.ToLower() == "__icon") && (field.Content.Length > 0))
                        _sIcon = field.Content;

                    if (field.Name.ToLower() == "__sortorder")
                        _sSortOrder = field.Content;

                    if ((field.Name.ToLower() == "__display name") && (field.Content != ""))
                        _sName = field.Content;

                    // Caching of template fields items
                    XmlNode templateFieldNode = null;
                    if (!_Options.ExistingTemplateFields.TryGetValue(field.TemplateFieldID, out templateFieldNode))
                    {
                        lock (_Options.ExistingTemplateFields)
                        {
                            try
                            {
                                templateFieldNode = GetItemXml(field.TemplateFieldID);
                                _Options.ExistingTemplateFields.Add(field.TemplateFieldID, templateFieldNode);
                            }
                            catch (Exception ex)
                            {
                                if (ex.Message.ToLower().IndexOf("object reference not set to an instance of an object.") > -1)
                                {
                                    // Do nothing this happens when there is content that is missing it's template field (probably the whole template)
                                    continue;
                                }
                                else
                                    throw new Exception("Error retrieving sitecore Field.", ex);
                            }
                        }
                    }

                    // Get name and field sortorder, unfortunately we have to retrieve the field item which is slow
                    field.SortOrder = templateFieldNode.Attributes["sortorder"].Value;
                    field.Name = templateFieldNode.Attributes["name"].Value;
                    // Get section from contentNode
                    XmlNode fieldNode = contentNode.SelectSingleNode("/field[@fieldid='" + field.TemplateFieldID + "']");
                    if ((fieldNode != null) && (fieldNode.Attributes["section"] != null))
                        field.Section = fieldNode.Attributes["section"].Value;

                    _fields.Add(field);
                }
            }

            // This is a template itemm
            if ((_sPath.ToLower().IndexOf("/sitecore/templates") > -1) && (_sName != "__Standard Values"))
            {
                XmlNode childrenNode = _sitecoreApi.GetChildren("{" + _ID.ToString().ToUpper() + "}", Util.CurrentDatabase, _credentials);

                XmlNodeList nodeList = childrenNode.SelectNodes("./item");
                foreach (XmlNode node in nodeList)
                {
                    // Get full-blown item
                    XmlNode item = GetItemXml(node.Attributes["id"].Value);
                    string sSection = "";
                    if (item.Attributes["template"].Value == "template section")
                    {
                        sSection = item.Attributes["name"].Value;

                        XmlNode sectionChildNodes = _sitecoreApi.GetChildren(node.Attributes["id"].Value, Util.CurrentDatabase, _credentials);
                        foreach (XmlNode tempNode in sectionChildNodes.SelectNodes("./item"))
                        {
                            XmlNode templateFieldNode = GetItemXml(tempNode.Attributes["id"].Value);

                            Sitecore6xField field = new Sitecore6xField(
                                        templateFieldNode.Attributes["name"].Value,
                                        templateFieldNode.Attributes["name"].Value.ToLower(),
                                        Util.GetNodeFieldValue(templateFieldNode, "//field[@key='type']/content"),
                                        new Guid(templateFieldNode.Attributes["id"].Value),
                                        "",
                                        Util.GetNodeFieldValue(templateFieldNode, "//field[@key='__sortorder']/content"),
                                        sSection);
                            field.Source = Util.GetNodeFieldValue(templateFieldNode, "//field[@key='source']/content");
                            field.LanguageTitle = Util.GetNodeFieldValue(templateFieldNode, "//field[@key='title']/content");

                            var existingfields = from f in _fields
                                                 where f.TemplateFieldID == field.TemplateFieldID
                                                 select f;
                            if (existingfields.Count() == 0)
                            {
                                _fields.Add(field);
                            }
                        }
                    }
                }

                // Fill template field values with standard values
                Sitecore6xItem standardValueItem = GetSitecore61Item(_sPath + "/__Standard Values");
                if (standardValueItem != null)
                {
                    foreach (Sitecore6xField standardField in standardValueItem._fields)
                    {
                        // Add field values from this and inherited templates
                        Sitecore6xField curField = Util.GetFieldByID(standardField.TemplateFieldID, Fields) as Sitecore6xField;

                        // Prevent lock from being copied, known to cause problems
                        if ((curField != null) && (curField.Name == "lock"))
                            continue;

                        if (curField == null)
                            _fields.Add(standardField);
                        else
                            curField.Content = standardField.Content;
                    }
                }
            }
            // This is a "__Standard Values" item for the current language layer
            else if ((_sPath.ToLower().IndexOf("/sitecore/templates") > -1) && (_sName == "__Standard Values"))
            {
            }

            _sXmlNode = itemNode.OuterXml;
        }