Esempio n. 1
0
    /// <summary>
    /// Creates authorization and authentication where condition.
    /// </summary>
    private string CreateAuthWhereCondition()
    {
        CurrentUserInfo currentUser = CMSContext.CurrentUser;

        // Allowed for all
        string securityWhere = " AND ((WidgetSecurity = 0) ";

        if (currentUser.IsAuthenticated())
        {
            // Authenticated
            securityWhere += " OR (WidgetSecurity = 1)";

            // Global admin
            if (currentUser.IsGlobalAdministrator)
            {
                securityWhere += " OR (WidgetSecurity = 7)";
            }

            // Authorized roles
            securityWhere += " OR ((WidgetSecurity = 2)";
            if (!currentUser.IsGlobalAdministrator)
            {
                securityWhere += "AND (WidgetID IN ( SELECT WidgetID FROM CMS_WidgetRole WHERE RoleID IN (SELECT RoleID FROM View_CMS_UserRole_MembershipRole_ValidOnly_Joined WHERE UserID = " + currentUser.UserID + ")))))";
            }
            else
            {
                securityWhere += "))";
            }
        }
        else
        {
            securityWhere += ")";
        }
        return(securityWhere);
    }
Esempio n. 2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            // Stop processing
            usUsers.StopProcessing = true;
        }
        else
        {
            CurrentUserInfo ui = CMSContext.CurrentUser;

            // Content is visible only for authenticated users
            if (ui.IsAuthenticated())
            {
                usUsers.UniSelector.OnSelectionChanged += UniSelector_OnSelectionChanged;
                usUsers.IsLiveSite     = IsLiveSite;
                usUsers.WhereCondition = "UserName NOT LIKE N'public'";

                // Global admin can see all users
                if (ui.UserSiteManagerAdmin)
                {
                    usUsers.DisplayUsersFromAllSites = true;
                }
                else
                {
                    usUsers.DisplayUsersFromAllSites = false;

                    // Show only users from current site for normal user
                    usUsers.SiteID = CMSContext.CurrentSiteID;

                    if (IsLiveSite && !CMSContext.CurrentUser.IsGlobalAdministrator)
                    {
                        usUsers.HideDisabledUsers    = true;
                        usUsers.HideHiddenUsers      = true;
                        usUsers.HideNonApprovedUsers = true;
                    }
                }

                // Hide site selector
                usUsers.ShowSiteFilter = false;

                currentValues = GetContactListValues();

                if (!RequestHelper.IsPostBack())
                {
                    usUsers.Value = currentValues;
                }

                if (string.IsNullOrEmpty(ZeroRowsText))
                {
                    // Use default text
                    ZeroRowsText = GetString("messaging.contactlist.nodatafound");
                }
            }
            else
            {
                Visible = false;
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            // Stop processing
        }
        else
        {
            CurrentUserInfo user = CMSContext.CurrentUser;

            // Content is visible only for authenticated users
            if (user.IsAuthenticated())
            {
                if (string.IsNullOrEmpty(ZeroRowsText))
                {
                    ZeroRowsText = GetString("friends.nofriendsfound");
                }
                // Register modal dialog JS function
                ScriptHelper.RegisterDialogScript(Page);

                gridFriends.OrderBy              = "UserName";
                gridFriends.OnExternalDataBound += gridFriends_OnExternalDataBound;
                gridFriends.IsLiveSite           = IsLiveSite;

                // Where condition
                string where = "FriendStatus = " + Convert.ToInt32(FriendshipStatusEnum.Approved);

                // If not global admin, filter out friends from different sites
                if (!user.IsGlobalAdministrator)
                {
                    where = SqlHelperClass.AddWhereCondition(where, "UserID IN(SELECT UserID FROM CMS_UserSite WHERE SiteID=" + CMSContext.CurrentSiteID + " )");
                }
                gridFriends.WhereCondition = where;
                // Add parameter @UserID
                if (gridFriends.QueryParameters == null)
                {
                    gridFriends.QueryParameters = new QueryDataParameters();
                }
                gridFriends.QueryParameters.Add("@UserID", user.UserID);
            }
            else
            {
                Visible = false;
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            Visible = false;
            return;
        }

        // Get setting values
        string          siteName    = CMSContext.CurrentSiteName;
        CurrentUserInfo currentUser = CMSContext.CurrentUser;
        int             expDays     = 0;

        if (currentUser.IsAuthenticated() && AuthenticationHelper.IsPasswordExpirationEnabled(siteName, out expDays))
        {
            int dayDiff     = (DateTime.Now - currentUser.UserPasswordLastChanged).Days - expDays;
            int warningDays = SettingsKeyProvider.GetIntValue(siteName + ".CMSPasswordExpirationWarningPeriod");

            string changePwdLink = string.Format(@"<a href=""#"" onclick=""modalDialog('{0}','ChangePassword','650','450',null,null,true);"">{1}</a>", ResolveUrl("~/CMSModules/Membership/" + (IsLiveSite ? "CMSPages" : "Pages") + "/ChangePassword.aspx"), DataHelper.GetNotEmpty(ChangePasswordLinkText, GetString("passwordexpiration.changepassword")));

            // Check if account password expired
            if (dayDiff >= 0)
            {
                lblExpText.Text = string.Format("{0}{1}{2}", ExpirationTextBefore, (ShowChangePasswordLink ? changePwdLink : ""), ExpirationTextAfter);
            }
            // Check for password expiration warning
            else if ((warningDays > 0) && (Math.Abs(dayDiff) <= warningDays))
            {
                lblExpText.Text = string.Format("{0}{1}{2}", ExpirationWarningTextBefore, (ShowChangePasswordLink ? changePwdLink : ""), ExpirationWarningTextAfter);
            }
            else
            {
                Visible = false;
            }
        }
        else
        {
            Visible = false;
        }

        // Ensure dialog script
        ScriptHelper.RegisterDialogScript(Page);
    }
Esempio n. 5
0
    /// <summary>
    /// Reload data.
    /// </summary>
    public void ReloadData()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            CurrentUserInfo currentUser = CMSContext.CurrentUser;

            // WAI validation
            lblText.AssociatedControlClientID = ucBBEditor.TextArea.ClientID;

            // Default settings
            pnlSendMessage.Visible = true;
            pnlNoUser.Visible      = false;

            if (currentUser.IsAuthenticated() || AllowAnonymousUsers)
            {
                // Decide if the user is anonymous
                isAnonymousUser = currentUser.IsPublic();

                // Change controls
                if (isAnonymousUser)
                {
                    lblFrom.Visible = false;
                    txtFrom.Visible = true;
                }
                else
                {
                    lblFrom.Visible = true;
                    lblFrom.Text    = HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(currentUser.UserName, currentUser.FullName, currentUser.UserNickName, IsLiveSite));
                    txtFrom.Visible = false;
                }

                // Reacting on the message
                // Get message
                if (Message != null)
                {
                    UserInfo sender = UserInfoProvider.GetUserInfo(Message.MessageSenderUserID);
                    // Reply
                    switch (SendMessageMode)
                    {
                    case MessageActionEnum.Reply:
                        if (sender != null)
                        {
                            hdnUserId.Value = sender.UserID.ToString();

                            // Check if postback wasn't caused by send button to avoid overriding values
                            if (ControlsHelper.GetPostBackControl(Page) != btnSendMessage)
                            {
                                // Set message subject
                                MessageSubject += Message.MessageSubject;
                                // Set message body
                                if (currentUser.UserSignature.Trim() != string.Empty)
                                {
                                    MessageBody += "\n\n\n" + currentUser.UserSignature;
                                }
                                if (PasteOriginalMessage)
                                {
                                    MessageBody += "\n\n// " + Message.MessageBody.Replace("\n", "\n// ");
                                }
                            }

                            // Set recipient
                            lblTo.Text    = HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(sender.UserName, sender.FullName, sender.UserNickName, IsLiveSite));
                            lblTo.Visible = true;
                            ucMessageUserSelector.Visible = false;
                        }
                        else
                        {
                            pnlNoUser.Visible      = true;
                            pnlSendMessage.Visible = false;
                            lblNoUser.Text         = GetString("SendMessage.NoUser");
                        }
                        break;

                    case MessageActionEnum.Forward:
                        // Check if postback wasn't caused by send button to avoid overriding values
                        if (ControlsHelper.GetPostBackControl(Page) != btnSendMessage)
                        {
                            MessageSubject += Message.MessageSubject;
                            string signature = (currentUser.UserSignature.Trim() != "") ? "\n\n\n" + currentUser.UserSignature : "";
                            MessageBody += signature + "\n\n// " + Message.MessageBody.Replace("\n", "\n//");
                        }

                        lblTo.Visible = false;
                        ucMessageUserSelector.Visible = true;
                        break;
                    }
                }
                // New message
                else if (SendMessageMode == MessageActionEnum.New)
                {
                    if (DefaultRecipient != "")
                    {
                        lblTo.Visible = true;
                        ucMessageUserSelector.Visible = false;

                        // Get default recipient name
                        string userName = UserInfoProvider.GetUserNameById(ValidationHelper.GetInteger(DefaultRecipient, 0));
                        userName = Functions.GetFormattedUserName(userName, IsLiveSite);

                        lblTo.Text      = HTMLHelper.HTMLEncode(userName);
                        hdnUserId.Value = DefaultRecipient;
                    }
                    else
                    {
                        lblTo.Visible = false;
                        if (isAnonymousUser)
                        {
                            ucMessageUserSelector.Visible = AllowAnonymousRecipientSelection;
                        }
                        else
                        {
                            ucMessageUserSelector.Visible = true;
                        }
                    }

                    // Add signature
                    if (!isAnonymousUser)
                    {
                        if (currentUser.UserSignature.Trim() != "")
                        {
                            MessageBody += "\n\n\n" + currentUser.UserSignature;
                        }
                    }
                }

                // Initialize subject and body
                if (txtSubject.Text == string.Empty)
                {
                    txtSubject.Text = MessageSubject;
                }
                if (ucBBEditor.Text == string.Empty)
                {
                    ucBBEditor.Text = MessageBody;
                }
            }
            else
            {
                Visible = false;
            }
        }
    }
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        string widgetId     = QueryHelper.GetString("widgetid", String.Empty);
        string aliasPath    = QueryHelper.GetString("aliasPath", String.Empty);
        int    templateId   = QueryHelper.GetInteger("templateid", 0);
        string zoneId       = QueryHelper.GetString("zoneid", String.Empty);
        Guid   instanceGUID = QueryHelper.GetGuid("instanceguid", Guid.Empty);

        bool   isNewWidget = QueryHelper.GetBoolean("isnew", false);
        bool   inline      = QueryHelper.GetBoolean("inline", false);
        int    variantId   = QueryHelper.GetInteger("variantid", 0);
        string culture     = QueryHelper.GetString("culture", CMSContext.PreferredCultureCode);

        // Set page title
        Page.Title = GetString(isNewWidget ? "widgets.propertiespage.titlenew" : "widgets.propertiespage.title");

        // Resize the header (enlarge) to make a space for the tabs header when displaying a widget variant
        if (variantId > 0)
        {
            rowsFrameset.Attributes.Add("rows", "67, *");
        }

        // Ensure correct view mode
        if (String.IsNullOrEmpty(aliasPath))
        {
            // Ensure the dashboard mode for the dialog
            if (QueryHelper.Contains("dashboard"))
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.DashboardWidgets);
                PortalContext.DashboardName     = QueryHelper.GetString("dashboard", String.Empty);
                PortalContext.DashboardSiteName = QueryHelper.GetString("sitename", String.Empty);
            }
            // Ensure the design mode for the dialog
            else
            {
                PortalContext.SetRequestViewMode(ViewModeEnum.Design);
            }
        }

        if (widgetId != "")
        {
            // Get pageinfo
            PageInfo pi = null;
            try
            {
                pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId, culture);
            }
            catch (PageNotFoundException)
            {
                // Do not throw exception if page info not found (e.g. bad alias path)
            }

            if (pi == null)
            {
                return;
            }

            // Get template instance
            PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);

            // Get widget from instance
            WidgetInfo wi = null;
            if (!isNewWidget)
            {
                // Get the instance of widget
                WebPartInstance widgetInstance = templateInstance.GetWebPart(instanceGUID, widgetId);
                if (widgetInstance == null)
                {
                    return;
                }

                // Get widget info by widget name(widget type)
                wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType);
            }
            // Widget instance hasn't created yet
            else
            {
                wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(widgetId, 0));
            }

            if (wi != null)
            {
                WebPartZoneInstance zone = templateInstance.GetZone(zoneId);
                if (zone != null)
                {
                    CurrentUserInfo currentUser = CMSContext.CurrentUser;

                    switch (zone.WidgetZoneType)
                    {
                    // Group zone => Only group widgets and group admin
                    case WidgetZoneTypeEnum.Group:
                        // Should always be, only group widget are allowed in group zone
                        if (!wi.WidgetForGroup || (!currentUser.IsGroupAdministrator(pi.NodeGroupID) && ((CMSContext.ViewMode != ViewModeEnum.Design) || ((CMSContext.ViewMode == ViewModeEnum.Design) && (!currentUser.IsAuthorizedPerResource("CMS.Design", "Design"))))))
                        {
                            RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                        }
                        break;

                    // Widget must be allowed for editor zones
                    case WidgetZoneTypeEnum.Editor:
                        if (!wi.WidgetForEditor)
                        {
                            RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                        }
                        break;

                    // Widget must be allowed for user zones
                    case WidgetZoneTypeEnum.User:
                        if (!wi.WidgetForUser)
                        {
                            RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                        }
                        break;
                    }

                    if ((zone.WidgetZoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated()))
                    {
                        RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                    }
                }

                // If all ok, set up frames
                frameHeader.Attributes.Add("src", "widgetproperties_header.aspx" + URLHelper.Url.Query);
                frameContent.Attributes.Add("src", "widgetproperties_properties_frameset.aspx" + URLHelper.Url.Query);
            }
        }

        frameHeader.Attributes.Add("src", "widgetproperties_header.aspx" + URLHelper.Url.Query);
        if (inline && !isNewWidget)
        {
            frameContent.Attributes.Add("src", ResolveUrl("~/CMSPages/Blank.htm"));
        }
        else
        {
            frameContent.Attributes.Add("src", "widgetproperties_properties_frameset.aspx" + URLHelper.Url.Query);
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            editForm.StopProcessing = true;
            editForm.Visible        = false;
        }
        else
        {
            pnlEdit.Visible = false;

            CurrentUserInfo currentUser = CMSContext.CurrentUser;

            // Get the document
            TreeNode node = TreeHelper.GetDocument(SiteName, CMSContext.ResolveCurrentPath(Path), CultureCode, false, null, false, CheckPermissions, currentUser);
            if (node != null)
            {
                bool authorized = false;

                // Check user group
                switch (AllowUsers)
                {
                case UserContributionAllowUserEnum.All:
                    authorized = true;
                    break;

                case UserContributionAllowUserEnum.Authenticated:
                    authorized = currentUser.IsAuthenticated();
                    break;

                case UserContributionAllowUserEnum.DocumentOwner:
                    authorized = (node.NodeOwner == currentUser.UserID);
                    break;
                }

                bool authorizedDelete = authorized;

                // Check control access permissions
                if (authorized && CheckPermissions)
                {
                    // Node owner has always permissions
                    if (node.NodeOwner != currentUser.UserID)
                    {
                        authorized       &= (currentUser.IsAuthorizedPerDocument(node, new NodePermissionsEnum[] { NodePermissionsEnum.Read, NodePermissionsEnum.Modify }) == AuthorizationResultEnum.Allowed);
                        authorizedDelete &= (currentUser.IsAuthorizedPerDocument(node, new NodePermissionsEnum[] { NodePermissionsEnum.Read, NodePermissionsEnum.Delete }) == AuthorizationResultEnum.Allowed);
                    }
                }
                else
                {
                    authorized       |= currentUser.IsGlobalAdministrator;
                    authorizedDelete |= currentUser.IsGlobalAdministrator;
                }

                // Do not allow edit for virtual user
                if (currentUser.IsVirtual)
                {
                    authorized       = false;
                    authorizedDelete = false;
                }

                // Display form if authorized
                if (authorized || authorizedDelete)
                {
                    // Set visibility of the edit and delete buttons
                    pnlEdit.Visible        = true;
                    btnEdit.Visible        = btnEdit.Visible && authorized;
                    btnDelete.Visible      = btnDelete.Visible && AllowDelete && authorizedDelete;
                    editForm.LogActivity   = LogActivity;
                    editForm.ComponentName = WebPartID;

                    if (pnlForm.Visible)
                    {
                        editForm.StopProcessing         = false;
                        editForm.AllowDelete            = AllowDelete;
                        editForm.CheckPermissions       = CheckPermissions;
                        editForm.NodeID                 = node.NodeID;
                        editForm.SiteName               = SiteName;
                        editForm.CultureCode            = CultureCode;
                        editForm.AlternativeFormName    = AlternativeFormName;
                        editForm.ValidationErrorMessage = ValidationErrorMessage;
                        editForm.CMSForm.IsLiveSite     = true;

                        // Reload data
                        editForm.ReloadData(false);
                    }

                    editForm.OnAfterApprove      += editForm_OnAfterChange;
                    editForm.OnAfterReject       += editForm_OnAfterChange;
                    editForm.OnAfterDelete       += editForm_OnAfterChange;
                    editForm.CMSForm.OnAfterSave += CMSForm_OnAfterSave;
                }
            }
        }
    }
