Пример #1
0
    /// <summary>
    /// Returns number of comments of given blog.
    /// </summary>
    /// <param name="postId">Post document id</param>
    /// <param name="postAliasPath">Post alias path</param>
    /// <param name="includingTrackbacks">Indicates if trackback comments should be included</param>
    public static int GetBlogCommentsCount(object postId, object postAliasPath, bool includingTrackbacks)
    {
        int             docId       = ValidationHelper.GetInteger(postId, 0);
        string          aliasPath   = ValidationHelper.GetString(postAliasPath, "");
        CurrentUserInfo currentUser = MembershipContext.AuthenticatedUser;

        // There has to be the current site
        if (SiteContext.CurrentSite == null)
        {
            throw new Exception("[BlogFunctions.GetBlogCommentsCount]: There is no current site!");
        }

        bool isOwner = false;

        // Is user authorized to manage comments?
        bool     selectOnlyPublished = (PortalContext.ViewMode == ViewModeEnum.LiveSite);
        TreeNode blogNode            = BlogHelper.GetParentBlog(aliasPath, SiteContext.CurrentSiteName, selectOnlyPublished);

        if (blogNode != null)
        {
            isOwner = (currentUser.UserID == ValidationHelper.GetInteger(blogNode.GetValue("NodeOwner"), 0));
        }

        bool isUserAuthorized = (currentUser.IsAuthorizedPerResource("cms.blog", "Manage") || isOwner || BlogHelper.IsUserBlogModerator(currentUser.UserName, blogNode));

        // Get post comments
        return(BlogCommentInfoProvider.GetPostCommentsCount(docId, !isUserAuthorized, isUserAuthorized, includingTrackbacks));
    }
Пример #2
0
    /// <summary>
    /// Method to fetch the record which user wants to edit and populates the fields with those values
    /// </summary>
    /// <param name="_categoryId">category id of editing record</param>

    private void SetFeild(int _categoryId)
    {
        try
        {
            TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
            CMS.DocumentEngine.TreeNode editPage = tree.SelectNodes("KDA.ProductCategory").OnCurrentSite().Where("ProductCategoryID", QueryOperator.Equals, _categoryId);
            if (editPage != null)
            {
                // get the properties of the page

                txtName.Text        = editPage.GetValue("ProductCategoryTitle").ToString();
                txtDescription.Text = editPage.GetValue("ProductCategoryDescription").ToString();
            }
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("CampaignCreateFormEdit", "EXCEPTION", ex);
        }
    }
Пример #3
0
 /// <summary>
 /// Returns the text of the specified region.
 /// </summary>
 /// <param name="aliasPath">Aliaspath of the region MenuItem</param>
 /// <param name="regionID">Region ID to get the text from</param>
 public static string GetEditableRegionText(string aliasPath, string regionID)
 {
     try
     {
         TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);
         TreeNode     node = tree.SelectSingleNode(CMSContext.CurrentSiteName, aliasPath, CMSContext.PreferredCultureCode);
         if (node != null)
         {
             PageInfo pi = new PageInfo();
             pi.LoadContentXml(Convert.ToString(node.GetValue("DocumentContent")));
             return(Convert.ToString(pi.EditableRegions[regionID.ToLowerCSafe()]));
         }
     }
     catch
     {
     }
     return(null);
 }
    private void RemoveWorkflow(object parameter)
    {
        VersionManager verMan = VersionManager.GetInstance(Tree);
        TreeNode       node   = null;

        // Custom logging
        Tree.LogEvents         = false;
        Tree.AllowAsyncActions = false;
        CanceledString         = GetString("workflowdocuments.removingcanceled", mCurrentCulture);
        try
        {
            // Begin log
            AddLog(GetString("content.preparingdocuments", mCurrentCulture));

            string where = parameter as string;

            // Get the documents
            DataSet documents = GetDocumentsToProcess(where);

            if (!DataHelper.DataSourceIsEmpty(documents))
            {
                // Begin log
                AddLog(GetString("workflowdocuments.removingwf", mCurrentCulture));

                foreach (DataTable classTable in documents.Tables)
                {
                    foreach (DataRow nodeRow in classTable.Rows)
                    {
                        // Get the current document
                        string className  = ValidationHelper.GetString(nodeRow["ClassName"], string.Empty);
                        string aliasPath  = ValidationHelper.GetString(nodeRow["NodeAliasPath"], string.Empty);
                        string docCulture = ValidationHelper.GetString(nodeRow["DocumentCulture"], string.Empty);
                        string siteName   = SiteInfoProvider.GetSiteName(nodeRow["NodeSiteID"].ToInteger(0));

                        // Get published version
                        node = Tree.SelectSingleNode(siteName, aliasPath, docCulture, false, className, false);
                        string encodedAliasPath = HTMLHelper.HTMLEncode(ValidationHelper.GetString(aliasPath, string.Empty) + " (" + node.GetValue("DocumentCulture") + ")");

                        // Destroy document history
                        verMan.DestroyDocumentHistory(node.DocumentID);

                        using (new CMSActionContext {
                            LogEvents = false
                        })
                        {
                            // Clear workflow
                            DocumentHelper.ClearWorkflowInformation(node);
                            node.Update();
                        }

                        // Add log record
                        AddLog(encodedAliasPath);

                        // Add record to eventlog
                        LogContext.LogEventToCurrent(EventType.INFORMATION, "Content", "REMOVEDOCWORKFLOW", string.Format(GetString("workflowdocuments.removeworkflowsuccess"), encodedAliasPath), RequestContext.RawURL, mCurrentUser.UserID, mCurrentUser.UserName, node.NodeID, node.GetDocumentName(), RequestContext.UserHostAddress, node.NodeSiteID, SystemContext.MachineName, RequestContext.URLReferrer, RequestContext.UserAgent, DateTime.Now);
                    }
                }
                CurrentInfo = GetString("workflowdocuments.removecomplete");
            }
            else
            {
                AddError(GetString("workflowdocuments.nodocumentstoclear", mCurrentCulture));
            }
        }
        catch (ThreadAbortException ex)
        {
            if (CMSThread.Stopped(ex))
            {
                // When canceled
                CurrentInfo = CanceledString;
            }
            else
            {
                int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID;
                // Log error
                LogExceptionToEventLog("REMOVEDOCWORKFLOW", "workflowdocuments.removefailed", ex, siteId);
            }
        }
        catch (Exception ex)
        {
            int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID;
            // Log error
            LogExceptionToEventLog("REMOVEDOCWORKFLOW", "workflowdocuments.removefailed", ex, siteId);
        }
    }
Пример #5
0
    protected void menuNew_OnReloadData(object sender, EventArgs e)
    {
        int nodeId = ValidationHelper.GetInteger(menuNew.Parameter, 0);

        // Get the node
        TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
        TreeNode     node = tree.SelectSingleNode(nodeId);

        plcNewVariant.Visible = false;

        if (node != null)
        {
            if (CurrentUser.IsAuthorizedToCreateNewDocument(node, null))
            {
                DocumentTypeScopeInfo scope = DocumentTypeScopeInfoProvider.GetScopeInfo(node);
                if (scope != null)
                {
                    plcNewLink.Visible = scope.ScopeAllowLinks;
                }

                // AB test variant settings
                if (SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSABTestingEnabled") &&
                    EnableABTestVariant &&
                    CurrentUser.IsAuthorizedPerResource("cms.ABTest", "Read") &&
                    ModuleEntryManager.IsModuleLoaded(ModuleName.ONLINEMARKETING) &&
                    ResourceSiteInfoProvider.IsResourceOnSite("CMS.ABTest", SiteContext.CurrentSiteName) &&
                    LicenseHelper.CheckFeature(RequestContext.CurrentDomain, FeatureEnum.ABTesting) &&
                    (node.NodeAliasPath != "/") &&
                    (node.NodeClassName != "CMS.Folder") &&
                    ((scope == null) || scope.ScopeAllowABVariant) &&
                    CurrentUser.IsAuthorizedToCreateNewDocument(node, node.ClassName))
                {
                    plcNewVariant.Visible = true;
                }

                pnlSepNewLinkVariant.Visible = (plcNewVariant.Visible || plcNewLink.Visible);

                string where = "ClassID IN (SELECT ChildClassID FROM CMS_AllowedChildClasses WHERE ParentClassID=" + ValidationHelper.GetInteger(node.GetValue("NodeClassID"), 0) + ") " +
                               "AND ClassID IN (SELECT ClassID FROM CMS_ClassSite WHERE SiteID = " + SiteContext.CurrentSiteID + ")";

                if (!string.IsNullOrEmpty(DocumentTypeWhere))
                {
                    where = SqlHelper.AddWhereCondition(where, DocumentTypeWhere);
                }

                if (scope != null)
                {
                    // Apply document type scope
                    where = SqlHelper.AddWhereCondition(where, DocumentTypeScopeInfoProvider.GetScopeClassWhereCondition(scope));
                }

                // Get the allowed child classes
                DataSet ds = DocumentTypeHelper.GetDocumentTypeClasses()
                             .Where(where)
                             .OrderBy(DocumentTypeOrderBy)
                             .TopN(50)
                             .Columns("ClassID", "ClassName", "ClassDisplayName", "(CASE WHEN (ClassName = 'CMS.MenuItem' OR ClassName = 'CMS.Wireframe')  THEN 0 ELSE 1 END) AS MenuItemOrder");

                var rows = new List <DataRow>();

                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    // Check user permissions for "Create" permission
                    bool hasNodeAllowCreate            = (CurrentUser.IsAuthorizedPerTreeNode(node, NodePermissionsEnum.Create) == AuthorizationResultEnum.Allowed);
                    bool isAuthorizedToCreateInContent = CurrentUser.IsAuthorizedPerResource("CMS.Content", "Create");

                    DataTable resultTable = ds.Tables[0].DefaultView.ToTable();

                    for (int i = 0; i < resultTable.Rows.Count; ++i)
                    {
                        DataRow dr  = resultTable.Rows[i];
                        string  doc = ValidationHelper.GetString(DataHelper.GetDataRowValue(dr, "ClassName"), "");

                        // Document type is not allowed, remove it from the data set
                        if (!isAuthorizedToCreateInContent && !CurrentUser.IsAuthorizedPerClassName(doc, "Create") && (!CurrentUser.IsAuthorizedPerClassName(doc, "CreateSpecific") || !hasNodeAllowCreate))
                        {
                            rows.Add(dr);
                        }
                        else if (doc.EqualsCSafe("cms.wireframe", true) && !CurrentUser.IsAuthorizedPerResource("CMS.Design", "Wireframing"))
                        {
                            rows.Add(dr);
                        }
                    }

                    // Remove the document types
                    foreach (DataRow dr in rows)
                    {
                        resultTable.Rows.Remove(dr);
                    }

                    bool classesRemoved = false;

                    // Leave only first 15 rows
                    while (resultTable.Rows.Count > 15)
                    {
                        resultTable.Rows.RemoveAt(resultTable.Rows.Count - 1);
                        classesRemoved = true;
                    }

                    if (!DataHelper.DataSourceIsEmpty(resultTable))
                    {
                        // Add show more item
                        if (classesRemoved)
                        {
                            DataRow dr = resultTable.NewRow();
                            dr["ClassID"]          = 0;
                            dr["ClassName"]        = "more";
                            dr["ClassDisplayName"] = ResHelper.GetString("class.showmore");
                            resultTable.Rows.InsertAt(dr, resultTable.Rows.Count);
                        }

                        // Create temp column
                        int        rowCount  = resultTable.Rows.Count;
                        DataColumn tmpColumn = new DataColumn("Count");
                        tmpColumn.DefaultValue = rowCount;
                        resultTable.Columns.Add(tmpColumn);

                        repNew.DataSource = resultTable;
                        repNew.DataBind();
                    }
                    else
                    {
                        DisplayErrorMessage(scope != null ? "Content.ScopeApplied" : "Content.NoPermissions");
                    }
                }
                else
                {
                    DisplayErrorMessage(scope != null ? "Content.ScopeApplied" : "NewMenu.NoChildAllowed");
                }
            }
            else
            {
                DisplayErrorMessage("Content.NoPermissions");
            }
        }
    }
Пример #6
0
    /// <summary>
    /// PreRender action on which security settings are set.
    /// </summary>
    private void Page_PreRender(object sender, EventArgs e)
    {
        if ((Form == null) || !mDocumentSaved)
        {
            return;
        }

        TreeNode editedNode = Form.EditedObject as TreeNode;

        // Create or rebuild department content index
        CreateDepartmentContentSearchIndex(editedNode);

        if ((editedNode == null) || !editedNode.NodeIsACLOwner)
        {
            return;
        }

        ForumInfo        fi = ForumInfoProvider.GetForumInfo("Default_department_" + editedNode.NodeGUID, SiteContext.CurrentSiteID);
        MediaLibraryInfo mi = MediaLibraryInfoProvider.GetMediaLibraryInfo("Department_" + editedNode.NodeGUID, SiteContext.CurrentSiteName);

        // Check if forum of media library exists
        if ((fi == null) && (mi == null))
        {
            return;
        }

        // Get allowed roles ID
        int     aclID     = ValidationHelper.GetInteger(editedNode.GetValue("NodeACLID"), 0);
        DataSet listRoles = AclItemInfoProvider.GetAllowedRoles(aclID, NodePermissionsEnum.Read, "RoleID");
        string  roleIDs   = null;

        if (!DataHelper.DataSourceIsEmpty(listRoles))
        {
            IList <string> roles = DataHelper.GetStringValues(listRoles.Tables[0], "RoleID");
            roleIDs = TextHelper.Join(";", roles);
        }

        // Set permissions for forum
        if (fi != null)
        {
            // Get resource object
            ResourceInfo resForums = ResourceInfoProvider.GetResourceInfo("CMS.Forums");

            // Get permissions IDs
            DataSet dsForumPerm      = PermissionNameInfoProvider.GetPermissionNames("ResourceID = " + resForums.ResourceID + " AND (PermissionName != '" + CMSAdminControl.PERMISSION_READ + "' AND PermissionName != '" + CMSAdminControl.PERMISSION_MODIFY + "')", null, 0, "PermissionID");
            string  forumPermissions = null;
            if (!DataHelper.DataSourceIsEmpty(dsForumPerm))
            {
                foreach (DataRow drForumPerm in dsForumPerm.Tables[0].Rows)
                {
                    forumPermissions += drForumPerm["PermissionID"] + ";";
                }
                forumPermissions = forumPermissions.TrimEnd(';');
            }

            // Delete old permissions apart attach file permission
            ForumRoleInfoProvider.DeleteAllRoles("ForumID = " + fi.ForumID + " AND PermissionID IN (" + forumPermissions.Replace(";", ", ") + ")");

            // Set forum permissions
            ForumRoleInfoProvider.SetPermissions(fi.ForumID, roleIDs, forumPermissions);

            // Log staging task
            SynchronizationHelper.LogObjectChange(fi, TaskTypeEnum.UpdateObject);
        }

        // Set permissions for media library
        if (mi == null)
        {
            return;
        }

        // Get resource object
        ResourceInfo resMediaLibs = ResourceInfoProvider.GetResourceInfo("CMS.MediaLibrary");

        // Get permissions IDs
        DataSet dsMediaLibPerm      = PermissionNameInfoProvider.GetPermissionNames("ResourceID = " + resMediaLibs.ResourceID + " AND (PermissionName = 'LibraryAccess' OR PermissionName = 'FileCreate')", null, 0, "PermissionID");
        string  mediaLibPermissions = null;

        if (!DataHelper.DataSourceIsEmpty(dsMediaLibPerm))
        {
            foreach (DataRow drMediaLibPerm in dsMediaLibPerm.Tables[0].Rows)
            {
                mediaLibPermissions += drMediaLibPerm["PermissionID"] + ";";
            }
            mediaLibPermissions = mediaLibPermissions.TrimEnd(';');
        }

        // Delete old permissions only for Create file and See library content permissions
        MediaLibraryRolePermissionInfoProvider.DeleteAllRoles("LibraryID = " + mi.LibraryID + " AND PermissionID IN (" + mediaLibPermissions.Replace(";", ", ") + ")");

        // Set media library permissions
        MediaLibraryRolePermissionInfoProvider.SetPermissions(mi.LibraryID, roleIDs, mediaLibPermissions);

        // Log staging task
        SynchronizationHelper.LogObjectChange(mi, TaskTypeEnum.UpdateObject);
    }
