/// <summary>
    /// Returns field caption of the specified column.
    /// </summary>
    /// <param name="ffi">Form field info</param>
    /// <param name="columnName">Column name</param>    
    protected string GetFieldCaption(FormFieldInfo ffi, string columnName, MacroResolver resolver)
    {
        string fieldCaption = string.Empty;

        // get field caption
        if (ffi != null)
        {
            fieldCaption = ffi.GetDisplayName(resolver);
        }
        if (string.IsNullOrEmpty(fieldCaption))
        {
            fieldCaption = columnName;
        }

        return fieldCaption;
    }
Beispiel #2
0
    private string BuildStartupScript()
    {
        bool       enBBCode = IsSupport || (ChatSettingsProvider.EnableBBCodeSetting && EnableBBCode);
        WebControl input    = enBBCode ? ucBBEditor.TextArea : txtMessage;

        if (enBBCode)
        {
            txtMessage.Visible = false;
        }
        else
        {
            ucBBEditor.Visible = false;
        }

        string json = JsonConvert.SerializeObject(
            new
        {
            roomID                        = RoomID,
            inputClientID                 = GetString(input),
            buttonClientID                = GetString(btnSendMessage),
            groupID                       = GroupID,
            chbWhisperClientID            = GetString(chbWhisper),
            drpRecipientClientID          = GetString(drpRecipient),
            pnlRecipientContainerClientID = GetString(pnlRecipientContainer),
            noneLabel                     = ResHelper.GetString("chat.everyone"),
            enableBBCode                  = enBBCode,
            bbCodeClientID                = GetString(ucBBEditor),
            btnCannedResponses            = GetString(btnCannedResponses),
            pnlContent                    = GetString(pnlWebpartContent),
            envelopeID                    = "#envelope_" + ClientID,
            informDialogID                = GetString(pnlChatMessageSendInfoDialog),
            btnInformDialogClose          = GetString(btnChatMessageSendInformDialogClose)
        },
            new JsonSerializerSettings {
            StringEscapeHandling = StringEscapeHandling.EscapeHtml
        }
            );
        string startupScript = String.Format("InitChatSenderWebpart({0});", json);

        // If this webpart is for support person -> generate "Canned responses"
        if ((ChatOnlineUserHelper.GetLoggedInChatUser() != null) && (IsSupport == true))
        {
            // Get canned responses from database
            IEnumerable <ChatSupportCannedResponseInfo> cannedResponses = ChatSupportCannedResponseInfoProvider.GetCannedResponses(ChatOnlineUserHelper.GetLoggedInChatUser().ChatUserID, SiteContext.CurrentSiteID);

            if (cannedResponses.Any())
            {
                plcCannedResponses.Visible = true;

                // Register necessary files
                ScriptHelper.RegisterScriptFile(Page, "~/CMSWebParts/Chat/ChatMessageSend_files/CannedResponses.js");
                CssRegistration.RegisterCssLink(Page, "~/App_Themes/Design/Chat/ChatIntelliSense.css");

                // Creates canned responses in format expected in javascript
                var cannedResponseToSerialize = from cr in cannedResponses
                                                let resolvedText = MacroResolver.Resolve(cr.ChatSupportCannedResponseText)
                                                                   select new
                {
                    label   = "#" + HTMLHelper.HTMLEncode(cr.ChatSupportCannedResponseTagName),
                    tooltip = HTMLHelper.HTMLEncode(TextHelper.LimitLength(resolvedText, mTooltipLength)),
                    value   = resolvedText
                };

                // Serialize canned responses to JS Array expected by javascript
                string cannedResponsesJSArray = "";
                try
                {
                    cannedResponsesJSArray = JsonConvert.SerializeObject(cannedResponseToSerialize, new JsonSerializerSettings {
                        StringEscapeHandling = StringEscapeHandling.EscapeHtml
                    });
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("Chat", "JSON serialization of canned responses", ex);
                }
                startupScript += string.Format("var CannedResponses = {0};", cannedResponsesJSArray);

                startupScript += string.Format("InitCannedResponses({0}, {1});", ScriptHelper.GetString("#" + input.ClientID), ScriptHelper.GetString("#" + btnCannedResponses.ClientID));
            }
        }

        return(startupScript);
    }
 public void SendEmail(MacroResolver mcr, string TemplateName, string ToEmail)
 {
     EmailMessage email = new EmailMessage();
     EmailTemplateInfo eti = EmailTemplateProvider.GetEmailTemplate(TemplateName, CMSContext.CurrentSiteID);
     email.EmailFormat = EmailFormatEnum.Html;
     email.Recipients = ToEmail;
     EmailSender.SendEmailWithTemplateText(CMSContext.CurrentSiteName, email, eti, mcr, true);
 }
    /// <summary>
    /// Sends the email.
    /// </summary>
    protected void Send()
    {
        // Check "modify" permission
        if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.Users", "Modify"))
        {
            RedirectToAccessDenied("CMS.Users", "Modify");
        }

        var sender = emailSender.Text;

        // Validate first
        if (!emailSender.IsValid() || string.IsNullOrEmpty(sender))
        {
            ShowError(GetString("general.correctemailformat"));
            return;
        }

        // Get recipients
        string groupIds = null;

        if (groupsControl != null)
        {
            groupIds = Convert.ToString(groupsControl.Value);
        }
        string userIDs = Convert.ToString(users.Value);
        string roleIDs = Convert.ToString(roles.Value);

        if (string.IsNullOrEmpty(groupIds) && string.IsNullOrEmpty(userIDs) && string.IsNullOrEmpty(roleIDs))
        {
            ShowError(GetString("massemail.norecipients"));
            return;
        }

        // Get resolver to resolve context macros
        MacroResolver resolver = MacroResolver.GetInstance();

        // Create the message
        EmailMessage message = new EmailMessage();

        message.Subject = resolver.ResolveMacros(txtSubject.Text);
        message.From    = sender;
        if (plcText.Visible)
        {
            message.Body = resolver.ResolveMacros(htmlText.ResolvedValue);
        }
        if (plcPlainText.Visible)
        {
            message.PlainTextBody = resolver.ResolveMacros(txtPlainText.Text);
        }

        // Get the attachments
        HttpPostedFile[] attachments = uploader.PostedFiles;
        foreach (HttpPostedFile att in attachments)
        {
            message.Attachments.Add(new EmailAttachment(att.InputStream, Path.GetFileName(att.FileName), Guid.NewGuid(), DateTime.Now, siteId));
        }

        // Check if list of roleIds contains generic role 'Everyone'
        bool containsEveryone = false;

        if (!String.IsNullOrEmpty(roleIDs))
        {
            RoleInfo roleEveryone = RoleInfoProvider.GetRoleInfo(RoleName.EVERYONE, siteId);
            if ((roleEveryone != null) && (";" + roleIDs + ";").Contains(";" + roleEveryone.RoleID + ";"))
            {
                containsEveryone = true;
            }
        }

        // Send messages using email engine
        EmailSender.SendMassEmails(message, userIDs, roleIDs, groupIds, siteId, containsEveryone);

        // Clear the form if email was sent successfully
        Clear();
        ShowConfirmation(GetString("system_email.emailsent"));
    }
Beispiel #5
0
    /// <summary>
    /// Gets parent node ID.
    /// </summary>
    private TreeNode GetParentNode()
    {
        TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

        return(tree.SelectSingleNode(SiteName, MacroResolver.ResolveCurrentPath(NewDocumentPath), TreeProvider.ALL_CULTURES));
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            editForm.StopProcessing = true;
            editForm.Visible        = false;
        }
        else
        {
            pnlEdit.Visible = false;

            var currentUser = MembershipContext.AuthenticatedUser;

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

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

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

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

                bool authorizedDelete = authorized;

                // Check control access permission
                if (authorized && 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)
                {
                    pnlEdit.Visible = true;

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

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

                    editForm.ComponentName = WebPartID;
                    editForm.LogActivity   = LogActivity;

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

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

                        // Reload data
                        editForm.ReloadData(false);
                    }
                }
            }
        }
    }
Beispiel #7
0
    /// <summary>
    /// Sends e-mail with password if required.
    /// </summary>
    /// <param name="subject">Subject of the e-mail sent</param>
    /// <param name="pswd">Password to send</param>
    /// <param name="emailType">Type of the e-mail specifying the template used (NEW, CHANGED, RESEND)</param>
    /// <param name="showPassword">Indicates whether password is shown in message.</param>
    private void SendEmail(string subject, string pswd, string emailType, bool showPassword)
    {
        // Check whether the 'From' element was specified
        string siteName    = SiteContext.CurrentSiteName;
        string emailFrom   = SettingsKeyInfoProvider.GetValue("CMSSendPasswordEmailsFrom", siteName);
        bool   fromMissing = string.IsNullOrEmpty(emailFrom);

        if ((!string.IsNullOrEmpty(emailType)) && (UserInfo != null) && (!fromMissing))
        {
            string emailTo = UserInfo.Email;
            if (!String.IsNullOrEmpty(emailTo))
            {
                EmailMessage em = new EmailMessage();

                em.From        = emailFrom;
                em.Recipients  = emailTo;
                em.Subject     = subject;
                em.EmailFormat = EmailFormatEnum.Default;

                string templateName = null;

                // Get e-mail template name
                switch (emailType.ToLowerCSafe())
                {
                case "new":
                    templateName = "Membership.NewPassword";
                    break;

                case "changed":
                    templateName = "Membership.ChangedPassword";
                    break;

                case "resend":
                    templateName = "Membership.ResendPassword";
                    break;
                }

                // Get template info object
                if (templateName != null)
                {
                    try
                    {
                        // Get e-mail template - try to get site specific template if edited user is assigned to current site
                        EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate(templateName, UserInfo.IsInSite(siteName) ? siteName : null);
                        if (template != null)
                        {
                            em.Body = template.TemplateText;

                            // Create macro resolver
                            MacroResolver resolver = MembershipResolvers.GetPasswordResolver(UserInfo, pswd);

                            // Add template attachments
                            EmailHelper.ResolveMetaFileImages(em, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);

                            // Send message immediately (+ resolve macros)
                            EmailSender.SendEmailWithTemplateText(siteName, em, template, resolver, true);

                            // Inform on success
                            ShowConfirmation(GetString("Administration-User_Edit_Password.PasswordsSent") + " " + HTMLHelper.HTMLEncode(emailTo));

                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        // Log the error to the event log
                        EventLogProvider.LogException("Password retrieval", "USERPASSWORD", ex);
                        ShowError("Failed to send the password: "******"Administration-User_Edit_Password.passshow"), pswd), true);
                }
                else
                {
                    ShowConfirmation(GetString("Administration-User_Edit_Password.PassChangedNotSent"));
                }

                return;
            }
        }

        // Inform on error
        string errorMessage = GetString("Administration-User_Edit_Password.PasswordsNotSent");

        if (fromMissing)
        {
            errorMessage += " " + GetString("Administration-User_Edit_Password.FromMissing");
        }

        ShowError(errorMessage);
    }
    protected void gridData_OnLoadColumns()
    {
        if ((bfi != null) && (FormInfo != null))
        {
            var    columnList = new List <string>();
            string columns    = bfi.FormReportFields;
            if (string.IsNullOrEmpty(columns))
            {
                columnList = GetExistingColumns();
            }
            else
            {
                // Get existing columns names
                var existingColumns = GetExistingColumns();

                // Get selected columns
                var selectedColumns = GetSelectedColumns(columns);

                columns     = string.Empty;
                columnNames = string.Empty;
                StringBuilder sb = new StringBuilder();

                // Remove nonexisting columns
                foreach (string col in selectedColumns)
                {
                    if (existingColumns.Contains(col))
                    {
                        columnList.Add(col);
                        sb.Append(",[").Append(col).Append("]");
                    }
                }
                columnNames = sb.ToString();

                // Ensure primary key
                if (!(columnNames.Contains(primaryColumn) || columnNames.Contains(primaryColumn)))
                {
                    columnNames = ",[" + primaryColumn + "]" + columnNames;
                }

                columnNames = columnNames.TrimStart(',');
            }

            // Get macro resolver for current form
            MacroResolver resolver = MacroResolverStorage.GetRegisteredResolver(FormHelper.FORM_PREFIX + dci.ClassName);

            // Loop trough all columns
            for (int i = 0; i < columnList.Count; i++)
            {
                string column = columnList[i];

                // Get field caption
                FormFieldInfo ffi = FormInfo.GetFormField(column);

                string fieldCaption = null;
                if (ffi == null)
                {
                    fieldCaption = column;
                }
                else
                {
                    string caption = ffi.GetDisplayName(resolver);
                    fieldCaption = (string.IsNullOrEmpty(caption)) ? column : ResHelper.LocalizeString(caption);
                }

                Column columnDefinition = new Column
                {
                    Caption      = fieldCaption,
                    Source       = column,
                    AllowSorting = true,
                    Wrap         = false
                };

                if (i == columnList.Count - 1)
                {
                    // Stretch last column
                    columnDefinition.Width = "100%";
                }

                gridData.GridColumns.Columns.Add(columnDefinition);
            }
        }
    }
Beispiel #9
0
    protected void drpTransformationType_SelectedIndexChanged(object sender, EventArgs e)
    {
        UpdateDirectives();

        if (ti.TransformationCheckedOutByUserID <= 0)
        {
            // Show checkout info corresponding to selected type
            TransformationTypeEnum type = TransformationInfoProvider.GetTransformationTypeEnum(drpType.SelectedValue);
            string path = Server.MapPath(TransformationInfoProvider.GetTransformationUrl(ti.TransformationFullName, null, type));
            lblCheckOutInfo.Text = string.Format(GetString("Transformation.CheckOutInfo"), path);
        }

        // Get the current code
        string code = "";

        if (txtCode.Visible)
        {
            code = this.txtCode.Text;
        }
        else
        {
            code = this.tbWysiwyg.ResolvedValue;
        }

        switch (drpType.SelectedValue.ToLower())
        {
        case "ascx":
            // Convert to ASCX syntax
            if (string.Equals(drpType.SelectedValue, "ascx", StringComparison.OrdinalIgnoreCase))
            {
                code = MacroResolver.RemoveSecurityParameters(code, false, null);

                code = code.Replace("{% Register", "<%@ Register").Replace("{%", "<%#").Replace("%}", "%>");
            }
            break;

        case "xslt":
            // No transformation
            break;

        default:
            // Convert to macro syntax
            code = code.Replace("<%@", "{%").Replace("<%#", "{%").Replace("<%=", "{%").Replace("<%", "{%").Replace("%>", "%}");
            break;
        }

        // Move the content if necessary
        if (string.Equals(drpType.SelectedValue, "html", StringComparison.OrdinalIgnoreCase))
        {
            // Move from text to WYSIWYG
            if (txtCode.Visible)
            {
                this.tbWysiwyg.ResolvedValue = code;
                this.tbWysiwyg.Visible       = true;

                this.txtCode.Text    = string.Empty;
                this.txtCode.Visible = false;
            }
        }
        else
        {
            // Move from WYSIWYG to text
            if (tbWysiwyg.Visible)
            {
                code = HttpUtility.HtmlDecode(code);

                this.txtCode.Text    = code;
                this.txtCode.Visible = true;

                this.tbWysiwyg.ResolvedValue = string.Empty;
                this.tbWysiwyg.Visible       = false;
            }
            else
            {
                this.txtCode.Text = code;
            }
        }
    }
Beispiel #10
0
    /// <summary>
    /// Setups control properties.
    /// </summary>
    protected void SetupControl()
    {
        // Check StopProcessing property
        if (StopProcessing)
        {
            Visible = false;
        }
        else
        {
            if (!Service.Entry <ILicenseService>().IsFeatureAvailable(FeatureEnum.OnlineUsers))
            {
                ShowLicenseLimitationError();

                return;
            }

            SetContext();

            DataSet users       = null;
            bool    transLoaded = false;

            // Load transformation
            if (!string.IsNullOrEmpty(TransformationName))
            {
                repUsers.ItemTemplate = TransformationHelper.LoadTransformation(this, TransformationName);
                transLoaded           = true;
            }

            if ((transLoaded) || (!String.IsNullOrEmpty(Path)))
            {
                // Try to get data from cache
                using (var cs = new CachedSection <DataSet>(ref users, CacheMinutes, true, CacheItemName, "onlineusers", SiteContext.CurrentSiteName, SelectTopN, Columns, Path))
                {
                    if (cs.LoadData)
                    {
                        // Get the data
                        users = SessionManager.GetOnlineUsers(null, null, SelectTopN, Columns, MacroResolver.ResolveCurrentPath(Path), SiteContext.CurrentSiteName, false, false);

                        // Prepare the cache dependency
                        if (cs.Cached)
                        {
                            cs.CacheDependency = GetCacheDependency();
                        }

                        cs.Data = users;
                    }
                }

                // Data bind
                if (!DataHelper.DataSourceIsEmpty(users))
                {
                    // Set to repeater
                    repUsers.DataSource = users;
                    repUsers.DataBind();
                }
            }

            int authenticated = 0;
            int publicUsers   = 0;

            string numbers = string.Empty;

            // Get or generate cache item name
            string cacheItemNameNumbers = CacheItemName;
            if (!string.IsNullOrEmpty(cacheItemNameNumbers))
            {
                cacheItemNameNumbers += "Number";
            }

            // Try to get data from cache
            using (var cs = new CachedSection <string>(ref numbers, CacheMinutes, true, cacheItemNameNumbers, "onlineusersnumber", SiteContext.CurrentSiteName, Path))
            {
                if (cs.LoadData)
                {
                    // Get the data
                    SessionManager.GetUsersNumber(CurrentSiteName, MacroResolver.ResolveCurrentPath(Path), false, false, out publicUsers, out authenticated);

                    // Save to the cache
                    if (cs.Cached)
                    {
                        cs.CacheDependency = GetCacheDependency();
                    }

                    cs.Data = publicUsers.ToString() + ";" + authenticated.ToString();
                }
                else if (!String.IsNullOrEmpty(numbers))
                {
                    // Retrieved from cache
                    string[] nums = numbers.Split(';');

                    publicUsers   = ValidationHelper.GetInteger(nums[0], 0);
                    authenticated = ValidationHelper.GetInteger(nums[1], 0);
                }
            }

            // Check if at least one user is online
            if ((publicUsers + authenticated) == 0)
            {
                ltrAdditionaInfos.Text = NoUsersOnlineText;
            }
            else
            {
                ltrAdditionaInfos.Text = string.Format(AdditionalInfoText, publicUsers + authenticated, publicUsers, authenticated);
            }
        }

        ReleaseContext();
    }