Esempio n. 8
0
    /// <summary>
    /// Init event handler.
    /// </summary>
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Setup basic form on live site
        formCustom.AllowMacroEditing = false;
        formCustom.IsLiveSite        = IsLiveSite;

        // Load settings
        if (!String.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID]))
        {
            IsNewWidget = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false);
        }
        if (!String.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID]))
        {
            InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty);
        }

        // Try to find the widget variant in the database and set its VariantID
        if (IsNewVariant)
        {
            Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable;
            if (properties != null)
            {
                // Get the variant code name from the WindowHelper
                string variantName = ValidationHelper.GetString(properties["codename"], string.Empty);

                // Check if the variant exists in the database
                int variantIdFromDB = 0;
                if (VariantMode == VariantModeEnum.MVT)
                {
                    variantIdFromDB = ModuleCommands.OnlineMarketingGetMVTVariantId(PageTemplateId, variantName);
                }
                else if (VariantMode == VariantModeEnum.ContentPersonalization)
                {
                    variantIdFromDB = ModuleCommands.OnlineMarketingGetContentPersonalizationVariantId(PageTemplateId, variantName);
                }

                // Set the variant id from the database
                if (variantIdFromDB > 0)
                {
                    VariantID    = variantIdFromDB;
                    IsNewVariant = false;
                }
            }
        }

        EnsureDashboard();

        if (!String.IsNullOrEmpty(WidgetId) && !IsInline)
        {
            // Get page info
            try
            {
                pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateId, CultureCode);
            }
            catch (PageNotFoundException)
            {
                // Do not throw exception if page info not found (e.g. bad alias path)
            }

            if (pi == null)
            {
                lblInfo.Text        = GetString("Widgets.Properties.aliasnotfound");
                lblInfo.Visible     = true;
                pnlFormArea.Visible = false;
                return;
            }

            // Get template instance
            templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);

            if (!IsNewWidget)
            {
                // Get the instance of widget
                widgetInstance = templateInstance.GetWebPart(InstanceGUID, WidgetId);
                if (widgetInstance == null)
                {
                    lblInfo.Text        = GetString("Widgets.Properties.WidgetNotFound");
                    lblInfo.Visible     = true;
                    pnlFormArea.Visible = false;
                    return;
                }

                if ((VariantID > 0) && (widgetInstance != null) && (widgetInstance.PartInstanceVariants != null))
                {
                    // Check OnlineMarketing permissions.
                    if (CheckPermissions("Read"))
                    {
                        widgetInstance = pi.DocumentTemplateInstance.GetWebPart(InstanceGUID, WidgetId);
                        widgetInstance = widgetInstance.PartInstanceVariants.Find(v => v.VariantID.Equals(VariantID));
                        // Set the widget variant mode
                        if (widgetInstance != null)
                        {
                            VariantMode = widgetInstance.VariantMode;
                        }
                    }
                    else
                    {
                        // Not authorized for OnlineMarketing - Manage.
                        RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest"));
                    }
                }

                // Get widget info by widget name(widget type)
                wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType);
            }
            // Widget instance hasn't created yet
            else
            {
                wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0));
            }

            // Keep xml version
            if (widgetInstance != null)
            {
                xmlVersion = widgetInstance.XMLVersion;
            }

            CMSPage.EditedObject = wi;
            zoneType             = ZoneType;

            // Get the zone to which it inserts
            WebPartZoneInstance zone = templateInstance.GetZone(ZoneId);
            if ((zoneType == WidgetZoneTypeEnum.None) && (zone != null))
            {
                zoneType = zone.WidgetZoneType;
            }

            // Check security
            CurrentUserInfo currentUser = CMSContext.CurrentUser;

            switch (zoneType)
            {
            // Group zone => Only group widgets and group admin
            case WidgetZoneTypeEnum.Group:
                // Should always be, only group widget are allowed in group zone
                if (!wi.WidgetForGroup || (!currentUser.IsGroupAdministrator(pi.NodeGroupID) && ((CMSContext.ViewMode != ViewModeEnum.Design) || ((CMSContext.ViewMode == ViewModeEnum.Design) && (!currentUser.IsAuthorizedPerResource("CMS.Design", "Design"))))))
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;

            // Widget must be allowed for editor zones
            case WidgetZoneTypeEnum.Editor:
                if (!wi.WidgetForEditor)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;

            // Widget must be allowed for user zones
            case WidgetZoneTypeEnum.User:
                if (!wi.WidgetForUser)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;

            // Widget must be allowed for dashboard zones
            case WidgetZoneTypeEnum.Dashboard:
                if (!wi.WidgetForDashboard)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;
            }

            // Check security
            if ((zoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated()))
            {
                if (OnNotAllowed != null)
                {
                    OnNotAllowed(this, null);
                }
            }

            // Get form schemas
            wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID);
            FormInfo zoneTypeDefinition = PortalFormHelper.GetPositionFormInfo(zoneType);
            string   widgetProperties   = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties);
            FormInfo fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), widgetProperties, zoneTypeDefinition, true);

            if (fi != null)
            {
                // Check if there are some editable properties
                var ffi = fi.GetFields(true, false).ToList <FormFieldInfo>();
                if ((ffi == null) || (ffi.Count == 0))
                {
                    lblInfo.Visible = true;
                    lblInfo.Text    = GetString("widgets.emptyproperties");
                }

                // Get datarows with required columns
                DataRow dr = PortalHelper.CombineWithDefaultValues(fi, wi);

                // Load default values for new widget
                if (IsNewWidget || (xmlVersion > 0))
                {
                    fi.LoadDefaultValues(dr, FormResolveTypeEnum.Visible);
                }

                if (IsNewWidget)
                {
                    // Override default value and set title as widget display name
                    DataHelper.SetDataRowValue(dr, "WidgetTitle", ResHelper.LocalizeString(wi.WidgetDisplayName));
                }

                // Load values from existing widget
                LoadDataRowFromWidget(dr, fi);

                // Init HTML toolbar if exists
                InitHTMLToobar(fi);

                // Init the form
                InitForm(formCustom, dr, fi);

                // Set the context name
                formCustom.ControlContext.ContextName = CMS.SiteProvider.ControlContext.WIDGET_PROPERTIES;
            }
        }

        if (IsInline)
        {
            // Load text definition from session
            string definition = ValidationHelper.GetString(SessionHelper.GetValue("WidgetDefinition"), string.Empty);
            if (String.IsNullOrEmpty(definition))
            {
                definition = Request.Form[hdnWidgetDefinition.UniqueID];
            }
            else
            {
                hdnWidgetDefinition.Value = definition;
            }

            Hashtable parameters = null;

            if (IsNewWidget)
            {
                // New widget - load widget info by id
                if (!String.IsNullOrEmpty(WidgetId))
                {
                    wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0));
                }
                else
                {
                    // Try to get widget from codename
                    mName = QueryHelper.GetString("WidgetName", String.Empty);
                    wi    = WidgetInfoProvider.GetWidgetInfo(mName);
                }
            }
            else
            {
                if (definition == null)
                {
                    DisplayError("widget.failedtoload");
                    return;
                }

                // Parse definition
                parameters = CMSDialogHelper.GetHashTableFromString(definition);

                // Trim control name
                if (parameters["name"] != null)
                {
                    mName = parameters["name"].ToString();
                }

                wi = WidgetInfoProvider.GetWidgetInfo(mName);
            }
            if (wi == null)
            {
                DisplayError("widget.failedtoload");
                return;
            }

            // If widget cant be used as inline
            if (!wi.WidgetForInline)
            {
                DisplayError("widget.cantbeusedasinline");
                return;
            }


            // Test permission for user
            CurrentUserInfo currentUser = CMSContext.CurrentUser;
            if (!WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated()))
            {
                mIsValidWidget = false;
                OnNotAllowed(this, null);
            }

            // If user is editor, more properties are shown
            WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.User;
            if (currentUser.IsEditor)
            {
                zoneType = WidgetZoneTypeEnum.Editor;
            }

            WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID);
            string      widgetProperties   = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties);
            FormInfo    zoneTypeDefinition = PortalFormHelper.GetPositionFormInfo(zoneType);
            FormInfo    fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), widgetProperties, zoneTypeDefinition, true);

            if (fi != null)
            {
                // Check if there are some editable properties
                mFields = fi.GetFields(true, true);
                if ((mFields == null) || !mFields.Any())
                {
                    lblInfo.Visible = true;
                    lblInfo.Text    = GetString("widgets.emptyproperties");
                }

                // Get datarows with required columns
                DataRow dr = PortalHelper.CombineWithDefaultValues(fi, wi);

                if (IsNewWidget)
                {
                    // Load default values for new widget
                    fi.LoadDefaultValues(dr, FormResolveTypeEnum.Visible);
                }
                else
                {
                    foreach (string key in parameters.Keys)
                    {
                        object value = parameters[key];
                        // Test if given property exists
                        if (dr.Table.Columns.Contains(key) && (value != null))
                        {
                            try
                            {
                                dr[key] = DataHelper.ConvertValue(value, dr.Table.Columns[key].DataType);
                            }
                            catch
                            {
                            }
                        }
                    }
                }

                // Override default value and set title as widget display name
                DataHelper.SetDataRowValue(dr, "WidgetTitle", wi.WidgetDisplayName);

                // Init HTML toolbar if exists
                InitHTMLToobar(fi);

                // Init the form
                InitForm(formCustom, dr, fi);

                // Set the context name
                formCustom.ControlContext.ContextName = CMS.SiteProvider.ControlContext.WIDGET_PROPERTIES;
            }
        }
    }
    /// <summary>
    /// Page_Load event.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            return;
        }

        // Create and set category provider
        UniTreeProvider categoryProvider = new UniTreeProvider();

        categoryProvider.DisplayNameColumn = "DisplayName";
        categoryProvider.IDColumn          = "ObjectID";
        categoryProvider.LevelColumn       = "ObjectLevel";
        categoryProvider.OrderColumn       = "ObjectType DESC, WidgetCategoryOrder";
        categoryProvider.ParentIDColumn    = "ParentID";
        categoryProvider.PathColumn        = "ObjectPath";
        categoryProvider.ValueColumn       = "ObjectID";
        categoryProvider.ChildCountColumn  = "CompleteChildCount";
        categoryProvider.QueryName         = "cms.widgetcategory.selectallview";
        categoryProvider.ObjectTypeColumn  = "ObjectType";
        categoryProvider.ImageColumn       = "WidgetCategoryImagePath";
        categoryProvider.Columns           = "ObjectID, DisplayName, ParentID, WidgetCategoryImagePath, ObjectPath, WidgetCategoryOrder, WidgetCategoryChildCount, ObjectLevel, CompleteChildCount, ObjectType";


        // Build where condition
        CurrentUserInfo currentUser   = CMSContext.CurrentUser;
        string          securityWhere = String.Empty;


        // Security where condition
        if (!SelectGroupWidgets && !currentUser.IsGlobalAdministrator)
        {
            securityWhere = "(WidgetSecurity = 0)"; // Allowed for all
            if (currentUser.IsAuthenticated())
            {
                securityWhere += " OR (WidgetSecurity = 1)"; // Authenticated
                if (currentUser.IsGlobalAdministrator)
                {
                    securityWhere += " OR (WidgetSecurity = 7)";                                                                                                                                                                                         // Global admin
                }
                securityWhere += " OR ((WidgetSecurity = 2) AND (ObjectID IN ( SELECT WidgetID FROM CMS_WidgetRole WHERE RoleID IN (SELECT RoleID FROM View_CMS_UserRole_MembershipRole_ValidOnly_Joined WHERE UserID = " + currentUser.UserID + "))))"; // Authorized roles
            }
        }

        //  Categories AND widgets
        if (SelectWidgets)
        {
            categoryProvider.WhereCondition = securityWhere;
            treeElem.OnGetImage            += new CMSAdminControls_UI_Trees_UniTree.GetImageEventHandler(treeElem_OnGetImage);
        }
        else // Only Categories
        {
            categoryProvider.WhereCondition   = "ObjectType = 'widgetcategory'";
            categoryProvider.ChildCountColumn = "WidgetCategoryChildCount";
            categoryProvider.ObjectTypeColumn = "";
            treeElem.DefaultImagePath         = GetImageUrl("Objects/CMS_WidgetCategory/list.png");

            // Create WHERE condition which filters categories without widgets
            string where = "";
            where        = @"0 <>(SELECT TOP 1 ObjectID FROM 
            (SELECT ObjectPath AS WidgetPath, ObjectType, WidgetForUser, WidgetForGroup, WidgetForEditor, WidgetSecurity, ObjectID, WidgetForInline, WidgetForDashboard
            FROM View_CMS_WidgetCategoryWidget_Joined) AS SUB 
            WHERE SUB.ObjectType = 'widget' AND SUB.WidgetPath LIKE ObjectPath + '%'";

            if (SelectEditorWidgets)
            {
                where += " AND SUB.WidgetForEditor = 1 ";
            }
            else if (SelectUserWidgets)
            {
                where += " AND SUB.WidgetForUser = 1 ";
            }
            else if (SelectGroupWidgets)
            {
                where += " AND SUB.WidgetForGroup = 1";
            }
            else if (SelectInlineWidgets)
            {
                where += " AND SUB.WidgetForInline = 1 ";
            }
            else if (SelectDashboardWidgets)
            {
                where += " AND SUB.WidgetForDashboard = 1 ";
            }
            else
            {
                where += " AND 1 = 2 ";
            }

            if (!string.IsNullOrEmpty(securityWhere))
            {
                where += " AND ( " + securityWhere + ")";
            }

            categoryProvider.WhereCondition = SqlHelperClass.AddWhereCondition(categoryProvider.WhereCondition, where + ")");
        }

        // Set up tree
        treeElem.ProviderObject = categoryProvider;

        if (SelectWidgets)
        {
            string script = "onclick=\"SelectNode(##NODEID##,'##OBJECTTYPE##', ##PARENTNODEID##);\"";
            treeElem.NodeTemplate         = String.Format("<span id=\"##OBJECTTYPE##_##NODEID##\" {0} name=\"treeNode\" class=\"ContentTreeItem\">##ICON## <span class=\"Name\">##NODENAME##</span></span>", script);
            treeElem.SelectedNodeTemplate = String.Format("<span id=\"##OBJECTTYPE##_##NODEID##\" {0} name=\"treeNode\" class=\"ContentTreeItem ContentTreeSelectedItem\">##ICON## <span class=\"Name\">##NODENAME##</span></span>", script);
        }
        else
        {
            treeElem.NodeTemplate                = "<span onclick=\"SelectNode(##NODEID##, this);\" class=\"ContentTreeItem\">##ICON## <span class=\"Name\">##NODENAME##</span></span>";
            treeElem.DefaultItemTemplate         = "<span onclick=\"SelectNode('recentlyused', this);\" class=\"ContentTreeItem\">##ICON##<span class=\"Name\">##NODENAME##</span></span>";
            treeElem.SelectedDefaultItemTemplate = "<span onclick=\"SelectNode('recentlyused', this);\" class=\"ContentTreeItem ContentTreeSelectedItem\">##ICON##<span class=\"Name\">##NODENAME##</span></span>";
            treeElem.SelectedNodeTemplate        = "<span onclick=\"SelectNode(##NODEID##, this);\" class=\"ContentTreeItem ContentTreeSelectedItem\">##ICON## <span class=\"Name\">##NODENAME##</span></span>";

            // Register jquery
            ScriptHelper.RegisterJQuery(Page);

            string js = "var selectedItem = $j('.ContentTreeSelectedItem');" +
                        "function SelectNode(nodeid, sender){" +
                        "selectedItem.removeClass('ContentTreeSelectedItem'); " +
                        "selectedItem.addClass('ContentTreeItem');" +
                        "selectedItem = $j(sender);" +
                        "selectedItem.removeClass('ContentTreeItem'); " +
                        "selectedItem.addClass('ContentTreeSelectedItem'); " +
                        "document.getElementById('" + treeElem.SelectedItemFieldId + "').value = nodeid;" +
                        treeElem.GetOnSelectedItemBackEventReference() +
                        "}";

            ScriptHelper.RegisterStartupScript(Page, typeof(string), "SelectTreeNode", ScriptHelper.GetScript(js));
        }

        // Add last recently used
        if (ShowRecentlyUsed)
        {
            treeElem.AddDefaultItem(GetString("widgets.recentlyused"), "recentlyused", ResolveUrl(GetImageUrl("CMSModules/CMS_Widgets/recentlyused.png")));
        }

        // Setup event handler
        treeElem.OnItemSelected += new CMSAdminControls_UI_Trees_UniTree.ItemSelectedEventHandler(treeElem_OnItemSelected);
        treeElem.OnNodeCreated  += new CMSAdminControls_UI_Trees_UniTree.NodeCreatedEventHandler(treeElem_OnNodeCreated);
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            currentUser = CMSContext.CurrentUser;

            if (currentUser.IsAuthenticated())
            {
                // Control initialiazation
                lblTitle.Text    = GetString("Ecommerce.Wishlist.Title");
                btnContinue.Text = GetString("Ecommerce.Wishlist.btnContinue");

                mSKUId      = QueryHelper.GetInteger("productID", 0);
                currentSite = CMSContext.CurrentSite;

                // Set repeater transformation
                repeater.TransformationName = TransformationName;
                repeater.ItemSeparator      = ItemSeparator;

                if ((currentUser != null) && (currentSite != null))
                {
                    if ((!RequestHelper.IsPostBack()) && (mSKUId > 0))
                    {
                        int addSKUId = mSKUId;

                        // Get added SKU info object from database
                        SKUInfo skuObj = SKUInfoProvider.GetSKUInfo(addSKUId);
                        if (skuObj != null)
                        {
                            // Can not add option as a product
                            if (skuObj.SKUOptionCategoryID > 0)
                            {
                                addSKUId = 0;
                            }
                            else if (!skuObj.IsGlobal)
                            {
                                // Site specific product must belong to the current site
                                if (skuObj.SKUSiteID != currentSite.SiteID)
                                {
                                    addSKUId = 0;
                                }
                            }
                            else
                            {
                                // Global products must be allowed when adding global product
                                if (!ECommerceSettings.AllowGlobalProducts(currentSite.SiteName))
                                {
                                    addSKUId = 0;
                                }
                            }
                        }

                        if (addSKUId > 0)
                        {
                            // Add specified product to the user's wishlist
                            WishlistItemInfoProvider.AddSKUToWishlist(currentUser.UserID, addSKUId, currentSite.SiteID);
                            LogProductAddedToWLActivity(addSKUId, ResHelper.LocalizeString(skuObj.SKUName));
                        }
                    }

                    if (mSKUId > 0)
                    {
                        // Remove product parameter from URL to avoid adding it next time
                        string newUrl = URLHelper.RemoveParameterFromUrl(URLRewriter.CurrentURL, "productID");
                        URLHelper.Redirect(newUrl);
                    }
                }
            }
            else
            {
                // Hide control if current user is not authenticated
                Visible = false;
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            pi = CMSContext.CurrentPageInfo;
            if (pi != null)
            {
                CMSPagePlaceholder parentPlaceHolder = PortalHelper.FindParentPlaceholder(this);

                // Nothing to render, nothing to do
                if ((!DisplayAddButton && !DisplayResetButton) || ((parentPlaceHolder != null) && (parentPlaceHolder.UsingDefaultPage)))
                {
                    Visible = false;
                    return;
                }

                CurrentUserInfo currentUser = CMSContext.CurrentUser;
                zoneType = WidgetZoneTypeCode.ToEnum(WidgetZoneType);


                // Check security
                if (((zoneType == WidgetZoneTypeEnum.Group) && !currentUser.IsGroupAdministrator(pi.NodeGroupID)) ||
                    ((zoneType == WidgetZoneTypeEnum.User || zoneType == WidgetZoneTypeEnum.Dashboard) && !currentUser.IsAuthenticated()))
                {
                    Visible      = false;
                    resetAllowed = false;
                    return;
                }

                // Displaying - Editor zone only in edit mode, User/Group zone only in Live site/Preview mode
                if (((zoneType == WidgetZoneTypeEnum.Editor) && ((CMSContext.ViewMode != ViewModeEnum.Edit) && (CMSContext.ViewMode != ViewModeEnum.EditLive))) ||
                    (((zoneType == WidgetZoneTypeEnum.User) || (zoneType == WidgetZoneTypeEnum.Group)) && ((CMSContext.ViewMode != ViewModeEnum.LiveSite) && (CMSContext.ViewMode != ViewModeEnum.Preview))) || ((zoneType == WidgetZoneTypeEnum.Dashboard) && ((CMSContext.ViewMode != ViewModeEnum.DashboardWidgets) || (String.IsNullOrEmpty(PortalContext.DashboardName)))))
                {
                    Visible      = false;
                    resetAllowed = false;
                    return;
                }

                // Get current document
                TreeNode currentNode = DocumentHelper.GetDocument(pi.DocumentID, TreeProvider);
                if (((zoneType == WidgetZoneTypeEnum.Editor) && (!currentUser.IsEditor || (currentUser.IsAuthorizedPerDocument(currentNode, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied))))
                {
                    Visible      = false;
                    resetAllowed = false;
                    return;
                }

                // If use checkin checkout enabled, check if document is checkout by current user
                if (zoneType == WidgetZoneTypeEnum.Editor)
                {
                    if (currentNode != null)
                    {
                        WorkflowManager wm = WorkflowManager.GetInstance(TreeProvider);
                        // Get workflow info
                        WorkflowInfo wi = wm.GetNodeWorkflow(currentNode);

                        // Check if node is under workflow and if use checkin checkout enabled
                        if ((wi != null) && (wi.UseCheckInCheckOut(CMSContext.CurrentSiteName)))
                        {
                            int checkedOutBy = currentNode.DocumentCheckedOutByUserID;

                            // Check if document is checkout by current user
                            if (checkedOutBy != CMSContext.CurrentUser.UserID)
                            {
                                Visible      = false;
                                resetAllowed = false;
                                return;
                            }
                        }
                    }
                }

                // Find widget zone
                PageTemplateInfo pti = pi.UsedPageTemplateInfo;

                // ZodeID specified directly
                if (!String.IsNullOrEmpty(WidgetZoneID))
                {
                    zoneInstance = pti.GetZone(WidgetZoneID);
                }

                // Zone not find or specified zone is not of correct type
                if ((zoneInstance != null) && (zoneInstance.WidgetZoneType != zoneType))
                {
                    zoneInstance = null;
                }

                // For delete all variants all zones are necessary
                if (parentPlaceHolder != null)
                {
                    var zones = parentPlaceHolder.WebPartZones;
                    if (zones != null)
                    {
                        foreach (CMSWebPartZone zone in zones)
                        {
                            if ((zone.ZoneInstance != null) && (zone.ZoneInstance.WidgetZoneType == zoneType))
                            {
                                zoneInstances.Add(zone.ZoneInstance);
                                if (zoneInstance == null)
                                {
                                    zoneInstance = zone.ZoneInstance;
                                }
                            }
                        }
                    }
                }

                // No suitable zones on the page, nothing to do
                if (zoneInstance == null)
                {
                    Visible      = false;
                    resetAllowed = false;
                    return;
                }

                // Adding is enabled
                if (DisplayAddButton)
                {
                    pnlAdd.Visible       = true;
                    lnkAddWidget.Visible = true;
                    lnkAddWidget.Text    = HTMLHelper.HTMLEncode(DataHelper.GetNotEmpty(AddButtonText, GetString("widgets.addwidget")));

                    int templateId = 0;
                    if (pi.UsedPageTemplateInfo != null)
                    {
                        templateId = pi.UsedPageTemplateInfo.PageTemplateId;
                    }

                    addScript = "NewWidget('" + HttpUtility.UrlEncode(zoneInstance.ZoneID) + "', '" + HttpUtility.UrlEncode(pi.NodeAliasPath) + "', '" + templateId + "'); return false;";
                    lnkAddWidget.Attributes.Add("onclick", addScript);
                }

                // Reset is enabled
                if (DisplayResetButton)
                {
                    pnlReset.Visible = true;
                    btnReset.Text    = HTMLHelper.HTMLEncode(DataHelper.GetNotEmpty(ResetButtonText, GetString("widgets.resettodefault")));
                    btnReset.Click  += new EventHandler(btnReset_Click);

                    // Add confirmation if required
                    if (ResetConfirmationRequired)
                    {
                        btnReset.Attributes.Add("onclick", "if (!confirm('" + GetString("widgets.resetzoneconfirmtext") + "')) return false;");
                    }
                }

                // Set the panel css clas with dependence on actions zone type
                switch (zoneType)
                {
                // Editor
                case WidgetZoneTypeEnum.Editor:
                    pnlWidgetActions.CssClass = "EditorWidgetActions";
                    break;

                // User
                case WidgetZoneTypeEnum.User:
                    pnlWidgetActions.CssClass = "UserWidgetActions";
                    break;

                // Group
                case WidgetZoneTypeEnum.Group:
                    pnlWidgetActions.CssClass = "GroupWidgetActions";
                    break;

                // Dashboard
                case WidgetZoneTypeEnum.Dashboard:
                {
                    if (pnlContextHelp.Controls.Count == 0)
                    {
                        // Load help control dynamically (due to faster start compilation)
                        var help = this.LoadUserControl("~/CMSAdminControls/UI/PageElements/Help.ascx") as HelpControl;
                        help.TopicName = "dashboard";
                    }
                }
                break;
                }
            }
        }
    }