Пример #7
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            commentView.StopProcessing = true;
            commentView.BlogProperties.StopProcessing = true;
        }
        else
        {
            commentView.ControlContext = ControlContext;

            // Get current page info
            PageInfo currentPage = DocumentContext.CurrentPageInfo;

            bool selectOnlyPublished = (PageManager.ViewMode.IsLiveSite());

            // Get current document
            commentView.PostNode = DocumentContext.CurrentDocument;

            // Get current parent blog
            TreeNode blogNode = BlogHelper.GetParentBlog(currentPage.NodeAliasPath, SiteContext.CurrentSiteName, selectOnlyPublished);

            // If blog node exists, set comment view properties
            if (blogNode != null)
            {
                commentView.BlogProperties.AllowAnonymousComments = ValidationHelper.GetBoolean(blogNode.GetValue("BlogAllowAnonymousComments"), true);
                commentView.BlogProperties.ModerateComments       = ValidationHelper.GetBoolean(blogNode.GetValue("BlogModerateComments"), false);
                commentView.BlogProperties.OpenCommentsFor        = ValidationHelper.GetInteger(blogNode.GetValue("BlogOpenCommentsFor"), BlogProperties.OPEN_COMMENTS_ALWAYS);
                commentView.BlogProperties.SendCommentsToEmail    = ValidationHelper.GetString(blogNode.GetValue("BlogSendCommentsToEmail"), "");
                commentView.BlogProperties.UseCaptcha             = ValidationHelper.GetBoolean(blogNode.GetValue("BlogUseCAPTCHAForComments"), true);
                commentView.BlogProperties.RequireEmails          = ValidationHelper.GetBoolean(blogNode.GetValue("BlogRequireEmails"), false);
                commentView.BlogProperties.EnableSubscriptions    = ValidationHelper.GetBoolean(blogNode.GetValue("BlogEnableSubscriptions"), false);
                commentView.BlogProperties.CheckPermissions       = CheckPermissions;
                commentView.BlogProperties.ShowDeleteButton       = ShowDeleteButton;
                commentView.BlogProperties.ShowEditButton         = ShowEditButton;
                commentView.BlogProperties.EnableUserPictures     = EnableUserPictures;
                commentView.BlogProperties.UserPictureMaxHeight   = UserPictureMaxHeight;
                commentView.BlogProperties.UserPictureMaxWidth    = UserPictureMaxWidth;
                commentView.Separator                 = CommentSeparator;
                commentView.ReloadPageAfterAction     = true;
                commentView.AbuseReportOwnerID        = blogNode.NodeOwner;
                commentView.AbuseReportRoles          = AbuseReportRoles;
                commentView.AbuseReportSecurityAccess = AbuseReportAccess;
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        // Set general properties
        repUsers.DataBindByDefault = false;
        pagerElem.PageControl      = repUsers.ID;

        if (StopProcessing)
        {
            // Do nothing
            filterUsers.StopProcessing = true;
            srcUsers.StopProcessing    = true;
        }
        else
        {
            filterUsers.Visible          = ShowFilterControl;
            filterUsers.OnFilterChanged += filterUsers_OnFilterChanged;
            srcUsers.OnFilterChanged    += filterUsers_OnFilterChanged;

            // Basic control properties
            repUsers.HideControlForZeroRows = HideControlForZeroRows;
            repUsers.ZeroRowsText           = ZeroRowsText;


            TreeNode     node = null;
            TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

            // Check if path is set
            if (String.IsNullOrEmpty(Path))
            {
                TreeNode curDoc = DocumentContext.CurrentDocument;
                // Check if current document is department
                if ((curDoc != null) && (curDoc.NodeClassName.ToLowerCSafe() == DEPARTMENT_CLASS_NAME))
                {
                    node = DocumentContext.CurrentDocument;
                }
            }
            else
            {
                // Obtain document from specified path
                node = tree.SelectSingleNode(SiteName, Path, LocalizationContext.PreferredCultureCode, true, DEPARTMENT_CLASS_NAME, false, false, false);
            }

            // If department document exists and has own ACL continue with initializing controls
            if ((node != null) && node.NodeIsACLOwner)
            {
                // Get users and roles with read permission for department document
                int     aclId   = ValidationHelper.GetInteger(node.GetValue("NodeACLID"), 0);
                DataSet dsRoles = AclItemInfoProvider.GetAllowedRoles(aclId, NodePermissionsEnum.Read, "RoleID");
                DataSet dsUsers = AclItemInfoProvider.GetAllowedUsers(aclId, NodePermissionsEnum.Read, "UserID");

                string where = null;

                // Process users dataset to where condition
                if (!DataHelper.DataSourceIsEmpty(dsUsers))
                {
                    // Get allowed users ids
                    IList <string> users   = DataHelper.GetStringValues(dsUsers.Tables[0], "UserID");
                    string         userIds = TextHelper.Join(", ", users);

                    // Populate where condition with user condition
                    where = SqlHelper.AddWhereCondition("UserID IN (" + userIds + ")", where);
                }

                // Process roles dataset to where condition
                if (!DataHelper.DataSourceIsEmpty(dsRoles))
                {
                    // Get allowed roles ids
                    IList <string> roles   = DataHelper.GetStringValues(dsRoles.Tables[0], "RoleID");
                    string         roleIds = TextHelper.Join(", ", roles);

                    // Populate where condition with role condition
                    where = SqlHelper.AddWhereCondition("UserID IN (SELECT UserID FROM View_CMS_UserRole_MembershipRole_ValidOnly_Joined WHERE RoleID IN (" + roleIds + "))", where, "OR");
                }


                if (!String.IsNullOrEmpty(where))
                {
                    // Check if exist where condition and add it to current where condition
                    where = SqlHelper.AddWhereCondition(WhereCondition, where);

                    // Data source properties
                    srcUsers.WhereCondition     = where;
                    srcUsers.OrderBy            = OrderBy;
                    srcUsers.TopN               = SelectTopN;
                    srcUsers.SelectedColumns    = Columns;
                    srcUsers.SiteName           = SiteName;
                    srcUsers.FilterName         = filterUsers.ID;
                    srcUsers.SourceFilterName   = FilterName;
                    srcUsers.CacheItemName      = CacheItemName;
                    srcUsers.CacheDependencies  = CacheDependencies;
                    srcUsers.CacheMinutes       = CacheMinutes;
                    srcUsers.SelectOnlyApproved = SelectOnlyApproved;
                    srcUsers.SelectHidden       = SelectHidden;

                    // Init data properties
                    filterUsers.InitDataProperties(srcUsers);


                    #region "Repeater template properties"

                    // Apply transformations if they exist
                    if (!String.IsNullOrEmpty(TransformationName))
                    {
                        repUsers.ItemTemplate = CMSDataProperties.LoadTransformation(this, TransformationName);
                    }
                    if (!String.IsNullOrEmpty(AlternatingItemTransformationName))
                    {
                        repUsers.AlternatingItemTemplate = CMSDataProperties.LoadTransformation(this, AlternatingItemTransformationName);
                    }
                    if (!String.IsNullOrEmpty(FooterTransformationName))
                    {
                        repUsers.FooterTemplate = CMSDataProperties.LoadTransformation(this, FooterTransformationName);
                    }
                    if (!String.IsNullOrEmpty(HeaderTransformationName))
                    {
                        repUsers.HeaderTemplate = CMSDataProperties.LoadTransformation(this, HeaderTransformationName);
                    }
                    if (!String.IsNullOrEmpty(SeparatorTransformationName))
                    {
                        repUsers.SeparatorTemplate = CMSDataProperties.LoadTransformation(this, SeparatorTransformationName);
                    }

                    #endregion


                    // UniPager properties
                    pagerElem.PageSize       = PageSize;
                    pagerElem.GroupSize      = GroupSize;
                    pagerElem.QueryStringKey = QueryStringKey;
                    pagerElem.DisplayFirstLastAutomatically    = DisplayFirstLastAutomatically;
                    pagerElem.DisplayPreviousNextAutomatically = DisplayPreviousNextAutomatically;
                    pagerElem.HidePagerForSinglePage           = HidePagerForSinglePage;
                    pagerElem.Enabled = EnablePaging;

                    switch (PagingMode.ToLowerCSafe())
                    {
                    case "querystring":
                        pagerElem.PagerMode = UniPagerMode.Querystring;
                        break;

                    default:
                        pagerElem.PagerMode = UniPagerMode.PostBack;
                        break;
                    }


                    #region "UniPager template properties"

                    // UniPager template properties
                    if (!String.IsNullOrEmpty(PagesTemplate))
                    {
                        pagerElem.PageNumbersTemplate = CMSDataProperties.LoadTransformation(pagerElem, PagesTemplate);
                    }

                    if (!String.IsNullOrEmpty(CurrentPageTemplate))
                    {
                        pagerElem.CurrentPageTemplate = CMSDataProperties.LoadTransformation(pagerElem, CurrentPageTemplate);
                    }

                    if (!String.IsNullOrEmpty(SeparatorTemplate))
                    {
                        pagerElem.PageNumbersSeparatorTemplate = CMSDataProperties.LoadTransformation(pagerElem, SeparatorTemplate);
                    }

                    if (!String.IsNullOrEmpty(FirstPageTemplate))
                    {
                        pagerElem.FirstPageTemplate = CMSDataProperties.LoadTransformation(pagerElem, FirstPageTemplate);
                    }

                    if (!String.IsNullOrEmpty(LastPageTemplate))
                    {
                        pagerElem.LastPageTemplate = CMSDataProperties.LoadTransformation(pagerElem, LastPageTemplate);
                    }

                    if (!String.IsNullOrEmpty(PreviousPageTemplate))
                    {
                        pagerElem.PreviousPageTemplate = CMSDataProperties.LoadTransformation(pagerElem, PreviousPageTemplate);
                    }

                    if (!String.IsNullOrEmpty(NextPageTemplate))
                    {
                        pagerElem.NextPageTemplate = CMSDataProperties.LoadTransformation(pagerElem, NextPageTemplate);
                    }

                    if (!String.IsNullOrEmpty(PreviousGroupTemplate))
                    {
                        pagerElem.PreviousGroupTemplate = CMSDataProperties.LoadTransformation(pagerElem, PreviousGroupTemplate);
                    }

                    if (!String.IsNullOrEmpty(NextGroupTemplate))
                    {
                        pagerElem.NextGroupTemplate = CMSDataProperties.LoadTransformation(pagerElem, NextGroupTemplate);
                    }

                    if (!String.IsNullOrEmpty(DirectPageTemplate))
                    {
                        pagerElem.DirectPageTemplate = CMSDataProperties.LoadTransformation(pagerElem, DirectPageTemplate);
                    }

                    if (!String.IsNullOrEmpty(LayoutTemplate))
                    {
                        pagerElem.LayoutTemplate = CMSDataProperties.LoadTransformation(pagerElem, LayoutTemplate);
                    }

                    #endregion


                    // Connects repeater with data source
                    repUsers.DataSource = srcUsers.DataSource;
                }
                else
                {
                    // Disable datasource
                    srcUsers.StopProcessing = true;
                }
            }
            else
            {
                // Disable datasource
                srcUsers.StopProcessing = true;
            }

            pagerElem.RebindPager();
            repUsers.DataBind();
        }
    }
Пример #9
0
    /// <summary>
    /// Reloads control.
    /// </summary>
    /// <param name="forceReload">Forces nested CMSForm to reload if true</param>
    public void ReloadData(bool forceReload)
    {
        if (!mFormLoaded || forceReload)
        {
            // Check License
            LicenseHelper.CheckFeatureAndRedirect(RequestContext.CurrentDomain, FeatureEnum.UserContributions);

            if (!StopProcessing)
            {
                // Set document manager mode
                if (NewDocument)
                {
                    DocumentManager.Mode           = FormModeEnum.Insert;
                    DocumentManager.ParentNodeID   = NodeID;
                    DocumentManager.NewNodeClassID = ClassID;
                    DocumentManager.CultureCode    = CultureCode;
                    DocumentManager.SiteName       = SiteName;
                }
                else if (NewCulture)
                {
                    DocumentManager.Mode             = FormModeEnum.InsertNewCultureVersion;
                    DocumentManager.NodeID           = NodeID;
                    DocumentManager.CultureCode      = CultureCode;
                    DocumentManager.SiteName         = SiteName;
                    DocumentManager.SourceDocumentID = CopyDefaultDataFromDocumentID;
                }
                else
                {
                    DocumentManager.Mode        = FormModeEnum.Update;
                    DocumentManager.NodeID      = NodeID;
                    DocumentManager.SiteName    = SiteName;
                    DocumentManager.CultureCode = CultureCode;
                }

                ScriptHelper.RegisterDialogScript(Page);

                titleElem.TitleText = String.Empty;

                pnlSelectClass.Visible = false;
                pnlEdit.Visible        = false;
                pnlInfo.Visible        = false;
                pnlNewCulture.Visible  = false;
                pnlDelete.Visible      = false;

                // If node found, init the form

                if (NewDocument || (Node != null))
                {
                    // Delete action
                    if (Delete)
                    {
                        // Delete document
                        pnlDelete.Visible = true;

                        titleElem.TitleText = GetString("Content.DeleteTitle");
                        chkAllCultures.Text = GetString("ContentDelete.AllCultures");
                        chkDestroy.Text     = GetString("ContentDelete.Destroy");

                        lblQuestion.Text = GetString("ContentDelete.Question");
                        btnYes.Text      = GetString("general.yes");
                        // Prevent button double-click
                        btnYes.Attributes.Add("onclick", string.Format("document.getElementById('{0}').disabled=true;this.disabled=true;{1};", btnNo.ClientID, ControlsHelper.GetPostBackEventReference(btnYes, string.Empty, true, false)));
                        btnNo.Text = GetString("general.no");

                        DataSet culturesDS = CultureSiteInfoProvider.GetSiteCultures(SiteName);
                        if ((DataHelper.DataSourceIsEmpty(culturesDS)) || (culturesDS.Tables[0].Rows.Count <= 1))
                        {
                            chkAllCultures.Visible = false;
                            chkAllCultures.Checked = true;
                        }

                        if (Node.IsLink)
                        {
                            titleElem.TitleText    = GetString("Content.DeleteTitleLink") + " \"" + HTMLHelper.HTMLEncode(Node.NodeName) + "\"";
                            lblQuestion.Text       = GetString("ContentDelete.QuestionLink");
                            chkAllCultures.Checked = true;
                            plcCheck.Visible       = false;
                        }
                        else
                        {
                            titleElem.TitleText = GetString("Content.DeleteTitle") + " \"" + HTMLHelper.HTMLEncode(Node.NodeName) + "\"";
                        }
                    }
                    // New document or edit action
                    else
                    {
                        if (NewDocument)
                        {
                            titleElem.TitleText = GetString("Content.NewTitle");
                        }

                        // Document type selection
                        if (NewDocument && (ClassID <= 0))
                        {
                            // Use parent node
                            TreeNode parentNode = DocumentManager.ParentNode;
                            if (parentNode != null)
                            {
                                // Select document type
                                pnlSelectClass.Visible = true;

                                // Apply document type scope
                                string whereCondition = DocumentTypeScopeInfoProvider.GetScopeClassWhereCondition(parentNode);

                                var parentClassId = ValidationHelper.GetInteger(parentNode.GetValue("NodeClassID"), 0);
                                var siteId        = SiteInfoProvider.GetSiteID(SiteName);

                                // Get the allowed child classes
                                DataSet ds = AllowedChildClassInfoProvider.GetAllowedChildClasses(parentClassId, siteId)
                                             .Where(whereCondition)
                                             .OrderBy("ClassID")
                                             .Columns("ClassName", "ClassDisplayName", "ClassID");

                                ArrayList deleteRows = new ArrayList();

                                if (!DataHelper.DataSourceIsEmpty(ds))
                                {
                                    // Get the unwanted classes
                                    string allowed = AllowedChildClasses.Trim().ToLowerCSafe();
                                    if (!string.IsNullOrEmpty(allowed))
                                    {
                                        allowed = String.Format(";{0};", allowed);
                                    }

                                    var    userInfo  = MembershipContext.AuthenticatedUser;
                                    string className = null;
                                    // Check if the user has 'Create' permission per Content
                                    bool isAuthorizedToCreateInContent = userInfo.IsAuthorizedPerResource("CMS.Content", "Create");
                                    bool hasNodeAllowCreate            = (userInfo.IsAuthorizedPerTreeNode(parentNode, NodePermissionsEnum.Create) != AuthorizationResultEnum.Allowed);
                                    foreach (DataRow dr in ds.Tables[0].Rows)
                                    {
                                        className = ValidationHelper.GetString(DataHelper.GetDataRowValue(dr, "ClassName"), String.Empty).ToLowerCSafe();
                                        // Document type is not allowed or user hasn't got permission, remove it from the data set
                                        if ((!string.IsNullOrEmpty(allowed) && (!allowed.Contains(";" + className + ";"))) ||
                                            (CheckPermissions && CheckDocPermissionsForInsert && !isAuthorizedToCreateInContent && !userInfo.IsAuthorizedPerClassName(className, "Create") && (!userInfo.IsAuthorizedPerClassName(className, "CreateSpecific") || !hasNodeAllowCreate)))
                                        {
                                            deleteRows.Add(dr);
                                        }
                                    }

                                    // Remove the rows
                                    foreach (DataRow dr in deleteRows)
                                    {
                                        ds.Tables[0].Rows.Remove(dr);
                                    }
                                }

                                // Check if some classes are available
                                if (!DataHelper.DataSourceIsEmpty(ds))
                                {
                                    // If number of classes is more than 1 display them in grid
                                    if (ds.Tables[0].Rows.Count > 1)
                                    {
                                        ds.Tables[0].DefaultView.Sort = "ClassDisplayName";
                                        lblError.Visible = false;
                                        lblInfo.Visible  = true;
                                        lblInfo.Text     = GetString("Content.NewInfo");

                                        DataSet sortedResult = new DataSet();
                                        sortedResult.Tables.Add(ds.Tables[0].DefaultView.ToTable());
                                        gridClass.DataSource = sortedResult;
                                        gridClass.ReloadData();
                                    }
                                    // else show form of the only class
                                    else
                                    {
                                        ClassID = ValidationHelper.GetInteger(DataHelper.GetDataRowValue(ds.Tables[0].Rows[0], "ClassID"), 0);
                                        ReloadData(true);
                                        return;
                                    }
                                }
                                else
                                {
                                    // Display error message
                                    lblError.Visible  = true;
                                    lblError.Text     = GetString("Content.NoAllowedChildDocuments");
                                    lblInfo.Visible   = false;
                                    gridClass.Visible = false;
                                }
                            }
                            else
                            {
                                pnlInfo.Visible  = true;
                                lblFormInfo.Text = GetString("EditForm.DocumentNotFound");
                            }
                        }
                        // Insert or update of a document
                        else
                        {
                            // Display the form
                            pnlEdit.Visible = true;

                            // Try to get GroupID if group context exists
                            int currentGroupId = ModuleCommands.CommunityGetCurrentGroupID();

                            btnDelete.Attributes.Add("style", "display: none;");
                            btnRefresh.Attributes.Add("style", "display: none;");

                            // CMSForm initialization
                            formElem.NodeID                 = Node.NodeID;
                            formElem.SiteName               = SiteName;
                            formElem.CultureCode            = CultureCode;
                            formElem.ValidationErrorMessage = ValidationErrorMessage;
                            formElem.IsLiveSite             = IsLiveSite;

                            // Set group ID if group context exists
                            formElem.GroupID = currentGroupId;

                            // External editing is allowed for live site only if the permissions are checked or user is global administrator or for group context - user is group administrator
                            formElem.AllowExternalEditing = !IsLiveSite || CheckPermissions || MembershipContext.AuthenticatedUser.IsGlobalAdministrator || MembershipContext.AuthenticatedUser.IsGroupAdministrator(currentGroupId);

                            // Set the form mode
                            if (NewDocument)
                            {
                                ci = DataClassInfoProvider.GetDataClassInfo(ClassID);
                                if (ci == null)
                                {
                                    throw new Exception(String.Format("[CMSAdminControls/EditForm.aspx]: Class ID '{0}' not found.", ClassID));
                                }

                                string classDisplayName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ci.ClassDisplayName));
                                titleElem.TitleText = GetString("Content.NewTitle") + ": " + classDisplayName;

                                // Set default template ID
                                formElem.DefaultPageTemplateID = TemplateID > 0 ? TemplateID : ci.ClassDefaultPageTemplateID;

                                // Set document owner
                                formElem.OwnerID  = OwnerID;
                                formElem.FormMode = FormModeEnum.Insert;
                                string newClassName = ci.ClassName;
                                string newFormName  = newClassName + ".default";
                                if (!String.IsNullOrEmpty(AlternativeFormName))
                                {
                                    // Set the alternative form full name
                                    formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName);
                                }
                                if (newFormName.ToLowerCSafe() != formElem.FormName.ToLowerCSafe())
                                {
                                    formElem.FormName = newFormName;
                                }
                            }
                            else if (NewCulture)
                            {
                                formElem.FormMode = FormModeEnum.InsertNewCultureVersion;
                                // Default data document ID
                                formElem.CopyDefaultDataFromDocumentId = CopyDefaultDataFromDocumentID;

                                ci = DataClassInfoProvider.GetDataClassInfo(Node.NodeClassName);
                                formElem.FormName = Node.NodeClassName + ".default";
                                if (!String.IsNullOrEmpty(AlternativeFormName))
                                {
                                    // Set the alternative form full name
                                    formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName);
                                }
                            }
                            else
                            {
                                formElem.FormMode = FormModeEnum.Update;
                                ci = DataClassInfoProvider.GetDataClassInfo(Node.NodeClassName);
                                formElem.FormName = String.Empty;
                                if (!String.IsNullOrEmpty(AlternativeFormName))
                                {
                                    // Set the alternative form full name
                                    formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName);
                                }
                            }

                            // Allow the CMSForm
                            formElem.StopProcessing = false;

                            ReloadForm();
                            formElem.LoadForm(true);
                        }
                    }
                }
                // New culture version
                else
                {
                    // Switch to new culture version mode
                    DocumentManager.Mode        = FormModeEnum.InsertNewCultureVersion;
                    DocumentManager.NodeID      = NodeID;
                    DocumentManager.CultureCode = CultureCode;
                    DocumentManager.SiteName    = SiteName;

                    if (Node != null)
                    {
                        // Offer a new culture creation
                        pnlNewCulture.Visible = true;

                        titleElem.TitleText    = GetString("Content.NewCultureVersionTitle") + " (" + HTMLHelper.HTMLEncode(MembershipContext.AuthenticatedUser.PreferredCultureCode) + ")";
                        lblNewCultureInfo.Text = GetString("ContentNewCultureVersion.Info");
                        radCopy.Text           = GetString("ContentNewCultureVersion.Copy");
                        radEmpty.Text          = GetString("ContentNewCultureVersion.Empty");

                        radCopy.Attributes.Add("onclick", "ShowSelection();");
                        radEmpty.Attributes.Add("onclick", "ShowSelection()");

                        AddScript(
                            "function ShowSelection() { \n" +
                            "   if (document.getElementById('" + radCopy.ClientID + "').checked) { document.getElementById('divCultures').style.display = 'block'; } \n" +
                            "   else { document.getElementById('divCultures').style.display = 'none'; } \n" +
                            "} \n"
                            );

                        btnOk.Text = GetString("ContentNewCultureVersion.Create");

                        // Load culture versions
                        SiteInfo si = SiteInfoProvider.GetSiteInfo(Node.NodeSiteID);
                        if (si != null)
                        {
                            lstCultures.Items.Clear();

                            DataSet nodes = TreeProvider.SelectNodes(si.SiteName, Node.NodeAliasPath, TreeProvider.ALL_CULTURES, false, null, null, null, 1, false);
                            foreach (DataRow nodeCulture in nodes.Tables[0].Rows)
                            {
                                ListItem li = new ListItem();
                                li.Text  = CultureInfoProvider.GetCultureInfo(nodeCulture["DocumentCulture"].ToString()).CultureName;
                                li.Value = nodeCulture["DocumentID"].ToString();
                                lstCultures.Items.Add(li);
                            }
                            if (lstCultures.Items.Count > 0)
                            {
                                lstCultures.SelectedIndex = 0;
                            }
                        }
                    }
                    else
                    {
                        pnlInfo.Visible  = true;
                        lblFormInfo.Text = GetString("EditForm.DocumentNotFound");
                    }
                }
            }
            // Set flag that the form is loaded
            mFormLoaded = true;
        }
    }