Beispiel #11
0
    /// <summary>
    /// Unigrid external data bound handler.
    /// </summary>
    protected object uniGrid_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        switch (sourceName.ToLowerCSafe())
        {
        case "yesno":
            return(UniGridFunctions.ColoredSpanYesNo(parameter));

        case "select":
        {
            DataRowView drv = (parameter as DataRowView);

            // Get item ID
            string itemID  = drv[returnColumnName].ToString();
            string hashKey = itemID;

            // Add global object name prefix if required
            if (AddGlobalObjectNamePrefix && !String.IsNullOrEmpty(iObjectType.SiteIDColumn) && (ValidationHelper.GetInteger(DataHelper.GetDataRowValue(drv.Row, iObjectType.SiteIDColumn), 0) == 0))
            {
                itemID = "." + itemID;
            }

            // Store hash codes for grid items
            if (!hashItems.ContainsKey(hashKey))
            {
                hashItems.Add(hashKey, ValidationHelper.GetHashString(itemID));
            }

            // Add checkbox for multiple selection
            switch (selectionMode)
            {
            case SelectionModeEnum.Multiple:
            case SelectionModeEnum.MultipleTextBox:
            case SelectionModeEnum.MultipleButton:
            {
                string checkBox = string.Format("<span class=\"checkbox\"><input id=\"chk{0}\" type=\"checkbox\" onclick=\"ProcessItem(this,'{1}',false,true);\" class=\"chckbox\" ", itemID, hashItems[hashKey]);
                if (hidItem.Value.IndexOfCSafe(valuesSeparator + itemID + valuesSeparator, true) >= 0)
                {
                    checkBox += "checked=\"checked\" ";
                }
                if (disabledItems.Contains(string.Format("{0}{1}{0}", valuesSeparator, itemID)))
                {
                    checkBox += "disabled=\"disabled\" ";
                }

                checkBox += string.Format("/><label for=\"chk{0}\">&nbsp;</label></span>", itemID);

                return(checkBox);
            }
            }
        }
        break;

        case "itemname":
        {
            DataRowView drv = (parameter as DataRowView);

            // Get item ID
            string itemID  = drv[returnColumnName].ToString();
            string hashKey = itemID;

            // Get item name
            string itemName;

            // Special formatted user name
            if (displayNameFormat == UniSelector.USER_DISPLAY_FORMAT)
            {
                string userName = ValidationHelper.GetString(DataHelper.GetDataRowValue(drv.Row, "UserName"), String.Empty);
                string fullName = ValidationHelper.GetString(DataHelper.GetDataRowValue(drv.Row, "FullName"), String.Empty);

                itemName = Functions.GetFormattedUserName(userName, fullName, IsLiveSite);
            }
            else if (displayNameFormat == null)
            {
                itemName = drv[iObjectType.DisplayNameColumn].ToString();
            }
            else
            {
                MacroResolver resolver = MacroResolver.GetInstance();
                foreach (DataColumn item in drv.Row.Table.Columns)
                {
                    resolver.SetNamedSourceData(item.ColumnName, drv.Row[item.ColumnName]);
                }
                itemName = resolver.ResolveMacros(displayNameFormat);
            }

            if (RemoveMultipleCommas)
            {
                itemName = TextHelper.RemoveMultipleCommas(itemName);
            }

            // Add the prefixes
            itemName = ItemPrefix + itemName;
            itemID   = ItemPrefix + itemID;

            // Add global object name prefix if required
            if (AddGlobalObjectNamePrefix && !String.IsNullOrEmpty(iObjectType.SiteIDColumn) && (ValidationHelper.GetInteger(DataHelper.GetDataRowValue(drv.Row, iObjectType.SiteIDColumn), 0) == 0))
            {
                itemID = "." + itemID;
            }

            if (String.IsNullOrEmpty(itemName))
            {
                itemName = emptyReplacement;
            }

            if (AddGlobalObjectSuffix)
            {
                if ((iObjectType != null) && !string.IsNullOrEmpty(iObjectType.SiteIDColumn))
                {
                    itemName += (ValidationHelper.GetInteger(DataHelper.GetDataRowValue(drv.Row, iObjectType.SiteIDColumn), 0) > 0 ? string.Empty : " " + GlobalObjectSuffix);
                }
            }

            // Link action
            string onclick  = null;
            bool   disabled = disabledItems.Contains(";" + itemID + ";");
            if (!disabled)
            {
                string safeItemID = GetSafe(itemID);
                string itemHash   = ValidationHelper.GetHashString(itemID);
                switch (selectionMode)
                {
                case SelectionModeEnum.Multiple:
                case SelectionModeEnum.MultipleTextBox:
                case SelectionModeEnum.MultipleButton:
                    onclick = string.Format("ProcessItem(document.getElementById('chk{0}'),'{1}',true,true); return false;", ScriptHelper.GetString(itemID).Trim('\''), hashItems[hashKey]);
                    break;

                case SelectionModeEnum.SingleButton:
                    onclick = string.Format("SelectItems({0},'{1}'); return false;", safeItemID, itemHash);
                    break;

                case SelectionModeEnum.SingleTextBox:
                    if (allowEditTextBox)
                    {
                        onclick = string.Format("SelectItems({0},{0},{1},{2},{3},'{4}'); return false;", safeItemID, ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hashId), itemHash);
                    }
                    else
                    {
                        onclick = string.Format("SelectItems({0},{1},{2},{3},{4},'{5}'); return false;", safeItemID, GetSafe(itemName), ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hashId), itemHash);
                    }
                    break;

                default:
                    onclick = string.Format("SelectItemsReload({0},{1},{2},{3},{4},{5},'{6}'); return false;", safeItemID, GetSafe(itemName), ScriptHelper.GetString(hdnClientId), ScriptHelper.GetString(txtClientId), ScriptHelper.GetString(hdnDrpId), ScriptHelper.GetString(hashId), itemHash);
                    break;
                }

                onclick = "onclick=\"" + onclick + "\" ";
            }

            if (LocalizeItems)
            {
                itemName = ResHelper.LocalizeString(itemName);
            }

            return("<div " + (!disabled ? "class=\"SelectableItem\" " : null) + onclick + ">" + HTMLHelper.HTMLEncode(TextHelper.LimitLength(itemName, 100)) + "</div>");
        }
        }

        return(null);
    }
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (PortalContext.IsDesignMode(PortalContext.ViewMode) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            String siteName = SiteContext.CurrentSiteName;


            #region "Banned IPs"

            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration))
            {
                ShowError(GetString("banip.ipisbannedregistration"));
                return;
            }

            #endregion


            #region "Check Email & password"

            string[] siteList = { siteName };

            // If AssignToSites field set
            if (!String.IsNullOrEmpty(AssignToSites))
            {
                siteList = AssignToSites.Split(';');
            }

            // Check whether another user with this user name (which is effectively email) does not exist
            UserInfo ui     = UserInfoProvider.GetUserInfo(txtEmail.Text);
            SiteInfo si     = SiteContext.CurrentSite;
            UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text, si));

            if ((ui != null) || (siteui != null))
            {
                ShowError(GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text)));
                return;
            }

            // Check whether password is same
            if (passStrength.Text != txtConfirmPassword.Text)
            {
                ShowError(GetString("Webparts_Membership_RegistrationForm.PassworDoNotMatch"));
                return;
            }

            if ((PasswordMinLength > 0) && (passStrength.Text.Length < PasswordMinLength))
            {
                ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), PasswordMinLength));
                return;
            }

            if (!passStrength.IsValid())
            {
                ShowError(AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName));
                return;
            }

            if ((!txtEmail.IsValid()) || (txtEmail.Text.Length > EMAIL_MAX_LENGTH))
            {
                ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid"), EMAIL_MAX_LENGTH));
                return;
            }

            #endregion


            #region "Captcha"

            // Check if captcha is required and verify captcha text
            if (DisplayCaptcha && !scCaptcha.IsValid())
            {
                // Display error message if catcha text is not valid
                ShowError(GetString("Webparts_Membership_RegistrationForm.captchaError"));
                return;
            }

            #endregion


            #region "User properties"

            var userEmail = txtEmail.Text.Trim();

            ui = new UserInfo();
            ui.PreferredCultureCode = "";
            ui.Email          = userEmail;
            ui.FirstName      = txtFirstName.Text.Trim();
            ui.LastName       = txtLastName.Text.Trim();
            ui.FullName       = UserInfoProvider.GetFullName(ui.FirstName, String.Empty, ui.LastName);
            ui.MiddleName     = "";
            ui.UserMFRequired = chkUseMultiFactorAutentization.Checked;

            // User name as put by user (no site prefix included)
            var plainUserName = userEmail;
            ui.UserName = plainUserName;

            // Check if the given email can be used as user name
            if (!ValidationHelper.IsUserName(plainUserName))
            {
                ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.UserNameNotValid"), HTMLHelper.HTMLEncode(plainUserName)));
                return;
            }

            // Ensure site prefixes
            if (UserInfoProvider.UserNameSitePrefixEnabled(siteName))
            {
                ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(plainUserName, si);
            }

            ui.Enabled         = EnableUserAfterRegistration;
            ui.UserURLReferrer = CookieHelper.GetValue(CookieName.UrlReferrer);
            ui.UserCampaign    = Service.Resolve <ICampaignService>().CampaignCode;

            ui.SiteIndependentPrivilegeLevel = UserPrivilegeLevelEnum.None;

            ui.UserSettings.UserRegistrationInfo.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;

            // Check whether confirmation is required
            bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
            bool requiresAdminApprove = false;

            if (!requiresConfirmation)
            {
                // If confirmation is not required check whether administration approval is required
                requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval");
                if (requiresAdminApprove)
                {
                    ui.Enabled = false;
                    ui.UserSettings.UserWaitingForApproval = true;
                }
            }
            else
            {
                // EnableUserAfterRegistration is overridden by requiresConfirmation - user needs to be confirmed before enable
                ui.Enabled = false;
            }

            // Set user's starting alias path
            if (!String.IsNullOrEmpty(StartingAliasPath))
            {
                ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath);
            }

            #endregion


            #region "Reserved names"

            // Check for reserved user names like administrator, sysadmin, ...
            if (UserInfoProvider.NameIsReserved(siteName, plainUserName))
            {
                ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true))));
                return;
            }

            if (UserInfoProvider.NameIsReserved(siteName, ui.UserNickName))
            {
                ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(ui.UserNickName)));
                return;
            }

            #endregion


            #region "License limitations"

            string errorMessage = String.Empty;
            UserInfoProvider.CheckLicenseLimitation(ui, ref errorMessage);

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

            #endregion


            // Check whether email is unique if it is required
            if (!UserInfoProvider.IsEmailUnique(userEmail, siteList, 0))
            {
                ShowError(GetString("UserInfo.EmailAlreadyExist"));
                return;
            }

            // Set password
            UserInfoProvider.SetPassword(ui, passStrength.Text);

            #region "Welcome Emails (confirmation, waiting for approval)"

            bool error = false;
            EmailTemplateInfo template = null;

            string emailSubject = null;
            // Send welcome message with username and password, with confirmation link, user must confirm registration
            if (requiresConfirmation)
            {
                template     = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", siteName);
                emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationConfirmationEmailSubject"));
            }
            // Send welcome message with username and password, with information that user must be approved by administrator
            else if (SendWelcomeEmail)
            {
                if (requiresAdminApprove)
                {
                    template     = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", siteName);
                    emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationWaitingForApprovalSubject"));
                }
                // Send welcome message with username and password, user can logon directly
                else
                {
                    template     = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", siteName);
                    emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationSubject"));
                }
            }

            if (template != null)
            {
                // Create relation between contact and user. This ensures that contact will be correctly recognized when user approves registration (if approval is required)
                // New contact with user data is created in case it is not disabled by Data protection settings, otherwise an anonymous contact is created. Moreover an another
                // anonymous contact could be created during approval process when a new browser is used for approval step (when contact isn't in browser cookies).
                int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID();
                if (contactId > 0)
                {
                    Service.Resolve <IContactRelationAssigner>().Assign(ui.UserID, MembershipType.CMS_USER, contactId, new UserContactDataPropagationChecker());
                }

                // Email message
                EmailMessage email = new EmailMessage();
                email.EmailFormat = EmailFormatEnum.Default;
                email.Recipients  = ui.Email;
                email.From        = SettingsKeyInfoProvider.GetValue(siteName + ".CMSNoreplyEmailAddress");
                email.Subject     = emailSubject;

                try
                {
                    var resolver = MembershipResolvers.GetMembershipRegistrationResolver(ui, AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, siteName, NotifyAdministrator));
                    EmailSender.SendEmailWithTemplateText(siteName, email, template, resolver, true);
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

            // If there was some error, user must be deleted
            if (error)
            {
                ShowError(GetString("RegistrationForm.UserWasNotCreated"));

                // Email was not send, user can't be approved - delete it
                UserInfoProvider.DeleteUser(ui);
                return;
            }

            #endregion


            #region "Administrator notification email"

            // Notify administrator if enabled and e-mail confirmation is not required
            if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
            {
                EmailTemplateInfo mEmailTemplate;
                if (SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval"))
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", siteName);
                }
                else
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", siteName);
                }

                if (mEmailTemplate == null)
                {
                    // Log missing e-mail template
                    EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                }
                else
                {
                    EmailMessage message = new EmailMessage();
                    message.EmailFormat = EmailFormatEnum.Default;
                    message.From        = EmailHelper.GetSender(mEmailTemplate, FromAddress);
                    message.Recipients  = ToAddress;
                    message.Subject     = GetString("RegistrationForm.EmailSubject");

                    try
                    {
                        MacroResolver resolver = MembershipResolvers.GetRegistrationResolver(ui);
                        EmailSender.SendEmailWithTemplateText(siteName, message, mEmailTemplate, resolver, false);
                    }
                    catch
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                    }
                }
            }

            #endregion


            #region "Web analytics"

            // Track successful registration conversion
            if (TrackConversionName != String.Empty)
            {
                if (AnalyticsHelper.AnalyticsEnabled(siteName) && Service.Resolve <IAnalyticsConsentProvider>().HasConsentForLogging() &&
                    !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress) &&
                    SystemContext.IsCMSRunningAsMainApplication)
                {
                    // Log conversion
                    HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                }
            }

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                AnalyticsHelper.LogRegisteredUser(siteName, ui);
            }

            #endregion


            #region "On-line marketing - activity"

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                IMembershipActivityLogger logger = Service.Resolve <IMembershipActivityLogger>();
                logger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);
                // Log login activity
                if (ui.Enabled)
                {
                    logger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);
                }
            }

            #endregion


            #region "Roles & authentication"

            string[] roleList = AssignRoles.Split(';');

            foreach (string sn in siteList)
            {
                // Add new user to the current site
                UserInfoProvider.AddUserToSite(ui.UserName, sn);
                foreach (string roleName in roleList)
                {
                    if (!String.IsNullOrEmpty(roleName))
                    {
                        String s = roleName.StartsWith(".", StringComparison.Ordinal) ? "" : sn;

                        // Add user to desired roles
                        if (RoleInfoProvider.RoleExists(roleName, s))
                        {
                            UserInfoProvider.AddUserToRole(ui.UserName, roleName, s);
                        }
                    }
                }
            }

            if (DisplayMessage.Trim() != String.Empty)
            {
                pnlForm.Visible = false;
                lblText.Visible = true;
                lblText.Text    = DisplayMessage;
            }
            else
            {
                if (ui.Enabled)
                {
                    AuthenticationHelper.AuthenticateUser(ui.UserName, true);
                }

                if (RedirectToURL != String.Empty)
                {
                    URLHelper.Redirect(UrlResolver.ResolveUrl(RedirectToURL));
                }

                else if (QueryHelper.GetString("ReturnURL", "") != String.Empty)
                {
                    string url = QueryHelper.GetString("ReturnURL", "");

                    // Do url decode
                    url = Server.UrlDecode(url);

                    // Check that url is relative path or hash is ok
                    if (url.StartsWith("~", StringComparison.Ordinal) || url.StartsWith("/", StringComparison.Ordinal) || QueryHelper.ValidateHash("hash", "aliaspath"))
                    {
                        URLHelper.Redirect(UrlResolver.ResolveUrl(url));
                    }
                    // Absolute path with wrong hash
                    else
                    {
                        URLHelper.Redirect(AdministrationUrlHelper.GetErrorPageUrl("dialogs.badhashtitle", "dialogs.badhashtext"));
                    }
                }
            }

            #endregion

            lblError.Visible = false;
        }
    }