Esempio n. 12
0
    /// <summary>
    /// Displays registration section depending on situation.
    /// </summary>
    protected void DisplayRegistration()
    {
        if (!string.IsNullOrEmpty(RegistrationTitle))
        {
            lblRegTitle.Text    = RegistrationTitle;
            lblRegTitle.Visible = true;
        }

        CurrentUserInfo userInfo = CMSContext.CurrentUser;

        // Display registration form to anonymous user only if this is allowed
        if ((AllowAnonymousRegistration || (userInfo != null && userInfo.IsAuthenticated())) && EventNode != null)
        {
            DateTime now = DateTime.Now;
            // Display registration form if opened
            if ((openFrom == DataHelper.DATETIME_NOT_SELECTED || openFrom < now) && (openTo == DataHelper.DATETIME_NOT_SELECTED || now <= openTo) && (now <= eventDate))
            {
                int actualCount = EventAttendeeInfoProvider.GetEventAttendeesCount(EventNode.OriginalNodeID);
                // Display registration form if capacity is not full
                if (allowRegistrationOverCapacity || (actualCount < capacity))
                {
                    // Preset fields with info of authenticated user
                    if (userInfo != null && userInfo.IsAuthenticated() && !RequestHelper.IsPostBack())
                    {
                        txtFirstName.Text = userInfo.FirstName;
                        txtLastName.Text  = userInfo.LastName;
                        txtEmail.Text     = userInfo.Email;
                    }

                    // Hide non-required fields
                    if (!RequireName)
                    {
                        plcName.Visible = false;
                    }
                    if (!RequirePhone)
                    {
                        plcPhone.Visible = false;
                    }
                }
                else
                {
                    pnlReg.Visible   = false;
                    lblError.Text    = GetString("eventmanager.fullcapacity");
                    lblError.Visible = true;
                    errorOccurs      = true;
                }
            }
            else
            {
                pnlReg.Visible   = false;
                lblError.Text    = GetString("eventmanager.notopened");
                lblError.Visible = true;
                errorOccurs      = true;
            }
        }
        else
        {
            pnlReg.Visible   = false;
            lblError.Text    = GetString("eventmanager.notauthenticated");
            lblError.Visible = true;
            errorOccurs      = true;
        }
    }