Пример #10
0
    /// <summary>
    /// Process additional department tasks.
    /// </summary>
    public void ProcessDepartment(object sender, EventArgs e)
    {
        TreeNode editedNode = Form.EditedObject as TreeNode;

        // Get department template source document
        TreeNode sourceNode = DocumentHelper.GetDocument(SiteContext.CurrentSiteName, DepartmentTemplatePath, null, true, null, null, null, 0, false, null, TreeProvider);

        // Copy relevant template data to department document
        if (sourceNode != null)
        {
            string excludeColumns = "DocumentName;NodeAlias;DocumentTagGroupID;DocumentStylesheetID;DocumentPublishFrom;DocumentPublishTo";
            DocumentHelper.CopyNodeData(sourceNode, editedNode, new CopyNodeDataSettings(true, true, false, true, true, false, false, false, excludeColumns));
            DocumentHelper.UpdateDocument(editedNode, TreeProvider);
        }


        #region "Create department tag group"

        // Get tag group info
        TagGroupInfo tgi = TagGroupInfoProvider.GetTagGroupInfo(editedNode.DocumentTagGroupID);

        // If not exist, create new tag group and set it to document
        if (tgi == null)
        {
            // Populate tag group info fields
            tgi = new TagGroupInfo();
            tgi.TagGroupDisplayName = editedNode.GetDocumentName();
            tgi.TagGroupName        = editedNode.NodeGUID.ToString();
            tgi.TagGroupDescription = "";
            tgi.TagGroupSiteID      = SiteContext.CurrentSiteID;
            tgi.TagGroupIsAdHoc     = false;

            // Store tag group info to DB
            TagGroupInfoProvider.SetTagGroupInfo(tgi);

            // Update document Tag group ID
            editedNode.DocumentTagGroupID = tgi.TagGroupID;
            DocumentHelper.UpdateDocument(editedNode, TreeProvider);
        }

        #endregion


        if (!DataHelper.DataSourceIsEmpty(TemplateDocuments))
        {
            // List of selected documents
            string selectedDocs = ";" + Value + ";";

            // Get already created documents under edited document
            DataSet       dsExistingDocs = DocumentHelper.GetDocuments(SiteContext.CurrentSiteName, editedNode.NodeAliasPath + "/%", editedNode.DocumentCulture, true, null, null, null, 1, false, 0, "NodeAlias, " + TreeProvider.SELECTNODES_REQUIRED_COLUMNS, null);
            StringBuilder sbExistDocs    = new StringBuilder();

            // Process existing documents to obtain list of aliases
            foreach (DataRow drExistDoc in dsExistingDocs.Tables[0].Rows)
            {
                sbExistDocs.Append(";");
                sbExistDocs.Append(drExistDoc["NodeAlias"].ToString().ToLowerCSafe());
            }
            sbExistDocs.Append(";");
            string existingDocs = sbExistDocs.ToString();

            // Set same ordering as for original template documents
            bool orgUseAutomaticOrdering = TreeProvider.UseAutomaticOrdering;
            TreeProvider.UseAutomaticOrdering = false;

            int targetClassId = ValidationHelper.GetInteger(editedNode.GetValue("NodeClassID"), 0);

            // Process template documents
            foreach (DataRow drDoc in TemplateDocuments.Tables[0].Rows)
            {
                if (DocumentHelper.IsDocumentTypeAllowed(editedNode, ValidationHelper.GetInteger(drDoc["NodeClassID"], 0)))
                {
                    string nodeAlias     = drDoc["NodeAlias"].ToString().ToLowerCSafe();
                    string contNodeAlias = ";" + nodeAlias + ";";

                    // Set marks
                    bool existing = existingDocs.Contains(contNodeAlias);
                    bool selected = selectedDocs.Contains(contNodeAlias);

                    int      nodeId     = ValidationHelper.GetInteger(drDoc["NodeID"], 0);
                    string   docCulture = ValidationHelper.GetString(drDoc["DocumentCulture"], "");
                    TreeNode srcNode    = DocumentHelper.GetDocument(nodeId, docCulture, editedNode.TreeProvider);

                    // Check if section exists
                    if (srcNode != null)
                    {
                        // Copy or remove marked document sections
                        if (selected)
                        {
                            if (!existing)
                            {
                                CopyDocumentSection(srcNode, editedNode.NodeID, TreeProvider);
                            }
                        }
                        else
                        {
                            if (existing)
                            {
                                // Select node to delete
                                TreeNode delNode = TreeHelper.SelectSingleNode(editedNode.NodeAliasPath + "/" + nodeAlias);
                                if (delNode != null)
                                {
                                    DeleteDocumentSection(delNode, TreeProvider);
                                }
                            }
                        }

                        // Process additional operations
                        if (selected && !existing)
                        {
                            switch (nodeAlias)
                            {
                            // Create department forum
                            case FORUM_DOCUMENT_ALIAS:
                                CreateDepartmentForumGroup(editedNode);
                                CreateDepartmentForumSearchIndex(editedNode);
                                break;

                            // Create media library
                            case MEDIA_DOCUMENT_ALIAS:
                                CreateDepartmentMediaLibrary(editedNode);
                                break;
                            }
                        }
                    }
                }
            }

            // Set previous ordering
            TreeProvider.UseAutomaticOrdering = orgUseAutomaticOrdering;
        }
        mDocumentSaved = true;
    }