Beispiel #13
0
    object Grid_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        string name = sourceName.ToLowerCSafe();

        switch (name)
        {
        case "chatmessageauthor":
        {
            DataRowView row = (DataRowView)parameter;

            if (row["AuthorNickname"] == DBNull.Value)
            {
                return("<span style=\"color: #777777; font-style: italic;\">" + GetString("chat.system") + "</span>");
            }

            int    chatUserID  = ValidationHelper.GetInteger(row["ChatMessageUserID"], 0);
            string nickname    = ValidationHelper.GetString(row["AuthorNickname"], "AuthorNickname");
            bool   isAnonymous = ValidationHelper.GetBoolean(row["AuthorIsAnonymous"], true);

            return(ChatUIHelper.GetCMSDeskChatUserField(this, chatUserID, nickname, isAnonymous));
        }

        case "edit":
        case "reject":
        case "delete":
        {
            DataRowView row = (DataRowView)((GridViewRow)parameter).DataItem;

            // Whisper message is consider as system here - it can't be rejected or edited
            ChatMessageTypeEnum msgType = (ChatMessageTypeEnum)ValidationHelper.GetInteger(row["ChatMessageSystemMessageType"], 0);
            bool isSystem = ((msgType != ChatMessageTypeEnum.ClassicMessage) && (msgType != ChatMessageTypeEnum.Announcement));

            bool enabled      = true;
            var  actionButton = (CMSGridActionButton)sender;

            if (isSystem)
            {
                if (name == "edit" || name == "reject")
                {
                    // Disable edit and reject buttons for system messages
                    enabled = false;
                }
            }
            else
            {
                if (name == "reject")
                {
                    bool isRejected = ValidationHelper.GetBoolean(row["ChatMessageRejected"], false);
                    if (isRejected)
                    {
                        actionButton.IconCssClass = "icon-check-circle";
                        actionButton.IconStyle    = GridIconStyle.Allow;
                        actionButton.ToolTip      = GetString("general.approve");
                    }
                }
            }

            if (!HasUserModifyPermission && name != "edit")
            {
                enabled = false;
            }

            actionButton.Enabled = enabled;

            break;
        }

        case "chatmessagesystemmessagetype":
        {
            DataRowView row = (DataRowView)parameter;

            ChatMessageTypeEnum messageType = (ChatMessageTypeEnum)ValidationHelper.GetInteger(row["ChatMessageSystemMessageType"], 0);

            if (messageType == ChatMessageTypeEnum.Whisper)
            {
                ChatUserInfo recipient = ChatUserInfoProvider.GetChatUserInfo(ValidationHelper.GetInteger(row["ChatMessageRecipientID"], 0));

                if (recipient != null)
                {
                    // Set text to the format "Whisper to somebody", where somebody may be link to the user if he is not anonymous

                    return(String.Format(ResHelper.GetString("chat.system.cmsdesk.whisperto"), ChatUIHelper.GetCMSDeskChatUserField(this, recipient)));
                }
            }

            return(messageType.ToStringValue((int)ChatMessageTypeStringValueUsageEnum.CMSDeskDescription));
        }

        case "chatmessagetext":
        {
            DataRowView row = (DataRowView)parameter;

            ChatMessageTypeEnum messageType = (ChatMessageTypeEnum)ValidationHelper.GetInteger(row["ChatMessageSystemMessageType"], 0);

            string messageText = ValidationHelper.GetString(row["ChatMessageText"], "");

            if (messageType.IsSystemMessage())
            {
                messageText = MacroResolver.Resolve(messageText);
            }

            return(HTMLHelper.HTMLEncode(messageText));
        }
        }

        return(parameter);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Attach events
        btnAutoIndent.Click      += btnAutoIndent_Click;
        btnDelete.Click          += (btnDelete_Click);
        btnIndent.Click          += btnIndent_Click;
        btnUnindent.Click        += btnUnindent_Click;
        btnChangeOperator.Click  += new EventHandler(btnChangeOperator_Click);
        btnChangeParameter.Click += new EventHandler(btnChangeParameter_Click);
        btnMove.Click            += new EventHandler(btnMove_Click);
        btnCancel.Click          += new EventHandler(btnCancel_Click);
        btnSetParameter.Click    += new EventHandler(btnSetParameter_Click);
        btnViewCode.Click        += btnViewCode_Click;
        btnAddClause.Click       += new EventHandler(btnAddClause_Click);
        btnClearAll.Click        += btnClearAll_Click;
        txtFilter.TextChanged    += new EventHandler(btnFilter_Click);

        btnFilter.Text       = GetString("general.filter");
        btnSetParameter.Text = GetString("general.ok");
        btnCodeOK.Text       = GetString("general.ok");
        btnCancel.Text       = GetString("general.cancel");
        btnIndent.ScreenReaderDescription     = btnIndent.ToolTip = GetString("macros.macrorule.indent");
        btnUnindent.ScreenReaderDescription   = btnUnindent.ToolTip = GetString("macros.macrorule.unindent");
        btnAutoIndent.ScreenReaderDescription = btnAutoIndent.ToolTip = GetString("macros.macrorule.autoindent");
        btnDelete.ScreenReaderDescription     = btnDelete.ToolTip = GetString("general.delete");
        btnClearAll.ScreenReaderDescription   = btnClearAll.ToolTip = GetString("macro.macrorule.clearall");
        btnViewCode.ScreenReaderDescription   = btnViewCode.ToolTip = GetString("macros.macrorule.viewcode");

        btnIndent.OnClientClick     = "if (isNothingSelected()) { alert(" + ScriptHelper.GetString(GetString("macros.macrorule.nothingselected")) + "); return false; }";
        btnUnindent.OnClientClick   = "if (isNothingSelected()) { alert(" + ScriptHelper.GetString(GetString("macros.macrorule.nothingselected")) + "); return false; }";
        btnDelete.OnClientClick     = "if (isNothingSelected()) { alert(" + ScriptHelper.GetString(GetString("macros.macrorule.nothingselected")) + "); return false; } else { if (!confirm('" + GetString("macros.macrorule.deleteconfirmation") + "')) { return false; }}";
        btnAutoIndent.OnClientClick = "if (!confirm(" + ScriptHelper.GetString(GetString("macros.macrorule.deleteautoindent")) + ")) { return false; }";
        btnClearAll.OnClientClick   = "if (!confirm(" + ScriptHelper.GetString(GetString("macros.macrorule.clearall.confirmation")) + ")) { return false; }";

        lstRules.Attributes.Add("ondblclick", ControlsHelper.GetPostBackEventReference(btnAddClause, null));

        pnlViewCode.Visible = false;

        // Basic form
        formElem.SubmitButton.Visible = false;
        formElem.SiteName             = SiteContext.CurrentSiteName;

        titleElem.TitleText   = GetString("macros.macrorule.changeparameter");
        btnAddaClause.ToolTip = GetString("macros.macrorule.addclause");
        btnAddaClause.Click  += btnAddClause_Click;

        // Drop cue
        Panel pnlCue = new Panel();

        pnlCue.ID       = "pnlCue";
        pnlCue.CssClass = "MacroRuleCue";
        pnlCondtion.Controls.Add(pnlCue);

        pnlCue.Controls.Add(new LiteralControl("&nbsp;"));
        pnlCue.Style.Add("display", "none");

        // Create drag and drop extender
        extDragDrop    = new DragAndDropExtender();
        extDragDrop.ID = "extDragDrop";
        extDragDrop.TargetControlID     = pnlCondtion.ID;
        extDragDrop.DragItemClass       = "MacroRule";
        extDragDrop.DragItemHandleClass = "MacroRuleHandle";
        extDragDrop.DropCueID           = pnlCue.ID;
        extDragDrop.OnClientDrop        = "OnDropRule";
        pnlCondtion.Controls.Add(extDragDrop);

        // Load the rule set
        if (!RequestHelper.IsPostBack())
        {
            if (ShowGlobalRules || !string.IsNullOrEmpty(RuleCategoryNames))
            {
                string where = (ShowGlobalRules ? "MacroRuleResourceName IS NULL OR MacroRuleResourceName = ''" : "");

                // Append rules module name condition
                if (!string.IsNullOrEmpty(RuleCategoryNames))
                {
                    bool          appendComma = false;
                    StringBuilder sb          = new StringBuilder();
                    string[]      names       = RuleCategoryNames.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string n in names)
                    {
                        string name = "'" + SqlHelper.GetSafeQueryString(n.Trim(), false) + "'";
                        if (appendComma)
                        {
                            sb.Append(",");
                        }
                        sb.Append(name);
                        appendComma = true;
                    }
                    where = SqlHelper.AddWhereCondition(where, "MacroRuleResourceName IN (" + sb.ToString() + ")", "OR");
                }

                // Append require context condition
                switch (DisplayRuleType)
                {
                case 1:
                    where = SqlHelper.AddWhereCondition(where, "MacroRuleRequiresContext = 0", "AND");
                    break;

                case 2:
                    where = SqlHelper.AddWhereCondition(where, "MacroRuleRequiresContext = 1", "AND");
                    break;
                }

                // Select only enabled rules
                where = SqlHelper.AddWhereCondition(where, "MacroRuleEnabled = 1");

                DataSet ds = MacroRuleInfoProvider.GetMacroRules(where, "MacroRuleDisplayName", 0, "MacroRuleID, MacroRuleDisplayName, MacroRuleDescription, MacroRuleRequiredData");
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    MacroResolver resolver = MacroResolverStorage.GetRegisteredResolver(ResolverName);
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        bool add = true;
                        if (resolver != null)
                        {
                            // Check the required data, all specified data have to be present in the resolver
                            string requiredData = ValidationHelper.GetString(dr["MacroRuleRequiredData"], "");
                            if (!string.IsNullOrEmpty(requiredData))
                            {
                                string[] required = requiredData.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (var req in required)
                                {
                                    if (!resolver.IsDataItemAvailable(req))
                                    {
                                        add = false;
                                        break;
                                    }
                                }
                            }
                        }

                        if (add)
                        {
                            var      ruleId = dr["MacroRuleID"].ToString();
                            ListItem item   = new ListItem(dr["MacroRuleDisplayName"].ToString(), ruleId);
                            lstRules.Items.Add(item);

                            // Save the tooltip
                            RulesTooltips[ruleId] = ResHelper.LocalizeString(ValidationHelper.GetString(dr["MacroRuleDescription"], ""));
                        }
                    }
                }
                if (lstRules.Items.Count > 0)
                {
                    lstRules.SelectedIndex = 0;
                }
            }
        }

        // Make sure that one user click somewhere else than to any rule, selection will disappear
        pnlCondtion.Attributes["onclick"] = "if (!doNotDeselect && !isCTRL) { jQuery('.RuleSelected').removeClass('RuleSelected'); document.getElementById('" + hdnSelected.ClientID + "').value = ';'; }; doNotDeselect = false;";

        LoadFormDefinition(false);

        // Set the default button for parameter edit dialog so that ENTER key works to submit the parameter value
        pnlParameterPopup.DefaultButton = btnSetParameter.ID;

        // Ensure correct edit dialog show/hide (because of form controls which cause postback)
        btnSetParameter.OnClientClick = "HideParamEdit();";
        btnCancel.OnClientClick       = "HideParamEdit();";
        if (ShowParameterEdit)
        {
            mdlDialog.Show();
        }

        if (!string.IsNullOrEmpty(hdnScroll.Value))
        {
            // Preserve scroll position
            ScriptHelper.RegisterStartupScript(this.Page, typeof(string), "MacroRulesScroll", "setTimeout('setScrollPosition()', 100);", true);
        }

        // Add tooltips to the rules in the list
        foreach (ListItem item in lstRules.Items)
        {
            if (RulesTooltips.ContainsKey(item.Value))
            {
                item.Attributes.Add("title", RulesTooltips[item.Value]);
            }
        }
    }