Esempio n. 13
0
    /// <summary>
    /// Reload data.
    /// </summary>
    public override void ReloadData()
    {
        requestedUserId = ValidationHelper.GetInteger(ContextMenu.Parameter, 0);

        DataTable table = new DataTable();

        table.Columns.Add("ActionIcon");
        table.Columns.Add("ActionDisplayName");
        table.Columns.Add("ActionScript");

        // Get resource strings prefix
        string resourcePrefix = ContextMenu.ResourcePrefix;

        // Add only if community is present
        if (CommunityPresent)
        {
            // Friendship request
            if ((requestedUserId != currentUser.UserID) && UIHelper.IsFriendsModuleEnabled(CMSContext.CurrentSiteName))
            {
                FriendshipStatusEnum status = currentUser.HasFriend(requestedUserId);
                // If friendship exists add reject action or request friendship
                if (status == FriendshipStatusEnum.Approved)
                {
                    table.Rows.Add(new object[] { "friendshipreject.png", ResHelper.GetString(resourcePrefix + ".rejectfriendship|friends.rejectfriendship"), currentUser.IsAuthenticated() ? "ContextFriendshipReject(GetContextMenuParameter('" + ContextMenu.MenuID + "'))" : "ContextRedirectToSignInUrl()" });
                }
                else if ((status == FriendshipStatusEnum.None) || currentUser.IsPublic())
                {
                    table.Rows.Add(new object[] { "friendshiprequest.png", ResHelper.GetString(resourcePrefix + ".requestfriendship|friends.requestfriendship"), currentUser.IsAuthenticated() ? "ContextFriendshipRequest(GetContextMenuParameter('" + ContextMenu.MenuID + "'))" : "ContextRedirectToSignInUrl()" });
                }
                // Group invitation
                table.Rows.Add(new object[] { "invitetogroup.png", ResHelper.GetString(resourcePrefix + ".invite|groupinvitation.invite"), currentUser.IsAuthenticated() ? "ContextGroupInvitation(GetContextMenuParameter('" + ContextMenu.MenuID + "'))" : "ContextRedirectToSignInUrl()" });
            }
        }

        // Add only if messaging is present
        if (MessagingPresent)
        {
            // Check if user is in ignore list
            isInIgnoreList = ModuleCommands.MessagingIsInIgnoreList(currentUser.UserID, requestedUserId);

            // Check if user is in contact list
            isInContactList = ModuleCommands.MessagingIsInContactList(currentUser.UserID, requestedUserId);

            table.Rows.Add(new object[] { "sendmessage.png", ResHelper.GetString(resourcePrefix + ".sendmessage|sendmessage.sendmessage"), currentUser.IsAuthenticated() ? "ContextPrivateMessage(GetContextMenuParameter('" + ContextMenu.MenuID + "'))" : "ContextRedirectToSignInUrl()" });

            // Not for the same user
            if (requestedUserId != currentUser.UserID)
            {
                // Add to ignore list or add to contact list actions
                if (!isInIgnoreList)
                {
                    table.Rows.Add(new object[] { "addtoignorelist.png", ResHelper.GetString(resourcePrefix + ".addtoignorelist|messsaging.addtoignorelist"), currentUser.IsAuthenticated() ? "ContextAddToIgnoretList(GetContextMenuParameter('" + ContextMenu.MenuID + "'))" : "ContextRedirectToSignInUrl()" });
                }

                if (!isInContactList)
                {
                    table.Rows.Add(new object[] { "addtocontactlist.png", ResHelper.GetString(resourcePrefix + ".addtocontactlist|messsaging.addtocontactlist"), currentUser.IsAuthenticated() ? "ContextAddToContactList(GetContextMenuParameter('" + ContextMenu.MenuID + "'))" : "ContextRedirectToSignInUrl()" });
                }
            }
        }

        // Add count column
        DataColumn countColumn = new DataColumn();

        countColumn.ColumnName   = "Count";
        countColumn.DefaultValue = table.Rows.Count;

        table.Columns.Add(countColumn);
        repItem.DataSource = table;
        repItem.DataBind();
    }
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // Do not process control by default
        StopProcessing = true;

        // Keep frequent objects
        cui = CMSContext.CurrentUser;
        PageInfo pi = CMSContext.CurrentPageInfo;

        if (pi == null)
        {
            IsPageNotFound = true;
            pi             = OnSiteEditHelper.PageInfoForPageNotFound;
        }

        ucUIToolbar.StopProcessing = true;
        largeCMSDeskButton         = !cui.UserSiteManagerAdmin;

        // Check whether user is authorized to edit page
        if ((pi != null) && cui.IsAuthenticated() && cui.IsEditor && ((IsPageNotFound && pi.NodeID == 0) || cui.IsAuthorizedPerTreeNode(pi.NodeID, NodePermissionsEnum.Read) == AuthorizationResultEnum.Allowed))
        {
            // Enable processing
            StopProcessing = false;

            // Check whether the preferred culture is RTL
            isRTL = CultureHelper.IsUICultureRTL();

            // Add link to CSS file
            CSSHelper.RegisterCSSLink(Page, "Design", "OnSiteEdit.css");

            // Filter UI element buttons
            ucUIToolbar.OnButtonFiltered += ucUIToolbar_OnButtonFiltered;
            ucUIToolbar.OnButtonCreated  += ucUIToolbar_OnButtonCreated;
            ucUIToolbar.OnButtonCreating += ucUIToolbar_OnButtonCreating;
            ucUIToolbar.OnGroupsCreated  += ucUIToolbar_OnGroupsCreated;
            ucUIToolbar.IsRTL             = isRTL;

            // Register edit script file
            RegisterEditScripts(pi);

            if (ViewMode == ViewModeEnum.EditLive)
            {
                popupHandler.Visible           = true;
                IsLiveSite                     = false;
                MessagesPlaceHolder.IsLiveSite = false;
                MessagesPlaceHolder.Opacity    = 100;

                // Display warning in the Safe mode
                if (PortalHelper.SafeMode)
                {
                    string safeModeText        = GetString("onsiteedit.safemode") + "<br/><a href=\"" + URLHelper.RawUrl.Replace("safemode=1", "safemode=0") + "\">" + GetString("general.close") + "</a> " + GetString("contentedit.safemode2");
                    string safeModeDescription = GetString("onsiteedit.safemode") + "<br/>" + GetString("general.seeeventlog");

                    // Display the warning message
                    ShowWarning(safeModeText, safeModeDescription, "");
                }

                ucUIToolbar.StopProcessing = false;

                // Ensure document redirection
                if (!String.IsNullOrEmpty(pi.DocumentMenuRedirectUrl))
                {
                    string redirectUrl = CMSContext.ResolveMacros(pi.DocumentMenuRedirectUrl);
                    redirectUrl = URLHelper.ResolveUrl(redirectUrl);
                    ShowInformation(GetString("onsiteedit.redirectinfo") + " <a href=\"" + redirectUrl + "\">" + redirectUrl + "</a>");
                }
            }
            // Mode menu on live site
            else if (ViewMode == ViewModeEnum.LiveSite)
            {
                // Hide the edit panel, show only slider button
                pnlToolbarSpace.Visible = false;
                pnlToolbar.Visible      = false;
                pnlSlider.Visible       = true;

                imgSliderButton.ImageUrl      = GetImageUrl("CMSModules/CMS_PortalEngine/OnSiteEdit/edit.png");
                imgSliderButton.ToolTip       = GetString("onsiteedit.editmode");
                imgSliderButton.AlternateText = GetString("onsitedit.editmode");

                pnlButton.Attributes.Add("onclick", "OnSiteEdit_ChangeEditMode();");

                imgMaximize.Style.Add("display", "none");
                imgMaximize.AlternateText = GetString("general.maximize");
                imgMaximize.ImageUrl      = GetImageUrl("CMSModules/CMS_PortalEngine/OnSiteEdit/ArrowDown.png");
                imgMinimize.ImageUrl      = GetImageUrl("CMSModules/CMS_PortalEngine/OnSiteEdit/ArrowUp.png");
                imgMinimize.AlternateText = GetString("general.minimize");
                pnlMinimize.Attributes.Add("onclick", "OESlideSideToolbar();");

                // Hide the OnSite edit button when displayed in CMSDesk
                pnlSlider.Style.Add("display", "none");
            }
        }
        // Hide control actions for unauthorized users
        else
        {
            plcEdit.Visible = false;
        }
    }