Пример #11
0
    protected void menuNew_OnReloadData(object sender, EventArgs e)
    {
        int nodeId = ValidationHelper.GetInteger(menuNew.Parameter, 0);

        // Get the node
        TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
        TreeNode     node = tree.SelectSingleNode(nodeId);

        if (node != null)
        {
            if (CurrentUser.IsAuthorizedToCreateNewDocument(node, null))
            {
                DocumentTypeScopeInfo scope = DocumentTypeScopeInfoProvider.GetScopeInfo(node);
                if (scope != null)
                {
                    plcNewLink.Visible = scope.ScopeAllowLinks;
                }

                pnlSepNewLinkVariant.Visible = plcNewLink.Visible;

                string where = "ClassID IN (SELECT ChildClassID FROM CMS_AllowedChildClasses WHERE ParentClassID=" + ValidationHelper.GetInteger(node.GetValue("NodeClassID"), 0) + ") " +
                               "AND ClassID IN (SELECT ClassID FROM CMS_ClassSite WHERE SiteID = " + SiteContext.CurrentSiteID + ")";

                if (!string.IsNullOrEmpty(DocumentTypeWhere))
                {
                    where = SqlHelper.AddWhereCondition(where, DocumentTypeWhere);
                }

                if (scope != null)
                {
                    // Apply document type scope
                    where = SqlHelper.AddWhereCondition(where, DocumentTypeScopeInfoProvider.GetScopeClassWhereCondition(scope).ToString(true));
                }

                // Get the allowed child classes
                DataSet ds = DocumentTypeHelper.GetDocumentTypeClasses()
                             .Where(where)
                             .OrderBy(DocumentTypeOrderBy)
                             .TopN(50)
                             .Columns("ClassID", "ClassName", "ClassDisplayName");

                var rows = new List <DataRow>();

                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    // Check user permissions for "Create" permission
                    bool hasNodeAllowCreate            = (CurrentUser.IsAuthorizedPerTreeNode(node, NodePermissionsEnum.Create) == AuthorizationResultEnum.Allowed);
                    bool isAuthorizedToCreateInContent = CurrentUser.IsAuthorizedPerResource("CMS.Content", "Create");

                    DataTable resultTable = ds.Tables[0].DefaultView.ToTable();

                    for (int i = 0; i < resultTable.Rows.Count; ++i)
                    {
                        DataRow dr  = resultTable.Rows[i];
                        string  doc = DataHelper.GetStringValue(dr, "ClassName");

                        // Document type is not allowed, remove it from the data set
                        if (!isAuthorizedToCreateInContent && !CurrentUser.IsAuthorizedPerClassName(doc, "Create") && (!CurrentUser.IsAuthorizedPerClassName(doc, "CreateSpecific") || !hasNodeAllowCreate))
                        {
                            rows.Add(dr);
                        }
                    }

                    // Remove the document types
                    foreach (DataRow dr in rows)
                    {
                        resultTable.Rows.Remove(dr);
                    }

                    bool classesRemoved = false;

                    // Leave only first 15 rows
                    while (resultTable.Rows.Count > 15)
                    {
                        resultTable.Rows.RemoveAt(resultTable.Rows.Count - 1);
                        classesRemoved = true;
                    }

                    if (!DataHelper.DataSourceIsEmpty(resultTable))
                    {
                        // Add show more item
                        if (classesRemoved)
                        {
                            DataRow dr = resultTable.NewRow();
                            dr["ClassID"]          = 0;
                            dr["ClassName"]        = "more";
                            dr["ClassDisplayName"] = ResHelper.GetString("class.showmore");
                            resultTable.Rows.InsertAt(dr, resultTable.Rows.Count);
                        }

                        // Create temp column
                        int        rowCount  = resultTable.Rows.Count;
                        DataColumn tmpColumn = new DataColumn("Count");
                        tmpColumn.DefaultValue = rowCount;
                        resultTable.Columns.Add(tmpColumn);

                        repNew.DataSource = resultTable;
                        repNew.DataBind();
                    }
                    else
                    {
                        DisplayErrorMessage(scope != null ? "Content.ScopeApplied" : "Content.NoPermissions");
                    }
                }
                else
                {
                    DisplayErrorMessage(scope != null ? "Content.ScopeApplied" : "NewMenu.NoChildAllowed");
                }
            }
            else
            {
                DisplayErrorMessage("Content.NoPermissions");
            }
        }
    }
Пример #12
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            calItems.StopProcessing = true;
        }
        else
        {
            calItems.ControlContext = repEvent.ControlContext = ControlContext;

            // Calendar properties
            calItems.CacheItemName = CacheItemName;

            calItems.CacheDependencies         = CacheDependencies;
            calItems.CacheMinutes              = CacheMinutes;
            calItems.CheckPermissions          = CheckPermissions;
            calItems.ClassNames                = ClassNames;
            calItems.CombineWithDefaultCulture = CombineWithDefaultCulture;

            calItems.CultureCode         = CultureCode;
            calItems.MaxRelativeLevel    = MaxRelativeLevel;
            calItems.OrderBy             = OrderBy;
            calItems.WhereCondition      = WhereCondition;
            calItems.Columns             = Columns;
            calItems.Path                = Path;
            calItems.SelectOnlyPublished = SelectOnlyPublished;
            calItems.SiteName            = SiteName;
            calItems.FilterName          = FilterName;

            calItems.RelationshipName           = RelationshipName;
            calItems.RelationshipWithNodeGuid   = RelationshipWithNodeGuid;
            calItems.RelatedNodeIsOnTheLeftSide = RelatedNodeIsOnTheLeftSide;

            calItems.TransformationName        = TransformationName;
            calItems.NoEventTransformationName = NoEventTransformationName;

            calItems.DayField             = DayField;
            calItems.EventEndField        = EventEndField;
            calItems.HideDefaultDayNumber = HideDefaultDayNumber;

            calItems.TodaysDate = CMSContext.ConvertDateTime(DateTime.Now, this);

            bool detail = false;

            // If calendar event path is defined event is loaded in accordance to the selected path
            string eventPath = QueryHelper.GetString("CalendarEventPath", null);
            if (!String.IsNullOrEmpty(eventPath))
            {
                detail        = true;
                repEvent.Path = eventPath;

                // Set selected date to specific document
                TreeNode node = TreeHelper.GetDocument(SiteName, eventPath, CultureCode, CombineWithDefaultCulture, ClassNames, SelectOnlyPublished, CheckPermissions, CMSContext.CurrentUser);
                if (node != null)
                {
                    object value = node.GetValue(DayField);
                    if (ValidationHelper.GetDateTime(value, DataHelper.DATETIME_NOT_SELECTED) != DataHelper.DATETIME_NOT_SELECTED)
                    {
                        calItems.TodaysDate = CMSContext.ConvertDateTime((DateTime)value, this);
                    }
                }
            }

            // By default select current event from current document value
            PageInfo currentPage = CMSContext.CurrentPageInfo;
            if ((currentPage != null) && (ClassNames.ToLowerCSafe().Contains(currentPage.ClassName.ToLowerCSafe())))
            {
                detail        = true;
                repEvent.Path = currentPage.NodeAliasPath;

                // Set selected date to current document
                object value = CMSContext.CurrentDocument.GetValue(DayField);
                if (ValidationHelper.GetDateTime(value, DataHelper.DATETIME_NOT_SELECTED) != DataHelper.DATETIME_NOT_SELECTED)
                {
                    calItems.TodaysDate = CMSContext.ConvertDateTime((DateTime)value, this);
                    // Get name of coupled class ID column
                    string idColumn = CMSContext.CurrentDocument.CoupledClassIDColumn;
                    if (!string.IsNullOrEmpty(idColumn))
                    {
                        // Set selected item ID and the ID column name so it is possible to highlight specific event in the calendar
                        calItems.SelectedItemIDColumn = idColumn;
                        calItems.SelectedItemID       = ValidationHelper.GetInteger(CMSContext.CurrentDocument.GetValue(idColumn), 0);
                    }
                }
            }

            if (detail)
            {
                // Setup the detail repeater
                repEvent.Visible        = true;
                repEvent.StopProcessing = false;

                repEvent.SelectedItemTransformationName = EventDetailTransformation;
                repEvent.ClassNames = ClassNames;
                repEvent.Columns    = Columns;

                if (!String.IsNullOrEmpty(CacheItemName))
                {
                    repEvent.CacheItemName = CacheItemName + "|detail";
                }

                repEvent.CacheDependencies         = CacheDependencies;
                repEvent.CacheMinutes              = CacheMinutes;
                repEvent.CheckPermissions          = CheckPermissions;
                repEvent.CombineWithDefaultCulture = CombineWithDefaultCulture;

                repEvent.CultureCode = CultureCode;

                repEvent.SelectOnlyPublished = SelectOnlyPublished;
                repEvent.SiteName            = SiteName;

                repEvent.WhereCondition = WhereCondition;
            }
        }
    }
Пример #13
0
    protected void menuNew_OnReloadData(object sender, EventArgs e)
    {
        int nodeId = ValidationHelper.GetInteger(menuNew.Parameter, 0);

        // Get the node
        TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);
        TreeNode     node = tree.SelectSingleNode(nodeId);

        iNewVariant.Visible = false;

        if (node != null)
        {
            CurrentUserInfo curUser = CMSContext.CurrentUser;
            if (!curUser.IsAuthorizedPerUIElement("CMS.Content", "New"))
            {
                DisplayErrorMessage(String.Format(ResHelper.GetString("CMSSiteManager.AccessDeniedOnUIElementName"), "New"));
                return;
            }

            if (curUser.IsAuthorizedToCreateNewDocument(node, null))
            {
                // Check user permissions for "Create" permission
                bool hasNodeAllowCreate            = (curUser.IsAuthorizedPerTreeNode(node, NodePermissionsEnum.Create) == AuthorizationResultEnum.Allowed);
                bool isAuthorizedToCreateInContent = curUser.IsAuthorizedPerResource("CMS.Content", "Create");

                // AB test variant settings
                if (SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSABTestingEnabled") &&
                    curUser.IsAuthorizedPerResource("cms.ABTest", "Read") &&
                    ModuleEntry.IsModuleLoaded("cms.onlinemarketing") &&
                    ResourceSiteInfoProvider.IsResourceOnSite("CMS.ABTest", CMSContext.CurrentSiteName) &&
                    LicenseHelper.CheckFeature(URLHelper.GetCurrentDomain(), FeatureEnum.ABTesting) &&
                    (node.NodeAliasPath != "/"))
                {
                    if (isAuthorizedToCreateInContent || curUser.IsAuthorizedPerClassName(node.NodeClassName, "Create") || (curUser.IsAuthorizedPerClassName(node.NodeClassName, "CreateSpecific") && hasNodeAllowCreate))
                    {
                        iNewVariant.Visible = true;
                        if (!iNewLink.Visible)
                        {
                            pnlNewVariantSeparator.Visible = true;
                        }
                    }
                }

                string where = "ClassID IN (SELECT ChildClassID FROM CMS_AllowedChildClasses WHERE ParentClassID=" + ValidationHelper.GetInteger(node.GetValue("NodeClassID"), 0) + ") " +
                               "AND ClassID IN (SELECT ClassID FROM CMS_ClassSite WHERE SiteID = " + CMSContext.CurrentSiteID + ")";

                if (!string.IsNullOrEmpty(DocumentTypeWhere))
                {
                    where = SqlHelperClass.AddWhereCondition(where, DocumentTypeWhere);
                }

                // Get the allowed child classes
                DataSet ds = DataClassInfoProvider.GetClasses("ClassID, ClassName, ClassDisplayName, (CASE WHEN (ClassName = 'CMS.MenuItem' OR ClassName = 'CMS.Wireframe')  THEN 0 ELSE 1 END) AS MenuItemOrder", where, DocumentTypeOrderBy, 50);

                DataTable resultTable = null;
                ArrayList rows        = new ArrayList();

                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    resultTable = ds.Tables[0].DefaultView.ToTable();

                    for (int i = 0; i < resultTable.Rows.Count; ++i)
                    {
                        DataRow dr  = resultTable.Rows[i];
                        string  doc = ValidationHelper.GetString(DataHelper.GetDataRowValue(dr, "ClassName"), "");

                        // Document type is not allowed, remove it from the data set
                        if (!isAuthorizedToCreateInContent && !curUser.IsAuthorizedPerClassName(doc, "Create") && (!curUser.IsAuthorizedPerClassName(doc, "CreateSpecific") || !hasNodeAllowCreate))
                        {
                            rows.Add(dr);
                        }
                        else if (doc.EqualsCSafe("cms.wireframe", true) && !curUser.IsAuthorizedPerResource("CMS.Design", "Wireframing"))
                        {
                            rows.Add(dr);
                        }
                    }

                    // Remove the document types
                    foreach (DataRow dr in rows)
                    {
                        resultTable.Rows.Remove(dr);
                    }

                    bool classesRemoved = false;

                    // Leave only first 15 rows
                    while (resultTable.Rows.Count > 15)
                    {
                        resultTable.Rows.RemoveAt(resultTable.Rows.Count - 1);
                        classesRemoved = true;
                    }

                    if (!DataHelper.DataSourceIsEmpty(resultTable))
                    {
                        // Add show more item
                        if (classesRemoved)
                        {
                            DataRow dr = resultTable.NewRow();
                            dr["ClassID"]          = 0;
                            dr["ClassName"]        = "more";
                            dr["ClassDisplayName"] = ResHelper.GetString("class.showmore");
                            resultTable.Rows.InsertAt(dr, resultTable.Rows.Count);
                        }

                        // Create temp column
                        int        rowCount  = resultTable.Rows.Count;
                        DataColumn tmpColumn = new DataColumn("Count");
                        tmpColumn.DefaultValue = rowCount;
                        resultTable.Columns.Add(tmpColumn);
                    }
                    else
                    {
                        DisplayErrorMessage("Content.NoPermissions");
                    }
                }
                else
                {
                    pnlNewVariantSeparator.Visible = true;
                    DisplayErrorMessage("NewMenu.NoChildAllowed");
                }

                repNew.DataSource = resultTable;
                repNew.DataBind();

                if (DataHelper.DataSourceIsEmpty(ds))
                {
                    DisplayErrorMessage("NewMenu.NoChildAllowed");
                }
            }
            else
            {
                DisplayErrorMessage("Content.NoPermissions");
            }
        }
    }