Beispiel #15
0
    /// <summary>
    /// Fills field list with available fields.
    /// </summary>
    protected void FillFieldsList()
    {
        drpAvailableFields.Items.Clear();

        DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(DataClassID);

        if (dci != null)
        {
            // Load form definition
            string formDefinition = dci.ClassFormDefinition;
            if (IsAlternative)
            {
                // Get alternative form definition and merge if with the original one
                AlternativeFormInfo afi = AlternativeFormInfoProvider.GetAlternativeFormInfo(ObjectID);

                if (afi.FormCoupledClassID > 0)
                {
                    // If coupled class is defined combine form definitions
                    DataClassInfo coupledDci = DataClassInfoProvider.GetDataClassInfo(afi.FormCoupledClassID);
                    if (coupledDci != null)
                    {
                        formDefinition = FormHelper.MergeFormDefinitions(formDefinition, coupledDci.ClassFormDefinition);
                    }
                }

                // Merge class and alternative form definitions
                formDefinition = FormHelper.MergeFormDefinitions(formDefinition, afi.FormDefinition);
            }
            FormInfo fi = new FormInfo(formDefinition);
            // Get visible fields
            var visibleFields = fi.GetFields(true, false);

            drpAvailableFields.Items.Clear();

            // Prepare arrays for JavaScript functions
            string script = "var formControlName = new Array(); var formControlCssClass = new Array();\n";

            if (FormLayoutType == FormLayoutTypeEnum.Document)
            {
                if (string.IsNullOrEmpty(dci.ClassNodeNameSource)) //if node name source is not set
                {
                    string docName = "DocumentName";
                    drpAvailableFields.Items.Add(new ListItem(GetString("DocumentType_Edit_Form.DocumentName"), docName));

                    // Add document name field form control to the script
                    script += String.Format("formControlName['{0}'] = '{1}';\n", docName, "TextBoxControl");
                    script += String.Format("formControlCssClass['{0}'] = '';\n", docName);
                }
            }

            if (visibleFields != null)
            {
                // Add public visible fields to the list
                foreach (FormFieldInfo ffi in visibleFields)
                {
                    drpAvailableFields.Items.Add(new ListItem(ffi.GetDisplayName(MacroResolver.GetInstance()), ffi.Name));

                    // Add fields' form controls to the script
                    script += String.Format("formControlName['{0}'] = '{1}';\n", ffi.Name, ffi.Settings["controlname"]);
                    script += String.Format("formControlCssClass['{0}'] = '{1}';\n", ffi.Name, ffi.GetPropertyValue(FormFieldPropertyEnum.ControlCssClass));
                }
            }

            if (FormLayoutType == FormLayoutTypeEnum.Document)
            {
                if (dci.ClassUsePublishFromTo)
                {
                    // Add publish from/to fields if they are not already in predefined fields
                    if (drpAvailableFields.Items.FindByValue("DocumentPublishFrom", true) == null)
                    {
                        string publishFrom = "DocumentPublishFrom";
                        drpAvailableFields.Items.Add(new ListItem(GetString("DocumentType_Edit_Form.DocumentPublishFrom"), publishFrom));

                        // Add Publish From field form control to the script
                        script += String.Format("formControlName['{0}'] = '{1}';\n", publishFrom, "CalendarControl");
                        script += String.Format("formControlCssClass['{0}'] = '';\n", publishFrom);
                    }
                    if (drpAvailableFields.Items.FindByValue("DocumentPublishTo", true) == null)
                    {
                        string publishTo = "DocumentPublishTo";
                        drpAvailableFields.Items.Add(new ListItem(GetString("DocumentType_Edit_Form.DocumentPublishTo"), publishTo));

                        // Add Publish To field form control to the script
                        script += String.Format("formControlName['{0}'] = '{1}';\n", publishTo, "CalendarControl");
                        script += String.Format("formControlCssClass['{0}'] = '';\n", publishTo);
                    }
                }
            }

            // Set script - it is registered on pre-render
            FormControlScript = script;
        }
    }
    /// <summary>
    /// Generate body of the matrix.
    /// </summary>
    /// <param name="matrixData">Data of the matrix to be generated</param>
    private void GenerateMatrixBody(List <DataRow> matrixData)
    {
        string lastRowId = "";
        int    colIndex  = 0;
        int    rowIndex  = 0;

        TableRow  tr = null;
        TableCell tc = null;

        // Render matrix rows
        int step = matrixData.Count;

        for (int i = 0; i < ds.Tables[0].Rows.Count; i = i + step)
        {
            foreach (int index in ColumnOrderIndex)
            {
                DataRow rowData = ds.Tables[0].Rows[i + index];
                string  rowId   = ValidationHelper.GetString(rowData[RowItemIDColumn], "");

                // Detect new matrix row
                if (rowId != lastRowId)
                {
                    if ((ItemsPerPage > 0) && (rowIndex++ >= ItemsPerPage))
                    {
                        break;
                    }

                    // New Table row
                    tr = new TableRow
                    {
                        CssClass        = GetAdditionalCssClass(rowData),
                        EnableViewState = false
                    };
                    tblMatrix.Rows.Add(tr);

                    // Header table cell
                    tc = new TableCell
                    {
                        CssClass        = "matrix-header",
                        Text            = HTMLHelper.HTMLEncode(MacroResolver.Resolve(ValidationHelper.GetString(rowData[RowItemDisplayNameColumn], null))),
                        ToolTip         = (RowItemTooltipColumn != null) ? GetTooltip(rowData, RowItemTooltipColumn) : null,
                        EnableViewState = false
                    };
                    tr.Cells.Add(tc);

                    // Add disabled mark if needed
                    if (!IsRowEditable(rowId))
                    {
                        tc.Text += DisabledRowMark;
                    }

                    // Add global suffix if is required
                    if ((index == 0) && (AddGlobalObjectSuffix) && (ValidationHelper.GetInteger(rowData[SiteIDColumnName], 0) == 0))
                    {
                        tc.Text += " " + GetString("general.global");
                    }

                    // Update
                    lastRowId = rowId;
                    colIndex  = 0;
                }

                object columnValue = rowData[ColumnItemIDColumn];
                var    cellId      = string.Format("chk:{0}:{1}", rowId, columnValue);

                // New table cell
                tc = new TableCell
                {
                    EnableViewState = false
                };
                tr.Cells.Add(tc);

                // Checkbox for data
                var chk = new CMSCheckBox
                {
                    ID           = cellId,
                    ClientIDMode = ClientIDMode.Static,
                    ToolTip      = GetTooltip(rowData, ItemTooltipColumn),
                    Checked      = ValidationHelper.GetBoolean(rowData["Allowed"], false),
                    Enabled      = Enabled &&
                                   !disabledColumns.Contains(colIndex) &&
                                   IsColumnEditable(columnValue) &&
                                   IsRowEditable(rowId),
                    EnableViewState = false
                };
                tc.Controls.Add(chk);

                // Add click event to enabled checkbox
                if (chk.Enabled)
                {
                    chk.Attributes.Add("onclick", "UM_ItemChanged_" + ClientID + "(this);");
                }

                colIndex++;
            }
        }
    }
        private void Extract(IConsole console, ExtractorSettings settings)
        {
            var redirects = new List <(string, string)>();

            // Create the output directories if needed
            if (!DryRun)
            {
                PrepareObjectDirectory(settings);
            }

            //Doc to save the actual content as xml
            var xmlDocument = new XmlDocument();
            var parentElem  = xmlDocument.CreateNode("element", settings.PageType.Replace(".", "-") + "s", "");

            //Fire up our Kentico Xperience instance
            ConnectionHelper.ConnectionString = settings.ConnectionString;
            ValidationHelper.HashStringSalt   = settings.HashStringSalt;
            CMSApplication.Init();

            // Gets an object representing a specific Kentico user
            UserInfo user = UserInfoProvider.GetUserInfo(settings.XperienceUser);

            // Sets the context of the user
            using (new CMSActionContext(user))
            {
                var wc = new WebClient();

                //Get me all published pages of the specified page type on the site
                var posts = DocumentHelper.GetDocuments(settings.PageType)
                            .Columns(settings.PageTypeColumns)
                            .Path(settings.RootNodeAliasPath, PathTypeEnum.Children)
                            .PublishedVersion()
                            .Published()
                            .TopN(settings.TopN)
                            .OrderBy(settings.OrderByColumns);

                console.WriteLine($"{posts.Count} nodes found.");
                console.WriteLine("Exporting node data...");

                int nodeOrder = 1;
                foreach (TreeNode post in posts)
                {
                    //Create a new AgilityPack doc for working with the page
                    HtmlDocument doc = new HtmlDocument();
                    doc.OptionOutputAsXml = false; //if true adds a weird span tag

                    doc.DocumentNode.AppendChild(HtmlNode.CreateNode("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
                    doc.DocumentNode.AppendChild(HtmlNode.CreateNode(Environment.NewLine));

                    string nodeAliasPath = post.NodeAliasPath;

                    nodeAliasPath = nodeAliasPath.Split('/').Last();   //clean it up to just the slug

                    // Add redirect to the list
                    redirects.Add((post.NodeAliasPath, nodeAliasPath));

                    // TODO: use FormInfo to determine "DocumentName" field
                    string nodeTitle = post.DocumentName;

                    //Create a parent folder path in the data directory to store all xml about this node in a structured way on the file system
                    string nodeDirPath = Path.Combine(settings.ObjectDirectory, settings.PageType, nodeAliasPath.Replace("/", "-"));
                    if (!Directory.Exists(nodeDirPath))
                    {
                        Directory.CreateDirectory(nodeDirPath);
                    }

                    //Create root xml Element of the pageTypeName ex. <cms-blogpost>
                    // and start saving fields as attributes and child elements in this xml structure
                    var rootNode = HtmlNode.CreateNode($"<{settings.PageType.Replace( ".", "-" )} />");
                    rootNode.Attributes.Append("originalAliasPath");
                    rootNode.SetAttributeValue("originalAliasPath", post.NodeAliasPath);
                    rootNode.AppendChild(HtmlNode.CreateNode(Environment.NewLine));

                    var aliasNode = HtmlNode.CreateNode($"<newaliaspath/>");
                    aliasNode.InnerHtml = nodeAliasPath;
                    rootNode.AppendChild(aliasNode);

                    var orderNode = HtmlNode.CreateNode($"<newnodeorder/>");
                    orderNode.InnerHtml = nodeOrder.ToString();
                    rootNode.AppendChild(orderNode);
                    nodeOrder++;

                    //Kentico dynamic properties or "With the Coupled Columns of the page type"
                    //Iterate through all of the fields of a document in order to serialize them to xml
                    foreach (var dprop in post.Properties)
                    {
                        if (Array.IndexOf(settings.PageTypeColumns, dprop) > 0)
                        {
                            //Create xml Element that represents each field ex. <blogpostsummary>data</blogpostsummary>
                            var node = HtmlNode.CreateNode($"<{dprop} />");
                            var data = post.GetValue(dprop, "");

                            //Special stuff for Mcbeev Blog Post Summary (can be ignored for others)
                            if (dprop.ToLower().Contains("summary"))
                            {
                                //Remove wrapped p tag on Mcbeev Blog Post Summary
                                HtmlDocument docSummary = new HtmlDocument();
                                docSummary.LoadHtml(data);
                                var newSummaryNode = HtmlNode.CreateNode($"<newblogpostsummary/>");
                                try
                                {
                                    if (docSummary.DocumentNode.SelectSingleNode("//p") != null)
                                    {
                                        newSummaryNode.InnerHtml = docSummary.DocumentNode.SelectSingleNode("//p").InnerText;
                                    }
                                    else
                                    {
                                        newSummaryNode.InnerHtml = docSummary.DocumentNode.InnerText;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //todo
                                    console.WriteLine(ex.Message);
                                }

                                rootNode.AppendChild(newSummaryNode);
                                rootNode.AppendChild(HtmlNode.CreateNode(Environment.NewLine));
                            }


                            //This is WYSIWYG content field most likely so try to resolve things as Kentico would
                            if (dprop.ToLower().Contains("title") || dprop.ToLower().Contains("body") || dprop.ToLower().Contains("content") || dprop.ToLower().Contains("summary"))
                            {
                                //Macro resolve inside of the content (handle K# macros in the text)
                                data = MacroResolver.Resolve(data);

                                //Url resolve inside of the content (handle relative urls into absolute urls) important!

                                data = HTMLHelper.ResolveUrls(data, settings.AbsoluteSiteName, true);

                                //Widget identifier (try to save a list of all Portal Inline Widgets that no longer work in MVC)
                                if (data.Contains("CMSInlineControl"))
                                {
                                    console.WriteLine("Found a widget in this content.");
                                    // TODO Make this a real log
                                    // //Render the value as html to HP NodedataRootDirectoryName
                                    // HtmlDocument docWidget = new HtmlDocument();
                                    // docWidget.LoadHtml(data);
                                    // var widgets = docWidget.DocumentNode.SelectNodes("//object[contains(@type, 'Widget')]");

                                    // foreach (var w in widgets)
                                    // {
                                    //     console.WriteLine(w.OuterHtml);
                                    // }
                                }

                                //Media library identifier
                                if (data.Contains("<img "))
                                {
                                    HtmlDocument docImg = new HtmlDocument();
                                    docImg.LoadHtml(data);
                                    var ImageURLs = docImg.DocumentNode.Descendants("img")
                                                    .Select(e => e.GetAttributeValue("src", null))
                                                    .Where(s => !String.IsNullOrEmpty(s));

                                    foreach (var oldImageURL in ImageURLs)
                                    {
                                        //Skip mp3s for now
                                        if (oldImageURL.EndsWith(".mp3") || oldImageURL.Contains(".mp3?"))
                                        {
                                            continue;
                                        }

                                        console.WriteLine($"trying to save {oldImageURL} ...");
                                        var safeName = oldImageURL.Split(new char[] { '?' })[0];
                                        safeName = safeName.Replace(".aspx", "");

                                        //Save the images locally if we can download from the "real" running site
                                        try
                                        {
                                            wc.DownloadFile(oldImageURL, Path.Combine(nodeDirPath, Path.GetFileName(safeName)));
                                        }
                                        catch (Exception ex)
                                        {
                                            console.WriteLine(ex.Message);
                                        }

                                        //rewrite the image path back in the data node
                                        // TODO - make this a config parameter and not hard coded to Mcbeev.com
                                        data = data.Replace(oldImageURL, "/MBV/media/blog/" + nodeAliasPath.Replace("/", "-") + "/" + oldImageURL.Split(new char[] { '/' }).Last());

                                        //replace the odd .png.aspx thing
                                        data = data.Replace(".png.aspx", ".png");
                                    }
                                }

                                //Use HTMLAgility Pack to fix non closed image tags
                                HtmlNode.ElementsFlags["img"] = HtmlElementFlag.Closed;
                                HtmlDocument docContent = new HtmlDocument();
                                docContent.LoadHtml(data);

                                data = $"<![CDATA[{docContent.DocumentNode.OuterHtml}]]>";
                            }

                            //Most likely image only field and not a WYSIWYG field
                            // TODO - is there a better way to check for this?
                            if ((data.Length > 2) && (data.StartsWith("~/")))
                            {
                                data = data.Replace("~/", settings.AbsoluteSiteName);

                                console.WriteLine($"trying to save {data} ...");
                                var safeName = data.Split(new char[] { '?' })[0];
                                safeName = safeName.Replace(".aspx", "");
                                wc.DownloadFile(data, Path.Combine(nodeDirPath, Path.GetFileName(safeName)));

                                //rewrite the image path back in the data node
                                safeName = "/MBV/media/blog/" + nodeAliasPath.Replace("/", "-") + "/" + safeName.Split(new char[] { '/' }).Last();

                                data = $"<![CDATA[{safeName}]]>";
                            }

                            node.AppendChild(doc.CreateTextNode(data));
                            rootNode.AppendChild(node);
                            rootNode.AppendChild(HtmlNode.CreateNode("\r\n"));
                        }
                    }
                    doc.DocumentNode.AppendChild(rootNode);

                    //Save the single node to its own XML document in its directory
                    doc.Save($@"{nodeDirPath}\{nodeAliasPath.Replace( "/", "-" )}.xml");

                    //Chop off the header to prepare for bundling
                    doc.DocumentNode.ChildNodes[0].Remove();

                    //add this node to all nodes in main XML doc
                    parentElem.InnerXml += doc.DocumentNode.OuterHtml;
                    xmlDocument.AppendChild(parentElem);
                }

                if (!DryRun)
                {
                    WriteRedirects(redirects, settings);
                    xmlDocument.Save(Path.Combine(settings.ObjectDirectory, settings.PageType, settings.AllNodesFilename));

                    console.WriteLine($"Extraction to {settings.ObjectDirectory} succeeded");
                }
                else
                {
                    console.WriteLine("Dry run succeeded");
                }
            }
        }
Beispiel #18
0
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    private void btnRegister_Click(object sender, EventArgs e)
    {
        string currentSiteName = SiteContext.CurrentSiteName;

        string[] siteList = { currentSiteName };

        // If AssignToSites field set
        if (!String.IsNullOrEmpty(AssignToSites))
        {
            siteList = AssignToSites.Split(';');
        }

        if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible))
        {
            // Do not process
        }
        else
        {
            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(currentSiteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("banip.ipisbannedregistration");
                return;
            }

            // Check if captcha is required and verify captcha text
            if (DisplayCaptcha && !captchaElem.IsValid())
            {
                // Display error message if captcha text is not valid
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.captchaError");
                return;
            }

            string userName       = String.Empty;
            string nickName       = String.Empty;
            string firstName      = String.Empty;
            string lastName       = String.Empty;
            string emailValue     = String.Empty;
            string pwd            = string.Empty;
            string confPassword   = string.Empty;
            string educationLevel = String.Empty;
            string interestArea   = String.Empty;
            string industry       = String.Empty;
            string referralSource = string.Empty;

            // Check duplicate user
            // 1. Find appropriate control and get its value (i.e. user name)
            // 2. Try to find user info
            //FormEngineUserControl txtUserName = formUser.FieldControls["UserName"];
            //if (txtUserName != null)
            //{
            //    userName = ValidationHelper.GetString(txtUserName.Value, String.Empty);
            //}

            FormEngineUserControl txtEmail = formUser.FieldControls["Email"];
            if (txtEmail != null)
            {
                emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty);
                userName   = emailValue;
            }

            // If user name and e-mail aren't filled stop processing and display error.
            if (string.IsNullOrEmpty(userName) && String.IsNullOrEmpty(emailValue))
            {
                formUser.StopProcessing = true;
                lblError.Visible        = true;
                lblError.Text           = GetString("customregistrationform.usernameandemail");
                return;
            }
            else
            {
                formUser.Data.SetValue("UserName", userName);
            }

            //check if email is valid
            if (!ValidationHelper.IsEmail(txtEmail.Text.ToLowerCSafe()))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid");
                return;
            }

            FormEngineUserControl txtNickName = formUser.FieldControls["UserNickName"];
            if (txtNickName != null)
            {
                nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty);
            }

            FormEngineUserControl txtFirstName = formUser.FieldControls["FirstName"];
            if (txtFirstName != null)
            {
                firstName = ValidationHelper.GetString(txtFirstName.Value, String.Empty);
            }

            FormEngineUserControl txtLastName = formUser.FieldControls["LastName"];
            if (txtLastName != null)
            {
                lastName = ValidationHelper.GetString(txtLastName.Value, String.Empty);
            }

            FormEngineUserControl txtPwd = formUser.FieldControls["UserPassword"];
            if (txtPwd != null)
            {
                pwd = ValidationHelper.GetString(txtPwd.Value, String.Empty);
            }

            FormEngineUserControl txtConfPassword = formUser.FieldControls["ReenterPassword"];
            if (txtConfPassword != null)
            {
                confPassword = ValidationHelper.GetString(txtConfPassword.Value, String.Empty);
            }

            if (string.IsNullOrEmpty(pwd) || string.IsNullOrEmpty(confPassword))
            {
                lblError.Visible = true;
                lblError.Text    = "please enter password with confirmation";
                return;
            }

            if (pwd != confPassword)
            {
                lblError.Visible = true;
                lblError.Text    = "Password doesn't match";
                return;
            }


            if (validateFields(formUser.FieldControls["UserPassword"].Value.ToString()))
            {
                // Test if "global" or "site" user exists.
                SiteInfo si     = SiteContext.CurrentSite;
                UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, si));
                if ((UserInfoProvider.GetUserInfo(userName) != null) || (siteui != null))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                    return;
                }

                // Check for reserved user names like administrator, sysadmin, ...
                if (UserInfoProvider.NameIsReserved(currentSiteName, userName))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)));
                    return;
                }

                if (UserInfoProvider.NameIsReserved(currentSiteName, nickName))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(nickName));
                    return;
                }

                // Check limitations for site members
                if (!UserInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.SiteMembers, ObjectActionEnum.Insert, false))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("License.MaxItemsReachedSiteMember");
                    return;
                }

                // Check whether email is unique if it is required
                if (!UserInfoProvider.IsEmailUnique(emailValue, siteList, 0))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                    return;
                }

                // Validate and save form with new user data
                if (!formUser.Save())
                {
                    // Return if saving failed
                    return;
                }

                // Get user info from form
                UserInfo ui = (UserInfo)formUser.Info;

                // Add user prefix if settings is on
                // Ensure site prefixes
                if (UserInfoProvider.UserNameSitePrefixEnabled(currentSiteName))
                {
                    ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, si);
                }

                ui.Enabled         = EnableUserAfterRegistration;
                ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer;
                ui.UserCampaign    = AnalyticsHelper.Campaign;

                ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None);

                // Fill optionally full user name
                if (String.IsNullOrEmpty(ui.FullName))
                {
                    ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, ui.MiddleName, ui.LastName);
                }

                // Ensure nick name
                if (ui.UserNickName.Trim() == String.Empty)
                {
                    ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true);
                }

                ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress;
                ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;
                ui.UserSettings.UserLogActivities        = true;
                ui.UserSettings.UserShowIntroductionTile = true;

                // Check whether confirmation is required
                bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationEmailConfirmation");
                bool requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationAdministratorApproval");
                if (!requiresConfirmation)
                {
                    // If confirmation is not required check whether administration approval is reqiures
                    if (requiresAdminApprove)
                    {
                        ui.Enabled = false;
                        ui.UserSettings.UserWaitingForApproval = true;
                    }
                }
                else
                {
                    // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable
                    ui.Enabled = false;
                }

                // Set user's starting alias path
                if (!String.IsNullOrEmpty(StartingAliasPath))
                {
                    ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath);
                }

                // Get user password and save it in apropriate format after form save
                string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty);
                UserInfoProvider.SetPassword(ui, password);

                var customerToken = PersonifyRegistered(emailValue, password, firstName, lastName);
                if (string.IsNullOrEmpty(customerToken))
                {
                    UserInfoProvider.DeleteUser(ui);
                    return;
                }
                else
                {
                    var    roles      = GetImsroles(customerToken);
                    string groupslist = "";
                    if (roles.Length > 0)
                    {
                        foreach (string s in roles)
                        {
                            if (s.Length > 0)
                            {
                                groupslist += s + ",";
                            }
                        }
                    }

                    //we need this mispelling.
                    groupslist += "peronifyUser" + ",";

                    new LoginUsertokentico().AddUserToRole(ui, groupslist, true, false);
                }


                // Prepare macro data source for email resolver
                UserInfo userForMail = ui.Clone();
                userForMail.SetValue("UserPassword", string.Empty);

                object[] data = new object[1];
                data[0] = userForMail;

                // Prepare resolver for notification and welcome emails
                MacroResolver resolver = MacroContext.CurrentResolver;
                resolver.SetAnonymousSourceData(data);

                #region "Welcome Emails (confirmation, waiting for approval)"

                bool error = false;
                EmailTemplateInfo template = null;

                // Prepare macro replacements
                string[,] replacements = new string[6, 2];
                replacements[0, 0]     = "confirmaddress";
                replacements[0, 1]     = AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, currentSiteName, NotifyAdministrator);
                replacements[1, 0]     = "username";
                replacements[1, 1]     = userName;
                replacements[2, 0]     = "password";
                replacements[2, 1]     = password;
                replacements[3, 0]     = "Email";
                replacements[3, 1]     = emailValue;
                replacements[4, 0]     = "FirstName";
                replacements[4, 1]     = firstName;
                replacements[5, 0]     = "LastName";
                replacements[5, 1]     = lastName;

                // Set resolver
                resolver.SetNamedSourceData(replacements);

                // Email message
                EmailMessage emailMessage = new EmailMessage();
                emailMessage.EmailFormat = EmailFormatEnum.Default;
                emailMessage.Recipients  = ui.Email;

                // Send welcome message with username and password, with confirmation link, user must confirm registration
                if (requiresConfirmation)
                {
                    template             = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", currentSiteName);
                    emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject");
                }
                // Send welcome message with username and password, with information that user must be approved by administrator
                else if (SendWelcomeEmail)
                {
                    if (requiresAdminApprove)
                    {
                        template             = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", currentSiteName);
                        emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject");
                    }
                    // Send welcome message with username and password, user can logon directly
                    else
                    {
                        template             = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", currentSiteName);
                        emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject");
                    }
                }

                if (template != null)
                {
                    emailMessage.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetStringValue(currentSiteName + ".CMSNoreplyEmailAddress"));
                    // Enable macro encoding for body
                    resolver.Settings.EncodeResolvedValues = true;
                    emailMessage.Body = resolver.ResolveMacros(template.TemplateText);
                    // Disable macro encoding for plaintext body and subject
                    resolver.Settings.EncodeResolvedValues = false;
                    emailMessage.PlainTextBody             = resolver.ResolveMacros(template.TemplatePlainText);
                    emailMessage.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(template, emailMessage.Subject));

                    emailMessage.CcRecipients  = template.TemplateCc;
                    emailMessage.BccRecipients = template.TemplateBcc;

                    try
                    {
                        EmailHelper.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                        // Send the e-mail immediately
                        EmailSender.SendEmail(currentSiteName, emailMessage, true);
                    }
                    catch (Exception ex)
                    {
                        EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex);
                        error = true;
                    }
                }

                // If there was some error, user must be deleted
                if (error)
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("RegistrationForm.UserWasNotCreated");

                    // Email was not send, user can't be approved - delete it
                    UserInfoProvider.DeleteUser(ui);
                    return;
                }

                #endregion


                #region "Administrator notification email"

                // Notify administrator if enabled and email confirmation is not required
                if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
                {
                    EmailTemplateInfo mEmailTemplate = null;

                    if (requiresAdminApprove)
                    {
                        mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", currentSiteName);
                    }
                    else
                    {
                        mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", currentSiteName);
                    }

                    if (mEmailTemplate == null)
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                    }
                    else
                    {
                        // E-mail template ok
                        replacements       = new string[4, 2];
                        replacements[0, 0] = "firstname";
                        replacements[0, 1] = ui.FirstName;
                        replacements[1, 0] = "lastname";
                        replacements[1, 1] = ui.LastName;
                        replacements[2, 0] = "email";
                        replacements[2, 1] = ui.Email;
                        replacements[3, 0] = "username";
                        replacements[3, 1] = userName;

                        // Set resolver
                        resolver.SetNamedSourceData(replacements);
                        // Enable macro encoding for body
                        resolver.Settings.EncodeResolvedValues = true;

                        EmailMessage message = new EmailMessage();
                        message.EmailFormat = EmailFormatEnum.Default;
                        message.From        = EmailHelper.GetSender(mEmailTemplate, FromAddress);
                        message.Recipients  = ToAddress;
                        message.Body        = resolver.ResolveMacros(mEmailTemplate.TemplateText);
                        // Disable macro encoding for plaintext body and subject
                        resolver.Settings.EncodeResolvedValues = false;
                        message.Subject       = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject")));
                        message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText);

                        message.CcRecipients  = mEmailTemplate.TemplateCc;
                        message.BccRecipients = mEmailTemplate.TemplateBcc;

                        try
                        {
                            // Attach template meta-files to e-mail
                            EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                            EmailSender.SendEmail(currentSiteName, message);
                        }
                        catch
                        {
                            EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail");
                        }
                    }
                }

                #endregion


                #region "Web analytics"

                // Track successful registration conversion
                if (TrackConversionName != String.Empty)
                {
                    if (AnalyticsHelper.AnalyticsEnabled(currentSiteName) && AnalyticsHelper.TrackConversionsEnabled(currentSiteName) && !AnalyticsHelper.IsIPExcluded(currentSiteName, RequestContext.UserHostAddress))
                    {
                        HitLogProvider.LogConversions(currentSiteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue);
                    }
                }

                // Log registered user if confirmation is not required
                if (!requiresConfirmation)
                {
                    AnalyticsHelper.LogRegisteredUser(currentSiteName, ui);
                }

                #endregion


                #region "On-line marketing - activity"

                // Log registered user if confirmation is not required
                if (!requiresConfirmation)
                {
                    Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                    if (activity.Data != null)
                    {
                        activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        activity.Log();
                    }

                    // Log login activity
                    if (ui.Enabled)
                    {
                        // Log activity
                        int      contactID     = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        Activity activityLogin = new ActivityUserLogin(contactID, ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        activityLogin.Log();
                    }
                }

                #endregion

                #region "Site and roles addition and authentication"

                string[] roleList = AssignRoles.Split(';');

                foreach (string siteName in siteList)
                {
                    // Add new user to the current site
                    UserInfoProvider.AddUserToSite(ui.UserName, siteName);
                    foreach (string roleName in roleList)
                    {
                        if (!String.IsNullOrEmpty(roleName))
                        {
                            String sn = roleName.StartsWithCSafe(".") ? String.Empty : siteName;

                            // Add user to desired roles
                            if (RoleInfoProvider.RoleExists(roleName, sn))
                            {
                                UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn);
                            }
                        }
                    }
                }
                if (ui.Enabled)
                {
                    if (this.AutoLoginAfterRegistration)
                    {
                        Session["UserName"]   = userName;
                        Session["Password"]   = password;
                        Session["RememberMe"] = true;
                        Session["RetryCount"] = null;

                        if (this.Request.QueryString["ReturnURL"] != null)
                        {
                            var returnURL = this.Request.QueryString["ReturnURL"];

                            Session["ReturnURL"] = returnURL;
                        }
                        else if (!String.IsNullOrEmpty(this.RedirectToURL))
                        {
                            var returnURL = this.Request.QueryString["ReturnURL"];

                            Session["ReturnURL"] = returnURL;
                        }
                        Response.Redirect("~/sso/ssohandler.aspx", true);
                    }
                    else if (!String.IsNullOrEmpty(this.LoginURL))
                    {
                        Response.Redirect(string.Format(this.LoginURL, userName), true);
                    }
                    else if (!String.IsNullOrEmpty(this.RedirectToURL))
                    {
                        Response.Redirect(this.RedirectToURL, true);
                    }
                }
                #endregion

                lblError.Visible = false;
            }
        }
    }
    /// <summary>
    /// Saves the control. Returns false, if error occurred.
    /// </summary>
    public bool Save()
    {
        // Validates input data
        String error = ValidateData();

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

        if (Report != null)
        {
            bool isNew = false;
            if (mReportSubscriptionInfo.ReportSubscriptionID <= 0)
            {
                // Insert mode - initialize reportSubscriptionID
                mReportSubscriptionInfo.ReportSubscriptionUserID = MembershipContext.AuthenticatedUser.UserID;
                mReportSubscriptionInfo.ReportSubscriptionSiteID = SiteContext.CurrentSiteID;
                mReportSubscriptionInfo.ReportSubscriptionSettings["ReportInterval"] = mIntervalStr;
                isNew = true;
            }

            if (!SimpleMode)
            {
                // Save basic form & validates basic form data
                if (!formElem.SaveData(null))
                {
                    return(false);
                }

                // Store all parameters in basic form to string XML representation
                mParameters = formElem.DataRow;
                mReportSubscriptionInfo.ReportSubscriptionValueID = 0;
                mReportSubscriptionInfo.ReportSubscriptionTableID = 0;
                mReportSubscriptionInfo.ReportSubscriptionGraphID = 0;

                // If subscription is not for whole report, store item ID
                string drpValue = drpItems.SelectedValue;
                if (drpValue != "all")
                {
                    int id = ValidationHelper.GetInteger(drpValue.Substring(1), 0);
                    if (drpValue.Contains('g'))
                    {
                        mReportSubscriptionInfo.ReportSubscriptionGraphID = id;
                    }
                    if (drpValue.Contains('t'))
                    {
                        mReportSubscriptionInfo.ReportSubscriptionTableID = id;
                    }
                    if (drpValue.Contains('v'))
                    {
                        mReportSubscriptionInfo.ReportSubscriptionValueID = id;
                    }
                }
            }
            else
            {
                mReportSubscriptionInfo.ReportSubscriptionGraphID = mGraphID;
                mReportSubscriptionInfo.ReportSubscriptionTableID = mTableID;
                mReportSubscriptionInfo.ReportSubscriptionValueID = mValueID;
            }

            if (mParameters != null)
            {
                // Find special 'from' and 'to' parameters.
                DataColumn dcFrom = mParameters.Table.Columns["fromdate"];
                DataColumn dcTo   = mParameters.Table.Columns["todate"];

                if (rbTime.Checked)
                {
                    if (dcTo != null)
                    {
                        // Convert column from datetime to string to enable store macros
                        mParameters.Table.Columns.Remove(dcTo.ColumnName);
                        mParameters.Table.Columns.Add(dcTo.ColumnName, typeof(String));

                        // Add current date time macro
                        mParameters[dcTo.ColumnName] = "{%CurrentDateTime%}";
                    }

                    // Create right macro datetime command based on given interval.
                    String dateAddCommand = String.Empty;
                    switch (drpLast.SelectedValue)
                    {
                    case "hour":
                        dateAddCommand = "AddHours";
                        break;

                    case "day":
                        dateAddCommand = "AddDays";
                        break;

                    case "week":
                        dateAddCommand = "AddWeeks";
                        break;

                    case "month":
                        dateAddCommand = "AddMonths";
                        break;

                    case "year":
                        dateAddCommand = "AddYears";
                        break;
                    }

                    // Create todate macro
                    int    lastXTimeUnits = ValidationHelper.GetInteger(txtLast.Text.Trim(), 0);
                    String dateMacro      = String.Format("{{%CurrentDateTime.{0}({1})%}}", dateAddCommand, -lastXTimeUnits);

                    // Convert fromdate to string
                    if (dcFrom != null)
                    {
                        mParameters.Table.Columns.Remove(dcFrom.ColumnName);
                        mParameters.Table.Columns.Add(dcFrom.ColumnName, typeof(String));
                        mParameters[dcFrom.ColumnName] = dateMacro;
                    }
                }
                else
                {
                    // Empty fromdate and todate for uncheck limit date
                    if (dcFrom != null)
                    {
                        mParameters[dcFrom.ColumnName] = DBNull.Value;
                    }

                    if (dcTo != null)
                    {
                        mParameters[dcTo.ColumnName] = DBNull.Value;
                    }
                }

                // Write parameters to XML string representation
                mReportSubscriptionInfo.ReportSubscriptionParameters = ReportHelper.WriteParametersToXml(mParameters);
            }

            String email        = txtEmail.Text.Trim();
            bool   emailChanged = mReportSubscriptionInfo.ReportSubscriptionEmail != email;

            mReportSubscriptionInfo.ReportSubscriptionEnabled      = chkEnabled.Checked;
            mReportSubscriptionInfo.ReportSubscriptionReportID     = Report.ReportID;
            mReportSubscriptionInfo.ReportSubscriptionInterval     = ucInterval.ScheduleInterval;
            mReportSubscriptionInfo.ReportSubscriptionEmail        = email;
            mReportSubscriptionInfo.ReportSubscriptionSubject      = txtSubject.Text;
            mReportSubscriptionInfo.ReportSubscriptionCondition    = ucMacroEditor.Text;
            mReportSubscriptionInfo.ReportSubscriptionOnlyNonEmpty = chkNonEmpty.Checked;
            mReportSubscriptionInfo.ReportSubscriptionNextPostDate = SchedulingHelper.GetFirstRunTime(ucInterval.TaskInterval);

            ReportSubscriptionInfoProvider.SetReportSubscriptionInfo(mReportSubscriptionInfo);

            // Check whether email changed (applies for new subscription also)
            if (emailChanged)
            {
                String siteName = SiteContext.CurrentSiteName;

                EmailTemplateInfo eti = EmailTemplateProvider.GetEmailTemplate("Reporting_Subscription_information", siteName);
                if (eti != null)
                {
                    // Send information email
                    EmailMessage em = new EmailMessage();
                    em.EmailFormat = EmailFormatEnum.Default;
                    em.From        = EmailHelper.Settings.NotificationsSenderAddress(siteName);
                    em.Recipients  = email;

                    MacroResolver resolver = ReportSubscriptionSender.CreateSubscriptionMacroResolver(Report, mReportSubscriptionInfo, SiteContext.CurrentSite, em.Recipients);
                    EmailSender.SendEmailWithTemplateText(siteName, em, eti, resolver, false);
                }
            }

            // For new item and advanced mode redirect to store ID in query string
            if ((isNew) && (!SimpleMode))
            {
                URLHelper.Redirect(RequestContext.CurrentURL + "&saved=1&subscriptionid=" + mReportSubscriptionInfo.ReportSubscriptionID);
            }

            ShowChangesSaved();
            return(true);
        }

        return(false);
    }