Esempio n. 15
0
    /// <summary>
    /// Adds the inline widget without the properties dialog.
    /// </summary>
    /// <param name="widgetId">The widget id</param>
    private string AddInlineWidgetWithoutDialog(int widgetId)
    {
        string script = string.Empty;

        if (widgetId > 0)
        {
            // New widget - load widget info by id
            WidgetInfo wi = WidgetInfoProvider.GetWidgetInfo(widgetId);

            if ((wi != null) && wi.WidgetForInline)
            {
                // Test permission for user
                CurrentUserInfo currentUser = CMSContext.CurrentUser;
                if (!WidgetRoleInfoProvider.IsWidgetAllowed(widgetId, currentUser.UserID, currentUser.IsAuthenticated()))
                {
                    return(string.Empty);
                }

                // If user is editor, more properties are shown
                WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.User;
                if (currentUser.IsEditor)
                {
                    zoneType = WidgetZoneTypeEnum.Editor;
                }

                WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID);

                // Get the properties xml according to the zone type
                FormInfo zoneTypeDefinition = PortalFormHelper.GetPositionFormInfo(zoneType);

                // Merge the parent web part properties definition with the widget properties definition
                string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties);

                // Create the FormInfo for the current widget properties definition
                FormInfo fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), widgetProperties, zoneTypeDefinition, true);
                DataRow  dr = null;

                if (fi != null)
                {
                    // Check if there are some editable properties
                    List <FormFieldInfo> mFields = fi.GetFields(true, true);

                    // Get data rows with required columns
                    dr = PortalHelper.CombineWithDefaultValues(fi, wi);

                    // Load default values for new widget
                    fi.LoadDefaultValues(dr, FormResolveTypeEnum.Visible);

                    // Override default value and set title as widget display name
                    DataHelper.SetDataRowValue(dr, "WidgetTitle", wi.WidgetDisplayName);
                }

                // Save inline widget script
                script = PortalHelper.GetAddInlineWidgetScript(wi, dr, fi.GetFields(true, true));

                script += " CloseDialog();";

                if (!string.IsNullOrEmpty(script))
                {
                    // Add to recently used widgets collection
                    CMSContext.CurrentUser.UserSettings.UpdateRecentlyUsedWidget(wi.WidgetName);
                }
            }
        }

        return(script);
    }
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // Do not process control by default
        StopProcessing = true;

        // Keep frequent objects
        cui = CMSContext.CurrentUser;
        PageInfo pi = CMSContext.CurrentPageInfo;

        if (pi == null)
        {
            IsPageNotFound = true;
            pi = OnSiteEditHelper.PageInfoForPageNotFound;
        }

        ucUIToolbar.StopProcessing = true;
        largeCMSDeskButton = !cui.UserSiteManagerAdmin;

        // Check whether user is authorized to edit page
        if ((pi != null) && cui.IsAuthenticated() && cui.IsEditor && ((IsPageNotFound && pi.NodeID == 0) || cui.IsAuthorizedPerTreeNode(pi.NodeID, NodePermissionsEnum.Read) == AuthorizationResultEnum.Allowed))
        {
            // Enable processing
            StopProcessing = false;

            // Check whether the preferred culture is RTL
            isRTL = CultureHelper.IsUICultureRTL();

            // Add link to CSS file
            CSSHelper.RegisterCSSLink(Page, "Design", "OnSiteEdit.css");

            // Filter UI element buttons
            ucUIToolbar.OnButtonFiltered += ucUIToolbar_OnButtonFiltered;
            ucUIToolbar.OnButtonCreated += ucUIToolbar_OnButtonCreated;
            ucUIToolbar.OnButtonCreating += ucUIToolbar_OnButtonCreating;
            ucUIToolbar.OnGroupsCreated += ucUIToolbar_OnGroupsCreated;
            ucUIToolbar.IsRTL = isRTL;

            // Register edit script file
            RegisterEditScripts(pi);

            if (ViewMode == ViewModeEnum.EditLive)
            {
                popupHandler.Visible = true;
                IsLiveSite = false;
                MessagesPlaceHolder.IsLiveSite = false;
                MessagesPlaceHolder.Opacity = 100;

                // Display warning in the Safe mode
                if (PortalHelper.SafeMode)
                {
                    string safeModeText = GetString("onsiteedit.safemode") + "<br/><a href=\"" + URLHelper.RawUrl.Replace("safemode=1", "safemode=0") + "\">" + GetString("general.close") + "</a> " + GetString("contentedit.safemode2");
                    string safeModeDescription = GetString("onsiteedit.safemode") + "<br/>" + GetString("general.seeeventlog");

                    // Display the warning message
                    ShowWarning(safeModeText, safeModeDescription, "");
                }

                ucUIToolbar.StopProcessing = false;

                // Ensure document redirection
                if (!String.IsNullOrEmpty(pi.DocumentMenuRedirectUrl))
                {
                    string redirectUrl = CMSContext.ResolveMacros(pi.DocumentMenuRedirectUrl);
                    redirectUrl = URLHelper.ResolveUrl(redirectUrl);
                    ShowInformation(GetString("onsiteedit.redirectinfo") + " <a href=\"" + redirectUrl + "\">" + redirectUrl + "</a>");
                }
            }
            // Mode menu on live site
            else if (ViewMode == ViewModeEnum.LiveSite)
            {
                // Hide the edit panel, show only slider button
                pnlToolbarSpace.Visible = false;
                pnlToolbar.Visible = false;
                pnlSlider.Visible = true;

                imgSliderButton.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/OnSiteEdit/edit.png");
                imgSliderButton.ToolTip = GetString("onsiteedit.editmode");
                imgSliderButton.AlternateText = GetString("onsitedit.editmode");

                pnlButton.Attributes.Add("onclick", "OnSiteEdit_ChangeEditMode();");

                imgMaximize.Style.Add("display", "none");
                imgMaximize.AlternateText = GetString("general.maximize");
                imgMaximize.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/OnSiteEdit/ArrowDown.png");
                imgMinimize.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/OnSiteEdit/ArrowUp.png");
                imgMinimize.AlternateText = GetString("general.minimize");
                pnlMinimize.Attributes.Add("onclick", "OESlideSideToolbar();");

                // Hide the OnSite edit button when displayed in CMSDesk
                pnlSlider.Style.Add("display", "none");
            }
        }
        // Hide control actions for unauthorized users
        else
        {
            plcEdit.Visible = false;
        }
    }