Пример #14
0
    /// <summary>
    /// Adds the field to the form.
    /// </summary>
    /// <param name="node">Document node</param>
    /// <param name="compareNode">Document compare node</param>
    /// <param name="columnName">Column name</param>
    private void AddField(TreeNode node, TreeNode compareNode, string columnName)
    {
        FormFieldInfo ffi = null;

        if (fi != null)
        {
            ffi = fi.GetFormField(columnName);
        }

        TableCell valueCell = new TableCell();

        valueCell.EnableViewState = false;
        TableCell valueCompare = new TableCell();

        valueCompare.EnableViewState = false;
        TableCell labelCell = new TableCell();

        labelCell.EnableViewState = false;
        TextComparison comparefirst  = null;
        TextComparison comparesecond = null;
        bool           switchSides   = true;
        bool           loadValue     = true;
        bool           empty         = true;
        bool           allowLabel    = true;

        // Get the caption
        if ((columnName == UNSORTED) || (ffi != null))
        {
            AttachmentInfo aiCompare = null;

            // Compare attachments
            if ((columnName == UNSORTED) || (ffi.DataType == FormFieldDataTypeEnum.DocumentAttachments))
            {
                allowLabel = false;

                string title = null;
                if (columnName == UNSORTED)
                {
                    title = GetString("attach.unsorted") + ":";
                }
                else
                {
                    title = (String.IsNullOrEmpty(ffi.Caption) ? ffi.Name : ffi.Caption) + ":";
                }

                // Prepare DataSource for original node
                loadValue = false;

                dsAttachments = new AttachmentsDataSource();
                dsAttachments.DocumentVersionHistoryID = versionHistoryId;
                if (columnName != UNSORTED)
                {
                    dsAttachments.AttachmentGroupGUID = ffi.Guid;
                }
                dsAttachments.Path        = node.NodeAliasPath;
                dsAttachments.CultureCode = CMSContext.PreferredCultureCode;
                SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID);
                dsAttachments.SiteName        = si.SiteName;
                dsAttachments.OrderBy         = "AttachmentOrder, AttachmentName, AttachmentHistoryID";
                dsAttachments.SelectedColumns = "AttachmentHistoryID, AttachmentGUID, AttachmentImageWidth, AttachmentImageHeight, AttachmentExtension, AttachmentName, AttachmentSize, AttachmentOrder, AttachmentTitle, AttachmentDescription";
                dsAttachments.IsLiveSite      = false;
                dsAttachments.DataSource      = null;
                dsAttachments.DataBind();

                // Get the attachments table
                attachments = GetAttachmentsTable((DataSet)dsAttachments.DataSource, versionHistoryId, node.DocumentID);

                // Prepare datasource for compared node
                if (compareNode != null)
                {
                    dsAttachmentsCompare = new AttachmentsDataSource();
                    dsAttachmentsCompare.DocumentVersionHistoryID = versionCompare;
                    if (columnName != UNSORTED)
                    {
                        dsAttachmentsCompare.AttachmentGroupGUID = ffi.Guid;
                    }
                    dsAttachmentsCompare.Path            = compareNode.NodeAliasPath;
                    dsAttachmentsCompare.CultureCode     = CMSContext.PreferredCultureCode;
                    dsAttachmentsCompare.SiteName        = si.SiteName;
                    dsAttachmentsCompare.OrderBy         = "AttachmentOrder, AttachmentName, AttachmentHistoryID";
                    dsAttachmentsCompare.SelectedColumns = "AttachmentHistoryID, AttachmentGUID, AttachmentImageWidth, AttachmentImageHeight, AttachmentExtension, AttachmentName, AttachmentSize, AttachmentOrder, AttachmentTitle, AttachmentDescription";
                    dsAttachmentsCompare.IsLiveSite      = false;
                    dsAttachmentsCompare.DataSource      = null;
                    dsAttachmentsCompare.DataBind();

                    // Get the table to compare
                    attachmentsCompare = GetAttachmentsTable((DataSet)dsAttachmentsCompare.DataSource, versionCompare, node.DocumentID);

                    // Switch the sides if older version is on the right
                    if (versionHistoryId > versionCompare)
                    {
                        Hashtable dummy = attachmentsCompare;
                        attachmentsCompare = attachments;
                        attachments        = dummy;
                    }

                    // Add comparison
                    AddTableComparison(attachments, attachmentsCompare, "<strong>" + title + "</strong>", true, true);
                }
                else
                {
                    // Normal display
                    if (attachments.Count != 0)
                    {
                        bool first = true;

                        foreach (DictionaryEntry item in attachments)
                        {
                            string itemValue = ValidationHelper.GetString(item.Value, null);
                            if (!String.IsNullOrEmpty(itemValue))
                            {
                                valueCell = new TableCell();
                                labelCell = new TableCell();

                                if (first)
                                {
                                    labelCell.Text = "<strong>" + String.Format(title, item.Key) + "</strong>";
                                    first          = false;
                                }
                                valueCell.Text = itemValue;

                                AddRow(labelCell, valueCell, null, even);
                                even = !even;
                            }
                        }
                    }
                }
            }
            // Compare single file attachment
            else if (ffi.DataType == FormFieldDataTypeEnum.File)
            {
                // Get the attachment
                AttachmentInfo ai = DocumentHelper.GetAttachment(ValidationHelper.GetGuid(node.GetValue(columnName), Guid.Empty), versionHistoryId, TreeProvider, false);

                if (compareNode != null)
                {
                    aiCompare = DocumentHelper.GetAttachment(ValidationHelper.GetGuid(compareNode.GetValue(columnName), Guid.Empty), versionCompare, TreeProvider, false);
                }

                loadValue = false;
                empty     = true;

                // Prepare text comparison controls
                if ((ai != null) || (aiCompare != null))
                {
                    string textorig = null;
                    if (ai != null)
                    {
                        textorig = CreateAttachment(ai.Generalized.DataClass, versionHistoryId);
                    }
                    string textcompare = null;
                    if (aiCompare != null)
                    {
                        textcompare = CreateAttachment(aiCompare.Generalized.DataClass, versionCompare);
                    }

                    comparefirst = new TextComparison();
                    comparefirst.SynchronizedScrolling = false;
                    comparefirst.IgnoreHTMLTags        = true;
                    comparefirst.ConsiderHTMLTagsEqual = true;
                    comparefirst.BalanceContent        = false;

                    comparesecond = new TextComparison();
                    comparesecond.SynchronizedScrolling = false;
                    comparesecond.IgnoreHTMLTags        = true;

                    // Source text must be older version
                    if (versionHistoryId < versionCompare)
                    {
                        comparefirst.SourceText      = textorig;
                        comparefirst.DestinationText = textcompare;
                    }
                    else
                    {
                        comparefirst.SourceText      = textcompare;
                        comparefirst.DestinationText = textorig;
                    }

                    comparefirst.PairedControl  = comparesecond;
                    comparesecond.RenderingMode = TextComparisonTypeEnum.DestinationText;

                    valueCell.Controls.Add(comparefirst);
                    valueCompare.Controls.Add(comparesecond);
                    switchSides = false;

                    // Add both cells
                    if (compareNode != null)
                    {
                        AddRow(labelCell, valueCell, valueCompare, switchSides, null, even);
                    }
                    // Add one cell only
                    else
                    {
                        valueCell.Controls.Clear();
                        Literal ltl = new Literal();
                        ltl.Text = textorig;
                        valueCell.Controls.Add(ltl);
                        AddRow(labelCell, valueCell, null, even);
                    }
                    even = !even;
                }
            }
        }

        if (allowLabel && (labelCell.Text == ""))
        {
            labelCell.Text = "<strong>" + columnName + ":</strong>";
        }

        if (loadValue)
        {
            string textcompare = null;

            switch (columnName.ToLowerCSafe())
            {
            // Document content - display content of editable regions and editable web parts
            case "documentcontent":
                EditableItems ei = new EditableItems();
                ei.LoadContentXml(ValidationHelper.GetString(node.GetValue(columnName), ""));

                // Add text comparison control
                if (compareNode != null)
                {
                    EditableItems eiCompare = new EditableItems();
                    eiCompare.LoadContentXml(ValidationHelper.GetString(compareNode.GetValue(columnName), ""));

                    // Create editable regions comparison
                    Hashtable hashtable;
                    Hashtable hashtableCompare;

                    // Source text must be older version
                    if (versionHistoryId < versionCompare)
                    {
                        hashtable        = ei.EditableRegions;
                        hashtableCompare = eiCompare.EditableRegions;
                    }
                    else
                    {
                        hashtable        = eiCompare.EditableRegions;
                        hashtableCompare = ei.EditableRegions;
                    }

                    // Add comparison
                    AddTableComparison(hashtable, hashtableCompare, "<strong>" + columnName + " ({0}):</strong>", false, false);

                    // Create editable webparts comparison
                    // Source text must be older version
                    if (versionHistoryId < versionCompare)
                    {
                        hashtable        = ei.EditableWebParts;
                        hashtableCompare = eiCompare.EditableWebParts;
                    }
                    else
                    {
                        hashtable        = eiCompare.EditableWebParts;
                        hashtableCompare = ei.EditableWebParts;
                    }

                    // Add comparison
                    AddTableComparison(hashtable, hashtableCompare, "<strong>" + columnName + " ({0}):</strong>", false, false);
                }
                // No compare node
                else
                {
                    // Editable regions
                    Hashtable hashtable = ei.EditableRegions;
                    if (hashtable.Count != 0)
                    {
                        foreach (DictionaryEntry region in hashtable)
                        {
                            string regionValue = ValidationHelper.GetString(region.Value, null);
                            if (!String.IsNullOrEmpty(regionValue))
                            {
                                string regionKey = ValidationHelper.GetString(region.Key, null);

                                valueCell = new TableCell();
                                labelCell = new TableCell();

                                labelCell.Text = "<strong>" + columnName + " (" + DictionaryHelper.GetFirstKey(regionKey) + "):</strong>";
                                valueCell.Text = HttpUtility.HtmlDecode(HTMLHelper.StripTags(regionValue, false));

                                AddRow(labelCell, valueCell, null, even);
                                even = !even;
                            }
                        }
                    }

                    // Editable web parts
                    hashtable = ei.EditableWebParts;
                    if (hashtable.Count != 0)
                    {
                        foreach (DictionaryEntry part in hashtable)
                        {
                            string partValue = ValidationHelper.GetString(part.Value, null);
                            if (!String.IsNullOrEmpty(partValue))
                            {
                                string partKey = ValidationHelper.GetString(part.Key, null);
                                valueCell = new TableCell();
                                labelCell = new TableCell();

                                labelCell.Text = "<strong>" + columnName + " (" + DictionaryHelper.GetFirstKey(partKey) + "):</strong>";
                                valueCell.Text = HttpUtility.HtmlDecode(HTMLHelper.StripTags(partValue, false));

                                AddRow(labelCell, valueCell, null, even);
                                even = !even;
                            }
                        }
                    }
                }

                break;

            // Others, display the string value
            default:
                // Shift date time values to user time zone
                object origobject = node.GetValue(columnName);
                string textorig   = null;
                if (origobject is DateTime)
                {
                    TimeZoneInfo usedTimeZone = null;
                    textorig = TimeZoneHelper.GetCurrentTimeZoneDateTimeString(ValidationHelper.GetDateTime(origobject, DateTimeHelper.ZERO_TIME), CurrentUser, CMSContext.CurrentSite, out usedTimeZone);
                }
                else
                {
                    textorig = ValidationHelper.GetString(origobject, "");
                }

                // Add text comparison control
                if (compareNode != null)
                {
                    // Shift date time values to user time zone
                    object compareobject = compareNode.GetValue(columnName);
                    if (compareobject is DateTime)
                    {
                        TimeZoneInfo usedTimeZone = null;
                        textcompare = TimeZoneHelper.GetCurrentTimeZoneDateTimeString(ValidationHelper.GetDateTime(compareobject, DateTimeHelper.ZERO_TIME), CurrentUser, CMSContext.CurrentSite, out usedTimeZone);
                    }
                    else
                    {
                        textcompare = ValidationHelper.GetString(compareobject, "");
                    }

                    comparefirst = new TextComparison();
                    comparefirst.SynchronizedScrolling = false;

                    comparesecond = new TextComparison();
                    comparesecond.SynchronizedScrolling = false;
                    comparesecond.RenderingMode         = TextComparisonTypeEnum.DestinationText;

                    // Source text must be older version
                    if (versionHistoryId < versionCompare)
                    {
                        comparefirst.SourceText      = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textorig, false));
                        comparefirst.DestinationText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textcompare, false));
                    }
                    else
                    {
                        comparefirst.SourceText      = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textcompare, false));
                        comparefirst.DestinationText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textorig, false));
                    }

                    comparefirst.PairedControl = comparesecond;

                    if (Math.Max(comparefirst.SourceText.Length, comparefirst.DestinationText.Length) < 100)
                    {
                        comparefirst.BalanceContent = false;
                    }

                    valueCell.Controls.Add(comparefirst);
                    valueCompare.Controls.Add(comparesecond);
                    switchSides = false;
                }
                else
                {
                    valueCell.Text = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textorig, false));
                }

                empty = (String.IsNullOrEmpty(textorig)) && (String.IsNullOrEmpty(textcompare));
                break;
            }
        }

        if (!empty)
        {
            if (compareNode != null)
            {
                AddRow(labelCell, valueCell, valueCompare, switchSides, null, even);
                even = !even;
            }
            else
            {
                AddRow(labelCell, valueCell, null, even);
                even = !even;
            }
        }
    }