Beispiel #20
0
 private MacroResolver GetMacroResolver()
 {
     return(MacroResolver.GetInstance(false));
 }
    /// <summary>
    /// Sets time controls (dropdown with interval and textbox with interval value). Returns true if time controls are to be hided.
    /// </summary>
    private bool SetTimeControls()
    {
        HitsIntervalEnum interval = HitsIntervalEnumFunctions.StringToHitsConversion(mIntervalStr);

        DateTime from = DateTimeHelper.ZERO_TIME;
        DateTime to   = DateTimeHelper.ZERO_TIME;

        object dcFrom = null;
        object dcTo   = null;

        if (mParameters != null)
        {
            // Load fromdate and todate from report parameters (passed from query string)
            dcFrom = mParameters.Table.Columns["FromDate"];
            dcTo   = mParameters.Table.Columns["ToDate"];

            if (dcFrom != null)
            {
                from = ValidationHelper.GetDateTime(mParameters["FromDate"], DateTimeHelper.ZERO_TIME);
            }

            if (dcTo != null)
            {
                to = ValidationHelper.GetDateTime(mParameters["ToDate"], DateTimeHelper.ZERO_TIME);
            }
        }

        // If one contains zero time, set all time radio button. In such situation, report can maintain unlimited fromdate or todate.
        if ((from == DateTimeHelper.ZERO_TIME) || (to == DateTimeHelper.ZERO_TIME))
        {
            mCheckLast = false;
        }

        // If one is not set, hide limitdata panel
        if ((dcFrom == null) || (dcTo == null))
        {
            ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_DAY;
            return(true);
        }

        int  diff        = 0;
        bool noAddToDiff = false;

        // If interval is not known, but 'from' and 'to' is set (f.e. preview, webpart,..) - compute interval from date values
        if (interval == HitsIntervalEnum.None)
        {
            string sFrom = ValidationHelper.GetString(mParameters["FromDate"], string.Empty).ToLowerInvariant();
            string sTo   = ValidationHelper.GetString(mParameters["ToDate"], string.Empty).ToLowerInvariant();
            mCheckLast = true;

            if (MacroProcessor.ContainsMacro(sFrom) && MacroProcessor.ContainsMacro(sTo))
            {
                if (sFrom.Contains("addhours"))
                {
                    interval = HitsIntervalEnum.Hour;
                }
                else if (sFrom.Contains("adddays"))
                {
                    interval = HitsIntervalEnum.Day;
                }
                else if (sFrom.Contains("addweeks"))
                {
                    interval = HitsIntervalEnum.Week;
                }
                else if (sFrom.Contains("addmonths"))
                {
                    interval = HitsIntervalEnum.Month;
                }
                else if (sFrom.Contains("addyears"))
                {
                    interval = HitsIntervalEnum.Year;
                }

                var macroResolverSettings = new MacroSettings
                {
                    AvoidInjection = false,
                    Culture        = CultureHelper.EnglishCulture.Name
                };
                to          = DateTime.Now;
                from        = ValidationHelper.GetDateTime(MacroResolver.Resolve(sFrom, macroResolverSettings), DateTime.Now, macroResolverSettings.Culture);
                noAddToDiff = true;
            }
            else if ((from != DateTimeHelper.ZERO_TIME) && (to != DateTimeHelper.ZERO_TIME))
            {
                // Set interval as greatest possible interval (365+ days -> years, 30+days->months ,...)
                diff = (int)(to - from).TotalDays;
                if (diff >= 365)
                {
                    interval = HitsIntervalEnum.Year;
                }
                else if (diff >= 30)
                {
                    interval = HitsIntervalEnum.Month;
                }
                else if (diff >= 7)
                {
                    interval = HitsIntervalEnum.Week;
                }
                else if (diff >= 1)
                {
                    interval = HitsIntervalEnum.Day;
                }
                else
                {
                    interval = HitsIntervalEnum.Hour;
                }
            }
        }

        // Set default period and diff based on interval
        switch (interval)
        {
        case HitsIntervalEnum.Year:
            diff = to.Year - from.Year;
            ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_MONTH;
            break;

        case HitsIntervalEnum.Month:
            diff = ((to.Year - from.Year) * 12) + to.Month - from.Month;
            ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_MONTH;
            break;

        case HitsIntervalEnum.Week:
            diff = (int)(to - from).TotalDays / 7;
            ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_WEEK;
            break;

        case HitsIntervalEnum.Day:
            diff = (int)(to - from).TotalDays;
            ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_DAY;
            break;

        case HitsIntervalEnum.Hour:
            diff = (int)(to - from).TotalHours;
            ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_HOUR;
            break;

        case HitsIntervalEnum.None:
            mCheckLast = false;
            break;
        }

        // Add current
        if (!noAddToDiff)
        {
            diff++;
        }

        if (interval != HitsIntervalEnum.None)
        {
            drpLast.SelectedValue = HitsIntervalEnumFunctions.HitsConversionToString(interval);
        }

        if (!mCheckLast)
        {
            // Defaul settings for no time
            ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_DAY;
        }

        if (diff != 0)
        {
            txtLast.Text = diff.ToString();
        }

        return(false);
    }