Esempio n. 17
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (this.StopProcessing)
        {
            // Do nothing
        }
        else
        {
            currentUser = CMSContext.CurrentUser;

            if (currentUser.IsAuthenticated())
            {
                // Control initialiazation
                lblTitle.Text = GetString("Ecommerce.Wishlist.Title");
                btnContinue.Text = GetString("Ecommerce.Wishlist.btnContinue");

                mSKUId = QueryHelper.GetInteger("productID", 0);
                currentSite = CMSContext.CurrentSite;

                // Set repeater transformation
                repeater.TransformationName = this.TransformationName;
                repeater.ItemSeparator = this.ItemSeparator;

                if ((currentUser != null) && (currentSite != null))
                {
                    if ((!RequestHelper.IsPostBack()) && (mSKUId > 0))
                    {
                        int addSKUId = mSKUId;

                        // Get added SKU info object from database
                        SKUInfo skuObj = SKUInfoProvider.GetSKUInfo(addSKUId);
                        if (skuObj != null)
                        {
                            // Can not add option as a product
                            if (skuObj.SKUOptionCategoryID > 0)
                            {
                                addSKUId = 0;
                            }
                            else if (!skuObj.IsGlobal)
                            {
                                // Site specific product must belong to the current site
                                if (skuObj.SKUSiteID != currentSite.SiteID)
                                {
                                    addSKUId = 0;
                                }
                            }
                            else
                            {
                                // Global products must be allowed when adding global product
                                if (!ECommerceSettings.AllowGlobalProducts(currentSite.SiteName))
                                {
                                    addSKUId = 0;
                                }
                            }
                        }

                        if (addSKUId > 0)
                        {
                            // Add specified product to the user's wishlist
                            WishlistItemInfoProvider.AddSKUToWishlist(currentUser.UserID, addSKUId, currentSite.SiteID);
                            LogProductAddedToWLActivity(addSKUId, ResHelper.LocalizeString(skuObj.SKUName), currentSite.SiteID);
                        }
                    }

                    if (mSKUId > 0)
                    {
                        // Remove product parameter from URL to avoid adding it next time
                        string newUrl = URLHelper.RemoveParameterFromUrl(URLRewriter.CurrentURL, "productID");
                        URLHelper.Redirect(newUrl);
                    }
                }
            }
            else
            {
                // Hide control if current user is not authenticated
                this.Visible = false;
            }
        }
    }