Пример #15
0
    private void RemoveWorkflow(object parameter)
    {
        VersionManager verMan = VersionManager.GetInstance(Tree);
        TreeNode       node   = null;

        // Custom logging
        Tree.LogEvents         = false;
        Tree.AllowAsyncActions = false;
        CanceledString         = ResHelper.GetString("workflowdocuments.removingcanceled", currentCulture);
        try
        {
            // Begin log
            AddLog(ResHelper.GetString("content.preparingdocuments", currentCulture));

            string where = parameter as string;

            // Get the documents
            DataSet documents = GetDocumentsToProcess(where);

            if (!DataHelper.DataSourceIsEmpty(documents))
            {
                // Begin log
                AddLog(ResHelper.GetString("workflowdocuments.removingwf", currentCulture));

                foreach (DataTable classTable in documents.Tables)
                {
                    foreach (DataRow nodeRow in classTable.Rows)
                    {
                        // Get the current document
                        string className  = ValidationHelper.GetString(nodeRow["ClassName"], string.Empty);
                        string aliasPath  = ValidationHelper.GetString(nodeRow["NodeAliasPath"], string.Empty);
                        string docCulture = ValidationHelper.GetString(nodeRow["DocumentCulture"], string.Empty);
                        string siteName   = ValidationHelper.GetString(nodeRow["SiteName"], string.Empty);

                        // Get published version
                        node = Tree.SelectSingleNode(siteName, aliasPath, docCulture, false, className, false);
                        string encodedAliasPath = HTMLHelper.HTMLEncode(ValidationHelper.GetString(aliasPath, string.Empty) + " (" + node.GetValue("DocumentCulture") + ")");

                        // Destroy document history
                        verMan.DestroyDocumentHistory(node.DocumentID);

                        // Clear workflow
                        DocumentHelper.ClearWorkflowInformation(node);
                        node.Update();

                        // Add log record
                        AddLog(encodedAliasPath);

                        // Add record to eventlog
                        LogContext.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "Content", "REMOVEDOCWORKFLOW", currentUser.UserID,
                                            currentUser.UserName, node.NodeID, node.GetDocumentName(),
                                            HTTPHelper.UserHostAddress, string.Format(GetString("workflowdocuments.removeworkflowsuccess"), encodedAliasPath),
                                            node.NodeSiteID, HTTPHelper.GetAbsoluteUri(), HTTPHelper.MachineName, HTTPHelper.GetUrlReferrer(), HTTPHelper.GetUserAgent());
                    }
                }
                CurrentInfo = GetString("workflowdocuments.removecomplete");
            }
            else
            {
                AddError(ResHelper.GetString("workflowdocuments.nodocumentstoclear", currentCulture));
            }
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state == CMSThread.ABORT_REASON_STOP)
            {
                // When canceled
                CurrentInfo = CanceledString;
            }
            else
            {
                int siteId = (node != null) ? node.NodeSiteID : CMSContext.CurrentSiteID;
                // Log error
                LogExceptionToEventLog("REMOVEDOCWORKFLOW", "workflowdocuments.removefailed", ex, siteId);
            }
        }
        catch (Exception ex)
        {
            int siteId = (node != null) ? node.NodeSiteID : CMSContext.CurrentSiteID;
            // Log error
            LogExceptionToEventLog("REMOVEDOCWORKFLOW", "workflowdocuments.removefailed", ex, siteId);
        }
    }
    /// <summary>
    /// Adds the field to the form.
    /// </summary>
    /// <param name="node">Document node</param>
    /// <param name="compareNode">Document compare node</param>
    /// <param name="columnName">Column name</param>
    private void AddField(TreeNode node, TreeNode compareNode, string columnName)
    {
        FormFieldInfo ffi = null;
        if (fi != null)
        {
            ffi = fi.GetFormField(columnName);
        }

        TableCell valueCell = new TableCell();
        valueCell.EnableViewState = false;
        TableCell valueCompare = new TableCell();
        valueCompare.EnableViewState = false;
        TableCell labelCell = new TableCell();
        labelCell.EnableViewState = false;
        TextComparison comparefirst;
        TextComparison comparesecond;
        bool loadValue = true;
        bool empty = true;
        bool allowLabel = true;

        // Get the caption
        if ((columnName == UNSORTED) || (ffi != null))
        {
            AttachmentInfo aiCompare = null;

            // Compare attachments
            if ((columnName == UNSORTED) || ((ffi != null) && (ffi.DataType == FieldDataType.DocAttachments)))
            {
                allowLabel = false;

                string title = String.Empty;
                if (columnName == UNSORTED)
                {
                    title = GetString("attach.unsorted") + ":";
                }
                else if (ffi != null)
                {
                    string caption = ffi.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, MacroContext.CurrentResolver);
                    title = (String.IsNullOrEmpty(caption) ? ffi.Name : caption) + ":";
                }

                // Prepare DataSource for original node
                loadValue = false;

                dsAttachments = new AttachmentsDataSource();
                dsAttachments.DocumentVersionHistoryID = versionHistoryId;
                if ((ffi != null) && (columnName != UNSORTED))
                {
                    dsAttachments.AttachmentGroupGUID = ffi.Guid;
                }
                dsAttachments.Path = node.NodeAliasPath;
                dsAttachments.CultureCode = LocalizationContext.PreferredCultureCode;
                SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID);
                dsAttachments.SiteName = si.SiteName;
                dsAttachments.OrderBy = "AttachmentOrder, AttachmentName, AttachmentHistoryID";
                dsAttachments.SelectedColumns = "AttachmentHistoryID, AttachmentGUID, AttachmentImageWidth, AttachmentImageHeight, AttachmentExtension, AttachmentName, AttachmentSize, AttachmentOrder, AttachmentTitle, AttachmentDescription";
                dsAttachments.IsLiveSite = false;
                dsAttachments.DataSource = null;
                dsAttachments.DataBind();

                // Get the attachments table
                attachments = GetAttachmentsTable((DataSet)dsAttachments.DataSource, versionHistoryId, node.DocumentID);

                // Prepare data source for compared node
                if (compareNode != null)
                {
                    dsAttachmentsCompare = new AttachmentsDataSource();
                    dsAttachmentsCompare.DocumentVersionHistoryID = versionCompare;
                    if ((ffi != null) && (columnName != UNSORTED))
                    {
                        dsAttachmentsCompare.AttachmentGroupGUID = ffi.Guid;
                    }
                    dsAttachmentsCompare.Path = compareNode.NodeAliasPath;
                    dsAttachmentsCompare.CultureCode = LocalizationContext.PreferredCultureCode;
                    dsAttachmentsCompare.SiteName = si.SiteName;
                    dsAttachmentsCompare.OrderBy = "AttachmentOrder, AttachmentName, AttachmentHistoryID";
                    dsAttachmentsCompare.SelectedColumns = "AttachmentHistoryID, AttachmentGUID, AttachmentImageWidth, AttachmentImageHeight, AttachmentExtension, AttachmentName, AttachmentSize, AttachmentOrder, AttachmentTitle, AttachmentDescription";
                    dsAttachmentsCompare.IsLiveSite = false;
                    dsAttachmentsCompare.DataSource = null;
                    dsAttachmentsCompare.DataBind();

                    // Get the table to compare
                    attachmentsCompare = GetAttachmentsTable((DataSet)dsAttachmentsCompare.DataSource, versionCompare, node.DocumentID);

                    // Switch the sides if older version is on the right
                    if (versionHistoryId > versionCompare)
                    {
                        Hashtable dummy = attachmentsCompare;
                        attachmentsCompare = attachments;
                        attachments = dummy;
                    }

                    // Add comparison
                    AddTableComparison(attachments, attachmentsCompare, "<strong>" + title + "</strong>", true, true);
                }
                else
                {
                    // Normal display
                    if (attachments.Count != 0)
                    {
                        bool first = true;

                        foreach (DictionaryEntry item in attachments)
                        {
                            string itemValue = ValidationHelper.GetString(item.Value, null);
                            if (!String.IsNullOrEmpty(itemValue))
                            {
                                valueCell = new TableCell();
                                labelCell = new TableCell();

                                if (first)
                                {
                                    labelCell.Text = "<strong>" + String.Format(title, item.Key) + "</strong>";
                                    first = false;
                                }
                                valueCell.Text = itemValue;

                                AddRow(labelCell, valueCell);
                            }
                        }
                    }
                }
            }
            // Compare single file attachment
            else if ((ffi != null) && (ffi.DataType == FieldDataType.File))
            {
                // Get the attachment
                AttachmentInfo ai = DocumentHelper.GetAttachment(ValidationHelper.GetGuid(node.GetValue(columnName), Guid.Empty), versionHistoryId, TreeProvider, false);

                if (compareNode != null)
                {
                    aiCompare = DocumentHelper.GetAttachment(ValidationHelper.GetGuid(compareNode.GetValue(columnName), Guid.Empty), versionCompare, TreeProvider, false);
                }

                loadValue = false;

                // Prepare text comparison controls
                if ((ai != null) || (aiCompare != null))
                {
                    string textorig = null;
                    if (ai != null)
                    {
                        textorig = CreateAttachment(ai.Generalized.DataClass, versionHistoryId);
                    }
                    string textcompare = null;
                    if (aiCompare != null)
                    {
                        textcompare = CreateAttachment(aiCompare.Generalized.DataClass, versionCompare);
                    }

                    comparefirst = new TextComparison();
                    comparefirst.SynchronizedScrolling = false;
                    comparefirst.IgnoreHTMLTags = true;
                    comparefirst.ConsiderHTMLTagsEqual = true;
                    comparefirst.BalanceContent = false;

                    comparesecond = new TextComparison();
                    comparesecond.SynchronizedScrolling = false;
                    comparesecond.IgnoreHTMLTags = true;

                    // Source text must be older version
                    if (versionHistoryId < versionCompare)
                    {
                        comparefirst.SourceText = textorig;
                        comparefirst.DestinationText = textcompare;
                    }
                    else
                    {
                        comparefirst.SourceText = textcompare;
                        comparefirst.DestinationText = textorig;
                    }

                    comparefirst.PairedControl = comparesecond;
                    comparesecond.RenderingMode = TextComparisonTypeEnum.DestinationText;

                    valueCell.Controls.Add(comparefirst);
                    valueCompare.Controls.Add(comparesecond);

                    // Add both cells
                    if (compareNode != null)
                    {
                        AddRow(labelCell, valueCell, valueCompare);
                    }
                    // Add one cell only
                    else
                    {
                        valueCell.Controls.Clear();
                        Literal ltl = new Literal();
                        ltl.Text = textorig;
                        valueCell.Controls.Add(ltl);
                        AddRow(labelCell, valueCell);
                    }
                }
            }
        }

        if (allowLabel && String.IsNullOrEmpty(labelCell.Text))
        {
            labelCell.Text = "<strong>" + columnName + ":</strong>";
        }

        if (loadValue)
        {
            string textcompare = null;

            switch (columnName.ToLowerCSafe())
            {
                // Document content - display content of editable regions and editable web parts
                case "documentcontent":
                    EditableItems ei = new EditableItems();
                    ei.LoadContentXml(ValidationHelper.GetString(node.GetValue(columnName), String.Empty));

                    // Add text comparison control
                    if (compareNode != null)
                    {
                        EditableItems eiCompare = new EditableItems();
                        eiCompare.LoadContentXml(ValidationHelper.GetString(compareNode.GetValue(columnName), String.Empty));

                        // Create editable regions comparison
                        Hashtable hashtable;
                        Hashtable hashtableCompare;

                        // Source text must be older version
                        if (versionHistoryId < versionCompare)
                        {
                            hashtable = ei.EditableRegions;
                            hashtableCompare = eiCompare.EditableRegions;
                        }
                        else
                        {
                            hashtable = eiCompare.EditableRegions;
                            hashtableCompare = ei.EditableRegions;
                        }

                        // Add comparison
                        AddTableComparison(hashtable, hashtableCompare, "<strong>" + columnName + " ({0}):</strong>", false, false);

                        // Create editable webparts comparison
                        // Source text must be older version
                        if (versionHistoryId < versionCompare)
                        {
                            hashtable = ei.EditableWebParts;
                            hashtableCompare = eiCompare.EditableWebParts;
                        }
                        else
                        {
                            hashtable = eiCompare.EditableWebParts;
                            hashtableCompare = ei.EditableWebParts;
                        }

                        // Add comparison
                        AddTableComparison(hashtable, hashtableCompare, "<strong>" + columnName + " ({0}):</strong>", false, false);
                    }
                    // No compare node
                    else
                    {
                        // Editable regions
                        Hashtable hashtable = ei.EditableRegions;
                        if (hashtable.Count != 0)
                        {
                            foreach (DictionaryEntry region in hashtable)
                            {
                                string regionValue = ValidationHelper.GetString(region.Value, null);
                                if (!String.IsNullOrEmpty(regionValue))
                                {
                                    string regionKey = ValidationHelper.GetString(region.Key, null);

                                    valueCell = new TableCell();
                                    labelCell = new TableCell();

                                    labelCell.Text = "<strong>" + columnName + " (" + DictionaryHelper.GetFirstKey(regionKey) + "):</strong>";
                                    valueCell.Text = HttpUtility.HtmlDecode(HTMLHelper.StripTags(regionValue, false));

                                    AddRow(labelCell, valueCell);
                                }
                            }
                        }

                        // Editable web parts
                        hashtable = ei.EditableWebParts;
                        if (hashtable.Count != 0)
                        {
                            foreach (DictionaryEntry part in hashtable)
                            {
                                string partValue = ValidationHelper.GetString(part.Value, null);
                                if (!String.IsNullOrEmpty(partValue))
                                {
                                    string partKey = ValidationHelper.GetString(part.Key, null);
                                    valueCell = new TableCell();
                                    labelCell = new TableCell();

                                    labelCell.Text = "<strong>" + columnName + " (" + DictionaryHelper.GetFirstKey(partKey) + "):</strong>";
                                    valueCell.Text = HttpUtility.HtmlDecode(HTMLHelper.StripTags(partValue, false));

                                    AddRow(labelCell, valueCell);
                                }
                            }
                        }
                    }

                    break;

                case "documentwebparts":
                    StringBuilder sbOriginal = new StringBuilder();
                    StringBuilder sbCompared = new StringBuilder();

                    // Set original web parts
                    string originalWebParts = Convert.ToString(node.GetValue(columnName));
                    GenerateWebPartsMarkup(ref sbOriginal, originalWebParts, true);

                    // Add text comparison control
                    if (compareNode != null)
                    {
                        string compareWebParts = Convert.ToString(compareNode.GetValue(columnName));
                        GenerateWebPartsMarkup(ref sbCompared, compareWebParts, false);
                    }

                    // Set empty flag
                    empty = ((sbOriginal.Length == 0) && (sbCompared.Length == 0));

                    if (!empty)
                    {
                        valueCell.Text += sbOriginal.ToString();
                        valueCompare.Text = sbCompared.ToString();
                    }
                    break;

                // Others, display the string value
                default:
                    // Shift date time values to user time zone
                    object origobject = node.GetValue(columnName);
                    string textorig;
                    if (origobject is DateTime)
                    {
                        textorig = TimeZoneHelper.ConvertToUserTimeZone(ValidationHelper.GetDateTime(origobject, DateTimeHelper.ZERO_TIME), true, CurrentUser, SiteContext.CurrentSite);
                    }
                    else
                    {
                        textorig = ValidationHelper.GetString(origobject, String.Empty);
                    }

                    // Add text comparison control
                    if (compareNode != null)
                    {
                        // Shift date time values to user time zone
                        object compareobject = compareNode.GetValue(columnName);
                        if (compareobject is DateTime)
                        {
                            textcompare = TimeZoneHelper.ConvertToUserTimeZone(ValidationHelper.GetDateTime(compareobject, DateTimeHelper.ZERO_TIME), true, CurrentUser, SiteContext.CurrentSite);
                        }
                        else
                        {
                            textcompare = ValidationHelper.GetString(compareobject, String.Empty);
                        }

                        comparefirst = new TextComparison();
                        comparefirst.SynchronizedScrolling = false;

                        comparesecond = new TextComparison();
                        comparesecond.SynchronizedScrolling = false;
                        comparesecond.RenderingMode = TextComparisonTypeEnum.DestinationText;

                        // Source text must be older version
                        if (versionHistoryId < versionCompare)
                        {
                            comparefirst.SourceText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textorig, false));
                            comparefirst.DestinationText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textcompare, false));
                        }
                        else
                        {
                            comparefirst.SourceText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textcompare, false));
                            comparefirst.DestinationText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textorig, false));
                        }

                        comparefirst.PairedControl = comparesecond;

                        if (Math.Max(comparefirst.SourceText.Length, comparefirst.DestinationText.Length) < 100)
                        {
                            comparefirst.BalanceContent = false;
                        }

                        valueCell.Controls.Add(comparefirst);
                        valueCompare.Controls.Add(comparesecond);
                    }
                    else
                    {
                        valueCell.Text = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textorig, false));
                    }

                    empty = (String.IsNullOrEmpty(textorig)) && (String.IsNullOrEmpty(textcompare));
                    break;
            }
        }

        if (!empty)
        {
            if (compareNode != null)
            {
                AddRow(labelCell, valueCell, valueCompare);
            }
            else
            {
                AddRow(labelCell, valueCell);
            }
        }
    }