Beispiel #22
0
    private void ReloadData()
    {
        if (StopProcessing)
        {
            // Do nothing
            gridDocs.StopProcessing = true;
            editDoc.StopProcessing  = true;
        }
        else
        {
            if (((AllowUsers == UserContributionAllowUserEnum.Authenticated) || (AllowUsers == UserContributionAllowUserEnum.DocumentOwner)) &&
                !AuthenticationHelper.IsAuthenticated())
            {
                // Not authenticated, do not display anything
                pnlList.Visible = false;
                pnlEdit.Visible = false;

                StopProcessing = true;
            }
            else
            {
                SetContext();

                // Hide document list
                gridDocs.Visible = false;

                // If the list of documents should be displayed ...
                if (DisplayList)
                {
                    // Get all documents of the current user
                    TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

                    // Generate additional where condition
                    WhereCondition condition = new WhereCondition(WhereCondition);

                    if (!String.IsNullOrEmpty(ClassNames))
                    {
                        condition.WhereIn("ClassName", ClassNames.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries));
                    }

                    // Add user condition
                    if (AllowUsers == UserContributionAllowUserEnum.DocumentOwner)
                    {
                        condition.WhereEquals("NodeOwner", MembershipContext.AuthenticatedUser.UserID);
                    }

                    // Ensure that required columns are included in "Columns" list
                    string columns = EnsureColumns();

                    // Get the documents
                    var query =
                        DocumentHelper.GetDocuments()
                        .OnSite(SiteName)
                        .Path(MacroResolver.ResolveCurrentPath(Path))
                        .Where(condition)
                        .OrderBy(OrderBy)
                        .Published(SelectOnlyPublished)
                        .Columns(columns)
                        .NestingLevel(MaxRelativeLevel)
                        .CheckPermissions(CheckPermissions);

                    TreeProvider.SetQueryCultures(query, CultureCode, CombineWithDefaultCulture);

                    // Do not apply published from / to columns to make sure the published information is correctly evaluated
                    query.Properties.ExcludedVersionedColumns = new[] { "DocumentPublishFrom", "DocumentPublishTo" };

                    var ds = query.Result;

                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        // Display and initialize grid if datasource is not empty
                        gridDocs.Visible            = true;
                        gridDocs.DataSource         = ds;
                        gridDocs.OrderBy            = OrderBy;
                        editDoc.AlternativeFormName = AlternativeFormName;
                    }
                }

                bool isAuthorizedToCreateDoc = false;
                if (ParentNode != null)
                {
                    // Check if single class name is set
                    string className = (!string.IsNullOrEmpty(AllowedChildClasses) && !AllowedChildClasses.Contains(";")) ? AllowedChildClasses : null;

                    // Check user's permission to create new document if allowed
                    isAuthorizedToCreateDoc = !CheckPermissions || MembershipContext.AuthenticatedUser.IsAuthorizedToCreateNewDocument(ParentNodeID, className);
                    // Check group's permission to create new document if allowed
                    isAuthorizedToCreateDoc &= CheckGroupPermission("createpages");

                    if (!CheckDocPermissionsForInsert && CheckPermissions)
                    {
                        // If document permissions are not required check create permission on parent document
                        isAuthorizedToCreateDoc = MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(ParentNode, NodePermissionsEnum.Create) == AuthorizationResultEnum.Allowed;
                    }

                    if (AllowUsers == UserContributionAllowUserEnum.DocumentOwner)
                    {
                        // Do not allow documents creation under virtual user
                        if (VirtualContext.IsUserInitialized)
                        {
                            isAuthorizedToCreateDoc = false;
                        }
                        else
                        {
                            // Check if user is document owner (or global admin)
                            isAuthorizedToCreateDoc = isAuthorizedToCreateDoc &&
                                                      ((ParentNode.NodeOwner == MembershipContext.AuthenticatedUser.UserID) ||
                                                       MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin));
                        }
                    }
                }

                // Enable/disable inserting new document
                pnlNewDoc.Visible = (isAuthorizedToCreateDoc && AllowInsert);

                if (!gridDocs.Visible && !pnlNewDoc.Visible && pnlList.Visible)
                {
                    // Not authenticated to create new docs and grid is hidden
                    StopProcessing = true;
                }

                ReleaseContext();
            }
        }
    }
    /// <summary>
    /// Sends e-mail to all attendees.
    /// </summary>
    protected void Send()
    {
        // Check 'Modify' permission
        if (!CheckPermissions("cms.eventmanager", "Modify"))
        {
            return;
        }

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

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

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

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

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

        if (node != null && CMSString.Equals(node.NodeClassName, "cms.bookingevent", true))
        {
            // Initialize macro resolver
            MacroResolver resolver = MacroResolver.GetInstance();
            resolver.Settings.KeepUnresolvedMacros = true;
            resolver.SetAnonymousSourceData(node);
            // Add named source data
            resolver.SetNamedSourceData("Event", node);

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

            resolver.SetNamedSourceData("eventdatestring", EventProvider.GetEventDateString(eventDate, eventEndDate, isAllDay, TimeZoneHelper.GetTimeZoneInfo(SiteContext.CurrentSite), SiteContext.CurrentSiteName), false);

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

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

            ShowConfirmation(GetString("Events_SendEmail.EmailSent"));
        }
    }
    /// <summary>
    /// Initializes control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
            ucAttachments.StopProcessing = true;
        }
        else
        {
            ucAttachments.GetBinary = false;

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

            // Data source properties
            ucAttachments.WhereCondition            = WhereCondition;
            ucAttachments.OrderBy                   = OrderBy;
            ucAttachments.FilterName                = FilterName;
            ucAttachments.CacheItemName             = CacheItemName;
            ucAttachments.CacheDependencies         = CacheDependencies;
            ucAttachments.CacheMinutes              = CacheMinutes;
            ucAttachments.AttachmentGroupGUID       = AttachmentGroupGUID;
            ucAttachments.CheckPermissions          = CheckPermissions;
            ucAttachments.CombineWithDefaultCulture = CombineWithDefaultCulture;
            if (string.IsNullOrEmpty(CultureCode))
            {
                ucAttachments.CultureCode = DocumentContext.CurrentDocumentCulture.CultureCode;
            }
            else
            {
                ucAttachments.CultureCode = CultureCode;
            }

            ucAttachments.Path     = TreePathUtils.EnsureSingleNodePath(MacroResolver.ResolveCurrentPath(Path));
            ucAttachments.SiteName = SiteName;
            ucAttachments.TopN     = TopN;


            #region "Repeater template properties"

            // Apply transformations if they exist
            ucAttachments.TransformationName = TransformationName;
            ucAttachments.AlternatingItemTransformationName = AlternatingItemTransformationName;
            ucAttachments.FooterTransformationName          = FooterTransformationName;
            ucAttachments.HeaderTransformationName          = HeaderTransformationName;
            ucAttachments.SeparatorTransformationName       = SeparatorTransformationName;

            #endregion


            // UniPager properties
            ucAttachments.PageSize       = PageSize;
            ucAttachments.GroupSize      = GroupSize;
            ucAttachments.QueryStringKey = QueryStringKey;
            ucAttachments.DisplayFirstLastAutomatically    = DisplayFirstLastAutomatically;
            ucAttachments.DisplayPreviousNextAutomatically = DisplayPreviousNextAutomatically;
            ucAttachments.HidePagerForSinglePage           = HidePagerForSinglePage;
            switch (PagingMode.ToLowerCSafe())
            {
            case "postback":
                ucAttachments.PagingMode = UniPagerMode.PostBack;
                break;

            default:
                ucAttachments.PagingMode = UniPagerMode.Querystring;
                break;
            }


            #region "UniPager template properties"

            // UniPager template properties
            ucAttachments.PagesTemplate         = PagesTemplate;
            ucAttachments.CurrentPageTemplate   = CurrentPageTemplate;
            ucAttachments.SeparatorTemplate     = SeparatorTemplate;
            ucAttachments.FirstPageTemplate     = FirstPageTemplate;
            ucAttachments.LastPageTemplate      = LastPageTemplate;
            ucAttachments.PreviousPageTemplate  = PreviousPageTemplate;
            ucAttachments.NextPageTemplate      = NextPageTemplate;
            ucAttachments.PreviousGroupTemplate = PreviousGroupTemplate;
            ucAttachments.NextGroupTemplate     = NextGroupTemplate;
            ucAttachments.LayoutTemplate        = LayoutTemplate;

            #endregion
        }
    }
    private void ReloadData()
    {
        if (StopProcessing)
        {
            // Do nothing
            gridDocs.StopProcessing = true;
            editDoc.StopProcessing  = true;
        }
        else
        {
            if (((AllowUsers == UserContributionAllowUserEnum.Authenticated) || (AllowUsers == UserContributionAllowUserEnum.DocumentOwner)) &&
                !AuthenticationHelper.IsAuthenticated())
            {
                // Not authenticated, do not display anything
                pnlList.Visible = false;
                pnlEdit.Visible = false;

                StopProcessing = true;
            }
            else
            {
                SetContext();

                // Hide document list
                gridDocs.Visible = false;

                // If the list of documents should be displayed ...
                if (DisplayList)
                {
                    // Get all documents of the current user
                    TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

                    // Generate additional where condition
                    string classWhere = null;
                    if (!String.IsNullOrEmpty(ClassNames))
                    {
                        // Remove ending semicolon
                        classWhere = ClassNames.TrimEnd(';');
                        // Replace single apostrophs
                        classWhere = SqlHelper.GetSafeQueryString(classWhere, false);
                        // Replace ; with ','
                        classWhere = classWhere.Replace(";", "','");
                        if (!String.IsNullOrEmpty(classWhere))
                        {
                            classWhere = String.Format("ClassName IN ('{0}')", classWhere);
                        }
                    }

                    string where = SqlHelper.AddWhereCondition(WhereCondition, classWhere);

                    // Add user condition
                    if (AllowUsers == UserContributionAllowUserEnum.DocumentOwner)
                    {
                        where = SqlHelper.AddWhereCondition(where, "NodeOwner = " + MembershipContext.AuthenticatedUser.UserID);
                    }

                    // Ensure that required columns are included in "Columns" list
                    string columns = EnsureColumns();

                    // Get the documents
                    DataSet ds = DocumentHelper.GetDocuments(SiteName, MacroResolver.ResolveCurrentPath(Path), CultureCode, CombineWithDefaultCulture, null, where, OrderBy, MaxRelativeLevel, SelectOnlyPublished, 0, columns, tree);
                    if (CheckPermissions)
                    {
                        ds = TreeSecurityProvider.FilterDataSetByPermissions(ds, NodePermissionsEnum.Read, MembershipContext.AuthenticatedUser);
                    }

                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        // Display and initialize grid if datasource is not empty
                        gridDocs.Visible            = true;
                        gridDocs.DataSource         = ds;
                        gridDocs.OrderBy            = OrderBy;
                        editDoc.AlternativeFormName = AlternativeFormName;
                    }
                }

                bool isAuthorizedToCreateDoc = false;
                if (ParentNode != null)
                {
                    // Check if single class name is set
                    string className = (!string.IsNullOrEmpty(AllowedChildClasses) && !AllowedChildClasses.Contains(";")) ? AllowedChildClasses : null;

                    // Check user's permission to create new document if allowed
                    isAuthorizedToCreateDoc = !CheckPermissions || MembershipContext.AuthenticatedUser.IsAuthorizedToCreateNewDocument(ParentNodeID, className);
                    // Check group's permission to create new document if allowed
                    isAuthorizedToCreateDoc &= CheckGroupPermission("createpages");

                    if (!CheckDocPermissionsForInsert && CheckPermissions)
                    {
                        // If document permissions are not required check create permission on parent document
                        isAuthorizedToCreateDoc = MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(ParentNode, NodePermissionsEnum.Create) == AuthorizationResultEnum.Allowed;
                    }

                    if (AllowUsers == UserContributionAllowUserEnum.DocumentOwner)
                    {
                        // Do not allow documents creation under virtual user
                        if (MembershipContext.AuthenticatedUser.IsVirtual)
                        {
                            isAuthorizedToCreateDoc = false;
                        }
                        else
                        {
                            // Check if user is document owner (or global admin)
                            isAuthorizedToCreateDoc = isAuthorizedToCreateDoc && ((ParentNode.NodeOwner == MembershipContext.AuthenticatedUser.UserID) || MembershipContext.AuthenticatedUser.IsGlobalAdministrator);
                        }
                    }
                }

                // Enable/disable inserting new document
                pnlNewDoc.Visible = (isAuthorizedToCreateDoc && AllowInsert);

                if (!gridDocs.Visible && !pnlNewDoc.Visible && pnlList.Visible)
                {
                    // Not authenticated to create new docs and grid is hidden
                    StopProcessing = true;
                }

                ReleaseContext();
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (EditedObject == null)
        {
            RedirectToAccessDenied(GetString("general.invalidparameters"));
        }

        Save += btnOK_Click;

        var user = MembershipContext.AuthenticatedUser;

        // Check permissions for Forms application
        if (!user.IsAuthorizedPerUIElement("cms.form", "Form"))
        {
            RedirectToUIElementAccessDenied("cms.form", "Form");
        }

        // Check 'ReadData' permission
        if (!user.IsAuthorizedPerResource("cms.form", "ReadData", SiteInfoProvider.GetSiteName(FormInfo.FormSiteID)))
        {
            RedirectToAccessDenied("cms.form", "ReadData");
        }

        // Check authorized roles for this form
        if (!FormInfo.IsFormAllowedForUser(MembershipContext.AuthenticatedUser.UserName, SiteContext.CurrentSiteName))
        {
            RedirectToAccessDenied(GetString("Bizforms.FormNotAllowedForUserRoles"));
        }

        List <String> columnNames  = null;
        DataClassInfo dci          = null;
        Hashtable     reportFields = new Hashtable();
        FormInfo      fi           = null;

        // Initialize controls
        PageTitle.TitleText = GetString("BizForm_Edit_Data_SelectFields.Title");
        CurrentMaster.DisplayActionsPanel = true;

        HeaderActions.AddAction(new HeaderAction
        {
            Text          = GetString("UniSelector.SelectAll"),
            OnClientClick = "ChangeFields(true); return false;",
            ButtonStyle   = ButtonStyle.Default,
        });

        HeaderActions.AddAction(new HeaderAction
        {
            Text          = GetString("UniSelector.DeselectAll"),
            OnClientClick = "ChangeFields(false); return false;",
            ButtonStyle   = ButtonStyle.Default,
        });

        if (!RequestHelper.IsPostBack())
        {
            if (FormInfo != null)
            {
                // Get dataclass info
                dci = DataClassInfoProvider.GetDataClassInfo(FormInfo.FormClassID);

                if (dci != null)
                {
                    // Get columns names
                    fi = FormHelper.GetFormInfo(dci.ClassName, false);

                    columnNames = fi.GetColumnNames(false, i => i.System);
                }

                // Get report fields
                if (String.IsNullOrEmpty(FormInfo.FormReportFields))
                {
                    reportFields = LoadReportFields(columnNames);
                }
                else
                {
                    reportFields.Clear();

                    foreach (string field in FormInfo.FormReportFields.Split(';'))
                    {
                        // Add field key to hastable
                        reportFields[field] = null;
                    }
                }

                if (columnNames != null)
                {
                    FormFieldInfo ffi  = null;
                    ListItem      item = null;

                    MacroResolver resolver = MacroResolverStorage.GetRegisteredResolver(FormHelper.FORM_PREFIX + FormInfo.ClassName);

                    foreach (string name in columnNames)
                    {
                        ffi = fi.GetFormField(name);

                        // Add checkboxes to the list
                        item = new ListItem(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(GetFieldCaption(ffi, name, resolver))), name);
                        if (reportFields.Contains(name))
                        {
                            // Select checkbox if field is reported
                            item.Selected = true;
                        }
                        chkListFields.Items.Add(item);
                    }
                }
            }
        }
    }
    /// <summary>
    /// Perform search.
    /// </summary>
    protected void Search()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            // Check if the search was triggered
            bool searchAllowed = SearchOnEachPageLoad || QueryHelper.Contains("searchtext");

            // Get query strings
            string searchText = QueryHelper.GetString("searchtext", "");
            // Check whether string passes text requirements settings
            bool searchTextIsNotEmptyOrNotRequired = (!SearchTextRequired || !String.IsNullOrEmpty(searchText));

            // Proceed when search was triggered and search text is passing requirements settings.
            // Requirements setting could be overriden on this level by obsolete web.config key. The reason is backward compatibility.
            // Search text required web part setting was introduced after this web.config key. Key default value was at the time set to true.
            // This default value had the same effect as this new web part setting. When somenone changed the web.config key to false and then upgraded the solution,
            // required wep part setting with default value true would override previous behaviour. That's the reason why this obsolete key can override this setting.
            if (searchAllowed && (searchTextIsNotEmptyOrNotRequired || !SearchHelper.SearchOnlyWhenContentPresent))
            {
                string         searchMode     = QueryHelper.GetString("searchMode", "");
                SearchModeEnum searchModeEnum = searchMode.ToEnum <SearchModeEnum>();

                // Get current culture
                string culture = CultureCode;
                if (string.IsNullOrEmpty(culture))
                {
                    culture = ValidationHelper.GetString(ViewState["CultureCode"], LocalizationContext.PreferredCultureCode);
                }

                var siteName = SiteContext.CurrentSiteName;

                // Get default culture
                string defaultCulture = CultureHelper.GetDefaultCultureCode(siteName);

                // Resolve path
                string path = Path;
                if (!string.IsNullOrEmpty(path))
                {
                    path = MacroResolver.ResolveCurrentPath(Path);
                }

                // Check if search action was fired really on the live site
                if (PortalContext.ViewMode.IsLiveSite() && (DocumentContext.CurrentPageInfo != null))
                {
                    if (AnalyticsHelper.AnalyticsEnabled(siteName))
                    {
                        if (AnalyticsHelper.JavascriptLoggingEnabled(siteName))
                        {
                            WebAnalyticsServiceScriptsRenderer.RegisterLogSearchCall(Page, DocumentContext.CurrentPageInfo, searchText);
                        }
                        else
                        {
                            // Log on site keywords
                            AnalyticsHelper.LogOnSiteSearchKeywords(siteName, DocumentContext.CurrentAliasPath, culture, searchText, 0, 1);
                        }
                    }
                }

                // Prepare search text
                var docCondition = new DocumentSearchCondition(DocumentTypes, culture, defaultCulture, CombineWithDefaultCulture);

                var searchCond = SearchCondition;
                if (!string.IsNullOrEmpty(FilterSearchCondition) && (searchModeEnum == SearchModeEnum.AnyWordOrSynonyms))
                {
                    // Make sure the synonyms are expanded before the filter condition is applied (filter condition is Lucene syntax, cannot be expanded)
                    searchCond     = SearchSyntaxHelper.ExpandWithSynonyms(searchCond, docCondition.Culture);
                    searchModeEnum = SearchModeEnum.AnyWord;
                }

                var condition = new SearchCondition(searchCond + FilterSearchCondition, searchModeEnum, SearchOptions, docCondition, DoFuzzySearch);

                searchText = SearchSyntaxHelper.CombineSearchCondition(searchText, condition);

                // Get positions and ranges for search method
                int startPosition     = 0;
                int numberOfProceeded = 100;
                int displayResults    = 100;
                if (pgr.PageSize != 0 && pgr.GroupSize != 0)
                {
                    // Reset pager if needed
                    if (mResetPager)
                    {
                        pgr.CurrentPage = 1;
                    }

                    startPosition = (pgr.CurrentPage - 1) * pgr.PageSize;
                    // Only results covered by current page group are proccessed (filtered) for performance reasons. This may cause decrease of the number of results while paging.
                    numberOfProceeded = (((pgr.CurrentPage / pgr.GroupSize) + 1) * pgr.PageSize * pgr.GroupSize) + pgr.PageSize;
                    displayResults    = pgr.PageSize;
                }

                if ((MaxResults > 0) && (numberOfProceeded > MaxResults))
                {
                    numberOfProceeded = MaxResults;
                }

                // Combine regular search sort with filter sort
                string srt       = ValidationHelper.GetString(SearchSort, String.Empty).Trim();
                string filterSrt = ValidationHelper.GetString(FilterSearchSort, String.Empty).Trim();

                if (!String.IsNullOrEmpty(filterSrt))
                {
                    if (!String.IsNullOrEmpty(srt))
                    {
                        srt += ", ";
                    }

                    srt += filterSrt;
                }

                // Prepare parameters
                SearchParameters parameters = new SearchParameters
                {
                    SearchFor                 = searchText,
                    SearchSort                = srt,
                    Path                      = path,
                    ClassNames                = DocumentTypes,
                    CurrentCulture            = culture,
                    DefaultCulture            = defaultCulture,
                    CombineWithDefaultCulture = CombineWithDefaultCulture,
                    CheckPermissions          = CheckPermissions,
                    SearchInAttachments       = SearchInAttachments,
                    User                      = MembershipContext.AuthenticatedUser,
                    SearchIndexes             = Indexes,
                    StartingPosition          = startPosition,
                    DisplayResults            = displayResults,
                    NumberOfProcessedResults  = numberOfProceeded,
                    NumberOfResults           = 0,
                    AttachmentWhere           = AttachmentsWhere,
                    AttachmentOrderBy         = AttachmentsOrderBy,
                    BlockFieldOnlySearch      = BlockFieldOnlySearch,
                };

                // Search
                DataSet results = SearchHelper.Search(parameters);

                int numberOfResults = parameters.NumberOfResults;
                if ((MaxResults > 0) && (numberOfResults > MaxResults))
                {
                    numberOfResults = MaxResults;
                }

                // Fill repeater with results
                repSearchResults.DataSource = results;
                repSearchResults.PagerForceNumberOfResults = numberOfResults;
                PagerForceNumberOfResults = numberOfResults;
                repSearchResults.DataBind();

                // Call page binding event
                if (OnPageBinding != null)
                {
                    OnPageBinding(this, null);
                }

                // Show no results found ?
                if (numberOfResults == 0)
                {
                    if (ShowParsingErrors)
                    {
                        Exception searchError = SearchContext.LastError;
                        if (searchError != null)
                        {
                            ShowError(GetString("smartsearch.searcherror") + " " + searchError.Message);
                        }
                    }
                    lblNoResults.Text    = NoResultsText;
                    lblNoResults.Visible = true;
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(SearchTextValidationFailedText) && searchAllowed)
                {
                    pnlSearchResults.AddCssClass(SearchTextValidationFailedCssClass);
                    lblNoResults.Text    = SearchTextValidationFailedText;
                    lblNoResults.Visible = true;
                }
                else
                {
                    Visible = false;
                }
            }

            // Invoke search completed event
            if (OnSearchCompleted != null)
            {
                OnSearchCompleted(Visible);
            }
        }
    }