Esempio n. 18
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Public user is not allowed for widgets
        if (!CMSContext.CurrentUser.IsAuthenticated())
        {
            RedirectToAccessDenied(GetString("widgets.security.notallowed"));
        }

        string widgetId     = QueryHelper.GetString("widgetid", String.Empty);
        string aliasPath    = QueryHelper.GetString("aliasPath", String.Empty);
        string zoneId       = QueryHelper.GetString("zoneid", String.Empty);
        Guid   instanceGUID = QueryHelper.GetGuid("instanceguid", Guid.Empty);
        bool   isNewWidget  = QueryHelper.GetBoolean("isnew", false);
        bool   inline       = QueryHelper.GetBoolean("inline", false);

        // Set page title
        Page.Title = GetString(isNewWidget ? "widgets.propertiespage.titlenew" : "widgets.propertiespage.title");

        if ((widgetId != string.Empty) && (aliasPath != string.Empty))
        {
            // Get pageinfo
            PageInfo pi = null;
            try
            {
                pi = PageInfoProvider.GetPageInfo(CMSContext.CurrentSiteName, aliasPath, CMSContext.PreferredCultureCode, null, CMSContext.CurrentSite.CombineWithDefaultCulture);
            }
            catch (PageNotFoundException)
            {
                // Do not throw exception if page info not found (e.g. bad alias path)
            }

            if (pi == null)
            {
                return;
            }

            // Get template instance
            PageTemplateInstance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi);

            // Get widget from instance
            WidgetInfo wi = null;
            if (!isNewWidget)
            {
                // Get the instance of widget
                WebPartInstance widgetInstance = templateInstance.GetWebPart(instanceGUID, widgetId);
                if (widgetInstance == null)
                {
                    return;
                }

                // Get widget info by widget name(widget type)
                wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType);
            }
            // Widget instance hasn't created yet
            else
            {
                wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(widgetId, 0));
            }


            if (wi != null)
            {
                WebPartZoneInstance zone = templateInstance.GetZone(zoneId);
                if (zone != null)
                {
                    CurrentUserInfo currentUser = CMSContext.CurrentUser;

                    bool checkSecurity = true;

                    // Check security
                    // It is group zone type but widget is not allowed in group
                    if (zone.WidgetZoneType == WidgetZoneTypeEnum.Group)
                    {
                        // Should always be, only group widget are allowed in group zone
                        if (wi.WidgetForGroup)
                        {
                            if (!currentUser.IsGroupAdministrator(pi.NodeGroupID))
                            {
                                RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                            }

                            // All ok, don't check classic security
                            checkSecurity = false;
                        }
                    }

                    if (checkSecurity && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated()))
                    {
                        RedirectToAccessDenied(GetString("widgets.security.notallowed"));
                    }
                }
            }
        }
        // If all ok, set up frames
        frameHeader.Attributes.Add("src", "widgetproperties_header.aspx" + URLHelper.Url.Query);
        if (inline && !isNewWidget)
        {
            frameContent.Attributes.Add("src", ResolveUrl("~/CMSPages/Blank.htm"));
        }
        else
        {
            frameContent.Attributes.Add("src", "widgetproperties_properties_frameset.aspx" + URLHelper.Url.Query);
        }
    }
Esempio n. 19
0
    /// <summary>
    /// OK click hadler.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        #region "Security"

        // Check whether forum exists
        if (ForumContext.CurrentForum == null)
        {
            return;
        }

        // Check security
        bool securityCheck = true;
        switch (ForumContext.CurrentState)
        {
        case ForumStateEnum.NewThread:
            securityCheck = IsAvailable(ForumContext.CurrentForum, ForumActionType.NewThread);
            break;

        case ForumStateEnum.ReplyToPost:
            securityCheck = IsAvailable(ForumContext.CurrentForum, ForumActionType.Reply);
            break;

        case ForumStateEnum.EditPost:
            securityCheck = ForumContext.CurrentPost != null && IsAvailable(ForumContext.CurrentPost, ForumActionType.Edit);
            break;
        }

        if (!securityCheck)
        {
            ShowError(GetString("ForumNewPost.PermissionDenied"));
            return;
        }


        #region "Captcha"

        // Check security code if is required
        if ((ForumContext.CurrentForum.ForumUseCAPTCHA) && (!SecurityCode1.IsValid()) && (ForumContext.CurrentState != ForumStateEnum.EditPost))
        {
            ShowError(GetString("ForumNewPost.InvalidCaptcha"));
            return;
        }

        #endregion



        #region "Email field"

        // Create instance of validator
        Validator validator = new Validator();

        // Check whether email is valid
        string result = validator.IsEmail(txtEmail.Text, rfvEmail.ErrorMessage).Result;

        // Check whether email is present with correct format if email is required
        // or when subscribtion to current post is checked
        if ((ForumContext.CurrentForum.ForumRequireEmail || chkSubscribe.Checked) && (!String.IsNullOrEmpty(result)))
        {
            ShowError(result);
            return;
        }

        // Check if email is added if is in correct format
        if ((txtEmail.Text.Trim() != "") && (!String.IsNullOrEmpty(result)))
        {
            ShowError(rfvEmail.ErrorMessage);
            return;
        }

        #endregion


        #region "Subject"

        // Check whether subject is filled
        if (txtSubject.Text.Trim() == "")
        {
            ShowError(rfvSubject.ErrorMessage);
            return;
        }

        #endregion


        #region "Text"

        validator = new Validator();

        // Check post text in HTML editor or text area
        if (!ForumContext.CurrentForum.ForumHTMLEditor)
        {
            // Check whether post text is added in text area
            if ((result = validator.NotEmpty(DiscussionMacroHelper.RemoveTags(ucBBEditor.Text), rfvText.ErrorMessage).Result) != "")
            {
                ShowError(result);
                return;
            }
        }
        else
        {
            // Check whether post text is added in HTML editor
            if ((result = validator.NotEmpty(htmlTemplateBody.ResolvedValue, rfvText.ErrorMessage).Result) != "")
            {
                ShowError(result);
                return;
            }
        }

        #endregion


        #region "User name"

        // Check whether user name is filled if user name field is visible
        if (ForumContext.CurrentForum.ForumAllowChangeName || MembershipContext.AuthenticatedUser.IsPublic() || ((ForumContext.CurrentForum != null) && (ForumContext.UserIsModerator(ForumContext.CurrentForum.ForumID, ForumContext.CommunityGroupID))))
        {
            validator = new Validator();

            if (!String.IsNullOrEmpty(result = validator.NotEmpty(txtUserName.Text, rfvUserName.ErrorMessage).Result))
            {
                ShowError(result);
                return;
            }
        }

        #endregion


        #endregion


        #region "Forum post properties"

        bool newPost = false;

        // Current forum info object
        ForumInfo fi = ForumContext.CurrentForum;

        // Forum post info object
        ForumPostInfo fp = null;

        // Get forum post info with dependence on current state
        if (ForumContext.CurrentState == ForumStateEnum.EditPost)
        {
            // Get existing object
            fp = ForumContext.CurrentPost;
            fp.PostLastEdit = DateTime.Now;
        }
        else
        {
            // Create new forum post info object
            fp      = new ForumPostInfo();
            newPost = true;
        }


        #region "Ad-hoc forum"

        if (IsAdHocForum && (ForumContext.CurrentForum.ForumID == 0))
        {
            if (DocumentContext.CurrentDocument == null)
            {
                ShowError(GetString("forums.documentdoesnotexist"));
                return;
            }

            fi.ForumGroupID     = ForumGroupInfoProvider.GetAdHocGroupInfo(SiteID).GroupID;
            fi.ForumName        = "AdHoc-" + Guid.NewGuid();
            fi.ForumDisplayName = TextHelper.LimitLength(DocumentContext.CurrentDocument.GetDocumentName(), POST_USERNAME_LENGTH, String.Empty);
            fi.ForumOpen        = true;
            fi.ForumModerated   = false;
            fi.ForumAccess      = 040000;
            fi.ForumThreads     = 0;
            fi.ForumPosts       = 0;
            fi.ForumLogActivity = LogActivity;
            ForumInfoProvider.SetForumInfo(fi);

            ForumContext.CurrentForum.ForumID = fi.ForumID;
            ForumContext.ForumID = fi.ForumID;
            ForumID = fi.ForumID;
        }

        #endregion


        // Post forum
        fp.PostForumID = ForumContext.CurrentForum.ForumID;
        // Get forum post info with dependence on current state
        if (ForumContext.CurrentState != ForumStateEnum.EditPost)
        {
            // Post time
            fp.PostTime = DateTime.Now;
            // User IP address
            fp.PostInfo.IPAddress = RequestContext.UserHostAddress;
            // User agent
            fp.PostInfo.Agent = Request.UserAgent;
            // Post user id
            if (!MembershipContext.AuthenticatedUser.IsPublic())
            {
                fp.PostUserID = MembershipContext.AuthenticatedUser.UserID;
            }

            // Post signature
            fp.PostUserSignature = txtSignature.Text;
        }

        // Post subject
        fp.PostSubject = txtSubject.Text;
        // Post user email
        fp.PostUserMail = txtEmail.Text;


        // Post type
        int forumType = ForumContext.CurrentForum.ForumType;
        if (forumType == 0)
        {
            if (ForumContext.CurrentReplyThread == null)
            {
                // New thread - use type which user chosen
                fp.PostType = (radTypeDiscussion.Checked ? 0 : 1);
            }
            else
            {
                // Reply - use parent type
                fp.PostType = ForumContext.CurrentReplyThread.PostType;
            }
        }
        else
        {
            // Fixed type - use the forum setting
            fp.PostType = forumType - 1;
        }

        bool newThread = (ForumContext.CurrentReplyThread == null);

        // Set username if change name is allowed
        if (fi.ForumAllowChangeName || MembershipContext.AuthenticatedUser.IsPublic() || ForumContext.UserIsModerator(fp.PostForumID, ForumContext.CommunityGroupID))
        {
            fp.PostUserName = TextHelper.LimitLength(txtUserName.Text, POST_USERNAME_LENGTH, "");
        }
        else
        {
            // Get forum post info with dependence on current state
            if (ForumContext.CurrentState != ForumStateEnum.EditPost)
            {
                fp.PostUserName = UserName;
            }
        }

        // Post parent id -> reply to
        if (ForumContext.CurrentReplyThread != null)
        {
            fp.PostParentID = ForumContext.CurrentReplyThread.PostId;

            // Check max relative level
            if ((MaxRelativeLevel > -1) && (ForumContext.CurrentReplyThread.PostLevel >= MaxRelativeLevel))
            {
                ShowError(GetString("Forums.MaxRelativeLevelError"));
                return;
            }
        }

        // Get post text from HTML editor if is enabled
        fp.PostText = ForumContext.CurrentForum.ForumHTMLEditor ? htmlTemplateBody.ResolvedValue : ucBBEditor.Text;

        // Approve post if forum is not moderated
        if (newPost)
        {
            if (!ForumContext.CurrentForum.ForumModerated)
            {
                fp.PostApproved = true;
            }
            else
            {
                if (ForumContext.UserIsModerator(fp.PostForumID, CommunityGroupID))
                {
                    fp.PostApproved         = true;
                    fp.PostApprovedByUserID = MembershipContext.AuthenticatedUser.UserID;
                }
            }
        }

        // If signature is enabled then
        if (EnableSignature)
        {
            fp.PostUserSignature = MembershipContext.AuthenticatedUser.UserSignature;
        }

        #endregion


        if (!BadWordInfoProvider.CanUseBadWords(MembershipContext.AuthenticatedUser, SiteContext.CurrentSiteName))
        {
            // Prepare columns to check
            Dictionary <string, int> columns = new Dictionary <string, int>();
            columns.Add("PostText", 0);
            columns.Add("PostSubject", 450);
            columns.Add("PostUserSignature", 0);
            columns.Add("PostUserName", 200);

            // Perform bad words check
            string badMessage = BadWordsHelper.CheckBadWords(fp, columns, "PostApproved", "PostApprovedByUserID", fp.PostText, MembershipContext.AuthenticatedUser.UserID, () => { return(ValidatePost(fp)); });

            if (String.IsNullOrEmpty(badMessage))
            {
                if (!ValidatePost(fp))
                {
                    badMessage = GetString("ForumNewPost.EmptyBadWord");
                }
            }

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



        // Flood protection
        if (FloodProtectionHelper.CheckFlooding(SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser))
        {
            ShowError(GetString("General.FloodProtection"));
            return;
        }

        // Check banned ip
        if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete))
        {
            ShowError(GetString("General.BannedIP"));
            return;
        }

        string baseUrl = ForumContext.CurrentForum.ForumBaseUrl;
        if (String.IsNullOrEmpty(baseUrl))
        {
            baseUrl = FriendlyBaseURL;
        }

        string unsubscriptionUrl = ForumContext.CurrentForum.ForumUnsubscriptionUrl;
        if (String.IsNullOrEmpty(unsubscriptionUrl))
        {
            unsubscriptionUrl = UnsubscriptionURL;
        }

        // USe parent post id for new post
        int subscibePostId = newPost ? fp.PostParentID : fp.PostId;

        // Check subscriptions
        if ((chkSubscribe.Checked) && (!String.IsNullOrEmpty(txtEmail.Text)) && (ForumSubscriptionInfoProvider.IsSubscribed(txtEmail.Text.Trim(), fp.PostForumID, subscibePostId)))
        {
            // Post of the forum is already subscribed to this email -> show an error
            chkSubscribe.Checked = false;
            ShowError(GetString("Forums.EmailAlreadySubscribed"));
            return;
        }

        // Save post object
        ForumPostInfoProvider.SetForumPostInfo(fp, baseUrl, unsubscriptionUrl);
        LogPostActivity(fp, fi);


        #region "Subscription"

        // If subscribe is checked create new subscription to the current post
        if ((chkSubscribe.Checked) && (!ForumSubscriptionInfoProvider.IsSubscribed(fp.PostUserMail, fp.PostForumID, fp.PostId)))
        {
            // Create new subscription info object
            ForumSubscriptionInfo fsi = new ForumSubscriptionInfo();
            // Set info properties
            fsi.SubscriptionForumID = fp.PostForumID;
            fsi.SubscriptionEmail   = fp.PostUserMail;
            fsi.SubscriptionPostID  = fp.PostId;
            fsi.SubscriptionUserID  = fp.PostUserID;
            fsi.SubscriptionGUID    = Guid.NewGuid();

            // Save subscription
            ForumSubscriptionInfoProvider.Subscribe(fsi, DateTime.Now, true, true);

            if (fsi.SubscriptionApproved)
            {
                LogSubscriptionActivity(fsi, fi);
            }
        }

        #endregion

        bool moderationRequired = false;
        if ((!fp.PostApproved) && (!ForumContext.UserIsModerator(fp.PostForumID, CommunityGroupID)))
        {
            moderationRequired = true;
            if (OnModerationRequired != null)
            {
                OnModerationRequired(this, null);
            }
        }

        // Keep current user info
        CurrentUserInfo currentUser = MembershipContext.AuthenticatedUser;

        if (currentUser.IsAuthenticated() && chkAttachFile.Checked && (currentUser.IsGlobalAdministrator || ForumContext.CurrentForum.AllowAttachFiles != SecurityAccessEnum.Nobody))
        {
            // Redirect to the post attachments
            string attachmentUrl = GetURL(fp, ForumActionType.Attachment);
            if (moderationRequired)
            {
                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "moderated", "1");
            }
            URLHelper.Redirect(attachmentUrl);
        }
        else
        {
            if (!StopProcessing)
            {
                // Redirect back to the forum or forum thread
                URLHelper.Redirect(ClearURL());
            }
        }
    }