Пример #17
0
    protected void libraryMenuElem_OnReloadData(object sender, EventArgs e)
    {
        string[] parameters = (libraryMenuElem.Parameter ?? string.Empty).Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
        if (parameters.Length == 2)
        {
            // Parse identifier and document culture from library parameter
            int    nodeId      = ValidationHelper.GetInteger(parameters[0], 0);
            string cultureCode = ValidationHelper.GetString(parameters[1], string.Empty);
            DocumentManager.Mode = FormModeEnum.Update;
            DocumentManager.ClearNode();
            DocumentManager.DocumentID  = 0;
            DocumentManager.NodeID      = nodeId;
            DocumentManager.CultureCode = cultureCode;
            TreeNode node = DocumentManager.Node;

            bool contextMenuVisible    = false;
            bool localizeVisible       = false;
            bool editVisible           = false;
            bool uploadVisible         = false;
            bool copyVisible           = false;
            bool deleteVisible         = false;
            bool openVisible           = false;
            bool propertiesVisible     = false;
            bool permissionsVisible    = false;
            bool versionHistoryVisible = false;

            bool checkOutVisible         = false;
            bool checkInVisible          = false;
            bool undoCheckoutVisible     = false;
            bool submitToApprovalVisible = false;
            bool rejectVisible           = false;
            bool archiveVisible          = false;

            if ((node != null) && (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Allowed))
            {
                // Get original node (in case of linked documents)
                TreeNode originalNode = TreeProvider.GetOriginalNode(node);

                string documentType           = ValidationHelper.GetString(node.GetValue("DocumentType"), string.Empty);
                string siteName               = CMSContext.CurrentSiteName;
                string currentDocumentCulture = CMSContext.CurrentDocumentCulture.CultureCode;

                if (CMSContext.CurrentSiteID != originalNode.NodeSiteID)
                {
                    SiteInfo si = SiteInfoProvider.GetSiteInfo(originalNode.NodeSiteID);
                    siteName = si.SiteName;
                }

                if (!DocumentManager.ProcessingAction)
                {
                    // Get permissions
                    const bool authorizedToRead              = true;
                    bool       authorizedToDelete            = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Delete) == AuthorizationResultEnum.Allowed);
                    bool       authorizedToModify            = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed);
                    bool       authorizedCultureToModify     = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify, false) == AuthorizationResultEnum.Allowed) && TreeSecurityProvider.HasUserCultureAllowed(NodePermissionsEnum.Modify, currentDocumentCulture, CMSContext.CurrentUser, siteName);
                    bool       authorizedToModifyPermissions = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.ModifyPermissions) == AuthorizationResultEnum.Allowed);
                    bool       authorizedToCreate            = CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(node.NodeParentID, node.NodeClassName);

                    // Hide menu when user has no 'Read' permissions on document
                    libraryMenuElem.Visible = authorizedToRead;

                    // First evaluation of control's visibility
                    bool differentCulture = (CMSString.Compare(node.DocumentCulture, currentDocumentCulture, true) != 0);
                    localizeVisible       = differentCulture && authorizedToCreate && authorizedCultureToModify;
                    uploadVisible         = authorizedToModify && DocumentManager.AllowSave;
                    copyVisible           = authorizedToCreate && authorizedToModify;
                    deleteVisible         = authorizedToDelete;
                    openVisible           = authorizedToRead;
                    propertiesVisible     = authorizedToModify;
                    permissionsVisible    = authorizedToModifyPermissions;
                    versionHistoryVisible = authorizedToModify;
                    editVisible           = authorizedToModify && CMSContext.IsWebDAVEnabled(CMSContext.CurrentSiteName) && RequestHelper.IsWindowsAuthentication() && WebDAVSettings.IsExtensionAllowedForEditMode(documentType, CMSContext.CurrentSiteName);

                    // Get next step info
                    List <WorkflowStepInfo> stps     = new List <WorkflowStepInfo>();
                    WorkflowInfo            workflow = DocumentManager.Workflow;
                    bool basicWorkflow = true;
                    if (workflow != null)
                    {
                        basicWorkflow = workflow.IsBasic;
                        stps          = WorkflowManager.GetNextStepInfo(node);
                    }
                    var appSteps  = stps.FindAll(s => !s.StepIsArchived);
                    var archSteps = stps.FindAll(s => s.StepIsArchived);

                    // Workflow actions
                    submitToApprovalVisible = DocumentManager.IsActionAllowed(DocumentComponentEvents.APPROVE) && (appSteps.Count > 0);
                    rejectVisible           = DocumentManager.IsActionAllowed(DocumentComponentEvents.REJECT);
                    archiveVisible          = DocumentManager.IsActionAllowed(DocumentComponentEvents.ARCHIVE) && ((archSteps.Count > 0) || basicWorkflow);
                    checkOutVisible         = DocumentManager.IsActionAllowed(DocumentComponentEvents.CHECKOUT);
                    checkInVisible          = DocumentManager.IsActionAllowed(DocumentComponentEvents.CHECKIN);
                    undoCheckoutVisible     = DocumentManager.IsActionAllowed(DocumentComponentEvents.UNDO_CHECKOUT);

                    string parameterScript = "GetContextMenuParameter('" + libraryMenuElem.MenuID + "')";

                    // Initialize edit menu item
                    Guid attachmentGuid = ValidationHelper.GetGuid(node.GetValue("FileAttachment"), Guid.Empty);

                    // If attachment field doesn't allow empty value and the value is empty
                    if ((FieldInfo != null) && !FieldInfo.AllowEmpty && (attachmentGuid == Guid.Empty))
                    {
                        submitToApprovalVisible = false;
                        archiveVisible          = false;
                        checkInVisible          = false;
                    }

                    // Get attachment
                    AttachmentInfo ai = DocumentHelper.GetAttachment(attachmentGuid, TreeProvider, siteName, false);

                    Panel previousPanel = null;
                    Panel currentPanel  = pnlEdit;

                    if (editVisible)
                    {
                        if (ai != null)
                        {
                            // Load WebDAV edit control and initialize it
                            WebDAVEditControl editAttachment = Page.LoadUserControl("~/CMSModules/WebDAV/Controls/AttachmentWebDAVEditControl.ascx") as WebDAVEditControl;

                            if (editAttachment != null)
                            {
                                editAttachment.ID                  = "editAttachment";
                                editAttachment.NodeAliasPath       = node.NodeAliasPath;
                                editAttachment.NodeCultureCode     = node.DocumentCulture;
                                editAttachment.AttachmentFieldName = "FileAttachment";
                                editAttachment.FileName            = ai.AttachmentName;
                                editAttachment.IsLiveSite          = IsLiveSite;
                                editAttachment.UseImageButton      = true;
                                editAttachment.LabelText           = GetString("general.edit");
                                editAttachment.CssClass            = "Icon";
                                editAttachment.LabelCssClass       = "Name";
                                editAttachment.RefreshScript       = JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'WebDAVRefresh');";
                                // Set Group ID for live site
                                editAttachment.GroupID = IsLiveSite ? node.GetIntegerValue("NodeGroupID") : 0;
                                editAttachment.ReloadData(true);

                                pnlEditPadding.Controls.Add(editAttachment);
                                pnlEditPadding.CssClass = editAttachment.EnabledResult ? "ItemPadding" : "ItemPaddingDisabled";
                            }
                        }
                        else
                        {
                            editVisible = false;
                            openVisible = false;
                        }
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlUpload;

                    // Initialize upload menu item
                    if (authorizedToModify)
                    {
                        StringBuilder uploaderInnerHtml = new StringBuilder();
                        uploaderInnerHtml.Append("<img class=\"UploaderImage\" src=\"", GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Upload.png", IsLiveSite), "\" alt=\"", GetString("general.update"), "\" />");
                        uploaderInnerHtml.Append("<span class=\"UploaderText\">", GetString("general.update"), "</span>");

                        // Initialize direct file uploader
                        updateAttachment.InnerDivHtml             = uploaderInnerHtml.ToString();
                        updateAttachment.InnerDivClass            = "LibraryContextUploader";
                        updateAttachment.DocumentID               = node.DocumentID;
                        updateAttachment.ParentElemID             = ClientID;
                        updateAttachment.SourceType               = MediaSourceEnum.Attachment;
                        updateAttachment.AttachmentGUIDColumnName = "FileAttachment";
                        updateAttachment.IsLiveSite               = IsLiveSite;

                        // Set allowed extensions
                        if ((FieldInfo != null) && ValidationHelper.GetString(FieldInfo.Settings["extensions"], "") == "custom")
                        {
                            // Load allowed extensions
                            updateAttachment.AllowedExtensions = ValidationHelper.GetString(FieldInfo.Settings["allowed_extensions"], "");
                        }
                        else
                        {
                            // Use site settings
                            updateAttachment.AllowedExtensions = SettingsKeyProvider.GetStringValue(siteName + ".CMSUploadExtensions");
                        }

                        updateAttachment.ReloadData();
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlLocalize;

                    // Initialize localize menu item
                    if (localizeVisible)
                    {
                        lblLocalize.RefreshText();
                        imgLocalize.AlternateText = lblLocalize.Text;
                        imgLocalize.ImageUrl      = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Localize.png", IsLiveSite);
                        pnlLocalize.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Localize');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = null;
                    currentPanel  = pnlCopy;

                    // Initialize copy menu item
                    if (copyVisible)
                    {
                        lblCopy.RefreshText();
                        imgCopy.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Copy.png", IsLiveSite);
                        pnlCopy.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ",'Copy');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlDelete;

                    // Initialize delete menu item
                    if (deleteVisible)
                    {
                        lblDelete.RefreshText();
                        imgDelete.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Delete.png", IsLiveSite);
                        pnlDelete.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Delete');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlOpen;

                    // Initialize open menu item
                    if (openVisible)
                    {
                        lblOpen.RefreshText();
                        imgOpen.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Open.png", IsLiveSite);
                        if (ai != null)
                        {
                            // Get document URL
                            string attachmentUrl = CMSContext.ResolveUIUrl(AttachmentURLProvider.GetPermanentAttachmentUrl(node.NodeGUID, node.NodeAlias));
                            if (authorizedToModify)
                            {
                                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "latestfordocid", ValidationHelper.GetString(node.DocumentID, string.Empty));
                                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "hash", ValidationHelper.GetHashString("d" + node.DocumentID));
                            }
                            attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

                            if (!string.IsNullOrEmpty(attachmentUrl))
                            {
                                pnlOpen.Attributes.Add("onclick", "location.href = " + ScriptHelper.GetString(attachmentUrl) + ";");
                            }
                        }
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = null;
                    currentPanel  = pnlProperties;

                    // Initialize properties menu item
                    lblProperties.RefreshText();
                    imgProperties.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Properties.png", IsLiveSite);
                    pnlProperties.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Properties');");
                    SetupPanelClasses(currentPanel, previousPanel);

                    previousPanel = currentPanel;
                    currentPanel  = pnlPermissions;

                    // Initialize permissions menu item
                    lblPermissions.RefreshText();
                    imgPermissions.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Permissions.png", IsLiveSite);
                    pnlPermissions.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Permissions');");
                    SetupPanelClasses(currentPanel, previousPanel);

                    previousPanel = currentPanel;
                    currentPanel  = pnlVersionHistory;

                    // Initialize version history menu item
                    lblVersionHistory.RefreshText();
                    imgVersionHistory.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/VersionHistory.png", IsLiveSite);
                    pnlVersionHistory.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'VersionHistory');");
                    SetupPanelClasses(currentPanel, previousPanel);

                    previousPanel = null;
                    currentPanel  = pnlCheckOut;

                    // Initialize checkout menu item
                    if (checkOutVisible)
                    {
                        lblCheckOut.RefreshText();
                        imgCheckOut.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/CheckOut.png", IsLiveSite);
                        pnlCheckOut.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'CheckOut');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlCheckIn;

                    // Initialize check in menu item
                    if (checkInVisible)
                    {
                        lblCheckIn.RefreshText();
                        imgCheckIn.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/CheckIn.png", IsLiveSite);
                        pnlCheckIn.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'CheckIn');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlUndoCheckout;

                    // Initialize undo checkout menu item
                    if (undoCheckoutVisible)
                    {
                        lblUndoCheckout.RefreshText();
                        imgUndoCheckout.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/UndoCheckout.png", IsLiveSite);
                        pnlUndoCheckout.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'UndoCheckout');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlSubmitToApproval;

                    // Initialize submit to approval / publish menu item
                    if (submitToApprovalVisible)
                    {
                        // Only one next step
                        if (appSteps.Count == 1)
                        {
                            if (appSteps[0].StepIsPublished)
                            {
                                // Set 'Publish' label
                                lblSubmitToApproval.ResourceString = "general.publish";
                                cmcApp.Parameter = "GetContextMenuParameter('libraryMenu_" + ClientID + "')" + string.Format(" + '|{0}'", DocumentComponentEvents.PUBLISH);
                            }
                            pnlSubmitToApproval.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'SubmitToApproval');");
                        }
                        // Multiple steps - display dialog
                        else
                        {
                            pnlSubmitToApproval.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'RefreshGridSimple');" + DocumentManager.GetJSFunction(ComponentEvents.COMMENT, string.Join("|", new string[] { "'" + DocumentComponentEvents.APPROVE + "'", node.DocumentID.ToString() }), null) + ";");
                            cmcApp.Enabled = false;
                        }

                        lblSubmitToApproval.RefreshText();
                        imgSubmitToApproval.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/SubmitToApproval.png", IsLiveSite);
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlReject;

                    // Initialize reject menu item
                    if (rejectVisible)
                    {
                        lblReject.RefreshText();
                        imgReject.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Reject.png", IsLiveSite);
                        pnlReject.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Reject');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlArchive;

                    // Initialize archive menu item
                    if (archiveVisible)
                    {
                        // Only one archive step
                        if ((archSteps.Count == 1) || basicWorkflow)
                        {
                            pnlArchive.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Archive');");
                        }
                        // Multiple archive steps - display dialog
                        else
                        {
                            pnlArchive.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'RefreshGridSimple');" + DocumentManager.GetJSFunction(ComponentEvents.COMMENT, string.Join("|", new string[] { "'" + DocumentComponentEvents.ARCHIVE + "'", node.DocumentID.ToString() }), null) + ";");
                            cmcArch.Enabled = false;
                        }

                        lblArchive.RefreshText();
                        imgArchive.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Archive.png", IsLiveSite);
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    // Set up visibility of menu items
                    pnlLocalize.Visible       = localizeVisible;
                    pnlUpload.Visible         = uploadVisible;
                    pnlDelete.Visible         = deleteVisible;
                    pnlCopy.Visible           = copyVisible;
                    pnlOpen.Visible           = openVisible;
                    pnlProperties.Visible     = propertiesVisible;
                    pnlPermissions.Visible    = permissionsVisible;
                    pnlVersionHistory.Visible = versionHistoryVisible;
                    pnlEdit.Visible           = editVisible;

                    pnlCheckOut.Visible         = checkOutVisible;
                    pnlCheckIn.Visible          = checkInVisible;
                    pnlUndoCheckout.Visible     = undoCheckoutVisible;
                    pnlSubmitToApproval.Visible = submitToApprovalVisible;
                    pnlReject.Visible           = rejectVisible;
                    pnlArchive.Visible          = archiveVisible;

                    // Set up visibility of whole menu
                    contextMenuVisible = true;
                }

                if (DocumentManager.ProcessingAction)
                {
                    // Setup 'No action available' menu item
                    pnlNoAction.Visible        = true;
                    lblNoAction.ResourceString = null;
                    lblNoAction.Text           = DocumentManager.GetDocumentInfo(true);
                    lblNoAction.RefreshText();
                }
                else
                {
                    // Set up visibility of separators
                    bool firstGroupVisible  = editVisible || uploadVisible || localizeVisible;
                    bool secondGroupVisible = copyVisible || deleteVisible || openVisible;
                    bool thirdGroupVisible  = propertiesVisible || permissionsVisible || versionHistoryVisible;
                    bool fourthGroupVisible = checkOutVisible || checkInVisible || undoCheckoutVisible || submitToApprovalVisible || rejectVisible || archiveVisible;

                    pnlSep1.Visible = firstGroupVisible && secondGroupVisible;
                    pnlSep2.Visible = secondGroupVisible && thirdGroupVisible;
                    pnlSep3.Visible = thirdGroupVisible && fourthGroupVisible;

                    // Setup 'No action available' menu item
                    pnlNoAction.Visible = !contextMenuVisible;
                    lblNoAction.RefreshText();
                }
            }
        }
    }
    /// <summary>
    /// Generate control output.
    /// </summary>
    public void GenerateContent()
    {
        string templatePath = DepartmentTemplatePath;

        if (String.IsNullOrEmpty(templatePath))
        {
            ltlContent.Text    = ResHelper.GetString("departmentsectionsmanager.notemplate");
            ltlContent.Visible = true;
        }
        else
        {
            if (!DataHelper.DataSourceIsEmpty(TemplateDocuments))
            {
                int   counter = 0;
                Table tb      = new Table();

                string value      = ValidationHelper.GetString(mSelectedValue, "");
                string docAliases = ";" + value.ToLowerCSafe() + ";";

                TreeNode editedNode    = Form.EditedObject as TreeNode;
                int      targetClassId = ValidationHelper.GetInteger(editedNode.GetValue("NodeClassID"), 0);

                TableRow tr = new TableRow();
                foreach (DataRow drDoc in TemplateDocuments.Tables[0].Rows)
                {
                    // For each section td element is generated
                    TableCell td     = new TableCell();
                    CheckBox  cbCell = new CheckBox();
                    cbCell.ID   = "chckSection" + counter;
                    cbCell.Text = drDoc["NodeAlias"].ToString();
                    cbCell.Attributes.Add("Value", drDoc["NodeAlias"].ToString());

                    // Check if child allowed
                    int sourceClassId = ValidationHelper.GetInteger(drDoc["NodeClassID"], 0);
                    if (!DataClassInfoProvider.IsChildClassAllowed(targetClassId, sourceClassId))
                    {
                        cbCell.Enabled = false;
                        cbCell.ToolTip = ResHelper.GetString("departmentsectionsmanager.notallowedchild");
                    }

                    // Disable default hidden documents
                    if (HIDDEN_DOCUMENT_ALIAS.Contains(";" + drDoc["NodeAlias"].ToString().ToLowerCSafe() + ";"))
                    {
                        cbCell.Checked = cbCell.Enabled;
                        cbCell.Enabled = false;
                    }


                    // Check for selected value
                    string docAlias = ValidationHelper.GetString(drDoc["NodeAlias"], "");

                    if (docAliases.Contains(";" + docAlias.ToLowerCSafe() + ";") || ((mSelectedValue == null) && (Form.Mode == FormModeEnum.Insert)))
                    {
                        if (cbCell.Enabled)
                        {
                            cbCell.Checked = true;
                        }
                    }

                    // If editing existing document register alert script
                    if ((Form.Mode != FormModeEnum.Insert) && cbCell.Checked)
                    {
                        cbCell.Attributes.Add("OnClick", "if(!this.checked){alert(" + ScriptHelper.GetString(ResHelper.GetString("departmentsectionsmanagerformcontrol.removesectionwarning")) + ");}");
                    }

                    // Add reference to checkbox arraylist
                    CheckboxReferences.Add(cbCell);
                    counter++;

                    td.Controls.Add(cbCell);
                    tr.Cells.Add(td);

                    // If necessary create new row
                    if ((counter % ITEMS_PER_ROW) == 0)
                    {
                        tr.CssClass = "Row";
                        tb.Rows.Add(tr);
                        tr = new TableRow();
                    }
                }
                // If last row contains data add it
                if (counter > 0)
                {
                    tb.Rows.Add(tr);
                }
                pnlContent.Controls.Add(tb);
            }
            else
            {
                ltlContent.Text    = ResHelper.GetString("departmentsectionsmanager.notemplate");
                ltlContent.Visible = true;
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
            srcUsers.StopProcessing = true;
        }
        else
        {
            TreeNode     node = null;
            TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

            // Check if path is set
            if (String.IsNullOrEmpty(Path))
            {
                TreeNode curDoc = DocumentContext.CurrentDocument;
                // Check if current document is department
                if ((curDoc != null) && (curDoc.NodeClassName.ToLowerCSafe() == DEPARTMENT_CLASS_NAME))
                {
                    node = DocumentContext.CurrentDocument;
                }
            }
            else
            {
                // Obtain document from specified path
                node = tree.SelectSingleNode(SiteName, Path, LocalizationContext.PreferredCultureCode, true, DEPARTMENT_CLASS_NAME, false, false, false);
            }

            // If department document exists and has own ACL continue with initializing controls
            if ((node != null) && AclInfoProvider.HasOwnAcl(node))
            {
                // Get users and roles with read permission for department document
                int     aclId   = ValidationHelper.GetInteger(node.GetValue("NodeACLID"), 0);
                DataSet dsRoles = AclItemInfoProvider.GetAllowedRoles(aclId, NodePermissionsEnum.Read, "RoleID");
                DataSet dsUsers = AclItemInfoProvider.GetAllowedUsers(aclId, NodePermissionsEnum.Read, "UserID");

                string where = null;

                // Process users dataset to where condition
                if (!DataHelper.DataSourceIsEmpty(dsUsers))
                {
                    // Get allowed users ids
                    IList <string> users   = DataHelper.GetStringValues(dsUsers.Tables[0], "UserID");
                    string         userIds = TextHelper.Join(", ", users);

                    // Populate where condition with user condition
                    where = SqlHelper.AddWhereCondition("UserID IN (" + userIds + ")", where);
                }

                // Process roles dataset to where condition
                if (!DataHelper.DataSourceIsEmpty(dsRoles))
                {
                    // Get allowed roles ids
                    IList <string> roles   = DataHelper.GetStringValues(dsRoles.Tables[0], "RoleID");
                    string         roleIds = TextHelper.Join(", ", roles);

                    // Populate where condition with role condition
                    where = SqlHelper.AddWhereCondition("UserID IN (SELECT UserID FROM View_CMS_UserRole_MembershipRole_ValidOnly_Joined WHERE RoleID IN (" + roleIds + "))", where, "OR");
                }


                if (!String.IsNullOrEmpty(where))
                {
                    // Check if exist where condition and add it to current where condition
                    where = SqlHelper.AddWhereCondition(WhereCondition, where);

                    // Set datasource properties
                    srcUsers.WhereCondition     = where;
                    srcUsers.OrderBy            = OrderBy;
                    srcUsers.TopN               = SelectTopN;
                    srcUsers.FilterName         = ValidationHelper.GetString(GetValue("WebPartControlID"), ID);
                    srcUsers.SourceFilterName   = FilterName;
                    srcUsers.SiteName           = SiteName;
                    srcUsers.CacheItemName      = CacheItemName;
                    srcUsers.CacheDependencies  = CacheDependencies;
                    srcUsers.CacheMinutes       = CacheMinutes;
                    srcUsers.SelectOnlyApproved = SelectOnlyApproved;
                    srcUsers.SelectHidden       = SelectHidden;
                    srcUsers.SelectedColumns    = Columns;
                }
                else
                {
                    srcUsers.StopProcessing = true;
                }
            }
            else
            {
                srcUsers.StopProcessing = true;
            }
        }
    }
    /// <summary>
    /// Sends e-mail to all attendees.
    /// </summary>
    protected void Send()
    {
        // Check 'Modify' permission
        if (!CheckPermissions("cms.eventmanager", "Modify"))
        {
            return;
        }

        txtSenderName.Text  = txtSenderName.Text.Trim();
        txtSenderEmail.Text = txtSenderEmail.Text.Trim();
        txtSubject.Text     = txtSubject.Text.Trim();

        // Validate the fields
        string errorMessage = new Validator().NotEmpty(txtSenderName.Text, GetString("Events_SendEmail.EmptySenderName"))
                              .NotEmpty(txtSenderEmail.Text, GetString("Events_SendEmail.EmptySenderEmail"))
                              .NotEmpty(txtSubject.Text, GetString("Events_SendEmail.EmptyEmailSubject"))
                              .IsEmail(txtSenderEmail.Text, GetString("Events_SendEmail.InvalidEmailFormat"))
                              .Result;

        if (!String.IsNullOrEmpty(errorMessage))
        {
            ShowError(errorMessage);
            return;
        }

        string subject   = txtSubject.Text;
        string emailBody = htmlEmail.ResolvedValue;

        // Get event node data
        TreeProvider mTree = new TreeProvider();
        DocTreeNode  node  = mTree.SelectSingleNode(EventID);

        if (node != null && CMSString.Equals(node.NodeClassName, "cms.bookingevent", true))
        {
            // Initialize macro resolver
            ContextResolver resolver = ContextResolver.GetInstance();
            resolver.KeepUnresolvedMacros = true;
            resolver.SourceData           = new object[] { node };
            // Add named source data
            resolver.SetNamedSourceData("Event", node);

            // Event date string macro
            DateTime eventDate    = ValidationHelper.GetDateTime(node.GetValue("EventDate"), DateTimeHelper.ZERO_TIME);
            DateTime eventEndDate = ValidationHelper.GetDateTime(node.GetValue("EventEndDate"), DateTimeHelper.ZERO_TIME);
            bool     isAllDay     = ValidationHelper.GetBoolean(node.GetValue("EventAllDay"), false);

            string[,] macro           = new string[1, 2];
            macro[0, 0]               = "eventdatestring";
            macro[0, 1]               = EventProvider.GetEventDateString(eventDate, eventEndDate, isAllDay, TimeZoneHelper.GetSiteTimeZoneInfo(CMSContext.CurrentSite), CMSContext.CurrentSiteName);
            resolver.SourceParameters = macro;

            // Resolve e-mail body and subject macros and make links absolute
            emailBody = resolver.ResolveMacros(emailBody);
            emailBody = URLHelper.MakeLinksAbsolute(emailBody);
            subject   = TextHelper.LimitLength(resolver.ResolveMacros(subject), 450);

            // EventSendEmail manages sending e-mails to all attendees
            EventSendEmail ese = new EventSendEmail(EventID, CMSContext.CurrentSiteName,
                                                    subject, emailBody, txtSenderName.Text.Trim(), txtSenderEmail.Text.Trim());

            ShowConfirmation(GetString("Events_SendEmail.EmailSent"));
        }
    }
    /// <summary>
    /// PreRender action on which security settings are set.
    /// </summary>
    private void Page_PreRender(object sender, EventArgs e)
    {
        if ((Form == null) || !mDocumentSaved)
        {
            return;
        }

        TreeNode editedNode = Form.EditedObject as TreeNode;

        // Create or rebuild department content index
        CreateDepartmentContentSearchIndex(editedNode);

        if ((editedNode == null) || !editedNode.NodeIsACLOwner)
        {
            return;
        }

        ForumInfo        fi = ForumInfoProvider.GetForumInfo("Default_department_" + editedNode.NodeGUID, SiteContext.CurrentSiteID);
        MediaLibraryInfo mi = MediaLibraryInfoProvider.GetMediaLibraryInfo("Department_" + editedNode.NodeGUID, SiteContext.CurrentSiteName);

        // Check if forum of media library exists
        if ((fi == null) && (mi == null))
        {
            return;
        }

        // Get allowed roles ID
        int         aclID     = ValidationHelper.GetInteger(editedNode.GetValue("NodeACLID"), 0);
        DataSet     listRoles = AclItemInfoProvider.GetAllowedRoles(aclID, NodePermissionsEnum.Read, "RoleID");
        IList <int> roleIds   = null;


        if (!DataHelper.DataSourceIsEmpty(listRoles))
        {
            roleIds = DataHelper.GetIntegerValues(listRoles.Tables[0], "RoleID") as List <int>;
        }

        // Set permissions for forum
        if (fi != null)
        {
            // Get resource object
            ResourceInfo resForums = ResourceInfoProvider.GetResourceInfo("CMS.Forums");

            // Get permissions IDs
            var forumPermissions = PermissionNameInfoProvider.GetPermissionNames()
                                   .Column("PermissionID")
                                   .WhereEquals("ResourceID", resForums.ResourceID)
                                   .WhereNotEquals("PermissionName", CMSAdminControl.PERMISSION_READ)
                                   .WhereNotEquals("PermissionName", CMSAdminControl.PERMISSION_MODIFY);

            // Delete old permissions apart attach file permission
            ForumRoleInfoProvider.DeleteAllRoles(new WhereCondition().WhereEquals("ForumID", fi.ForumID).WhereIn("PermissionID", forumPermissions));

            // Set forum permissions
            ForumRoleInfoProvider.SetPermissions(fi.ForumID, roleIds, forumPermissions.Select(p => p.PermissionId).ToArray());

            // Log staging task
            SynchronizationHelper.LogObjectChange(fi, TaskTypeEnum.UpdateObject);
        }

        // Set permissions for media library
        if (mi == null)
        {
            return;
        }

        // Get resource object
        ResourceInfo resMediaLibs = ResourceInfoProvider.GetResourceInfo("CMS.MediaLibrary");

        // Get permissions IDs
        var where = new WhereCondition()
                    .WhereEquals("ResourceID", resMediaLibs.ResourceID)
                    .And()
                    .Where(new WhereCondition()
                           .WhereEquals("PermissionName", "LibraryAccess")
                           .Or()
                           .WhereEquals("PermissionName", "FileCreate"));

        DataSet     dsMediaLibPerm         = PermissionNameInfoProvider.GetPermissionNames().Where(where).Column("PermissionID");
        IList <int> mediaLibPermissionsIds = null;

        if (!DataHelper.DataSourceIsEmpty(dsMediaLibPerm))
        {
            mediaLibPermissionsIds = DataHelper.GetIntegerValues(dsMediaLibPerm.Tables[0], "PermissionID");
        }

        var deleteWhere = new WhereCondition()
                          .WhereEquals("LibraryID", mi.LibraryID)
                          .WhereIn("PermissionID", mediaLibPermissionsIds);

        // Delete old permissions only for Create file and See library content permissions
        MediaLibraryRolePermissionInfoProvider.DeleteAllRoles(deleteWhere.ToString(true));

        MediaLibraryRolePermissionInfoProvider.SetPermissions(mi.LibraryID, roleIds, mediaLibPermissionsIds);

        // Log staging task;
        SynchronizationHelper.LogObjectChange(mi, TaskTypeEnum.UpdateObject);
    }
Пример #22
0
    private void ReloadData()
    {
        if (node != null)
        {
            bool isRoot = (node.NodeAliasPath == "/");

            // Check read permissions
            if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied)
            {
                RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath));
            }
            // Check modify permissions
            else if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied)
            {
                hasModifyPermission     = false;
                pnlForm.Enabled         = false;
                tagSelectorElem.Enabled = false;
            }

            TreeNode tmpNode = node.Clone();

            // If values are inherited set nulls
            tmpNode.SetValue("DocumentPageTitle", DBNull.Value);
            tmpNode.SetValue("DocumentPageKeyWords", DBNull.Value);
            tmpNode.SetValue("DocumentPageDescription", DBNull.Value);
            tmpNode.SetValue("DocumentTagGroupID", DBNull.Value);

            // Load the inherited values
            SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID);
            if (si != null)
            {
                tmpNode.LoadInheritedValues(new string[] { "DocumentPageTitle", "DocumentPageKeyWords", "DocumentPageDescription", "DocumentTagGroupID" }, SiteInfoProvider.CombineWithDefaultCulture(si.SiteName));
            }

            if (!pnlUIPage.IsHidden)
            {
                // Page title
                if (node.GetValue("DocumentPageTitle") != null)
                {
                    txtTitle.Text = node.GetValue("DocumentPageTitle").ToString();
                }
                else
                {
                    if (!isRoot)
                    {
                        txtTitle.Enabled = false;
                        chkTitle.Checked = true;
                        txtTitle.Text    = ValidationHelper.GetString(tmpNode.GetValue("DocumentPageTitle"), "");
                    }
                }

                // Page key words
                if (node.GetValue("DocumentPageKeyWords") != null)
                {
                    txtKeywords.Text = node.GetValue("DocumentPageKeyWords").ToString();
                }
                else
                {
                    if (!isRoot)
                    {
                        txtKeywords.Enabled = false;
                        chkKeyWords.Checked = true;
                        txtKeywords.Text    = ValidationHelper.GetString(tmpNode.GetValue("DocumentPageKeyWords"), "");
                    }
                }

                // Page description
                if (node.GetValue("DocumentPageDescription") != null)
                {
                    txtDescription.Text = node.GetValue("DocumentPageDescription").ToString();
                }
                else
                {
                    if (!isRoot)
                    {
                        txtDescription.Enabled = false;
                        chkDescription.Checked = true;
                        txtDescription.Text    = ValidationHelper.GetString(tmpNode.GetValue("DocumentPageDescription"), "");
                    }
                }
            }

            if (!pnlUITags.IsHidden)
            {
                // Tag group
                if (node.GetValue("DocumentTagGroupID") != null)
                {
                    object tagGroupId = node.GetValue("DocumentTagGroupID");
                    tagGroupSelectorElem.Value = tagGroupId;
                }
                else
                {
                    if (!isRoot)
                    {
                        // Get the inherited tag group
                        int tagGroup = ValidationHelper.GetInteger(tmpNode.GetValue("DocumentTagGroupID"), 0);
                        if (tagGroup > 0)
                        {
                            tagGroupSelectorElem.Value = tagGroup;
                        }
                        else
                        {
                            tagGroupSelectorElem.AddNoneItemsRecord = true;
                        }
                        tagGroupSelectorElem.Enabled = false;
                        chkTagGroupSelector.Checked  = true;
                    }
                    else
                    {
                        // Add 'none' option to Root document
                        tagGroupSelectorElem.AddNoneItemsRecord = true;
                    }
                }

                // Tags
                tagSelectorElem.Value = node.DocumentTags;
            }
        }
    }