Beispiel #28
0
    /// <summary>
    /// Loads fields to drop down control.
    /// </summary>
    private void SetupFieldSelector(string selectedValue, bool forceReload)
    {
        if (forceReload || (fieldSelector.Items.Count == 0))
        {
            // Clear dropdown list
            fieldSelector.Items.Clear();

            // Get data class info
            string className = ValidationHelper.GetString(classSelector.Value, null);
            if (!String.IsNullOrEmpty(className) && (className != SpecialFieldValue.NONE.ToString()))
            {
                // Get fields of type file
                var dci = DataClassInfoProvider.GetDataClassInfo(className);
                var fi  = FormHelper.GetFormInfo(dci.ClassName, false);
                var ffi = fi.GetFields(true, true);

                // Filter fields
                if (!String.IsNullOrEmpty(FieldCondition))
                {
                    MacroResolver resolver      = MacroResolver.GetInstance();
                    var           visibleFields = new List <FormFieldInfo>();
                    foreach (FormFieldInfo field in ffi)
                    {
                        resolver.SetAnonymousSourceData(field);
                        bool result = ValidationHelper.GetBoolean(resolver.ResolveMacros(FieldCondition), true);
                        if (result)
                        {
                            visibleFields.Add(field);
                        }
                    }

                    ffi = visibleFields;
                }

                if (ffi.Count > 0)
                {
                    // Fill dropdown list with fields
                    var list = ffi.Select(t => new Tuple <string, string>(!String.IsNullOrEmpty(t.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, ContextResolver)) ? t.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, ContextResolver) : t.Name, t.Guid.ToString())).OrderBy(t => t.Item1);
                    foreach (var item in list)
                    {
                        fieldSelector.Items.Add(new ListItem(item.Item1, item.Item2));
                    }

                    if (!String.IsNullOrEmpty(selectedValue) && (fieldSelector.Items.FindByValue(selectedValue) != null) && !forceReload)
                    {
                        // Selected value from database
                        fieldSelector.SelectedValue = selectedValue;
                    }
                    else
                    {
                        // Select first item if nothing selected or class name was changed
                        fieldSelector.SelectedIndex = 0;
                    }

                    fieldSelector.Enabled = true;
                }
                else
                {
                    fieldSelector.Enabled = false;
                }

                pnlFields.Visible = true;
            }
            else
            {
                // Hide field selector for (none) option
                pnlFields.Visible = false;
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            editForm.StopProcessing = true;
            editForm.Visible        = false;
        }
        else
        {
            pnlEdit.Visible = false;

            var currentUser = MembershipContext.AuthenticatedUser;

            // Get the document
            TreeNode node = TreeHelper.GetDocument(SiteName, MacroResolver.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 = AuthenticationHelper.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;
                }
            }
        }
    }