Esempio n. 20
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (this.StopProcessing)
        {
            this.editForm.StopProcessing = true;
            this.editForm.Visible        = false;
        }
        else
        {
            this.pnlEdit.Visible = false;

            CurrentUserInfo currentUser = CMSContext.CurrentUser;

            // Get the document
            TreeNode node = TreeHelper.GetDocument(this.SiteName, CMSContext.ResolveCurrentPath(this.Path), this.CultureCode, false, null, false, this.CheckPermissions, currentUser);
            if (node != null)
            {
                bool authorized = false;

                // Check allowed users
                switch (this.AllowUsers)
                {
                case UserContributionAllowUserEnum.All:
                    authorized = true;
                    break;

                case UserContributionAllowUserEnum.Authenticated:
                    authorized = currentUser.IsAuthenticated();
                    break;

                case UserContributionAllowUserEnum.DocumentOwner:
                    authorized = (node.NodeOwner == currentUser.UserID);
                    break;
                }

                bool authorizedDelete = authorized;

                // Check control access permission
                if (authorized && this.CheckPermissions)
                {
                    // Node owner has always permission
                    if (node.NodeOwner != currentUser.UserID)
                    {
                        authorized       &= (currentUser.IsAuthorizedPerDocument(node, new NodePermissionsEnum[] { NodePermissionsEnum.Read, NodePermissionsEnum.Modify }) == AuthorizationResultEnum.Allowed);
                        authorizedDelete &= (currentUser.IsAuthorizedPerDocument(node, new NodePermissionsEnum[] { NodePermissionsEnum.Read, NodePermissionsEnum.Delete }) == AuthorizationResultEnum.Allowed);
                    }
                }

                // Check group permissions
                authorized       &= CheckGroupPermission("editpages");
                authorizedDelete &= CheckGroupPermission("deletepages");
                // Global admin has always permission
                authorized       |= currentUser.IsGlobalAdministrator;
                authorizedDelete |= currentUser.IsGlobalAdministrator;

                // Do not allow edit for virtual user
                if (currentUser.IsVirtual)
                {
                    authorized       = false;
                    authorizedDelete = false;
                }

                // Display form if authorized
                if (authorized || authorizedDelete)
                {
                    this.pnlEdit.Visible = true;

                    // Set visibility of edit and delete buttons
                    this.btnEdit.Visible   = this.btnEdit.Visible && authorized;
                    this.btnDelete.Visible = this.btnDelete.Visible && this.AllowDelete && authorizedDelete;

                    if ((!RequestHelper.IsPostBack()) && ((this.btnEdit.Text.Trim() == string.Empty) || (this.btnDelete.Text.Trim() == string.Empty)))
                    {
                        // Initialize labels and css classes
                        this.btnEdit.ResourceString   = this.EditButtonText;
                        this.btnEdit.CssClass         = "EditContributionEdit";
                        this.btnDelete.ResourceString = this.DeleteButtonText;
                        this.btnDelete.CssClass       = "EditContributionDelete";
                    }

                    if (this.pnlForm.Visible)
                    {
                        this.editForm.StopProcessing         = false;
                        this.editForm.FunctionsPrefix        = this.ID + "_";
                        this.editForm.AllowDelete            = this.AllowDelete && CheckGroupPermission("deletepages");
                        this.editForm.CheckPermissions       = this.CheckPermissions;
                        this.editForm.NodeID                 = node.NodeID;
                        this.editForm.SiteName               = this.SiteName;
                        this.editForm.CultureCode            = this.CultureCode;
                        this.editForm.AlternativeFormName    = this.AlternativeFormName;
                        this.editForm.ValidationErrorMessage = this.ValidationErrorMessage;
                        this.editForm.CMSForm.IsLiveSite     = true;

                        this.editForm.OnAfterApprove      += editForm_OnAfterChange;
                        this.editForm.OnAfterReject       += editForm_OnAfterChange;
                        this.editForm.OnAfterDelete       += editForm_OnAfterChange;
                        this.editForm.CMSForm.OnAfterSave += CMSForm_OnAfterSave;
                        this.editForm.LogActivity          = this.LogActivity;

                        // Reload data
                        this.editForm.ReloadData(false);
                    }
                }
            }
        }
    }