Beispiel #30
0
    /// <summary>
    /// Updates the current Group or creates new if no GroupID is present.
    /// </summary>
    public void SaveData()
    {
        // Check banned IP
        if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete))
        {
            ShowError(GetString("General.BannedIP"));
            return;
        }

        // Validate form entries
        string errorMessage = ValidateForm();

        if (!String.IsNullOrEmpty(errorMessage))
        {
            // Display error message
            ShowError(errorMessage);
            return;
        }

        try
        {
            GroupInfo group = new GroupInfo();
            group.GroupDisplayName    = txtDisplayName.Text;
            group.GroupDescription    = txtDescription.Text;
            group.GroupAccess         = GetGroupAccess();
            group.GroupSiteID         = mSiteId;
            group.GroupApproveMembers = GetGroupApproveMembers();
            // Automatic code name can be set after display name + site id is set
            group.Generalized.EnsureCodeName();

            // Set columns GroupCreatedByUserID and GroupApprovedByUserID to current user
            var user = MembershipContext.AuthenticatedUser;

            if (user != null)
            {
                group.GroupCreatedByUserID = user.UserID;

                if ((!RequireApproval) || (CurrentUserIsAdmin()))
                {
                    group.GroupApprovedByUserID = user.UserID;
                    group.GroupApproved         = true;
                }
            }

            // Save Group in the database
            GroupInfoProvider.SetGroupInfo(group);

            // Create group admin role
            RoleInfo roleInfo = new RoleInfo();
            roleInfo.RoleDisplayName          = "Group admin";
            roleInfo.RoleName                 = group.GroupName + "_groupadmin";
            roleInfo.RoleGroupID              = group.GroupID;
            roleInfo.RoleIsGroupAdministrator = true;
            roleInfo.SiteID = mSiteId;
            // Save group admin role
            RoleInfoProvider.SetRoleInfo(roleInfo);

            if (user != null)
            {
                // Set user as member of group
                GroupMemberInfo gmi = new GroupMemberInfo();
                gmi.MemberUserID           = user.UserID;
                gmi.MemberGroupID          = group.GroupID;
                gmi.MemberJoined           = DateTime.Now;
                gmi.MemberStatus           = GroupMemberStatus.Approved;
                gmi.MemberApprovedWhen     = DateTime.Now;
                gmi.MemberApprovedByUserID = user.UserID;

                // Save user as member of group
                GroupMemberInfoProvider.SetGroupMemberInfo(gmi);

                // Set user as member of admin group role
                UserRoleInfo userRole = new UserRoleInfo();
                userRole.UserID = user.UserID;
                userRole.RoleID = roleInfo.RoleID;

                // Save user as member of admin group role
                UserRoleInfoProvider.SetUserRoleInfo(userRole);
            }

            // Clear user session a request
            MembershipContext.AuthenticatedUser.Generalized.Invalidate(false);
            MembershipContext.AuthenticatedUser = null;

            string culture = CultureHelper.EnglishCulture.ToString();
            if (DocumentContext.CurrentDocument != null)
            {
                culture = DocumentContext.CurrentDocument.DocumentCulture;
            }

            // Copy document
            errorMessage = GroupInfoProvider.CopyGroupDocument(group, GroupTemplateSourceAliasPath, GroupTemplateTargetAliasPath, GroupProfileURLPath, culture, CombineWithDefaultCulture, MembershipContext.AuthenticatedUser, roleInfo);

            if (!String.IsNullOrEmpty(errorMessage))
            {
                // Display error message
                ShowError(errorMessage);
                return;
            }

            // Create group forum
            if (CreateForum)
            {
                CreateGroupForum(group);

                // Create group forum search index
                if (CreateSearchIndexes)
                {
                    CreateGroupForumSearchIndex(group);
                }
            }

            // Create group media library
            if (CreateMediaLibrary)
            {
                CreateGroupMediaLibrary(group);
            }

            // Create search index for group documents
            if (CreateSearchIndexes)
            {
                CreateGroupContentSearchIndex(group);
            }

            // Display information on success
            ShowConfirmation(GetString("group.group.createdinfo"));

            // If URL is set, redirect user to specified page
            if (!String.IsNullOrEmpty(RedirectToURL))
            {
                URLHelper.Redirect(UrlResolver.ResolveUrl(ResolveUrl(DocumentURLProvider.GetUrl(RedirectToURL))));
            }

            // After registration message
            if ((RequireApproval) && (!CurrentUserIsAdmin()))
            {
                ShowConfirmation(SuccessfullRegistrationWaitingForApprovalText);

                // Send approval email to admin
                if (!String.IsNullOrEmpty(SendWaitingForApprovalEmailTo))
                {
                    var siteName = SiteContext.CurrentSiteName;

                    // Create the message
                    EmailTemplateInfo eti = EmailTemplateProvider.GetEmailTemplate("Groups.WaitingForApproval", siteName);
                    if (eti != null)
                    {
                        MacroResolver resolver = MacroContext.CurrentResolver;
                        resolver.SetAnonymousSourceData(group);
                        resolver.SetNamedSourceData("Group", group);

                        EmailMessage message = new EmailMessage
                        {
                            From       = SettingsKeyInfoProvider.GetValue(siteName + ".CMSSendEmailNotificationsFrom"),
                            Recipients = SendWaitingForApprovalEmailTo
                        };

                        // Send the message using email engine
                        EmailSender.SendEmailWithTemplateText(siteName, message, eti, resolver, false);
                    }
                }
            }
            else
            {
                string groupPath = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSGroupProfilePath");
                string url       = String.Empty;

                if (!String.IsNullOrEmpty(groupPath))
                {
                    url = DocumentURLProvider.GetUrl(groupPath.Replace("{GroupName}", group.GroupName));
                }
                ShowConfirmation(String.Format(SuccessfullRegistrationText, url));
            }

            // Hide form
            if (HideFormAfterRegistration)
            {
                plcForm.Visible = false;
            }
            else
            {
                ClearForm();
            }
        }
        catch (Exception ex)
        {
            // Display error message
            ShowError(GetString("general.saveerror"), ex.Message);
        }
    }
    protected void btnRun_Click(object sender, EventArgs e)
    {
        var text = editorElem.Text;

        // Get the number of iterations
        int iterations = ValidationHelper.GetInteger(txtIterations.Text, 0);

        if (iterations <= 0)
        {
            ShowError(GetString("macros.benchmark.invaliditerations"));
            return;
        }

        string result = String.Empty;

        int runs = 0;

        var startTime = DateTime.Now;

        double minRunSeconds = double.MaxValue;
        double maxRunSeconds = 0;

        double totalRunSeconds = 0;

        // Run the benchmark
        for (int i = 0; i < iterations; i++)
        {
            var runStart = DateTime.Now;

            // Execute the run
            result = MacroResolver.Resolve(text);

            runs++;

            // Count the run time
            var runEnd     = DateTime.Now;
            var runTime    = runEnd - runStart;
            var runSeconds = runTime.TotalSeconds;

            if (runSeconds < minRunSeconds)
            {
                minRunSeconds = runSeconds;
            }
            if (runSeconds > maxRunSeconds)
            {
                maxRunSeconds = runSeconds;
            }

            totalRunSeconds += runSeconds;
        }

        var endTime = DateTime.Now;

        if (Math.Abs(minRunSeconds - double.MaxValue) < Math.E)
        {
            minRunSeconds = 0;
        }

        editorElem.Text = text;
        txtOutput.Text  = result;

        var totalTime = endTime - startTime;

        var totalSeconds  = totalTime.TotalSeconds;
        var secondsPerRun = totalSeconds / runs;

        txtResults.Text = String.Format(
            @"
Total runs: {0}s
Total benchmark time: {1:f5}s
Total run time: {5:f5}s

Average time per run: {2:f5}s
Min run time: {3:f5}s
Max run time: {4:f5}s

Evaluated text: 
---------------
{6}
"
            , runs
            , totalSeconds
            , secondsPerRun
            , minRunSeconds
            , maxRunSeconds
            , totalRunSeconds
            , text
            );
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Security test
        if (!MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin))
        {
            RedirectToAccessDenied(GetString("attach.actiondenied"));
        }

        // Add link to external stylesheet
        CSSHelper.RegisterCSSLink(this, "Default", "/CMSDesk.css");

        // Get current resolver
        resolver = MacroContext.CurrentResolver.CreateChild();

        DataSet ds = null;
        DataSet cds = null;

        // Check init settings
        bool allWidgets = QueryHelper.GetBoolean("allWidgets", false);
        bool allWebParts = QueryHelper.GetBoolean("allWebparts", false);
        bool allWireframes = QueryHelper.GetBoolean("allwireframes", false);

        // Get webpart (widget) from querystring - only if no allwidget or allwebparts set
        bool isWebpartInQuery = false;
        bool isWidgetInQuery = false;
        String webpartQueryParam = String.Empty;

        //If not show all widgets or webparts - check if any widget or webpart is present
        if (!allWidgets && !allWebParts && !allWireframes)
        {
            webpartQueryParam = QueryHelper.GetString("webpart", "");
            if (!string.IsNullOrEmpty(webpartQueryParam))
            {
                isWebpartInQuery = true;
            }
            else
            {
                webpartQueryParam = QueryHelper.GetString("widget", "");
                if (!string.IsNullOrEmpty(webpartQueryParam))
                {
                    isWidgetInQuery = true;
                }
            }
        }

        // Set development option if is required
        if (QueryHelper.GetString("details", "0") == "1")
        {
            development = true;
        }

        // Generate all webparts
        if (allWebParts)
        {
            // Get all webpart categories
            cds = WebPartCategoryInfoProvider.GetCategories();
        }
        // Generate all widgets
        else if (allWidgets)
        {
            // Get all widget categories
            cds = WidgetCategoryInfoProvider.GetWidgetCategories();
        }
        else if (allWireframes)
        {
            WebPartCategoryInfo wpci = WebPartCategoryInfoProvider.GetWebPartCategoryInfoByCodeName("Wireframes");
            if (wpci != null)
            {
                cds = WebPartCategoryInfoProvider.GetCategories(wpci.CategoryID);
            }
        }
        // Generate single webpart
        else if (isWebpartInQuery)
        {
            // Split weparts
            string[] webparts = webpartQueryParam.Split(';');
            if (webparts.Length > 0)
            {
                string webpartWhere = SqlHelper.GetWhereCondition("WebpartName", webparts);
                ds = WebPartInfoProvider.GetWebParts().Where(webpartWhere);

                // If any webparts found
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    StringBuilder categoryWhere = new StringBuilder("");
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        categoryWhere.Append(ValidationHelper.GetString(dr["WebpartCategoryID"], "NULL") + ",");
                    }

                    string ctWhere = "CategoryID IN (" + categoryWhere.ToString().TrimEnd(',') + ")";
                    cds = WebPartCategoryInfoProvider.GetCategories().Where(ctWhere);
                }
            }
        }
        // Generate single widget
        else if (isWidgetInQuery)
        {
            string[] widgets = webpartQueryParam.Split(';');
            if (widgets.Length > 0)
            {
                string widgetsWhere = SqlHelper.GetWhereCondition("WidgetName", widgets);
                ds = WidgetInfoProvider.GetWidgets().Where(widgetsWhere);
            }

            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                StringBuilder categoryWhere = new StringBuilder("");
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    categoryWhere.Append(ValidationHelper.GetString(dr["WidgetCategoryID"], "NULL") + ",");
                }

                string ctWhere = "WidgetCategoryID IN (" + categoryWhere.ToString().TrimEnd(',') + ")";
                cds = WidgetCategoryInfoProvider.GetWidgetCategories().Where(ctWhere);
            }
        }

        if (allWidgets || isWidgetInQuery)
        {
            documentationTitle = "Kentico Widgets";
            Page.Header.Title = "Widgets documentation";
        }

        if (!allWebParts && !allWidgets && !allWireframes && !isWebpartInQuery && !isWidgetInQuery)
        {
            pnlContent.Visible = false;
            pnlInfo.Visible = true;
        }

        // Check whether at least one category is present
        if (!DataHelper.DataSourceIsEmpty(cds))
        {
            string namePrefix = ((isWidgetInQuery) || (allWidgets)) ? "Widget" : String.Empty;

            // Loop through all web part categories
            foreach (DataRow cdr in cds.Tables[0].Rows)
            {
                // Get all webpart in the categories
                if (allWebParts || allWireframes)
                {
                    ds = WebPartInfoProvider.GetAllWebParts(Convert.ToInt32(cdr["CategoryId"]));
                }
                // Get all widgets in the category
                else if (allWidgets)
                {
                    int categoryID = Convert.ToInt32(cdr["WidgetCategoryId"]);
                    ds = WidgetInfoProvider.GetWidgets().WhereEquals("WidgetCategoryID", categoryID);
                }

                // Check whether current category contains at least one webpart
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    // Generate category name code
                    menu += "<br /><strong>" + HTMLHelper.HTMLEncode(cdr[namePrefix + "CategoryDisplayName"].ToString()) + "</strong><br /><br />";

                    // Loop through all web web parts in categories
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        // Init
                        isImagePresent = false;
                        undocumentedProperties = 0;
                        documentation = 0;

                        // Webpart (Widget) information
                        string itemDisplayName = String.Empty;
                        string itemDescription = String.Empty;
                        string itemDocumentation = String.Empty;
                        string itemType = String.Empty;
                        int itemID = 0;

                        WebPartInfo wpi = null;
                        WidgetInfo wi = null;

                        // Set webpart info
                        if (isWebpartInQuery || allWebParts || allWireframes)
                        {
                            wpi = new WebPartInfo(dr);
                            if (wpi != null)
                            {
                                itemDisplayName = wpi.WebPartDisplayName;
                                itemDescription = wpi.WebPartDescription;
                                itemDocumentation = wpi.WebPartDocumentation;
                                itemID = wpi.WebPartID;
                                itemType = WebPartInfo.OBJECT_TYPE;

                                if (wpi.WebPartCategoryID != ValidationHelper.GetInteger(cdr["CategoryId"], 0))
                                {
                                    wpi = null;
                                }
                            }
                        }
                        // Set widget info
                        else if ((isWidgetInQuery) || (allWidgets))
                        {
                            wi = new WidgetInfo(dr);
                            if (wi != null)
                            {
                                itemDisplayName = wi.WidgetDisplayName;
                                itemDescription = wi.WidgetDescription;
                                itemDocumentation = wi.WidgetDocumentation;
                                itemType = WidgetInfo.OBJECT_TYPE;
                                itemID = wi.WidgetID;

                                if (wi.WidgetCategoryID != ValidationHelper.GetInteger(cdr["WidgetCategoryId"], 0))
                                {
                                    wi = null;
                                }
                            }
                        }

                        // Check whether web part (widget) exists
                        if ((wpi != null) || (wi != null))
                        {
                            // Link GUID
                            Guid mguid = Guid.NewGuid();

                            // Whether description is present in webpart
                            bool isDescription = false;

                            // Image url
                            string wimgurl = GetItemImage(itemID, itemType);

                            // Set description text
                            string descriptionText = itemDescription;

                            // Parent webpart info
                            WebPartInfo pwpi = null;

                            // If webpart look for parent's description and documentation
                            if (wpi != null)
                            {
                                // Get parent description if webpart is inherited
                                if (wpi.WebPartParentID > 0)
                                {
                                    pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                                    if (pwpi != null)
                                    {
                                        if ((descriptionText == null || descriptionText.Trim() == ""))
                                        {
                                            // Set description from parent
                                            descriptionText = pwpi.WebPartDescription;
                                        }

                                        // Set documentation text from parent if WebPart is inherited
                                        if ((wpi.WebPartDocumentation == null) || (wpi.WebPartDocumentation.Trim() == ""))
                                        {
                                            itemDocumentation = pwpi.WebPartDocumentation;
                                            if (!String.IsNullOrEmpty(itemDocumentation))
                                            {
                                                documentation = 2;
                                            }
                                        }
                                    }
                                }
                            }

                            // Set description as present
                            if (descriptionText.Trim().Length > 0)
                            {
                                isDescription = true;
                            }

                            // Generate HTML for menu and content
                            menu += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#_" + mguid.ToString() + "\">" + HTMLHelper.HTMLEncode(itemDisplayName) + "</a>&nbsp;";

                            // Generate webpart header
                            content += "<table style=\"width:100%;\"><tr><td><h1><a name=\"_" + mguid.ToString() + "\">" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(cdr[namePrefix + "CategoryDisplayName"].ToString())) + "&nbsp;>&nbsp;" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(itemDisplayName)) + "</a></h1></td><td style=\"text-align:right;\">&nbsp;<a href=\"#top\" class=\"noprint\">top</a></td></tr></table>";

                            // Generate WebPart content
                            content +=
                                @"<table style=""width: 100%; height: 200px; border: solid 1px #DDDDDD;"">
                                   <tr>
                                     <td style=""width: 50%; text-align:center; border-right: solid 1px #DDDDDD; vertical-align: middle;margin-left: auto; margin-right:auto; text-align:center;"">
                                         <img src=""" + wimgurl + @""" alt=""imageTeaser"">
                                     </td>
                                     <td style=""width: 50%; vertical-align: center;text-align:center;"">"
                                + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(descriptionText)) + @"
                                     </td>
                                   </tr>
                                </table>";

                            // Properties content
                            content += "<div class=\"DocumentationWebPartsProperties\">";

                            // Generate content
                            if (wpi != null)
                            {
                                GenerateDocContent(CreateFormInfo(wpi));
                            }
                            else if (wi != null)
                            {
                                GenerateDocContent(CreateFormInfo(wi));
                            }

                            // Close content area
                            content += "</div>";

                            // Generate documentation text content
                            content += "<br /><div style=\"border: solid 1px #dddddd;width: 100%;\">" +
                                       DataHelper.GetNotEmpty(HTMLHelper.ResolveUrls(itemDocumentation, null), "<strong>Additional documentation text is not provided.</strong>") +
                                       "</div>";

                            // Set page break tag for print
                            content += "<br /><p style=\"page-break-after: always;width:100%\">&nbsp;</p><hr class=\"noprint\" />";

                            // If development is required - highlight missing description, images and doc. text
                            if (development)
                            {
                                // Check image
                                if (!isImagePresent)
                                {
                                    menu += "<span style=\"color:Brown;\">image&nbsp;</span>";
                                }

                                // Check properties
                                if (undocumentedProperties > 0)
                                {
                                    menu += "<span style=\"color:Red;\">properties(" + undocumentedProperties + ")&nbsp;</span>";
                                }

                                // Check properties
                                if (!isDescription)
                                {
                                    menu += "<span style=\"color:#37627F;\">description&nbsp;</span>";
                                }

                                // Check documentation text
                                if (String.IsNullOrEmpty(itemDocumentation))
                                {
                                    documentation = 1;
                                }

                                switch (documentation)
                                {
                                        // Display information about missing documentation
                                    case 1:
                                        menu += "<span style=\"color:Green;\">documentation&nbsp;</span>";
                                        break;

                                        // Display information about inherited documentation
                                    case 2:
                                        menu += "<span style=\"color:Green;\">documentation (inherited)&nbsp;</span>";
                                        break;
                                }
                            }

                            menu += "<br />";
                        }
                    }
                }
            }
        }

        ltlContent.Text = menu + "<br /><p style=\"page-break-after: always;width:100%\">&nbsp;</p><hr class=\"noprint\" />" + content;
    }
    /// <summary>
    /// Sends e-mail with password in case the user has specified his email address.
    /// Otherwise, displays the newly generated password to the current user.
    /// </summary>
    /// <param name="pswd">Password to send</param>
    private void SendEmail(string pswd)
    {
        if (UserInfo == null)
        {
            return;
        }

        // Check whether the 'From' element was specified
        string siteName  = SiteContext.CurrentSiteName;
        string emailFrom = SettingsKeyInfoProvider.GetValue("CMSSendPasswordEmailsFrom", siteName);

        if (string.IsNullOrEmpty(emailFrom))
        {
            ShowError(String.Format("{0} {1}", GetString("Administration-User_Edit_Password.PassChangedNotSent"), GetString("Administration-User_Edit_Password.FromMissing")));

            return;
        }

        string emailTo = UserInfo.Email;

        if (!String.IsNullOrEmpty(emailTo))
        {
            EmailMessage em = new EmailMessage
            {
                From        = emailFrom,
                Recipients  = emailTo,
                Subject     = GetString("Administration-User_Edit_Password.NewGen"),
                EmailFormat = EmailFormatEnum.Default
            };

            // Get e-mail template - try to get site specific template if edited user is assigned to current site
            EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate("Membership.ChangedPassword", UserInfo.IsInSite(siteName) ? siteName : null);
            if (template != null)
            {
                em.Body = template.TemplateText;

                // Because the password was generated by the system, it's included in the e-mail
                MacroResolver resolver = MembershipResolvers.GetPasswordResolver(UserInfo, pswd);

                try
                {
                    EmailHelper.ResolveMetaFileImages(em, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);

                    // Send message immediately (+ resolve macros)
                    EmailSender.SendEmailWithTemplateText(siteName, em, template, resolver, true);

                    // Inform on success
                    ShowConfirmation(GetString("Administration-User_Edit_Password.PasswordsSent") + " " + HTMLHelper.HTMLEncode(emailTo));

                    return;
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("PasswordRetrieval", "USERPASSWORD", ex);
                    ShowError("Failed to send the password: "******"Administration-User_Edit_Password.PassChangedNotSent"));
            }
        }
        else
        {
            ShowConfirmation(String.Format(GetString("Administration-User_Edit_Password.passshow"), pswd), true);
        }
    }
 /// <summary>
 /// Returns field caption of the specified column.
 /// </summary>
 /// <param name="ffi">Form field info</param>
 /// <param name="columnName">Column name</param>
 /// <param name="resolver">Macro resolver</param>
 protected string GetFieldCaption(FormFieldInfo ffi, string columnName, MacroResolver resolver)
 {
     // Get field caption
     string caption = ffi.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, resolver);
     return ((ffi == null) || (caption == string.Empty)) ? columnName : caption;
 }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        // Check 'Modify' permission
        if (!CheckPermissions("cms.eventmanager", "Modify"))
        {
            return;
        }

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

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

        if (!String.IsNullOrEmpty(errorMessage))
        {
            lblError.Visible = true;
            lblError.Text = errorMessage;
            return;
        }

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

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

        if (node != null && String.Equals(node.NodeClassName, "cms.bookingevent", StringComparison.InvariantCultureIgnoreCase))
        {
            // Initialize macro resolver
            MacroResolver resolver = new MacroResolver();
            resolver.KeepUnresolvedMacros = true;
            resolver.SourceData = new object[] { node };

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

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

            lblInfo.Visible = true;
            lblInfo.Text = GetString("Events_SendEmail.EmailSent");
        }
    }