Beispiel #1
0
        /// <summary>
        /// Sends the specified medium data to the specified list of recipients.
        /// </summary>
        /// <param name="mediumData">The medium data.</param>
        /// <param name="recipients">The recipients.</param>
        /// <param name="appRoot">The application root.</param>
        /// <param name="themeRoot">The theme root.</param>
        /// <param name="createCommunicationHistory">if set to <c>true</c> [create communication history].</param>
        /// <param name="metaData">The meta data.</param>
        public void Send(Dictionary <string, string> mediumData, List <string> recipients, string appRoot, string themeRoot, bool createCommunicationHistory, Dictionary <string, string> metaData)
        {
            try
            {
                var globalAttributes = GlobalAttributesCache.Read();

                string from     = string.Empty;
                string fromName = string.Empty;
                mediumData.TryGetValue("From", out from);

                if (string.IsNullOrWhiteSpace(from))
                {
                    from     = globalAttributes.GetValue("OrganizationEmail");
                    fromName = globalAttributes.GetValue("OrganizationName");
                }

                if (!string.IsNullOrWhiteSpace(from))
                {
                    // Resolve any possible merge fields in the from address
                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                    from     = from.ResolveMergeFields(mergeFields);
                    fromName = fromName.ResolveMergeFields(mergeFields);

                    string subject = string.Empty;
                    mediumData.TryGetValue("Subject", out subject);

                    string body = string.Empty;
                    mediumData.TryGetValue("Body", out body);

                    if (!string.IsNullOrWhiteSpace(themeRoot))
                    {
                        subject = subject.Replace("~~/", themeRoot);
                        body    = body.Replace("~~/", themeRoot);
                    }

                    if (!string.IsNullOrWhiteSpace(appRoot))
                    {
                        subject = subject.Replace("~/", appRoot);
                        body    = body.Replace("~/", appRoot);
                        body    = body.Replace(@" src=""/", @" src=""" + appRoot);
                        body    = body.Replace(@" href=""/", @" href=""" + appRoot);
                    }

                    MailMessage message = new MailMessage();

                    if (string.IsNullOrWhiteSpace(fromName))
                    {
                        message.From = new MailAddress(from);
                    }
                    else
                    {
                        message.From = new MailAddress(from, fromName);
                    }

                    // Reply To
                    try
                    {
                        string replyTo = string.Empty;
                        mediumData.TryGetValue("ReplyTo", out replyTo);

                        if (!string.IsNullOrWhiteSpace(replyTo))
                        {
                            message.ReplyToList.Add(new MailAddress(replyTo));
                        }
                    }
                    catch { }

                    CheckSafeSender(message, globalAttributes);

                    message.IsBodyHtml = true;
                    message.Priority   = MailPriority.Normal;

                    message.To.Clear();
                    recipients.ForEach(r => message.To.Add(r));
                    message.Subject = subject;
                    message.Body    = body;

                    AddAdditionalHeaders(message, metaData);

                    using (var smtpClient = GetSmtpClient())
                    {
                        smtpClient.Send(message);
                    }

                    if (createCommunicationHistory)
                    {
                        var transaction = new SaveCommunicationTransaction(
                            recipients, fromName, from, subject, body);
                        RockQueue.TransactionQueue.Enqueue(transaction);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, null);
            }
        }
        /// <summary>
        /// Formats the specified field value for a cell in the <see cref="T:System.Web.UI.WebControls.BoundField"/> object.
        /// </summary>
        /// <param name="dataValue">The field value to format.</param>
        /// <param name="encode">true to encode the value; otherwise, false.</param>
        /// <returns>
        /// The field value converted to the format specified by <see cref="P:System.Web.UI.WebControls.BoundField.DataFormatString"/>.
        /// </returns>
        protected override string FormatDataValue(object dataValue, bool encode)
        {
            string value = base.FormatDataValue(dataValue, encode);

            return(String.Format("{0}{1}", GlobalAttributesCache.Value("CurrencySymbol"), value));
        }
Beispiel #3
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState != null)
            {
                List <string> labelCodes = new List <string>();

                var volAttributeGuid = GetAttributeValue(action, "VolunteerGroupAttribute").AsGuid();
                var volAttribute     = AttributeCache.Get(volAttributeGuid);

                List <int> ChildGroupIds;

                if (volAttribute != null)
                {
                    AttributeValueService attributeValueService = new AttributeValueService(rockContext);
                    ChildGroupIds = attributeValueService.Queryable().Where(av => av.AttributeId == volAttribute.Id && av.Value == "False").Select(av => av.EntityId.Value).ToList();
                }
                else
                {
                    ChildGroupIds = new List <int>();
                }


                var globalAttributes  = GlobalAttributesCache.Get();
                var globalMergeValues = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

                var groupMemberService = new GroupMemberService(rockContext);

                AttendanceService attendanceService = new AttendanceService(rockContext);

                foreach (var family in checkInState.CheckIn.Families.Where(f => f.Selected))
                {
                    foreach (var person in family.People)
                    {
                        var attendances = attendanceService.Queryable("AttendanceCode")
                                          .Where(a => a.CreatedDateTime >= Rock.RockDateTime.Today &&
                                                 person.Person.Id == a.PersonAlias.PersonId &&
                                                 ChildGroupIds.Contains(a.Occurrence.GroupId ?? 0) &&
                                                 a.AttendanceCode != null)
                                          .DistinctBy(a => a.AttendanceCodeId).ToList();
                        foreach (var attendance in attendances)
                        {
                            if (attendance != null && attendance.AttendanceCode != null)
                            {
                                labelCodes.Add(attendance.AttendanceCode.Code + "-" + LabelAge(person.Person));
                            }
                        }
                    }

                    //Add in custom labels for parents
                    //This is the aggregate part
                    List <CheckInLabel> customLabels = new List <CheckInLabel>();

                    List <string> mergeCodes = (( string )GetAttributeValue(action, "MergeText")).Split(',').ToList();
                    while (labelCodes.Count > 0)
                    {
                        var mergeDict = new Dictionary <string, string>();

                        foreach (var mergeCode in mergeCodes)
                        {
                            if (labelCodes.Count > 0)
                            {
                                mergeDict.Add(mergeCode, labelCodes[0]);
                                labelCodes.RemoveAt(0);
                            }
                            else
                            {
                                mergeDict.Add(mergeCode, "");
                            }
                        }

                        var labelCache = KioskLabel.Get(new Guid(GetAttributeValue(action, "AggregatedLabel")));
                        if (labelCache != null)
                        {
                            var checkInLabel = new CheckInLabel(labelCache, new Dictionary <string, object>());
                            checkInLabel.FileGuid = new Guid(GetAttributeValue(action, "AggregatedLabel"));

                            foreach (var keyValue in mergeDict)
                            {
                                if (checkInLabel.MergeFields.ContainsKey(keyValue.Key))
                                {
                                    checkInLabel.MergeFields[keyValue.Key] = keyValue.Value;
                                }
                                else
                                {
                                    checkInLabel.MergeFields.Add(keyValue.Key, keyValue.Value);
                                }
                            }

                            checkInLabel.MergeFields.Add("Date", Rock.RockDateTime.Today.DayOfWeek.ToString().Substring(0, 3) + " " + Rock.RockDateTime.Today.ToMonthDayString());

                            checkInLabel.PrintFrom = checkInState.Kiosk.Device.PrintFrom;
                            checkInLabel.PrintTo   = checkInState.Kiosk.Device.PrintToOverride;

                            if (checkInLabel.PrintTo == PrintTo.Kiosk)
                            {
                                var device = checkInState.Kiosk.Device;
                                if (device != null)
                                {
                                    checkInLabel.PrinterDeviceId = device.PrinterDeviceId;
                                }
                            }

                            if (checkInLabel.PrinterDeviceId.HasValue)
                            {
                                var printerDevice = new DeviceService(rockContext).Get(checkInLabel.PrinterDeviceId.Value);
                                checkInLabel.PrinterAddress = printerDevice.IPAddress;
                            }
                            var firstPerson = family.People.Where(p => p.GroupTypes.Any()).FirstOrDefault();
                            if (firstPerson != null)
                            {
                                //we have to set as selected or it wil not print
                                firstPerson.Selected = true;
                                var firstGroupType = firstPerson.GroupTypes.FirstOrDefault();
                                firstGroupType.Selected = true;
                                if (firstGroupType.Labels == null)
                                {
                                    firstGroupType.Labels = new List <CheckInLabel>()
                                    {
                                        checkInLabel
                                    };
                                }
                                else
                                {
                                    firstGroupType.Labels.Add(checkInLabel);
                                }
                            }
                        }
                    }
                }

                return(true);
            }

            return(false);
        }
Beispiel #4
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (IsUserAuthorized(Rock.Security.Authorization.EDIT))
            {
                var rockContext = new RockContext();

                rockContext.WrapTransaction(() =>
                {
                    var personService = new PersonService(rockContext);

                    var changes = new List <string>();

                    var person = personService.Get(Person.Id);

                    int?orphanedPhotoId = null;
                    if (person.PhotoId != imgPhoto.BinaryFileId)
                    {
                        orphanedPhotoId = person.PhotoId;
                        person.PhotoId  = imgPhoto.BinaryFileId;

                        if (orphanedPhotoId.HasValue)
                        {
                            if (person.PhotoId.HasValue)
                            {
                                changes.Add("Modified the photo.");
                            }
                            else
                            {
                                changes.Add("Deleted the photo.");
                            }
                        }
                        else if (person.PhotoId.HasValue)
                        {
                            changes.Add("Added a photo.");
                        }
                    }

                    int?newTitleId = ddlTitle.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Title", DefinedValueCache.GetName(person.TitleValueId), DefinedValueCache.GetName(newTitleId));
                    person.TitleValueId = newTitleId;

                    History.EvaluateChange(changes, "First Name", person.FirstName, tbFirstName.Text);
                    person.FirstName = tbFirstName.Text;

                    string nickName = string.IsNullOrWhiteSpace(tbNickName.Text) ? tbFirstName.Text : tbNickName.Text;
                    History.EvaluateChange(changes, "Nick Name", person.NickName, nickName);
                    person.NickName = tbNickName.Text;

                    History.EvaluateChange(changes, "Middle Name", person.MiddleName, tbMiddleName.Text);
                    person.MiddleName = tbMiddleName.Text;

                    History.EvaluateChange(changes, "Last Name", person.LastName, tbLastName.Text);
                    person.LastName = tbLastName.Text;

                    int?newSuffixId = ddlSuffix.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Suffix", DefinedValueCache.GetName(person.SuffixValueId), DefinedValueCache.GetName(newSuffixId));
                    person.SuffixValueId = newSuffixId;

                    var birthMonth = person.BirthMonth;
                    var birthDay   = person.BirthDay;
                    var birthYear  = person.BirthYear;

                    var birthday = bpBirthDay.SelectedDate;
                    if (birthday.HasValue)
                    {
                        // If setting a future birthdate, subtract a century until birthdate is not greater than today.
                        var today = RockDateTime.Today;
                        while (birthday.Value.CompareTo(today) > 0)
                        {
                            birthday = birthday.Value.AddYears(-100);
                        }

                        person.BirthMonth = birthday.Value.Month;
                        person.BirthDay   = birthday.Value.Day;
                        if (birthday.Value.Year != DateTime.MinValue.Year)
                        {
                            person.BirthYear = birthday.Value.Year;
                        }
                        else
                        {
                            person.BirthYear = null;
                        }
                    }
                    else
                    {
                        person.SetBirthDate(null);
                    }

                    History.EvaluateChange(changes, "Birth Month", birthMonth, person.BirthMonth);
                    History.EvaluateChange(changes, "Birth Day", birthDay, person.BirthDay);
                    History.EvaluateChange(changes, "Birth Year", birthYear, person.BirthYear);

                    int?graduationYear = null;
                    if (ypGraduation.SelectedYear.HasValue)
                    {
                        graduationYear = ypGraduation.SelectedYear.Value;
                    }

                    History.EvaluateChange(changes, "Graduation Year", person.GraduationYear, graduationYear);
                    person.GraduationYear = graduationYear;

                    History.EvaluateChange(changes, "Anniversary Date", person.AnniversaryDate, dpAnniversaryDate.SelectedDate);
                    person.AnniversaryDate = dpAnniversaryDate.SelectedDate;

                    var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>();
                    History.EvaluateChange(changes, "Gender", person.Gender, newGender);
                    person.Gender = newGender;

                    int?newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(newMaritalStatusId));
                    person.MaritalStatusValueId = newMaritalStatusId;

                    int?newConnectionStatusId = ddlConnectionStatus.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Connection Status", DefinedValueCache.GetName(person.ConnectionStatusValueId), DefinedValueCache.GetName(newConnectionStatusId));
                    person.ConnectionStatusValueId = newConnectionStatusId;

                    var phoneNumberTypeIds = new List <int>();

                    bool smsSelected = false;

                    foreach (RepeaterItem item in rContactInfo.Items)
                    {
                        HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                        PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox;
                        CheckBox cbUnlisted     = item.FindControl("cbUnlisted") as CheckBox;
                        CheckBox cbSms          = item.FindControl("cbSms") as CheckBox;

                        if (hfPhoneType != null &&
                            pnbPhone != null &&
                            cbSms != null &&
                            cbUnlisted != null)
                        {
                            if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                            {
                                int phoneNumberTypeId;
                                if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                                {
                                    var phoneNumber       = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                                    string oldPhoneNumber = string.Empty;
                                    if (phoneNumber == null)
                                    {
                                        phoneNumber = new PhoneNumber {
                                            NumberTypeValueId = phoneNumberTypeId
                                        };
                                        person.PhoneNumbers.Add(phoneNumber);
                                    }
                                    else
                                    {
                                        oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                                    }

                                    phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                                    phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);

                                    // Only allow one number to have SMS selected
                                    if (smsSelected)
                                    {
                                        phoneNumber.IsMessagingEnabled = false;
                                    }
                                    else
                                    {
                                        phoneNumber.IsMessagingEnabled = cbSms.Checked;
                                        smsSelected = cbSms.Checked;
                                    }

                                    phoneNumber.IsUnlisted = cbUnlisted.Checked;
                                    phoneNumberTypeIds.Add(phoneNumberTypeId);

                                    History.EvaluateChange(
                                        changes,
                                        string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumberTypeId)),
                                        oldPhoneNumber,
                                        phoneNumber.NumberFormattedWithCountryCode);
                                }
                            }
                        }
                    }

                    // Remove any blank numbers
                    var phoneNumberService = new PhoneNumberService(rockContext);
                    foreach (var phoneNumber in person.PhoneNumbers
                             .Where(n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains(n.NumberTypeValueId.Value))
                             .ToList())
                    {
                        History.EvaluateChange(
                            changes,
                            string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumber.NumberTypeValueId)),
                            phoneNumber.ToString(),
                            string.Empty);

                        person.PhoneNumbers.Remove(phoneNumber);
                        phoneNumberService.Delete(phoneNumber);
                    }

                    History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text);
                    person.Email = tbEmail.Text.Trim();

                    History.EvaluateChange(changes, "Email Active", person.IsEmailActive, cbIsEmailActive.Checked);
                    person.IsEmailActive = cbIsEmailActive.Checked;

                    var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();
                    History.EvaluateChange(changes, "Email Preference", person.EmailPreference, newEmailPreference);
                    person.EmailPreference = newEmailPreference;

                    int?newGivingGroupId = ddlGivingGroup.SelectedValueAsId();
                    if (person.GivingGroupId != newGivingGroupId)
                    {
                        string oldGivingGroupName = string.Empty;
                        if (Person.GivingGroup != null)
                        {
                            oldGivingGroupName = GetFamilyNameWithFirstNames(Person.GivingGroup.Name, Person.GivingGroup.Members);
                        }

                        string newGivingGroupName = newGivingGroupId.HasValue ? ddlGivingGroup.Items.FindByValue(newGivingGroupId.Value.ToString()).Text : string.Empty;
                        History.EvaluateChange(changes, "Giving Group", oldGivingGroupName, newGivingGroupName);
                    }

                    // Save the Envelope Number attribute if it exists and has changed
                    var personGivingEnvelopeAttribute = AttributeCache.Read(Rock.SystemGuid.Attribute.PERSON_GIVING_ENVELOPE_NUMBER.AsGuid());
                    if (GlobalAttributesCache.Read().EnableGivingEnvelopeNumber&& personGivingEnvelopeAttribute != null)
                    {
                        if (person.Attributes == null)
                        {
                            person.LoadAttributes(rockContext);
                        }

                        var newEnvelopeNumber = tbGivingEnvelopeNumber.Text;
                        var oldEnvelopeNumber = person.GetAttributeValue(personGivingEnvelopeAttribute.Key);
                        if (newEnvelopeNumber != oldEnvelopeNumber)
                        {
                            // If they haven't already comfirmed about duplicate, see if the envelope number if assigned to somebody else
                            if (!string.IsNullOrWhiteSpace(newEnvelopeNumber) && hfGivingEnvelopeNumberConfirmed.Value != newEnvelopeNumber)
                            {
                                var otherPersonIdsWithEnvelopeNumber = new AttributeValueService(rockContext).Queryable()
                                                                       .Where(a => a.AttributeId == personGivingEnvelopeAttribute.Id && a.Value == newEnvelopeNumber && a.EntityId != person.Id)
                                                                       .Select(a => a.EntityId);
                                if (otherPersonIdsWithEnvelopeNumber.Any())
                                {
                                    var personList           = new PersonService(rockContext).Queryable().Where(a => otherPersonIdsWithEnvelopeNumber.Contains(a.Id)).AsNoTracking().ToList();
                                    string personListMessage = personList.Select(a => a.FullName).ToList().AsDelimited(", ", " and ");
                                    int maxCount             = 5;
                                    if (personList.Count > maxCount)
                                    {
                                        var otherCount    = personList.Count() - maxCount;
                                        personListMessage = personList.Select(a => a.FullName).Take(10).ToList().AsDelimited(", ") + " and " + otherCount.ToString() + " other " + "person".PluralizeIf(otherCount > 1);
                                    }

                                    string givingEnvelopeWarningText = string.Format(
                                        "The envelope #{0} is already assigned to {1}. Do you want to also assign this number to {2}?",
                                        newEnvelopeNumber,
                                        personListMessage,
                                        person.FullName);

                                    string givingEnvelopeWarningScriptFormat = @"
                                        Rock.dialogs.confirm('{0}', function (result) {{
                                            if ( result )
                                                {{
                                                   $('#{1}').val('{2}');
                                                }}
                                        }})";

                                    string givingEnvelopeWarningScript = string.Format(
                                        givingEnvelopeWarningScriptFormat,
                                        givingEnvelopeWarningText,
                                        hfGivingEnvelopeNumberConfirmed.ClientID,
                                        newEnvelopeNumber);

                                    ScriptManager.RegisterStartupScript(hfGivingEnvelopeNumberConfirmed, hfGivingEnvelopeNumberConfirmed.GetType(), "confirm-envelope-number", givingEnvelopeWarningScript, true);
                                    return;
                                }
                            }

                            History.EvaluateChange(changes, "Giving Envelope Number", oldEnvelopeNumber, newEnvelopeNumber);
                            person.SetAttributeValue(personGivingEnvelopeAttribute.Key, newEnvelopeNumber);
                        }
                    }

                    person.GivingGroupId = newGivingGroupId;

                    bool recordStatusChangedToOrFromInactive = false;
                    var recordStatusInactiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id;

                    int?newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                    // Is the person's record status changing?
                    if (person.RecordStatusValueId.HasValue && person.RecordStatusValueId != newRecordStatusId)
                    {
                        //  If it was inactive OR if the new status is inactive, flag this for use later below.
                        if (person.RecordStatusValueId == recordStatusInactiveId || newRecordStatusId == recordStatusInactiveId)
                        {
                            recordStatusChangedToOrFromInactive = true;
                        }
                    }

                    History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(person.RecordStatusValueId), DefinedValueCache.GetName(newRecordStatusId));
                    person.RecordStatusValueId = newRecordStatusId;

                    int?newRecordStatusReasonId = null;
                    if (person.RecordStatusValueId.HasValue && person.RecordStatusValueId.Value == recordStatusInactiveId)
                    {
                        newRecordStatusReasonId = ddlReason.SelectedValueAsInt();
                    }

                    History.EvaluateChange(changes, "Inactive Reason", DefinedValueCache.GetName(person.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId));
                    person.RecordStatusReasonValueId = newRecordStatusReasonId;
                    History.EvaluateChange(changes, "Inactive Reason Note", person.InactiveReasonNote, tbInactiveReasonNote.Text);
                    person.InactiveReasonNote = tbInactiveReasonNote.Text.Trim();

                    // Save any Removed/Added Previous Names
                    var personPreviousNameService = new PersonPreviousNameService(rockContext);
                    var databasePreviousNames     = personPreviousNameService.Queryable().Where(a => a.PersonAlias.PersonId == person.Id).ToList();
                    foreach (var deletedPreviousName in databasePreviousNames.Where(a => !PersonPreviousNamesState.Any(p => p.Guid == a.Guid)))
                    {
                        personPreviousNameService.Delete(deletedPreviousName);

                        History.EvaluateChange(
                            changes,
                            "Previous Name",
                            deletedPreviousName.ToString(),
                            string.Empty);
                    }

                    foreach (var addedPreviousName in PersonPreviousNamesState.Where(a => !databasePreviousNames.Any(d => d.Guid == a.Guid)))
                    {
                        addedPreviousName.PersonAliasId = person.PrimaryAliasId.Value;
                        personPreviousNameService.Add(addedPreviousName);

                        History.EvaluateChange(
                            changes,
                            "Previous Name",
                            string.Empty,
                            addedPreviousName.ToString());
                    }

                    if (person.IsValid)
                    {
                        var saveChangeResult = rockContext.SaveChanges();

                        // if AttributeValues where loaded and set (for example Giving Envelope Number), Save Attribute Values
                        if (person.AttributeValues != null)
                        {
                            person.SaveAttributeValues(rockContext);
                        }

                        if (saveChangeResult > 0)
                        {
                            if (changes.Any())
                            {
                                HistoryService.SaveChanges(
                                    rockContext,
                                    typeof(Person),
                                    Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                    Person.Id,
                                    changes);
                            }

                            if (orphanedPhotoId.HasValue)
                            {
                                BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                                var binaryFile = binaryFileService.Get(orphanedPhotoId.Value);
                                if (binaryFile != null)
                                {
                                    string errorMessage;
                                    if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                                    {
                                        binaryFileService.Delete(binaryFile);
                                        rockContext.SaveChanges();
                                    }
                                }
                            }

                            // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up
                            if (imgPhoto.CropBinaryFileId.HasValue)
                            {
                                if (imgPhoto.CropBinaryFileId != person.PhotoId)
                                {
                                    BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                                    var binaryFile = binaryFileService.Get(imgPhoto.CropBinaryFileId.Value);
                                    if (binaryFile != null && binaryFile.IsTemporary)
                                    {
                                        string errorMessage;
                                        if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                                        {
                                            binaryFileService.Delete(binaryFile);
                                            rockContext.SaveChanges();
                                        }
                                    }
                                }
                            }

                            // If the person's record status was changed to or from inactive,
                            // we need to check if any of their families need to be activated or inactivated.
                            if (recordStatusChangedToOrFromInactive)
                            {
                                foreach (var family in personService.GetFamilies(person.Id))
                                {
                                    // Are there any more members of the family who are NOT inactive?
                                    // If not, mark the whole family inactive.
                                    if (!family.Members.Where(m => m.Person.RecordStatusValueId != recordStatusInactiveId).Any())
                                    {
                                        family.IsActive = false;
                                    }
                                    else
                                    {
                                        family.IsActive = true;
                                    }
                                }

                                rockContext.SaveChanges();
                            }
                        }

                        Response.Redirect(string.Format("~/Person/{0}", Person.Id), false);
                    }
                });
            }
        }
        private void BindPeople(RockContext rockContext, IQueryable <Person> personQry)
        {
            var people = personQry
                         .OrderBy(p => p.LastName)
                         .ThenBy(p => p.NickName)
                         .Take(GetAttributeValue(AttributeKey.MaxResults).AsInteger())
                         .Select(p => new PersonDirectoryItem
            {
                Id = p.Id,
                RecordTypeValueId = p.RecordTypeValueId,
                AgeClassification = p.AgeClassification,
                NickName          = p.NickName,
                LastName          = p.LastName,
                Email             = p.Email,
                BirthMonth        = p.BirthMonth,
                BirthDay          = p.BirthDay,
                BirthDate         = p.BirthDate,
                DeceasedDate      = p.DeceasedDate,
                Gender            = p.Gender,
                PhotoId           = p.PhotoId,
                GraduationYear    = p.GraduationYear
            })
                         .ToList();

            if (_showAddress || _phoneNumberCaptions.Any())
            {
                var personIds = people.Select(p => p.Id).ToList();

                if (_showAddress)
                {
                    var familyGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid());
                    var homeLoc         = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());
                    if (familyGroupType != null && homeLoc != null)
                    {
                        _addresses = new GroupMemberService(rockContext)
                                     .Queryable().AsNoTracking()
                                     .Where(m =>
                                            personIds.Contains(m.PersonId) &&
                                            m.Group.GroupTypeId == familyGroupType.Id)
                                     .Select(m => new
                        {
                            m.PersonId,
                            HomeLocations = m.Group.GroupLocations
                                            .Where(gl =>
                                                   gl.GroupLocationTypeValueId.HasValue &&
                                                   gl.GroupLocationTypeValueId == homeLoc.Id)
                                            .Select(gl => gl.Location)
                                            .ToList()
                        })
                                     .GroupBy(m => m.PersonId)
                                     .Select(g => new
                        {
                            PersonId      = g.Key,
                            HomeLocations = g.SelectMany(m => m.HomeLocations).ToList()
                        })
                                     .ToDictionary(k => k.PersonId, v => v.HomeLocations);
                    }
                }

                LoadPhoneNumbers(rockContext, personIds);
            }

            if (_showEnvelopeNumber && GlobalAttributesCache.Get().EnableGivingEnvelopeNumber)
            {
                LoadEnvelopeNumbers(rockContext, people.Select(p => p.Id).ToList());
            }

            rptPeople.DataSource = people;
            rptPeople.DataBind();
            rptPeople.Visible = true;

            rptFamilies.Visible = false;
        }
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        /// <param name="lookupContext">The lookup context.</param>
        private static void LoadRockData(RockContext lookupContext = null)
        {
            lookupContext = lookupContext ?? new RockContext();

            // initialize file providers
            DatabaseProvider   = new Database();
            FileSystemProvider = new FileSystem();

            // core-specified attribute guid for setting file root path
            RootPathAttribute = AttributeCache.Read(new Guid("3CAFA34D-9208-439B-A046-CB727FB729DE"));

            // core-specified blacklist files
            FileTypeBlackList = (GlobalAttributesCache.Read().GetValue("ContentFiletypeBlacklist")
                                 ?? string.Empty).Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);

            // clean up blacklist
            FileTypeBlackList = FileTypeBlackList.Select(a => a.ToLower().TrimStart(new char[] { '.', ' ' }));
            FileTypes         = new BinaryFileTypeService(lookupContext).Queryable().AsNoTracking().ToList();

            // get all the types we'll be importing
            var binaryTypeSettings = ConfigurationManager.GetSection("binaryFileTypes") as NameValueCollection;

            // create any custom types defined in settings that don't exist yet
            foreach (var typeKey in binaryTypeSettings.AllKeys)
            {
                if (!FileTypes.Any(f => f.Name == typeKey))
                {
                    var newFileType = new BinaryFileType();
                    lookupContext.BinaryFileTypes.Add(newFileType);
                    newFileType.Name         = typeKey;
                    newFileType.Description  = typeKey;
                    newFileType.AllowCaching = true;

                    var typeValue = binaryTypeSettings[typeKey];
                    if (typeValue != null)
                    {
                        // #TODO: support additional storage types (like AWS?)
                        newFileType.StorageEntityTypeId = typeValue.Equals("Database") ? DatabaseStorageTypeId : FileSystemStorageTypeId;
                        newFileType.Attributes          = new Dictionary <string, AttributeCache>();
                        newFileType.AttributeValues     = new Dictionary <string, AttributeValueCache>();

                        // save changes to binary type to get an ID
                        lookupContext.SaveChanges();

                        var newRootPath = new AttributeValue()
                        {
                            AttributeId = RootPathAttribute.Id,
                            EntityId    = newFileType.Id,
                            Value       = typeValue
                        };

                        newFileType.Attributes.Add(RootPathAttribute.Key, RootPathAttribute);
                        newFileType.AttributeValues.Add(RootPathAttribute.Key, new AttributeValueCache(newRootPath));

                        // save attribute values with the current type ID
                        lookupContext.AttributeValues.Add(newRootPath);
                    }

                    lookupContext.SaveChanges();
                    FileTypes.Add(newFileType);
                }
            }

            // load attributes on file system types to get the default storage location
            foreach (var type in FileTypes)
            {
                type.LoadAttributes(lookupContext);

                if (type.StorageEntityTypeId == FileSystemStorageTypeId && binaryTypeSettings.AllKeys.Any(k => type.Name.Equals(k)))
                {
                    // override the configured storage location since we can't handle relative paths
                    type.AttributeValues["RootPath"].Value = binaryTypeSettings[type.Name];
                }
            }

            // get a list of all the imported people keys
            var personAliasList = new PersonAliasService(lookupContext).Queryable().AsNoTracking().ToList();

            ImportedPeople = personAliasList.Select(pa =>
                                                    new PersonKeys()
            {
                PersonAliasId    = pa.Id,
                PersonId         = pa.PersonId,
                PersonForeignId  = pa.ForeignId,
                PersonForeignKey = pa.ForeignKey
            }).ToList();
        }
Beispiel #7
0
        private void BindGrid()
        {
            string type = PageParameter("SearchType");
            string term = PageParameter("SearchTerm");

            if (!string.IsNullOrWhiteSpace(type) && !string.IsNullOrWhiteSpace(term))
            {
                term = term.Trim();
                type = type.Trim();
                var rockContext = new RockContext();

                var personService          = new PersonService(rockContext);
                IQueryable <Person> people = null;

                switch (type.ToLower())
                {
                case ("name"):
                {
                    bool allowFirstNameOnly = false;
                    if (!bool.TryParse(PageParameter("allowFirstNameOnly"), out allowFirstNameOnly))
                    {
                        allowFirstNameOnly = false;
                    }
                    people = personService.GetByFullName(term, allowFirstNameOnly, true);
                    break;
                }

                case ("phone"):
                {
                    var phoneService         = new PhoneNumberService(rockContext);
                    var phoneNumberPersonIds = phoneService.GetPersonIdsByNumber(term);
                    people = personService.Queryable(new PersonService.PersonQueryOptions {
                            IncludeNameless = true
                        }).Where(p => phoneNumberPersonIds.Contains(p.Id));
                    break;
                }

                case ("address"):
                {
                    var groupMemberService   = new GroupMemberService(rockContext);
                    var groupMemberPersonIds = groupMemberService.GetPersonIdsByHomeAddress(term);
                    people = personService.Queryable().Where(p => groupMemberPersonIds.Contains(p.Id));
                    break;
                }

                case ("email"):
                {
                    var searchKeyQry = new PersonSearchKeyService(rockContext).Queryable();
                    people = personService.Queryable()
                             .Where(p => (term != "" && p.Email == term) ||
                                    searchKeyQry.Any(a => a.PersonAlias.PersonId == p.Id && a.SearchValue == term));
                    break;
                }

                case ("birthdate"):
                {
                    DateTime?birthDate = Request.QueryString["birthdate"].AsDateTime();
                    int?     personId  = Request.QueryString["person-id"].AsIntegerOrNull();
                    if (birthDate == null)
                    {
                        birthDate = term.AsDateTime();
                    }

                    if (personId.HasValue)
                    {
                        people = personService.Queryable().Where(a => a.Id == personId.Value);
                    }
                    else
                    {
                        people = personService.Queryable().Where(p => p.BirthDate.HasValue && birthDate.HasValue && p.BirthDate == birthDate.Value);
                    }

                    break;
                }
                }

                IEnumerable <int> personIdList = people.Select(p => p.Id);

                // just leave the personIdList as a Queryable if it is over 10000 so that we don't throw a SQL exception due to the big list of ids
                if (people.Count() < 10000)
                {
                    personIdList = personIdList.ToList();
                }

                if (personIdList.Count() == 1)
                {
                    // if there is exactly one result, just redirect to the person page
                    int personId = personIdList.First();
                    Response.Redirect(string.Format("~/Person/{0}", personId), false);
                    Context.ApplicationInstance.CompleteRequest();
                    return;
                }

                // since there is not exactly one person found, show the list of people in the grid

                var familyGroupType   = GroupTypeCache.GetFamilyGroupType();
                int familyGroupTypeId = familyGroupType != null ? familyGroupType.Id : 0;

                var groupLocationTypeHome = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());
                int homeAddressTypeId     = groupLocationTypeHome != null ? groupLocationTypeHome.Id : 0;

                var birthDateCol = gPeople.ColumnsOfType <DateField>().First(c => c.DataField == "BirthDate");
                var ageCol       = gPeople.ColumnsOfType <RockBoundField>().First(c => c.DataField == "Age");
                var genderCol    = gPeople.ColumnsOfType <RockBoundField>().First(c => c.DataField == "Gender");

                var envelopeNumberField = gPeople.ColumnsOfType <RockLiteralField>().First(c => c.ID == "lEnvelopeNumber");
                var spouseCol           = gPeople.ColumnsOfType <RockTemplateField>().First(c => c.HeaderText == "Spouse");

                var personGivingEnvelopeAttribute = AttributeCache.Get(Rock.SystemGuid.Attribute.PERSON_GIVING_ENVELOPE_NUMBER.AsGuid());
                if (personGivingEnvelopeAttribute != null)
                {
                    envelopeNumberField.Visible = GlobalAttributesCache.Get().EnableGivingEnvelopeNumber&& this.GetAttributeValue("ShowEnvelopeNumber").AsBoolean();
                }
                else
                {
                    envelopeNumberField.Visible = false;
                }

                birthDateCol.Visible = GetAttributeValue("ShowBirthdate").AsBoolean();
                ageCol.Visible       = GetAttributeValue("ShowAge").AsBoolean();
                genderCol.Visible    = GetAttributeValue("ShowGender").AsBoolean();
                spouseCol.Visible    = _showSpouse;

                people = personService.Queryable(true).Where(p => personIdList.Contains(p.Id));

                SortProperty sortProperty = gPeople.SortProperty;
                if (sortProperty != null)
                {
                    people = people.Sort(sortProperty);
                }
                else
                {
                    people = people.OrderBy(p => p.LastName).ThenBy(p => p.FirstName);
                }

                var personList = people.Select(p => new PersonSearchResult
                {
                    Id         = p.Id,
                    FirstName  = p.FirstName,
                    NickName   = p.NickName,
                    LastName   = p.LastName,
                    BirthDate  = p.BirthDate,
                    BirthYear  = p.BirthYear,
                    BirthMonth = p.BirthMonth,
                    BirthDay   = p.BirthDay,
                    ConnectionStatusValueId = p.ConnectionStatusValueId,
                    RecordStatusValueId     = p.RecordStatusValueId,
                    RecordTypeValueId       = p.RecordTypeValueId,
                    AgeClassification       = p.AgeClassification,
                    SuffixValueId           = p.SuffixValueId,
                    IsDeceased = p.IsDeceased,
                    Email      = p.Email,
                    Gender     = p.Gender,
                    PhotoId    = p.PhotoId,
                    CampusIds  = p.Members
                                 .Where(m =>
                                        m.Group.GroupTypeId == familyGroupTypeId &&
                                        m.Group.CampusId.HasValue)
                                 .Select(m => m.Group.CampusId.Value)
                                 .ToList(),
                    HomeAddresses = p.Members
                                    .Where(m => m.Group.GroupTypeId == familyGroupTypeId)
                                    .SelectMany(m => m.Group.GroupLocations)
                                    .Where(gl => gl.GroupLocationTypeValueId == homeAddressTypeId)
                                    .Select(gl => gl.Location),
                    PhoneNumbers = p.PhoneNumbers
                                   .Where(n => n.NumberTypeValueId.HasValue)
                                   .Select(n => new PersonSearchResultPhone
                    {
                        NumberTypeValueId = n.NumberTypeValueId.Value,
                        Number            = n.NumberFormatted,
                        PhoneTypeName     = n.NumberTypeValue.Value
                    })
                                   .ToList(),
                    TopSignalColor        = p.TopSignalColor,
                    TopSignalIconCssClass = p.TopSignalIconCssClass
                }).ToList();


                if (type.ToLower() == "name")
                {
                    var similarNames = personService.GetSimilarNames(term,
                                                                     personList.Select(p => p.Id).ToList(), true);
                    if (similarNames.Any())
                    {
                        var hyperlinks = new List <string>();
                        foreach (string name in similarNames.Distinct())
                        {
                            var pageRef = CurrentPageReference;
                            pageRef.Parameters["SearchTerm"] = name;
                            hyperlinks.Add(string.Format("<a href='{0}'>{1}</a>", pageRef.BuildUrl(), name));
                        }
                        string altNames = string.Join(", ", hyperlinks);
                        nbNotice.Text    = string.Format("Other Possible Matches: {0}", altNames);
                        nbNotice.Visible = true;
                    }
                }

                _inactiveStatus = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE);
                var personIds = personList.Select(a => a.Id).ToList();

                if (envelopeNumberField != null && envelopeNumberField.Visible)
                {
                    _envelopeNumbers = new AttributeValueService(rockContext).Queryable()
                                       .Where(a => a.AttributeId == personGivingEnvelopeAttribute.Id)
                                       .Where(a => personIds.Contains(a.EntityId.Value))
                                       .Select(a => new
                    {
                        PersonId = a.EntityId.Value,
                        Value    = a.Value
                    }).ToList().ToDictionary(k => k.PersonId, v => v.Value);
                }

                gPeople.EntityTypeId = EntityTypeCache.GetId <Person>();

                gPeople.DataSource = personList;
                gPeople.DataBind();
            }
        }
Beispiel #8
0
        /// <summary>
        /// Invoked on page load.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            // Set timeout for up to 15 minutes (just like installer)
            Server.ScriptTimeout = 900;
            ScriptManager.GetCurrent(Page).AsyncPostBackTimeout = 900;

            DisplayRockVersion();
            if (!IsPostBack)
            {
                if (NuGetService == null)
                {
                    pnlNoUpdates.Visible = false;
                    pnlError.Visible     = true;
                    nbErrors.Text        = string.Format("Your UpdateServerUrl is not valid. It is currently set to: {0}", GlobalAttributesCache.Get().GetValue("UpdateServerUrl"));
                }
                else
                {
                    try
                    {
                        _isEarlyAccessOrganization = CheckEarlyAccess();

                        btnIssues.NavigateUrl = string.Format("http://www.rockrms.com/earlyaccessissues?RockInstanceId={0}", Rock.Web.SystemSettings.GetRockInstanceId());

                        if (_isEarlyAccessOrganization)
                        {
                            hlblEarlyAccess.LabelType = Rock.Web.UI.Controls.LabelType.Success;
                            hlblEarlyAccess.Text      = "Early Access: Enabled";

                            pnlEarlyAccessNotEnabled.Visible = false;
                            pnlEarlyAccessEnabled.Visible    = true;
                        }

                        VersionCheckResult result = CheckFrameworkVersion();
                        if (result == VersionCheckResult.Pass)
                        {
                            _isOkToProceed = true;
                        }
                        else if (result == VersionCheckResult.Fail)
                        {
                            _isOkToProceed          = false;
                            nbVersionIssue.Visible  = true;
                            nbVersionIssue.Text    += "<p>You will need to upgrade your hosting server in order to proceed with the next update.</p>";
                            nbBackupMessage.Visible = false;
                        }
                        else
                        {
                            _isOkToProceed          = true;
                            nbVersionIssue.Visible  = true;
                            nbVersionIssue.Text    += "<p>You may need to upgrade your hosting server in order to proceed with the next update. We were <b>unable to determine which Framework version</b> your server is using.</p>";
                            nbVersionIssue.Details += "<div class='alert alert-warning'>We were unable to check your server to verify that the .Net 4.5.2 Framework is installed! <b>You MUST verify this manually before you proceed with the update</b> otherwise your Rock application will be broken until you update the server.</div>";
                            nbBackupMessage.Visible = false;
                        }

                        _hasSqlServer14OrHigher = CheckSqlServerVersionGreaterThenSqlServer2012();
                        if (!_hasSqlServer14OrHigher)
                        {
                            nbSqlServerVersionIssue.Visible = true;
                        }

                        _releases          = GetReleasesList();
                        _availablePackages = NuGetService.SourceRepository.FindPackagesById(_rockPackageId).OrderByDescending(p => p.Version);
                        if (IsUpdateAvailable())
                        {
                            pnlUpdatesAvailable.Visible = true;
                            pnlUpdates.Visible          = true;
                            pnlNoUpdates.Visible        = false;
                            cbIncludeStats.Visible      = true;
                            BindGrid();
                        }

                        RemoveOldRDeleteFiles();
                    }
                    catch (System.InvalidOperationException ex)
                    {
                        HandleNuGetException(ex);
                    }
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// Sets up the page to report the error in a nicer manner.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleNuGetException(Exception ex)
        {
            pnlError.Visible         = true;
            pnlUpdateSuccess.Visible = false;
            pnlNoUpdates.Visible     = false;

            if (ex.Message.Contains("404"))
            {
                nbErrors.Text = string.Format("It appears that someone configured your <code>UpdateServerUrl</code> setting incorrectly: {0}", GlobalAttributesCache.Get().GetValue("UpdateServerUrl"));
            }
            else if (ex.Message.Contains("could not be resolved"))
            {
                nbErrors.Text = string.Format("I think either the update server is down or your <code>UpdateServerUrl</code> setting is incorrect: {0}", GlobalAttributesCache.Get().GetValue("UpdateServerUrl"));
            }
            else if (ex.Message.Contains("Unable to connect"))
            {
                nbErrors.Text = "The update server is down. Try again later.";
            }
            else
            {
                nbErrors.Text = string.Format("...actually, I'm not sure what happened here: {0}", ex.Message);
            }
        }
        /// <summary>
        /// Determine the logical page being requested by evaluating the routedata, or querystring and
        /// then loading the appropriate layout (ASPX) page
        ///
        /// Pick url on the following priority order:
        /// 1. PageId
        /// 2. Route match and site match
        /// 3. ShortLink match and site match
        /// 4. Route and no site match
        /// 5. ShortLink with no site match
        /// 6. If there is no routing info in the request then set to default page
        /// 7. 404 if route does not exist
        ///
        /// </summary>
        /// <param name="requestContext"></param>
        /// <returns></returns>
        System.Web.IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        {
            string pageId      = string.Empty;
            int    routeId     = 0;
            bool   isSiteMatch = false;
            Dictionary <string, string> parms;
            string          host;
            HttpRequestBase routeHttpRequest;
            HttpCookie      siteCookie;
            SiteCache       site;

            // Context cannot be null
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }

            try
            {
                routeHttpRequest = requestContext.HttpContext.Request;
                siteCookie       = routeHttpRequest.Cookies["last_site"];
                parms            = new Dictionary <string, string>();
                host             = WebRequestHelper.GetHostNameFromRequest(HttpContext.Current);
                site             = GetSite(host, siteCookie);

                if (requestContext.RouteData.Values["PageId"] != null)
                {
                    // Pages using the default routing URL will have the page id in the RouteData.Values collection
                    pageId = ( string )requestContext.RouteData.Values["PageId"];

                    // Does the page ID exist on the requesting site
                    isSiteMatch = IsSiteMatch(site, pageId.AsIntegerOrNull());

                    if (site != null && site.EnableExclusiveRoutes && !isSiteMatch)
                    {
                        // If the site has to match and does not then don't use the page ID. Set it to empty so the 404 can be returned.
                        pageId = string.Empty;
                    }
                    else if (!isSiteMatch)
                    {
                        // This page belongs to another site, make sure it is allowed to be loaded.
                        if (IsPageExclusiveToAnotherSite(site, pageId.AsIntegerOrNull(), null))
                        {
                            // If the page has to match the site and does not then don't use the page ID. Set it to empty so the 404 can be returned.
                            pageId = string.Empty;
                        }
                    }
                }
                else if (requestContext.RouteData.DataTokens["PageRoutes"] != null)
                {
                    // Pages that use a custom URL route will have the page id in the RouteData.DataTokens collection
                    GetPageIdFromDataTokens(requestContext, site, out pageId, out routeId, out isSiteMatch);

                    foreach (var routeParm in requestContext.RouteData.Values)
                    {
                        parms.Add(routeParm.Key, ( string )routeParm.Value);
                    }
                }
                else if (((System.Web.Routing.Route)requestContext.RouteData.Route).Url.IsNullOrWhiteSpace())
                {
                    // if we don't have routing info then set the page ID to the default page for the site.

                    // Get the site, if not found use the default site
                    if (site == null)
                    {
                        site = SiteCache.Get(SystemGuid.Site.SITE_ROCK_INTERNAL.AsGuid());
                    }

                    if (site.DefaultPageId.HasValue)
                    {
                        pageId      = site.DefaultPageId.Value.ToString();
                        isSiteMatch = true;
                    }
                    else
                    {
                        throw new SystemException("Invalid Site Configuration");
                    }
                }

                // If the page ID and site has not yet been matched
                if (string.IsNullOrEmpty(pageId) || !isSiteMatch)
                {
                    // if not found use the default site
                    if (site == null)
                    {
                        site = SiteCache.Get(SystemGuid.Site.SITE_ROCK_INTERNAL.AsGuid());
                    }

                    // Are shortlinks enabled for this site? If so, check for a matching shortlink route.
                    if (site != null)
                    {
                        if (site.EnabledForShortening)
                        {
                            // Check to see if this is a short link route
                            string shortlink = null;
                            if (requestContext.RouteData.Values.ContainsKey("shortlink"))
                            {
                                shortlink = requestContext.RouteData.Values["shortlink"].ToString();
                            }
                            else
                            {
                                // Because we implemented shortlinks using a {shortlink} (catchall) route, it's
                                // possible the organization added a custom {catchall} route (at root level; no slashes)
                                // and it is overriding our shortlink route.  If they did, use it for a possible 'shortlink'
                                // route match.
                                if (requestContext.RouteData.DataTokens["RouteName"] != null && requestContext.RouteData.DataTokens["RouteName"].ToStringSafe().StartsWith("{"))
                                {
                                    var routeName = requestContext.RouteData.DataTokens["RouteName"].ToStringSafe().Trim(new Char[] { '{', '}' });
                                    shortlink = requestContext.RouteData.Values[routeName].ToStringSafe();
                                }
                            }

                            if (shortlink.IsNullOrWhiteSpace() && requestContext.RouteData.DataTokens["RouteName"] != null)
                            {
                                shortlink = requestContext.RouteData.DataTokens["RouteName"].ToString();
                            }

                            if (shortlink.IsNotNullOrWhiteSpace())
                            {
                                using (var rockContext = new Rock.Data.RockContext())
                                {
                                    var pageShortLink = new PageShortLinkService(rockContext).GetByToken(shortlink, site.Id);

                                    // Use the short link if the site IDs match or the current site and shortlink site are not exclusive.
                                    // Note: this is only a restriction based on the site chosen as the owner of the shortlink, the acutal URL can go anywhere.
                                    if (pageShortLink != null && (pageShortLink.SiteId == site.Id || (!site.EnableExclusiveRoutes && !pageShortLink.Site.EnableExclusiveRoutes)))
                                    {
                                        if (pageShortLink.SiteId == site.Id || requestContext.RouteData.DataTokens["RouteName"] == null)
                                        {
                                            pageId  = string.Empty;
                                            routeId = 0;

                                            string trimmedUrl = pageShortLink.Url.RemoveCrLf().Trim();

                                            var addShortLinkInteractionMsg = new AddShortLinkInteraction.Message
                                            {
                                                PageShortLinkId = pageShortLink.Id,
                                                Token           = pageShortLink.Token,
                                                Url             = trimmedUrl,
                                                DateViewed      = RockDateTime.Now,
                                                IPAddress       = WebRequestHelper.GetClientIpAddress(routeHttpRequest),
                                                UserAgent       = routeHttpRequest.UserAgent ?? string.Empty,
                                                UserName        = requestContext.HttpContext.User?.Identity.Name
                                            };


                                            addShortLinkInteractionMsg.Send();

                                            requestContext.HttpContext.Response.Redirect(trimmedUrl, false);
                                            requestContext.HttpContext.ApplicationInstance.CompleteRequest();

                                            // Global.asax.cs will throw and log an exception if null is returned, so just return a new page.
                                            return(new System.Web.UI.Page());
                                        }
                                    }
                                }
                            }
                        }

                        // If site has has been enabled for mobile redirect, then we'll need to check what type of device is being used
                        if (site.EnableMobileRedirect)
                        {
                            // get the device type
                            string u = routeHttpRequest.UserAgent;

                            var clientType = InteractionDeviceType.GetClientType(u);

                            bool redirect = false;

                            // first check if device is a mobile device
                            if (clientType == "Mobile")
                            {
                                redirect = true;
                            }

                            // if not, mobile device and tables should be redirected also, check if device is a tablet
                            if (!redirect && site.RedirectTablets && clientType == "Tablet")
                            {
                                redirect = true;
                            }

                            if (redirect)
                            {
                                if (site.MobilePageId.HasValue)
                                {
                                    pageId  = site.MobilePageId.Value.ToString();
                                    routeId = 0;
                                }
                                else if (!string.IsNullOrWhiteSpace(site.ExternalUrl))
                                {
                                    requestContext.HttpContext.Response.Redirect(site.ExternalUrl, false);
                                    requestContext.HttpContext.ApplicationInstance.CompleteRequest();

                                    // Global.asax.cs will throw and log an exception if null is returned, so just return a new page.
                                    return(new System.Web.UI.Page());
                                }
                            }
                        }
                    }
                }

                PageCache page = null;
                if (!string.IsNullOrEmpty(pageId))
                {
                    int pageIdNumber = 0;
                    if (int.TryParse(pageId, out pageIdNumber))
                    {
                        page = PageCache.Get(pageIdNumber);
                    }
                }

                if (page == null)
                {
                    // try to get site's 404 page
                    if (site != null && site.PageNotFoundPageId != null)
                    {
                        if (Convert.ToBoolean(GlobalAttributesCache.Get().GetValue("Log404AsException")))
                        {
                            Rock.Model.ExceptionLogService.LogException(
                                new Exception($"404 Error: {routeHttpRequest.UrlProxySafe().AbsoluteUri}"),
                                requestContext.HttpContext.ApplicationInstance.Context);
                        }

                        page = PageCache.Get(site.PageNotFoundPageId ?? 0);
                        requestContext.HttpContext.Response.StatusCode             = 404;
                        requestContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                    }
                    else
                    {
                        // no 404 page found for the site, return the default 404 error page
                        return((System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Http404Error.aspx", typeof(System.Web.UI.Page)));
                    }
                }

                CreateOrUpdateSiteCookie(siteCookie, requestContext, page);

                string theme      = page.Layout.Site.Theme;
                string layout     = page.Layout.FileName;
                string layoutPath = PageCache.FormatPath(theme, layout);

                try
                {
                    return(CreateRockPage(page, layoutPath, routeId, parms, routeHttpRequest));
                }
                catch (System.Web.HttpException)
                {
                    // The Selected theme and/or layout didn't exist so try to use the layout in the default theme.
                    theme = "Rock";

                    // Verify that Layout exists in the default theme directory and if not try use the default layout of the default theme
                    string layoutPagePath = string.Format("~/Themes/Rock/Layouts/{0}.aspx", layout);
                    if (!File.Exists(requestContext.HttpContext.Server.MapPath(layoutPagePath)))
                    {
                        layout = "FullWidth";
                    }

                    layoutPath = PageCache.FormatPath(theme, layout);

                    return(CreateRockPage(page, layoutPath, routeId, parms, routeHttpRequest));
                }
            }
            catch (Exception ex)
            {
                if (requestContext.HttpContext != null)
                {
                    requestContext.HttpContext.Cache["RockExceptionOrder"] = "66";
                    requestContext.HttpContext.Cache["RockLastException"]  = ex;
                }

                return((System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Error.aspx", typeof(System.Web.UI.Page)));
            }
        }
 public MobilePage GetHome()
 {
     return(GetPage(GlobalAttributesCache.Value("AvalancheHomePage").AsInteger()));
 }
Beispiel #12
0
        /// <summary>
        /// Sends the specified communication.
        /// </summary>
        /// <param name="communication">The communication.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        public override void Send(Rock.Model.Communication communication)
        {
            var rockContext = new RockContext();

            // Requery the Communication
            communication = new CommunicationService(rockContext).Get(communication.Id);

            if (communication != null &&
                communication.Status == Model.CommunicationStatus.Approved &&
                communication.Recipients.Where(r => r.Status == Model.CommunicationRecipientStatus.Pending).Any() &&
                (!communication.FutureSendDateTime.HasValue || communication.FutureSendDateTime.Value.CompareTo(RockDateTime.Now) <= 0))
            {
                string fromPhone   = string.Empty;
                string fromValue   = communication.GetMediumDataValue("FromValue");
                int    fromValueId = int.MinValue;
                if (int.TryParse(fromValue, out fromValueId))
                {
                    fromPhone = DefinedValueCache.Read(fromValueId, rockContext).Value;
                }

                if (!string.IsNullOrWhiteSpace(fromPhone))
                {
                    string accountSid = GetAttributeValue("SID");
                    string authToken  = GetAttributeValue("Token");
                    var    twilio     = new TwilioRestClient(accountSid, authToken);

                    var historyService   = new HistoryService(rockContext);
                    var recipientService = new CommunicationRecipientService(rockContext);

                    var personEntityTypeId        = EntityTypeCache.Read("Rock.Model.Person").Id;
                    var communicationEntityTypeId = EntityTypeCache.Read("Rock.Model.Communication").Id;
                    var communicationCategoryId   = CategoryCache.Read(Rock.SystemGuid.Category.HISTORY_PERSON_COMMUNICATIONS.AsGuid(), rockContext).Id;

                    var globalConfigValues = GlobalAttributesCache.GetMergeFields(null);

                    bool recipientFound = true;
                    while (recipientFound)
                    {
                        var recipient = recipientService.Get(communication.Id, CommunicationRecipientStatus.Pending).FirstOrDefault();
                        if (recipient != null)
                        {
                            try
                            {
                                var phoneNumber = recipient.PersonAlias.Person.PhoneNumbers
                                                  .Where(p => p.IsMessagingEnabled)
                                                  .FirstOrDefault();

                                if (phoneNumber != null)
                                {
                                    // Create merge field dictionary
                                    var    mergeObjects = recipient.CommunicationMergeValues(globalConfigValues);
                                    string message      = communication.GetMediumDataValue("Message");
                                    message = message.ResolveMergeFields(mergeObjects);

                                    string twilioNumber = phoneNumber.Number;
                                    if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode))
                                    {
                                        twilioNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                    }

                                    var    globalAttributes = Rock.Web.Cache.GlobalAttributesCache.Read();
                                    string callbackUrl      = globalAttributes.GetValue("PublicApplicationRoot") + "Webhooks/Twilio.ashx";

                                    var response = twilio.SendMessage(fromPhone, twilioNumber, message, callbackUrl);

                                    recipient.Status = CommunicationRecipientStatus.Delivered;
                                    recipient.TransportEntityTypeName = this.GetType().FullName;
                                    recipient.UniqueMessageId         = response.Sid;

                                    try
                                    {
                                        historyService.Add(new History
                                        {
                                            CreatedByPersonAliasId = communication.SenderPersonAliasId,
                                            EntityTypeId           = personEntityTypeId,
                                            CategoryId             = communicationCategoryId,
                                            EntityId            = recipient.PersonAlias.PersonId,
                                            Summary             = "Sent SMS message.",
                                            Caption             = message.Truncate(200),
                                            RelatedEntityTypeId = communicationEntityTypeId,
                                            RelatedEntityId     = communication.Id
                                        });
                                    }
                                    catch (Exception ex)
                                    {
                                        ExceptionLogService.LogException(ex, null);
                                    }
                                }
                                else
                                {
                                    recipient.Status     = CommunicationRecipientStatus.Failed;
                                    recipient.StatusNote = "No Phone Number with Messaging Enabled";
                                }
                            }
                            catch (Exception ex)
                            {
                                recipient.Status     = CommunicationRecipientStatus.Failed;
                                recipient.StatusNote = "Twilio Exception: " + ex.Message;
                            }

                            rockContext.SaveChanges();
                        }
                        else
                        {
                            recipientFound = false;
                        }
                    }
                }
            }
        }
Beispiel #13
0
        /// <summary>
        /// Load the SignNow control.
        /// </summary>
        /// <param name="currentRegistrantIndex">The current registrant index</param>
        /// <param name="registrationState">The registration state from RegistrationEntry</param>
        /// <param name="registrationInstanceState">The registration instance</param>
        /// <param name="digitalSignatureComponent">The digital signature component</param>
        /// <returns></returns>
        public bool Load(int currentRegistrantIndex, RegistrationInfo registrationState, RegistrationInstance registrationInstanceState)
        {
            CurrentRegistrantIndex    = currentRegistrantIndex;
            RegistrationState         = registrationState;
            RegistrationInstanceState = registrationInstanceState;

            var provider = DigitalSignatureContainer.GetComponent(RegistrationInstanceState.RegistrationTemplate.RequiredSignatureDocumentTemplate.ProviderEntityType.Name);

            if (provider != null && provider.IsActive)
            {
                DigitalSignatureComponent = provider;
            }
            var registrant = RegistrationState.Registrants[CurrentRegistrantIndex];

            string firstName = RegistrationInstanceState.RegistrationTemplate.RegistrantTerm;

            if (RegistrationState != null && RegistrationState.RegistrantCount > CurrentRegistrantIndex)
            {
                firstName = registrant.GetFirstName(RegistrationInstanceState.RegistrationTemplate);
                string lastName = registrant.GetLastName(RegistrationInstanceState.RegistrationTemplate);
                string email    = registrant.GetEmail(RegistrationInstanceState.RegistrationTemplate);

                object   dateOfBirthObj = registrant.GetPersonFieldValue(RegistrationInstanceState.RegistrationTemplate, RegistrationPersonFieldType.Birthdate);
                DateTime?dateOfBirth    = null;
                if (dateOfBirthObj != null && dateOfBirthObj is DateTime? )
                {
                    dateOfBirth = dateOfBirthObj as DateTime?;
                }

                // If we have a single person, then we check to see if we already have the document
                var           rockContext     = new Rock.Data.RockContext();
                PersonService personService   = new PersonService(rockContext);
                var           possiblePersons = personService.GetByMatch(firstName, lastName, dateOfBirth, email: email);
                if (possiblePersons.Count() == 1)
                {
                    var person                   = possiblePersons.First();
                    var personAliasIds           = person.Aliases.Select(pa => pa.Id).ToList();
                    var signatureDocumentService = new SignatureDocumentService(rockContext);
                    var validSignatureDocuments  = signatureDocumentService.Queryable().Where(sd =>
                                                                                              personAliasIds.Contains(sd.AppliesToPersonAliasId.Value) &&
                                                                                              sd.SignatureDocumentTemplateId == RegistrationInstanceState.RegistrationTemplate.RequiredSignatureDocumentTemplate.Id &&
                                                                                              sd.Status == SignatureDocumentStatus.Signed
                                                                                              ).OrderBy(sd => sd.CreatedDateTime);
                    if (validSignatureDocuments.Any())
                    {
                        registrant.SignatureDocumentId       = validSignatureDocuments.First().Id;
                        registrant.SignatureDocumentKey      = validSignatureDocuments.First().DocumentKey;
                        registrant.SignatureDocumentLastSent = validSignatureDocuments.First().LastInviteDate;
                        return(true);
                    }
                }
            }


            nbDigitalSignature.Heading = "Signature Required";
            nbDigitalSignature.Text    = string.Format(
                "This {0} requires that you sign a {1} for each registrant, please click the button below and then follow the prompts to digitally sign this document for {2}.  This will open the signing request within our digital signature provider's website.  When you have successfully signed this document, you will be returned to this page which will automatically proceed to the next step of your registration.",
                RegistrationInstanceState.RegistrationTemplate.RegistrationTerm,
                RegistrationInstanceState.RegistrationTemplate.RequiredSignatureDocumentTemplate.Name,
                firstName);

            var    errors     = new List <string>();
            string inviteLink = DigitalSignatureComponent.GetInviteLink(RegistrationInstanceState.RegistrationTemplate.RequiredSignatureDocumentTemplate.ProviderTemplateKey, out errors);

            if (!string.IsNullOrWhiteSpace(inviteLink))
            {
                var key = Guid.NewGuid();

                string returnUrl = GlobalAttributesCache.Get().GetValue("PublicApplicationRoot").EnsureTrailingForwardslash() +
                                   ResolveUrl(Request.RawUrl).TrimStart('/');

                // We need to make sure if someone click's back that we don't end up with extra parameters
                var uri = new Uri(returnUrl);
                var qs  = HttpUtility.ParseQueryString(uri.Query);
                qs.Set("registration_key", key.ToString());
                qs.Remove("document_id");
                // Put the URL back together again
                var uriBuilder = new UriBuilder(uri);
                uriBuilder.Query = qs.ToString();

                // Snap off a copy of the viewstate and set the button URL
                hfRegistrantKey.Value = key.ToString();

                hfRequiredDocumentLinkUrl.Value = string.Format("{0}?redirect_uri={1}", inviteLink, uriBuilder.ToString().UrlEncode());
                btnRequiredDocument.Visible     = true;
            }
            else
            {
                nbDigitalSignature.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Danger;
                nbDigitalSignature.Heading             = "Digital Signature Error";
                nbDigitalSignature.Text = string.Format("An Error Occurred Trying to Get Document Link... <ul><li>{0}</li></ul>", errors.AsDelimited("</li><li>"));
            }
            return(false);
        }
Beispiel #14
0
        /// <summary>
        /// Sends the specified recipients.
        /// </summary>
        /// <param name="recipients">The recipients.</param>
        /// <param name="from">From.</param>
        /// <param name="fromName">From name.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="body">The body.</param>
        /// <param name="appRoot">The application root.</param>
        /// <param name="themeRoot">The theme root.</param>
        /// <param name="attachments">Attachments.</param>
        /// <param name="createCommunicationHistory">if set to <c>true</c> [create communication history].</param>
        public void Send(List <string> recipients, string from, string fromName, string subject, string body, string appRoot, string themeRoot, List <Attachment> attachments, bool createCommunicationHistory)
        {
            try
            {
                var globalAttributes = GlobalAttributesCache.Read();

                if (string.IsNullOrWhiteSpace(from))
                {
                    from = globalAttributes.GetValue("OrganizationEmail");
                }

                if (!string.IsNullOrWhiteSpace(from))
                {
                    // Resolve any possible merge fields in the from address
                    var    mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                    string msgFrom     = from.ResolveMergeFields(mergeFields);

                    string msgSubject = subject;
                    string msgBody    = body;
                    if (!string.IsNullOrWhiteSpace(themeRoot))
                    {
                        msgSubject = msgSubject.Replace("~~/", themeRoot);
                        msgBody    = msgBody.Replace("~~/", themeRoot);
                    }

                    if (!string.IsNullOrWhiteSpace(appRoot))
                    {
                        msgSubject = msgSubject.Replace("~/", appRoot);
                        msgBody    = msgBody.Replace("~/", appRoot);
                        msgBody    = msgBody.Replace(@" src=""/", @" src=""" + appRoot);
                        msgBody    = msgBody.Replace(@" href=""/", @" href=""" + appRoot);
                    }

                    MailMessage message = new MailMessage();

                    // set from
                    if (!string.IsNullOrWhiteSpace(fromName))
                    {
                        message.From = new MailAddress(msgFrom, fromName);
                    }
                    else
                    {
                        message.From = new MailAddress(msgFrom);
                    }

                    CheckSafeSender(message, globalAttributes);

                    message.IsBodyHtml = true;
                    message.Priority   = MailPriority.Normal;

                    message.To.Clear();
                    recipients.ForEach(r => message.To.Add(r));

                    message.Subject = msgSubject;

                    // strip out any unsubscribe links since we don't know the person
                    msgBody = Regex.Replace(msgBody, @"\[\[\s*UnsubscribeOption\s*\]\]", string.Empty);

                    message.Body = msgBody;

                    // add attachments
                    if (attachments != null)
                    {
                        foreach (var attachment in attachments)
                        {
                            message.Attachments.Add(attachment);
                        }
                    }

                    AddAdditionalHeaders(message, null);

                    using (var smtpClient = GetSmtpClient())
                    {
                        smtpClient.Send(message);
                    }

                    if (createCommunicationHistory)
                    {
                        var transaction = new SaveCommunicationTransaction(
                            recipients, fromName, from, subject, body);
                        RockQueue.TransactionQueue.Enqueue(transaction);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, null);
            }
        }
Beispiel #15
0
        /// <summary>
        /// Sends the email.
        /// </summary>
        private void SendEmail()
        {
            // ensure this is not from a bot
            string[] bots          = GlobalAttributesCache.Value("EmailExceptionsFilter").Split('|');
            string   test          = GlobalAttributesCache.Value("EmailExceptionsFilter");
            var      serverVarList = Context.Request.ServerVariables;
            bool     isBot         = false;

            foreach (var bot in bots)
            {
                string[] botParms = bot.Split('^');
                if (botParms.Length == 2)
                {
                    var serverValue = serverVarList[botParms[0]];
                    if (serverValue != null && serverValue.ToUpper().Contains(botParms[1].ToUpper().Trim()))
                    {
                        isBot = true;
                    }
                }
            }

            if (!isBot)
            {
                var message = new RockEmailMessage();
                message.EnabledLavaCommands = GetAttributeValue("EnabledLavaCommands");

                // create merge objects
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

                // create merge object for fields
                Regex rgxRockControls = new Regex(@"^ctl\d*\$.*");
                var   formFields      = new Dictionary <string, object>();
                for (int i = 0; i < Request.Form.Count; i++)
                {
                    string formFieldKey = Request.Form.GetKey(i);
                    if (formFieldKey != null &&
                        formFieldKey.Substring(0, 1) != "_" &&
                        formFieldKey != "searchField_hSearchFilter" &&
                        formFieldKey != "send" &&
                        !rgxRockControls.IsMatch(formFieldKey))
                    {
                        formFields.Add(formFieldKey, Request.Form[formFieldKey]);
                    }
                }

                mergeFields.Add("FormFields", formFields);

                // get attachments
                var rockContext       = new RockContext();
                var binaryFileService = new BinaryFileService(rockContext);
                var binaryFileType    = new BinaryFileTypeService(rockContext).Get(Rock.SystemGuid.BinaryFiletype.DEFAULT.AsGuid());
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    var uploadedFile = Request.Files[i];
                    if (uploadedFile.ContentLength > 0 && uploadedFile.FileName.IsNotNullOrWhiteSpace())
                    {
                        var binaryFile = new BinaryFile();
                        binaryFileService.Add(binaryFile);
                        binaryFile.BinaryFileTypeId = binaryFileType.Id;
                        binaryFile.IsTemporary      = false;
                        binaryFile.MimeType         = uploadedFile.ContentType;
                        binaryFile.FileSize         = uploadedFile.ContentLength;
                        binaryFile.FileName         = Path.GetFileName(uploadedFile.FileName);
                        binaryFile.ContentStream    = uploadedFile.InputStream;
                        rockContext.SaveChanges();

                        message.Attachments.Add(binaryFileService.Get(binaryFile.Id));
                    }
                }

                mergeFields.Add("AttachmentCount", message.Attachments.Count);

                // send email
                foreach (string recipient in GetAttributeValue("RecipientEmail").Split(',').ToList())
                {
                    message.AddRecipient(new RecipientData(recipient, mergeFields));
                }

                message.CCEmails  = GetAttributeValue("CCEmail").ResolveMergeFields(mergeFields, GetAttributeValue("EnabledLavaCommands")).Split(',').ToList();
                message.BCCEmails = GetAttributeValue("BCCEmail").ResolveMergeFields(mergeFields, GetAttributeValue("EnabledLavaCommands")).Split(',').ToList();
                message.FromEmail = GetAttributeValue("FromEmail").ResolveMergeFields(mergeFields, GetAttributeValue("EnabledLavaCommands"));
                message.FromName  = GetAttributeValue("FromName").ResolveMergeFields(mergeFields, GetAttributeValue("EnabledLavaCommands"));
                message.Subject   = GetAttributeValue("Subject");
                message.Message   = GetAttributeValue("MessageBody");
                message.AppRoot   = ResolveRockUrl("~/");
                message.ThemeRoot = ResolveRockUrl("~~/");
                message.CreateCommunicationRecord = GetAttributeValue("SaveCommunicationHistory").AsBoolean();
                message.Send();

                // set response
                if (!string.IsNullOrWhiteSpace(GetAttributeValue("ResponsePage")))
                {
                    NavigateToLinkedPage("ResponsePage");
                }

                // display response message
                lResponse.Visible  = true;
                lEmailForm.Visible = false;
                lResponse.Text     = GetAttributeValue("ResponseMessage").ResolveMergeFields(mergeFields, GetAttributeValue("EnabledLavaCommands"));

                // show debug info
                if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
                {
                    lDebug.Visible = true;
                    lDebug.Text    = mergeFields.lavaDebugInfo();
                }
            }
            else
            {
                lResponse.Visible  = true;
                lEmailForm.Visible = false;
                lResponse.Text     = "You appear to be a computer. Check the global attribute 'Email Exceptions Filter' if you are getting this in error.";
            }
        }
Beispiel #16
0
        /// <summary>
        /// Renders the base control.
        /// </summary>
        /// <param name="writer">The writer.</param>
        public void RenderBaseControl(HtmlTextWriter writer)
        {
            bool rockMergeFieldEnabled   = MergeFields.Any();
            bool rockFileBrowserEnabled  = false;
            bool rockAssetManagerEnabled = false;
            var  currentPerson           = this.RockBlock().CurrentPerson;

            // only show the File/Image plugin if they have Auth to the file browser page
            var fileBrowserPage = new Rock.Model.PageService(new RockContext()).Get(Rock.SystemGuid.Page.HTMLEDITOR_ROCKFILEBROWSER_PLUGIN_FRAME.AsGuid());

            if (fileBrowserPage != null && currentPerson != null)
            {
                rockFileBrowserEnabled = fileBrowserPage.IsAuthorized(Authorization.VIEW, currentPerson);
            }

            var assetManagerPage = new Rock.Model.PageService(new RockContext()).Get(Rock.SystemGuid.Page.HTMLEDITOR_ROCKASSETMANAGER_PLUGIN_FRAME.AsGuid());

            if (assetManagerPage != null && currentPerson != null)
            {
                rockAssetManagerEnabled = assetManagerPage.IsAuthorized(Authorization.VIEW, currentPerson);
            }

            //TODO: Look for a valid asset manager and disable the control if one is not found



            var globalAttributesCache = GlobalAttributesCache.Get();

            string imageFileTypeWhiteList = globalAttributesCache.GetValue("ContentImageFiletypeWhitelist");
            string fileTypeBlackList      = globalAttributesCache.GetValue("ContentFiletypeBlacklist");
            string fileTypeWhiteList      = globalAttributesCache.GetValue("ContentFiletypeWhitelist");

            string documentFolderRoot = this.DocumentFolderRoot;
            string imageFolderRoot    = this.ImageFolderRoot;

            if (this.UserSpecificRoot)
            {
                var currentUser = this.RockBlock().CurrentUser;
                if (currentUser != null)
                {
                    documentFolderRoot = System.Web.VirtualPathUtility.Combine(documentFolderRoot.EnsureTrailingBackslash(), currentUser.UserName.ToString());
                    imageFolderRoot    = System.Web.VirtualPathUtility.Combine(imageFolderRoot.EnsureTrailingBackslash(), currentUser.UserName.ToString());
                }
            }

            string callbacksOption = string.Empty;

            if (!string.IsNullOrEmpty(this.CallbackOnKeyupScript) || !string.IsNullOrEmpty(this.CallbackOnChangeScript))
            {
                callbacksOption =
                    $@" 
onKeyup: function(e) {{  
    {this.CallbackOnKeyupScript}  
}},
onChange: function(contents, $editable) {{  
    {this.CallbackOnChangeScript}  
}}
";
            }


            string summernoteInitScript = $@"
function pageLoad() {{
  // remove any leftover popovers that summernote might have created and orphaned  
  $('.note-popover.popover').hide();
}}

$(document).ready( function() {{

    // workaround for https://github.com/summernote/summernote/issues/2017 and/or https://github.com/summernote/summernote/issues/1984
    if(!!document.createRange) {{
      document.getSelection().removeAllRanges();
    }}

    var summerNoteEditor_{this.ClientID} = $('#{this.ClientID}').summernote({{
        height: '{this.Height}', //set editable area's height
        toolbar: Rock.htmlEditor.toolbar_RockCustomConfig{this.Toolbar.ConvertToString()},

        popover: {{
          image: [
            ['custom1', ['rockimagelink']],
            ['imagesize', ['imageSize100', 'imageSize50', 'imageSize25']],
            ['custom2', ['rockimagebrowser', 'rockassetmanager']],
            ['float', ['floatLeft', 'floatRight', 'floatNone']],
            ['remove', ['removeMedia']]
          ],
          link: [
            ['link', ['linkDialogShow', 'unlink']]
          ],
          air: [
            ['color', ['color']],
            ['font', ['bold', 'underline', 'clear']],
            ['para', ['ul', 'paragraph']],
            ['table', ['table']],
            ['insert', ['link', 'picture']]
          ]
        }},

        callbacks: {{
           {callbacksOption} 
        }},

        buttons: {{
            rockfilebrowser: RockFileBrowser,
            rockimagebrowser: RockImageBrowser, 
            rockimagelink: RockImageLink,
            rockassetmanager: RockAssetManager,
            rockmergefield: RockMergeField,
            rockcodeeditor: RockCodeEditor,
            rockpastetext: RockPasteText,
            rockpastefromword: RockPasteFromWord
        }},

        rockFileBrowserOptions: {{ 
            enabled: {rockFileBrowserEnabled.ToTrueFalse().ToLower()},
            documentFolderRoot: '{Rock.Security.Encryption.EncryptString( documentFolderRoot )}', 
            imageFolderRoot: '{Rock.Security.Encryption.EncryptString( imageFolderRoot )}',
            imageFileTypeWhiteList: '{imageFileTypeWhiteList}',
            fileTypeBlackList: '{fileTypeBlackList}',
            fileTypeWhiteList: '{fileTypeWhiteList}'
        }},

        rockAssetManagerOptions: {{
            enabled: { rockAssetManagerEnabled.ToTrueFalse().ToLower() }
        }},

        rockMergeFieldOptions: {{ 
            enabled: {rockMergeFieldEnabled.ToTrueFalse().ToLower()},
            mergeFields: '{this.MergeFields.AsDelimited( "," )}' 
        }},
        rockTheme: '{( ( RockPage ) this.Page ).Site.Theme}',

        codeEditorOptions: {{
            controlId: '{_ceEditor.ClientID}',
            inCodeEditorModeHiddenFieldId: '{_hfInCodeEditorMode.ClientID}'
        }},
    }});

    if ({StartInCodeEditorMode.ToTrueFalse().ToLower()} && RockCodeEditor) {{
        RockCodeEditor(summerNoteEditor_{this.ClientID}.data('summernote'), true).click();
    }}

}});
";

            ScriptManager.RegisterStartupScript(this, this.GetType(), "summernote_init_script_" + this.ClientID, summernoteInitScript, true);

            // add script on demand only when there will be an htmleditor rendered
            if (ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack)
            {
                ScriptManager.RegisterClientScriptInclude(this.Page, this.Page.GetType(), "summernote-lib", ((RockPage)this.Page).ResolveRockUrl("~/Scripts/summernote/summernote.min.js", true));
                var bundleUrl = System.Web.Optimization.BundleResolver.Current.GetBundleUrl("~/Scripts/Bundles/RockHtmlEditorPlugins");
                ScriptManager.RegisterClientScriptInclude(this.Page, this.Page.GetType(), "summernote-plugins", bundleUrl);
            }

            // set this textbox hidden until we can run the js to attach summernote to it
            this.Style[HtmlTextWriterStyle.Display] = "none";

            base.RenderControl(writer);
        }
Beispiel #17
0
        /// <summary>
        /// Process inbound messages that are sent to a SMS number.
        /// </summary>
        /// <param name="toPhone">The transport (e.g. Twilio) phone number a message is sent to.</param>
        /// <param name="fromPhone">The phone number a message is sent from. (This would be the number from somebody's mobile device)</param>
        /// <param name="message">The message that was sent.</param>
        /// <param name="attachments">The attachments.</param>
        /// <param name="errorMessage">The error message.</param>
        public void ProcessResponse(string toPhone, string fromPhone, string message, List <BinaryFile> attachments, out string errorMessage)
        {
            errorMessage = string.Empty;

            using (var rockContext = new RockContext())
            {
                // the person associated with the SMS Phone Defined Value
                Person toPerson = null;

                var mobilePhoneNumberValueId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Id;
                fromPhone = fromPhone.Replace("+", "");
                toPhone   = toPhone.Replace("+", "");

                // Get the person who sent the message. This will always return a Person record since we want to get a nameless Person record if there isn't a regular person record found
                var fromPerson = new PersonService(rockContext).GetPersonFromMobilePhoneNumber(fromPhone, true);

                // get recipient from defined value
                var rockSmsFromPhoneDv = FindRockSMSPhoneDefinedValue(toPhone);
                if (rockSmsFromPhoneDv != null)
                {
                    // NOTE: As of 9.0 the SMS from number DefinedValue no longer has to have a person (toPersonAliasGuid) assigned to it.
                    var toPersonAliasGuid = rockSmsFromPhoneDv.GetAttributeValue("ResponseRecipient").AsGuidOrNull();
                    if (toPersonAliasGuid.HasValue)
                    {
                        toPerson = new PersonAliasService(rockContext)
                                   .Queryable().Where(p => p.Guid.Equals(toPersonAliasGuid.Value))
                                   .Select(p => p.Person)
                                   .FirstOrDefault();
                    }
                }

                if (rockSmsFromPhoneDv != null)
                {
                    string plainMessage = message;

                    if (toPerson != null && fromPerson != null && toPerson.Id == fromPerson.Id)
                    {
                        // From and To person are the same person. For example, in an SMS Conversation, the SMS DefinedValue person replies to the conversation

                        // look for response code in the message
                        Match match = Regex.Match(message, @"@\d{3,5}");
                        if (match.Success)
                        {
                            string responseCode = match.ToString();

                            var recipient = new CommunicationRecipientService(rockContext).Queryable("Communication")
                                            .Where(r => r.ResponseCode == responseCode && r.CreatedDateTime.HasValue)
                                            .OrderByDescending(r => r.CreatedDateTime).FirstOrDefault();

                            if (recipient != null && recipient.Communication.SenderPersonAliasId.HasValue)
                            {
                                CreateCommunication(fromPerson, fromPhone, recipient.Communication.SenderPersonAliasId.Value, message.Replace(responseCode, ""), plainMessage, rockSmsFromPhoneDv, "", rockContext, out errorMessage, attachments);
                            }
                            else // send a warning message back to the medium recipient
                            {
                                string warningMessage = string.Format("A conversation could not be found with the response token {0}.", responseCode);
                                CreateCommunication(fromPerson, fromPhone, fromPerson.PrimaryAliasId.Value, warningMessage, plainMessage, rockSmsFromPhoneDv, "", rockContext, out errorMessage, attachments);
                            }
                        }
                        else
                        {
                            errorMessage = "There was no response code (e.g., @321) found in the message and the from/to person were the same.";
                        }
                    }
                    else
                    {
                        // From and To person are not same person. For example, a person sent a message to the SMS PhoneNumber (DefinedValue).
                        string messageId = GenerateResponseCode(rockContext);
                        int?   toPersonPrimaryAliasId = toPerson?.PrimaryAliasId;

                        // NOTE: fromPerson will never be null since we would have created a Nameless Person record if there wasn't a regular person found
                        message = $"-{fromPerson.FullName}-\n{message}\n( {messageId} )";
                        CreateCommunication(fromPerson, fromPhone, toPersonPrimaryAliasId, message, plainMessage, rockSmsFromPhoneDv, messageId, rockContext, out errorMessage, attachments);
                    }
                }
                else
                {
                    var    globalAttributes = GlobalAttributesCache.Get();
                    string organizationName = globalAttributes.GetValue("OrganizationName");

                    errorMessage = string.Format("Could not deliver message. This phone number is not registered in the {0} database.", organizationName);
                }
            }
        }
Beispiel #18
0
        /// <summary>
        /// Job that will run quick SQL queries on a schedule.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            // get registrations where
            //    + template is active
            //    + instance is active
            //    + template has a number of days between reminders
            //    + template as fields needed to send a reminder email
            //    + the registration has a cost
            //    + the registration has been closed within the last xx days (to prevent eternal nagging)

            using (RockContext rockContext = new RockContext())
            {
                int sendCount = 0;
                int registrationInstanceCount = 0;

                var appRoot = GlobalAttributesCache.Get().GetValue("PublicApplicationRoot");

                RegistrationService registrationService = new RegistrationService(rockContext);

                var currentDate = RockDateTime.Today;
                var cutoffDays  = dataMap.GetString("CutoffDate").AsIntegerOrNull() ?? 30;

                // Do not filter registrations by template or instance cost, it will miss $0 registrations that have optional fees.
                var registrations = registrationService.Queryable("RegistrationInstance")
                                    .Where(r =>
                                           r.RegistrationInstance.RegistrationTemplate.IsActive &&
                                           r.RegistrationInstance.IsActive == true &&
                                           (r.RegistrationInstance.RegistrationTemplate.PaymentReminderTimeSpan != null && r.RegistrationInstance.RegistrationTemplate.PaymentReminderTimeSpan != 0) &&
                                           r.RegistrationInstance.RegistrationTemplate.PaymentReminderEmailTemplate != null && r.RegistrationInstance.RegistrationTemplate.PaymentReminderEmailTemplate.Length > 0 &&
                                           r.RegistrationInstance.RegistrationTemplate.PaymentReminderFromEmail != null && r.RegistrationInstance.RegistrationTemplate.PaymentReminderFromEmail.Length > 0 &&
                                           r.RegistrationInstance.RegistrationTemplate.PaymentReminderSubject != null && r.RegistrationInstance.RegistrationTemplate.PaymentReminderSubject.Length > 0 &&
                                           (r.RegistrationInstance.EndDateTime == null || currentDate <= System.Data.Entity.SqlServer.SqlFunctions.DateAdd("day", cutoffDays, r.RegistrationInstance.EndDateTime)))
                                    .ToList();

                registrationInstanceCount = registrations.Select(r => r.RegistrationInstance.Id).Distinct().Count();

                var errors = new List <string>();
                foreach (var registration in registrations)
                {
                    if (registration.DiscountedCost > registration.TotalPaid)
                    {
                        var reminderDate = RockDateTime.Now.AddDays(registration.RegistrationInstance.RegistrationTemplate.PaymentReminderTimeSpan.Value * -1);

                        if (registration.LastPaymentReminderDateTime < reminderDate)
                        {
                            Dictionary <string, object> mergeObjects = new Dictionary <string, object>();
                            mergeObjects.Add("Registration", registration);
                            mergeObjects.Add("RegistrationInstance", registration.RegistrationInstance);

                            var emailMessage = new RockEmailMessage();
                            emailMessage.AdditionalMergeFields = mergeObjects;
                            emailMessage.AddRecipient(registration.GetConfirmationRecipient(mergeObjects));
                            emailMessage.FromEmail = registration.RegistrationInstance.RegistrationTemplate.PaymentReminderFromEmail;
                            emailMessage.FromName  = registration.RegistrationInstance.RegistrationTemplate.PaymentReminderSubject;
                            emailMessage.Subject   = registration.RegistrationInstance.RegistrationTemplate.PaymentReminderFromName;
                            emailMessage.Message   = registration.RegistrationInstance.RegistrationTemplate.PaymentReminderEmailTemplate;
                            var emailErrors = new List <string>();
                            emailMessage.Send(out errors);

                            registration.LastPaymentReminderDateTime = RockDateTime.Now;
                            rockContext.SaveChanges();

                            if (!emailErrors.Any())
                            {
                                sendCount++;
                            }
                        }
                    }
                }

                context.Result = string.Format("Sent {0} from {1}", "reminder".ToQuantity(sendCount), "registration instances".ToQuantity(registrationInstanceCount));
                if (errors.Any())
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine();
                    sb.Append(string.Format("{0} Errors: ", errors.Count()));
                    errors.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                    string errorMessage = sb.ToString();
                    context.Result += errorMessage;
                    var         exception = new Exception(errorMessage);
                    HttpContext context2  = HttpContext.Current;
                    ExceptionLogService.LogException(exception, context2);
                    throw exception;
                }
            }
        }
Beispiel #19
0
        /// <summary>
        /// Gets the <see cref="System.Object"/> with the specified key.
        /// </summary>
        /// <remarks>
        /// This method is necessary to support getting AttributeValues in Lava templates and
        /// to support the old way of getting attribute values in Lava templates
        /// (e.g. {{ Person.BaptismData }} ).  Once support for this method is
        /// removed and only the new method of using the Attribute filter is
        /// supported (e.g. {{ Person | Attribute:'BaptismDate' }} ), this method can be
        /// trimmed to only support the AttributeValues key.
        /// </remarks>
        /// <value>
        /// The <see cref="System.Object"/>.
        /// </value>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public override object this[object key]
        {
            get
            {
                string keyString = key.ToStringSafe();

                object item = base[key];
                if (item == null)
                {
                    var lavaSupportLevel = GlobalAttributesCache.Get().LavaSupportLevel;

                    if (this.Attributes == null)
                    {
                        this.LoadAttributes();
                    }

                    if (keyString == "AttributeValues")
                    {
                        return(AttributeValues.Select(a => a.Value).ToList());
                    }

                    // The remainder of this method is only necessary to support the old way of getting attribute
                    // values in liquid templates (e.g. {{ Person.BaptismData }} ).  Once support for this method is
                    // deprecated ( in v4.0 ), and only the new method of using the Attribute filter is
                    // supported (e.g. {{ Person | Attribute:'BaptismDate' }} ), the remainder of this method
                    // can be removed

                    if (lavaSupportLevel == Lava.LavaSupportLevel.NoLegacy)
                    {
                        return(null);
                    }

                    if (this.Attributes != null)
                    {
                        string attributeKey = keyString;
                        bool   unformatted  = false;
                        bool   url          = false;

                        if (attributeKey.EndsWith("_unformatted"))
                        {
                            attributeKey = attributeKey.Replace("_unformatted", "");
                            unformatted  = true;
                        }
                        else if (attributeKey.EndsWith("_url"))
                        {
                            attributeKey = attributeKey.Replace("_url", "");
                            url          = true;
                        }

                        if (this.Attributes.ContainsKey(attributeKey))
                        {
                            var attribute = this.Attributes[attributeKey];
                            if (attribute.IsAuthorized(Authorization.VIEW, null))
                            {
                                Rock.Model.ExceptionLogService.LogException(new Rock.Lava.LegacyLavaSyntaxDetectedException(this.GetType().GetFriendlyTypeName(), attributeKey), System.Web.HttpContext.Current);

                                if (unformatted)
                                {
                                    return(GetAttributeValueAsType(attribute.Key));
                                }

                                var    field = attribute.FieldType.Field;
                                string value = GetAttributeValue(attribute.Key);

                                if (url && field is Rock.Field.ILinkableFieldType)
                                {
                                    return(((Rock.Field.ILinkableFieldType)field).UrlLink(value, attribute.QualifierValues));
                                }

                                return(field.FormatValue(null, attribute.EntityTypeId, this.Id, value, attribute.QualifierValues, false));
                            }
                        }
                    }
                }

                return(item);
            }
        }
        public HttpResponseMessage ForgotPassword([FromBody] string email)
        {
            OAuthContext  oAuthContext  = new OAuthContext();
            ClientService clientService = new ClientService(oAuthContext);
            var           clientId      = HttpContext.Current.User.Identity.Name;
            Client        oAuthClient   = clientService.GetByApiKey(clientId.AsGuid());

            if (oAuthClient.Active)
            {
                var              response         = new StandardResponse();
                var              rockContext      = new Rock.Data.RockContext();
                PersonService    personService    = new PersonService(rockContext);
                UserLoginService userLoginService = new UserLoginService(rockContext);
                bool             hasAccountWithPasswordResetAbility = false;
                var              results = new List <IDictionary <string, object> >();

                // Check to make sure we have accounts matching the email address given
                foreach (Person person in personService.GetByEmail(email)
                         .Where(p => p.Users.Any()))
                {
                    var users = new List <UserLogin>();
                    foreach (UserLogin user in userLoginService.GetByPersonId(person.Id))
                    {
                        if (user.EntityType != null)
                        {
                            var component = Rock.Security.AuthenticationContainer.GetComponent(user.EntityType.Name);
                            if (component != null && !component.RequiresRemoteAuthentication)
                            {
                                users.Add(user);
                                hasAccountWithPasswordResetAbility = true;
                            }
                        }
                    }

                    var resultsDictionary = new Dictionary <string, object>();
                    resultsDictionary.Add("Person", person);
                    resultsDictionary.Add("Users", users);
                    results.Add(resultsDictionary);
                }
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null, null);

                // If we found matching accounts that have the ability to be reset, go ahead and send the email
                if (results.Count > 0 && hasAccountWithPasswordResetAbility)
                {
                    mergeFields.Add("Results", results.ToArray());

                    var emailMessage = new RockEmailMessage(Rock.SystemGuid.SystemCommunication.SECURITY_FORGOT_USERNAME.AsGuid());
                    emailMessage.AddRecipient(RockEmailMessageRecipient.CreateAnonymous(email, mergeFields));
                    emailMessage.AppRoot = GlobalAttributesCache.Get().GetValue("PublicApplicationRoot").EnsureTrailingForwardslash();
                    emailMessage.CreateCommunicationRecord = false;
                    emailMessage.Send();
                    response.Result  = StandardResponse.ResultCode.Success;
                    response.Message = "Forgot password email has been sent successfully.";
                }
                else
                {
                    // the person either has no user accounts or none of them are allowed to have their passwords reset (Facebook/Google/SMS/etc)
                    response.Result  = StandardResponse.ResultCode.Error;
                    response.Message = "No accounts associated with this email address are able to be reset via email.";
                }
                return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, response));
            }

            return(ControllerContext.Request.CreateResponse(HttpStatusCode.Forbidden));
        }
Beispiel #21
0
        /// <summary>
        /// Creates the child controls.
        /// </summary>
        /// <param name="parentControl"></param>
        /// <returns></returns>
        public override System.Web.UI.Control[] CreateChildControls(System.Web.UI.Control parentControl)
        {
            RockDropDownList locationTypeList = new RockDropDownList();

            locationTypeList.Items.Clear();
            foreach (var value in DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.GROUP_LOCATION_TYPE.AsGuid()).DefinedValues.OrderBy(a => a.Order).ThenBy(a => a.Value))
            {
                locationTypeList.Items.Add(new ListItem(value.Value, value.Guid.ToString()));
            }

            locationTypeList.ID            = parentControl.ID + "_grouplocationType";
            locationTypeList.Label         = "Address Type";
            locationTypeList.SelectedIndex = 0;
            parentControl.Controls.Add(locationTypeList);

            RockRadioButtonList addressPartRadioButtonList = new RockRadioButtonList();

            addressPartRadioButtonList.Items.Clear();
            addressPartRadioButtonList.BindToEnum <RockUdfHelper.AddressNamePart>(false);

            // Localises the radio button list by modifying the text Value of radio buttons
            Dictionary <string, string> newLabels = new Dictionary <string, string>();
            var globalAttributesCache             = GlobalAttributesCache.Read();
            var defaultCountry = (!string.IsNullOrWhiteSpace(globalAttributesCache.OrganizationCountry)) ? globalAttributesCache.OrganizationCountry : "US";
            var countryValue   = DefinedTypeCache.Read(new Guid(SystemGuid.DefinedType.LOCATION_COUNTRIES))
                                 .DefinedValues
                                 .Where(v => v.Value.Equals(defaultCountry, StringComparison.OrdinalIgnoreCase))
                                 .FirstOrDefault();

            if (countryValue != null)
            {
                if (!newLabels.ContainsKey("City"))
                {
                    newLabels.Add("City", countryValue.GetAttributeValue("CityLabel"));
                }

                if (!newLabels.ContainsKey("Region"))
                {
                    newLabels.Add("Region", countryValue.GetAttributeValue("StateLabel"));
                }

                if (!newLabels.ContainsKey("PostalCode"))
                {
                    newLabels.Add("PostalCode", countryValue.GetAttributeValue("PostalCodeLabel"));
                }
            }

            foreach (KeyValuePair <string, string> pair in newLabels)
            {
                string oldValue = pair.Key.SplitCase();
                string newValue = pair.Value.SplitCase();
                var    listItem = addressPartRadioButtonList.Items.FindByText(oldValue);
                if (listItem != null)
                {
                    listItem.Text = newValue;
                }
            }

            // default to first one
            addressPartRadioButtonList.SelectedIndex = 0;
            addressPartRadioButtonList.ID            = parentControl.ID + "_addressPartRadioButtonList";
            addressPartRadioButtonList.Label         = "Address Part";
            addressPartRadioButtonList.Help          = "Select the part of the address to show in the grid, or select Full to show the full address";
            parentControl.Controls.Add(addressPartRadioButtonList);

            return(new System.Web.UI.Control[] { locationTypeList, addressPartRadioButtonList });
        }
        public HttpResponseMessage CreateAccount(Account account)
        {
            OAuthContext  oAuthContext  = new OAuthContext();
            ClientService clientService = new ClientService(oAuthContext);
            var           clientId      = HttpContext.Current.User.Identity.Name;
            Client        oAuthClient   = clientService.GetByApiKey(clientId.AsGuid());

            if (oAuthClient.Active)
            {
                var              rockContext      = new Rock.Data.RockContext();
                PersonService    personService    = new PersonService(rockContext);
                UserLoginService userLoginService = new UserLoginService(rockContext);

                // Validate the Model
                if (!string.IsNullOrEmpty(account.Username))
                {
                    // Make sure the username is unique
                    UserLogin user = userLoginService.GetByUserName(account.Username);
                    if (user != null)
                    {
                        ModelState.AddModelError("Account.Username", "Username already exists");
                    }

                    // Make sure the password is valid
                    if (!UserLoginService.IsPasswordValid(account.Password))
                    {
                        ModelState.AddModelError("Account.Password", UserLoginService.FriendlyPasswordRules());
                    }

                    // Make sure this person meets the minimum age requirement
                    var birthday = account.Birthdate ?? Rock.RockDateTime.Today;
                    if (RockDateTime.Today.AddYears(MINIMUM_AGE * -1) < birthday)
                    {
                        ModelState.AddModelError("Account.Birthdate", string.Format("We are sorry, you must be at least {0} years old to create an account.", MINIMUM_AGE));
                    }
                }
                if (!ModelState.IsValid)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }

                // Try to match the person
                var matchPerson = personService.GetByMatch(account.FirstName, account.LastName, account.Birthdate, account.EmailAddress, account.MobileNumber, null, null);

                bool   confirmed = false;
                Person person    = new Person();
                if (matchPerson != null && matchPerson.Count() == 1)
                {
                    var mobilePhone = matchPerson.First().PhoneNumbers.Where(pn => pn.NumberTypeValueId == DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Id).FirstOrDefault();
                    // The emails MUST match for security
                    if (matchPerson.First().Email == account.EmailAddress && (mobilePhone == null || mobilePhone.Number.Right(10) == account.MobileNumber.Right(10)))
                    {
                        person = matchPerson.First();

                        // If they don't have a current mobile phone, go ahead and set it
                        if (mobilePhone == null)
                        {
                            string cleanNumber = PhoneNumber.CleanNumber(account.MobileNumber);
                            var    phoneNumber = new PhoneNumber {
                                NumberTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Id
                            };
                            person.PhoneNumbers.Add(phoneNumber);
                            phoneNumber.CountryCode        = cleanNumber.Length > 10 ? cleanNumber.Left(10 - cleanNumber.Length) : PhoneNumber.DefaultCountryCode();
                            phoneNumber.Number             = cleanNumber.Right(10);
                            phoneNumber.IsMessagingEnabled = true;
                        }

                        // Make sure the gender matches
                        person.Gender = account.Gender;

                        confirmed = true;
                    }
                }

                // If we don't have a match, create a new web prospect
                if (!confirmed)
                {
                    DefinedValueCache dvcConnectionStatus = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_WEB_PROSPECT.AsGuid());
                    DefinedValueCache dvcRecordStatus     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid());

                    person.FirstName         = account.FirstName;
                    person.LastName          = account.LastName;
                    person.NickName          = account.NickName;
                    person.Email             = account.EmailAddress;
                    person.IsEmailActive     = true;
                    person.EmailPreference   = EmailPreference.EmailAllowed;
                    person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                    if (dvcConnectionStatus != null)
                    {
                        person.ConnectionStatusValueId = dvcConnectionStatus.Id;
                    }

                    if (dvcRecordStatus != null)
                    {
                        person.RecordStatusValueId = dvcRecordStatus.Id;
                    }

                    person.Gender = account.Gender;

                    var birthday = account.Birthdate;
                    if (birthday.HasValue)
                    {
                        person.BirthMonth = birthday.Value.Month;
                        person.BirthDay   = birthday.Value.Day;
                        if (birthday.Value.Year != DateTime.MinValue.Year)
                        {
                            person.BirthYear = birthday.Value.Year;
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(account.MobileNumber))
                    {
                        string cleanNumber = PhoneNumber.CleanNumber(account.MobileNumber);
                        var    phoneNumber = new PhoneNumber {
                            NumberTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Id
                        };
                        person.PhoneNumbers.Add(phoneNumber);
                        phoneNumber.CountryCode        = cleanNumber.Length > 10 ? cleanNumber.Left(10 - cleanNumber.Length) : PhoneNumber.DefaultCountryCode();
                        phoneNumber.Number             = cleanNumber.Right(10);
                        phoneNumber.IsMessagingEnabled = true;
                    }

                    PersonService.SaveNewPerson(person, rockContext);
                }
                UserLogin userLogin = null;

                if (!string.IsNullOrWhiteSpace(account.Username) && UserLoginService.IsPasswordValid(account.Password))
                {
                    // Create the user login (only require confirmation if we didn't match the person)
                    userLogin = UserLoginService.Create(
                        rockContext,
                        person,
                        AuthenticationServiceType.Internal,
                        EntityTypeCache.Get(Rock.SystemGuid.EntityType.AUTHENTICATION_DATABASE.AsGuid()).Id,
                        account.Username,
                        account.Password,
                        confirmed);
                }
                else if (!string.IsNullOrWhiteSpace(account.EmailAddress) && !confirmed)
                {
                    userLogin = userLoginService.Queryable()
                                .Where(u => u.UserName == ("SMS_" + person.Id.ToString()))
                                .FirstOrDefault();

                    // Create an unconfirmed SMS user login if does not exist
                    if (userLogin == null)
                    {
                        var entityTypeId = EntityTypeCache.Get("Rock.Security.ExternalAuthentication.SMSAuthentication").Id;

                        userLogin = new UserLogin()
                        {
                            UserName     = "******" + person.Id.ToString(),
                            EntityTypeId = entityTypeId,
                            IsConfirmed  = false,
                            PersonId     = person.Id
                        };
                        userLoginService.Add(userLogin);
                    }
                }
                // Send an email to confirm the account.
                if (userLogin != null && userLogin.IsConfirmed != true)
                {
                    // For mobile we will make a custom/short confirmation code
                    var mobileConfirmationCode = new BigInteger(MD5.Create().ComputeHash(userLogin.Guid.ToByteArray())).ToString().Right(6);
                    var mergeFields            = Rock.Lava.LavaHelper.GetCommonMergeFields(null, person);
                    mergeFields.Add("MobileConfirmationCode", mobileConfirmationCode);
                    mergeFields.Add("ConfirmAccountUrl", GlobalAttributesCache.Get().GetValue("PublicApplicationRoot").EnsureTrailingForwardslash() + "ConfirmAccount");
                    mergeFields.Add("Person", userLogin.Person);
                    mergeFields.Add("User", userLogin);

                    var recipients = new List <RockEmailMessageRecipient>();
                    recipients.Add(new RockEmailMessageRecipient(userLogin.Person, mergeFields));

                    var message = new RockEmailMessage(Rock.SystemGuid.SystemCommunication.SECURITY_CONFIRM_ACCOUNT.AsGuid());
                    message.SetRecipients(recipients);
                    message.AppRoot = GlobalAttributesCache.Get().GetValue("PublicApplicationRoot").EnsureTrailingForwardslash();
                    message.CreateCommunicationRecord = false;
                    message.Send();
                }

                rockContext.SaveChanges();

                return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, new StandardResponse()
                {
                    Message = string.Format("Account has been created.{0}", confirmed ? "" : " An email has been sent to confirm the email address."),
                    Result = StandardResponse.ResultCode.Success
                }
                                                                ));
            }

            return(ControllerContext.Request.CreateResponse(HttpStatusCode.Forbidden));
        }
Beispiel #23
0
        /// <summary>
        /// Shows the details.
        /// </summary>
        private void ShowDetails()
        {
            lTitle.Text = string.Format("Edit: {0}", Person.FullName).FormatAsHtmlTitle();

            imgPhoto.BinaryFileId = Person.PhotoId;
            imgPhoto.NoPictureUrl = Person.GetPersonPhotoUrl(Person, 400, 400);

            ddlTitle.SelectedValue  = Person.TitleValueId.HasValue ? Person.TitleValueId.Value.ToString() : string.Empty;
            tbFirstName.Text        = Person.FirstName;
            tbNickName.Text         = string.IsNullOrWhiteSpace(Person.NickName) ? string.Empty : (Person.NickName.Equals(Person.FirstName, StringComparison.OrdinalIgnoreCase) ? string.Empty : Person.NickName);
            tbMiddleName.Text       = Person.MiddleName;
            tbLastName.Text         = Person.LastName;
            ddlSuffix.SelectedValue = Person.SuffixValueId.HasValue ? Person.SuffixValueId.Value.ToString() : string.Empty;
            bpBirthDay.SelectedDate = Person.BirthDate;

            if (Person.GraduationYear.HasValue)
            {
                ypGraduation.SelectedYear = Person.GraduationYear.Value;
            }
            else
            {
                ypGraduation.SelectedYear = null;
            }

            if (!Person.HasGraduated ?? false)
            {
                int gradeOffset    = Person.GradeOffset.Value;
                var maxGradeOffset = ddlGradePicker.MaxGradeOffset;

                // keep trying until we find a Grade that has a gradeOffset that that includes the Person's gradeOffset (for example, there might be combined grades)
                while (!ddlGradePicker.Items.OfType <ListItem>().Any(a => a.Value.AsInteger() == gradeOffset) && gradeOffset <= maxGradeOffset)
                {
                    gradeOffset++;
                }

                ddlGradePicker.SetValue(gradeOffset);
            }
            else
            {
                ddlGradePicker.SelectedIndex = 0;
            }

            dpAnniversaryDate.SelectedDate = Person.AnniversaryDate;
            rblGender.SelectedValue        = Person.Gender.ConvertToString(false);
            ddlMaritalStatus.SetValue(Person.MaritalStatusValueId);
            ddlConnectionStatus.SetValue(Person.ConnectionStatusValueId);
            lConnectionStatusReadOnly.Text = Person.ConnectionStatusValueId.HasValue ? Person.ConnectionStatusValue.Value : string.Empty;

            tbEmail.Text                     = Person.Email;
            cbIsEmailActive.Checked          = Person.IsEmailActive;
            rblEmailPreference.SelectedValue = Person.EmailPreference.ConvertToString(false);

            ddlRecordStatus.SetValue(Person.RecordStatusValueId);
            lRecordStatusReadOnly.Text = Person.RecordStatusValueId.HasValue ? Person.RecordStatusValue.Value : string.Empty;
            ddlReason.SetValue(Person.RecordStatusReasonValueId);
            lReasonReadOnly.Text = Person.RecordStatusReasonValueId.HasValue ? Person.RecordStatusReasonValue.Value : string.Empty;

            tbInactiveReasonNote.Text = Person.InactiveReasonNote;
            lReasonNoteReadOnly.Text  = Person.InactiveReasonNote;

            ddlRecordStatus_SelectedIndexChanged(null, null);

            var mobilePhoneType = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE));

            var phoneNumbers     = new List <PhoneNumber>();
            var phoneNumberTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE));

            if (phoneNumberTypes.DefinedValues.Any())
            {
                foreach (var phoneNumberType in phoneNumberTypes.DefinedValues)
                {
                    var phoneNumber = Person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberType.Id);
                    if (phoneNumber == null)
                    {
                        var numberType = new DefinedValue();
                        numberType.Id    = phoneNumberType.Id;
                        numberType.Value = phoneNumberType.Value;

                        phoneNumber = new PhoneNumber {
                            NumberTypeValueId = numberType.Id, NumberTypeValue = numberType
                        };
                        phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id;
                    }
                    else
                    {
                        // Update number format, just in case it wasn't saved correctly
                        phoneNumber.NumberFormatted = PhoneNumber.FormattedNumber(phoneNumber.CountryCode, phoneNumber.Number);
                    }

                    phoneNumbers.Add(phoneNumber);
                }

                rContactInfo.DataSource = phoneNumbers;
                rContactInfo.DataBind();
            }

            ddlGivingGroup.SetValue(Person.GivingGroupId);
            var personGivingEnvelopeAttribute = AttributeCache.Read(Rock.SystemGuid.Attribute.PERSON_GIVING_ENVELOPE_NUMBER.AsGuid());

            rcwEnvelope.Visible = GlobalAttributesCache.Read().EnableGivingEnvelopeNumber&& personGivingEnvelopeAttribute != null;
            if (personGivingEnvelopeAttribute != null)
            {
                tbGivingEnvelopeNumber.Text = Person.GetAttributeValue(personGivingEnvelopeAttribute.Key);
            }

            this.PersonPreviousNamesState = Person.GetPreviousNames().ToList();

            BindPersonPreviousNamesGrid();
        }
Beispiel #24
0
        /// <summary>
        /// Sends the specified rock message.
        /// </summary>
        /// <param name="rockMessage">The rock message.</param>
        /// <param name="mediumEntityTypeId">The medium entity type identifier.</param>
        /// <param name="mediumAttributes">The medium attributes.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Send(RockMessage rockMessage, int mediumEntityTypeId, Dictionary <string, string> mediumAttributes, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var emailMessage = rockMessage as RockEmailMessage;

            if (emailMessage != null)
            {
                // From - if none is set, use the one in the Organization's GlobalAttributes.
                var    globalAttributes = GlobalAttributesCache.Read();
                string fromAddress      = emailMessage.FromEmail;
                if (string.IsNullOrWhiteSpace(fromAddress))
                {
                    fromAddress = globalAttributes.GetValue("OrganizationEmail");
                }
                string fromName = emailMessage.FromName;
                if (string.IsNullOrWhiteSpace(fromName))
                {
                    fromName = globalAttributes.GetValue("OrganizationName");
                }
                if (fromAddress.IsNullOrWhiteSpace())
                {
                    errorMessages.Add("A From address was not provided.");
                    return(false);
                }

                // Common Merge Field
                var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null, rockMessage.CurrentPerson);
                foreach (var mergeField in rockMessage.AdditionalMergeFields)
                {
                    mergeFields.AddOrReplace(mergeField.Key, mergeField.Value);
                }

                // Resolve any possible merge fields in the from address
                fromAddress = fromAddress.ResolveMergeFields(mergeFields, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands);
                fromName    = fromName.ResolveMergeFields(mergeFields, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands);

                MailMessage message = new MailMessage();

                // Reply To
                try
                {
                    if (emailMessage.ReplyToEmail.IsNotNullOrWhitespace())
                    {
                        // Resolve any possible merge fields in the replyTo address
                        message.ReplyToList.Add(new MailAddress(emailMessage.ReplyToEmail.ResolveMergeFields(mergeFields, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands)));
                    }
                }
                catch { }

                message.IsBodyHtml = true;
                message.Priority   = MailPriority.Normal;

                using (var smtpClient = GetSmtpClient())
                {
                    foreach (var recipientData in rockMessage.GetRecipientData())
                    {
                        try
                        {
                            foreach (var mergeField in mergeFields)
                            {
                                recipientData.MergeFields.AddOrIgnore(mergeField.Key, mergeField.Value);
                            }

                            message.To.Clear();
                            message.CC.Clear();
                            message.Bcc.Clear();
                            message.Headers.Clear();

                            // Set From/To and check safe sender
                            message.From = new MailAddress(fromAddress, fromName);
                            message.To.Add(new MailAddress(
                                               recipientData.To.ResolveMergeFields(recipientData.MergeFields, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands),
                                               recipientData.Name.ResolveMergeFields(recipientData.MergeFields, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands)));
                            CheckSafeSender(message, globalAttributes);

                            // cc
                            foreach (string cc in emailMessage.CCEmails.Where(e => e != ""))
                            {
                                // Resolve any possible merge fields in the cc address
                                string ccRecipient = cc.ResolveMergeFields(recipientData.MergeFields, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands);
                                message.CC.Add(new MailAddress(ccRecipient));
                            }

                            // bcc
                            foreach (string bcc in emailMessage.BCCEmails.Where(e => e != ""))
                            {
                                // Resolve any possible merge fields in the cc address
                                string bccRecipient = bcc.ResolveMergeFields(recipientData.MergeFields, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands);
                                message.Bcc.Add(new MailAddress(bccRecipient));
                            }

                            // Subject
                            string subject = ResolveText(emailMessage.Subject, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands, recipientData.MergeFields, emailMessage.AppRoot, emailMessage.ThemeRoot);

                            // Body
                            string body = ResolveText(emailMessage.Message, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands, recipientData.MergeFields, emailMessage.AppRoot, emailMessage.ThemeRoot);
                            body = Regex.Replace(body, @"\[\[\s*UnsubscribeOption\s*\]\]", string.Empty);

                            message.Subject = subject;
                            message.Body    = body;

                            var metaData = new Dictionary <string, string>(emailMessage.MessageMetaData);

                            // If a communicatoin is going to get created, create a guid for tracking the opens/clicks
                            Guid?recipientGuid = null;
                            if (emailMessage.CreateCommunicationRecord)
                            {
                                recipientGuid = Guid.NewGuid();
                                metaData.Add("communication_recipient_guid", recipientGuid.Value.ToString());
                            }

                            using (var rockContext = new RockContext())
                            {
                                // Recreate the attachments
                                message.Attachments.Clear();
                                if (emailMessage.Attachments.Any())
                                {
                                    var binaryFileService = new BinaryFileService(rockContext);
                                    foreach (var binaryFileId in emailMessage.Attachments.Where(a => a != null).Select(a => a.Id))
                                    {
                                        var attachment = binaryFileService.Get(binaryFileId);
                                        if (attachment != null)
                                        {
                                            message.Attachments.Add(new Attachment(attachment.ContentStream, attachment.FileName));
                                        }
                                    }
                                }

                                AddAdditionalHeaders(message, metaData);

                                smtpClient.Send(message);
                            }

                            if (emailMessage.CreateCommunicationRecord)
                            {
                                var transaction = new SaveCommunicationTransaction(recipientData.To, emailMessage.FromName, emailMessage.FromName, subject, body);
                                transaction.RecipientGuid = recipientGuid;
                                RockQueue.TransactionQueue.Enqueue(transaction);
                            }
                        }
                        catch (Exception ex)
                        {
                            errorMessages.Add(ex.Message);
                            ExceptionLogService.LogException(ex);
                        }
                    }
                }
            }

            return(!errorMessages.Any());
        }
        private void BindFamilies(RockContext rockContext, IQueryable <Person> personQry, IQueryable <int> dataviewPersonIdQry)
        {
            var familyGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid());

            var personIds = personQry.Select(p => p.Id);

            var groupMemberQry = new GroupMemberService(rockContext)
                                 .Queryable().AsNoTracking()
                                 .Where(m =>
                                        m.Group.GroupTypeId == familyGroupType.Id &&
                                        personIds.Contains(m.PersonId));

            var familyIdQry = groupMemberQry.Select(m => m.GroupId).Distinct();

            _familyMembers = new GroupService(rockContext)
                             .Queryable().AsNoTracking()
                             .Where(g => familyIdQry.Contains(g.Id))
                             .Select(g => new
            {
                GroupId = g.Id,
                People  = g.Members
                          .Where(m => dataviewPersonIdQry.Contains(m.PersonId))
                          .OrderBy(m => m.GroupRole.Order)
                          .ThenBy(m => m.Person.BirthDate)
                          .Select(m => m.Person)
                          .Select(p => new PersonDirectoryItem
                {
                    Id = p.Id,
                    RecordTypeValueId = p.RecordTypeValueId,
                    NickName          = p.NickName,
                    LastName          = p.LastName,
                    Email             = p.Email,
                    BirthMonth        = p.BirthMonth,
                    BirthDay          = p.BirthDay,
                    BirthDate         = p.BirthDate,
                    DeceasedDate      = p.DeceasedDate,
                    Gender            = p.Gender,
                    PhotoId           = p.PhotoId,
                    GraduationYear    = p.GraduationYear
                })
                          .ToList()
            })
                             .ToDictionary(k => k.GroupId, v => v.People);

            if (_showAddress)
            {
                var homeLoc = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());
                if (familyGroupType != null && homeLoc != null)
                {
                    _addresses = new GroupService(rockContext)
                                 .Queryable().AsNoTracking()
                                 .Where(g => familyIdQry.Contains(g.Id))
                                 .Select(g => new
                    {
                        g.Id,
                        HomeLocations = g.GroupLocations
                                        .Where(gl =>
                                               gl.GroupLocationTypeValueId.HasValue &&
                                               gl.GroupLocationTypeValueId == homeLoc.Id)
                                        .Select(gl => gl.Location)
                                        .ToList()
                    })
                                 .ToDictionary(k => k.Id, v => v.HomeLocations);
                }
            }

            var familyPersonIds = _familyMembers
                                  .SelectMany(m => m.Value)
                                  .Select(p => p.Id)
                                  .Distinct()
                                  .ToList();

            if (_phoneNumberCaptions.Any())
            {
                LoadPhoneNumbers(rockContext, familyPersonIds);
            }

            if (_showEnvelopeNumber && GlobalAttributesCache.Get().EnableGivingEnvelopeNumber)
            {
                LoadEnvelopeNumbers(rockContext, familyPersonIds);
            }

            var families = groupMemberQry.Select(m => new FamilyDirectoryItem
            {
                Id   = m.GroupId,
                Name = m.Group.Name
            })
                           .Distinct()
                           .OrderBy(f => f.Name)
                           .Take(GetAttributeValue(AttributeKey.MaxResults).AsInteger())
                           .ToList();

            rptFamilies.DataSource = families;
            rptFamilies.DataBind();
            rptFamilies.Visible = true;

            rptPeople.Visible = false;
        }
Beispiel #26
0
        /// <summary>
        /// Checks to make sure the sender's email address domain is one from the
        /// SystemGuid.DefinedType.COMMUNICATION_SAFE_SENDER_DOMAINS.  If it is not
        /// it will replace the From address with the one defined by the OrganizationEmail
        /// global attribute.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="globalAttributes">The global attributes.</param>
        private void CheckSafeSender(MailMessage message, GlobalAttributesCache globalAttributes)
        {
            if (message != null && message.From != null)
            {
                string from     = message.From.Address;
                string fromName = message.From.DisplayName;

                // Get the safe sender domains
                var safeDomainValues = DefinedTypeCache.Read(SystemGuid.DefinedType.COMMUNICATION_SAFE_SENDER_DOMAINS.AsGuid()).DefinedValues;
                var safeDomains      = safeDomainValues.Select(v => v.Value).ToList();

                // Check to make sure the From email domain is a safe sender
                var fromParts = from.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
                if (fromParts.Length != 2 || !safeDomains.Contains(fromParts[1], StringComparer.OrdinalIgnoreCase))
                {
                    // The sending email address is not a safe sender domain, but check to see if all the recipients have a domain
                    // that does not require a safe sender domain
                    bool unsafeToDomain = false;
                    foreach (var to in message.To)
                    {
                        bool safe    = false;
                        var  toParts = to.Address.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
                        if (toParts.Length == 2 && safeDomains.Contains(toParts[1], StringComparer.OrdinalIgnoreCase))
                        {
                            var domain = safeDomainValues.FirstOrDefault(dv => dv.Value.Equals(toParts[1], StringComparison.OrdinalIgnoreCase));
                            safe = domain != null && domain.GetAttributeValue("SafeToSendTo").AsBoolean();
                        }

                        if (!safe)
                        {
                            unsafeToDomain = true;
                            break;
                        }
                    }

                    if (unsafeToDomain)
                    {
                        string orgEmail = globalAttributes.GetValue("OrganizationEmail");
                        if (!string.IsNullOrWhiteSpace(orgEmail) && !orgEmail.Equals(from, StringComparison.OrdinalIgnoreCase))
                        {
                            message.From = new MailAddress(orgEmail);

                            bool addReplyTo = true;
                            foreach (var replyTo in message.ReplyToList)
                            {
                                if (replyTo.Address.Equals(from, StringComparison.OrdinalIgnoreCase))
                                {
                                    addReplyTo = false;
                                    break;
                                }
                            }

                            if (addReplyTo)
                            {
                                message.ReplyToList.Add(new MailAddress(from, fromName));
                            }
                        }
                    }
                }
            }
        }
        public IQueryable <Group> GetByLocation(int geofenceGroupTypeId, int groupTypeId,
                                                string street, string city, string state, string postalCode)
        {
            var fenceGroups = new List <Group>();

            string street2 = string.Empty;
            string country = GlobalAttributesCache.Read().OrganizationCountry;

            // Get a new location record for the address
            var rockContext = (RockContext)Service.Context;
            var location    = new LocationService(rockContext).Get(street, street2, city, state, postalCode, country);

            // If address was geocoded succesfully
            if (location.GeoPoint != null)
            {
                // Find all the groupLocation records ( belonging to groups of the "geofenceGroupType" )
                // where the geofence surrounds the location
                var groupLocationService = new GroupLocationService(rockContext);
                foreach (var fenceGroupLocation in groupLocationService
                         .Queryable("Group,Location").AsNoTracking()
                         .Where(gl =>
                                gl.Group.GroupTypeId == geofenceGroupTypeId &&
                                gl.Location.GeoFence != null &&
                                location.GeoPoint.Intersects(gl.Location.GeoFence))
                         .ToList())
                {
                    var fenceGroup = fenceGroups.FirstOrDefault(g => g.Id == fenceGroupLocation.GroupId);
                    if (fenceGroup == null)
                    {
                        fenceGroup = fenceGroupLocation.Group;
                        fenceGroups.Add(fenceGroup);
                    }
                    fenceGroupLocation.Group = null;

                    // Find all the group groupLocation records ( with group of the "groupTypeId" ) that have a location
                    // within the fence
                    var groups = new List <Group>();
                    foreach (var groupLocation in groupLocationService
                             .Queryable("Group,Location").AsNoTracking()
                             .Where(gl =>
                                    gl.Group.GroupTypeId == groupTypeId &&
                                    gl.Location.GeoPoint != null &&
                                    gl.Location.GeoPoint.Intersects(fenceGroupLocation.Location.GeoFence)))
                    {
                        var group = groups.FirstOrDefault(g => g.Id == groupLocation.GroupId);
                        if (group == null)
                        {
                            group = groupLocation.Group;
                            group.LoadAttributes();
                            groups.Add(group);
                        }
                        groupLocation.Group = null;
                    }

                    // Add the group as a child of the fence group
                    groups.ForEach(g => fenceGroup.Groups.Add(g));
                }
            }

            return(fenceGroups.AsQueryable());
        }
Beispiel #28
0
        /// <summary>
        /// Searches the specified query.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="searchType">Type of the search.</param>
        /// <param name="entities">The entities.</param>
        /// <param name="fieldCriteria">The field criteria.</param>
        /// <param name="size">The size.</param>
        /// <param name="from">From.</param>
        /// <param name="totalResultsAvailable">The total results available.</param>
        /// <returns></returns>
        public override List <IndexModelBase> Search(string query, SearchType searchType, List <int> entities, SearchFieldCriteria fieldCriteria, int?size, int?from, out long totalResultsAvailable)
        {
            List <IndexModelBase> documents = new List <IndexModelBase>();

            totalResultsAvailable = 0;

            if (_client != null)
            {
                ISearchResponse <dynamic> results       = null;
                List <SearchResultModel>  searchResults = new List <SearchResultModel>();

                QueryContainer queryContainer = new QueryContainer();

                // add and field constraints
                var searchDescriptor = new SearchDescriptor <dynamic>().AllIndices();

                if (entities == null || entities.Count == 0)
                {
                    searchDescriptor = searchDescriptor.AllTypes();
                }
                else
                {
                    var entityTypes = new List <string>();
                    foreach (var entityId in entities)
                    {
                        // get entities search model name
                        var entityType = new EntityTypeService(new RockContext()).Get(entityId);
                        entityTypes.Add(entityType.IndexModelType.Name.ToLower());

                        // check if this is a person model, if so we need to add two model types one for person and the other for businesses
                        // wish there was a cleaner way to do this
                        if (entityType.Guid == SystemGuid.EntityType.PERSON.AsGuid())
                        {
                            entityTypes.Add("businessindex");
                        }
                    }

                    searchDescriptor = searchDescriptor.Type(string.Join(",", entityTypes));     // todo: consider adding indexmodeltype to the entity cache
                }

                QueryContainer matchQuery = null;
                if (fieldCriteria != null && fieldCriteria.FieldValues?.Count > 0)
                {
                    foreach (var match in fieldCriteria.FieldValues)
                    {
                        if (fieldCriteria.SearchType == CriteriaSearchType.Or)
                        {
                            matchQuery |= new MatchQuery {
                                Field = match.Field, Query = match.Value, Boost = match.Boost
                            };
                        }
                        else
                        {
                            matchQuery &= new MatchQuery {
                                Field = match.Field, Query = match.Value
                            };
                        }
                    }
                }

                switch (searchType)
                {
                case SearchType.ExactMatch:
                {
                    if (!string.IsNullOrWhiteSpace(query))
                    {
                        queryContainer &= new QueryStringQuery {
                            Query = query, AnalyzeWildcard = true
                        };
                    }

                    // special logic to support emails
                    if (query.Contains("@"))
                    {
                        queryContainer |= new QueryStringQuery {
                            Query = "email:" + query, Analyzer = "whitespace"
                        };                                                                                                    // analyzer = whitespace to keep the email from being parsed into 3 variables because the @ will act as a delimitor by default
                    }

                    // special logic to support phone search
                    if (query.IsDigitsOnly())
                    {
                        queryContainer |= new QueryStringQuery {
                            Query = "phone:*" + query + "*", AnalyzeWildcard = true
                        };
                    }

                    // add a search for all the words as one single search term
                    queryContainer |= new QueryStringQuery {
                        Query = query, AnalyzeWildcard = true, PhraseSlop = 0
                    };

                    if (matchQuery != null)
                    {
                        queryContainer &= matchQuery;
                    }

                    if (size.HasValue)
                    {
                        searchDescriptor.Size(size.Value);
                    }

                    if (from.HasValue)
                    {
                        searchDescriptor.From(from.Value);
                    }

                    searchDescriptor.Query(q => queryContainer);

                    results = _client.Search <dynamic>(searchDescriptor);
                    break;
                }

                case SearchType.Fuzzy:
                {
                    results = _client.Search <dynamic>(d =>
                                                       d.AllIndices().AllTypes()
                                                       .Query(q =>
                                                              q.Fuzzy(f => f.Value(query)
                                                                      .Rewrite(RewriteMultiTerm.TopTermsN))
                                                              )
                                                       );
                    break;
                }

                case SearchType.Wildcard:
                {
                    bool enablePhraseSearch = true;

                    if (!string.IsNullOrWhiteSpace(query))
                    {
                        QueryContainer wildcardQuery = null;

                        // break each search term into a separate query and add the * to the end of each
                        var queryTerms = query.Split(' ').Select(p => p.Trim()).ToList();

                        // special logic to support emails
                        if (queryTerms.Count == 1 && query.Contains("@"))
                        {
                            wildcardQuery |= new QueryStringQuery {
                                Query = "email:*" + query + "*", Analyzer = "whitespace"
                            };
                            enablePhraseSearch = false;
                        }
                        else
                        {
                            foreach (var queryTerm in queryTerms)
                            {
                                if (!string.IsNullOrWhiteSpace(queryTerm))
                                {
                                    wildcardQuery &= new QueryStringQuery {
                                        Query = queryTerm + "*", Analyzer = "whitespace", Rewrite = RewriteMultiTerm.ScoringBoolean
                                    };                                                                                                                                             // without the rewrite all results come back with the score of 1; analyzer of whitespaces says don't fancy parse things like check-in to 'check' and 'in'
                                }
                            }

                            // add special logic to help boost last names
                            if (queryTerms.Count > 1)
                            {
                                QueryContainer nameQuery = null;
                                nameQuery &= new QueryStringQuery {
                                    Query = "lastName:" + queryTerms.Last() + "*", Analyzer = "whitespace", Boost = 30
                                };
                                nameQuery &= new QueryStringQuery {
                                    Query = "firstName:" + queryTerms.First() + "*", Analyzer = "whitespace"
                                };
                                wildcardQuery |= nameQuery;
                            }

                            // special logic to support phone search
                            if (query.IsDigitsOnly())
                            {
                                wildcardQuery |= new QueryStringQuery {
                                    Query = "phoneNumbers:*" + query, Analyzer = "whitespace"
                                };
                            }
                        }

                        queryContainer &= wildcardQuery;
                    }

                    // add a search for all the words as one single search term
                    if (enablePhraseSearch)
                    {
                        queryContainer |= new QueryStringQuery {
                            Query = query, AnalyzeWildcard = true, PhraseSlop = 0
                        };
                    }

                    if (matchQuery != null)
                    {
                        queryContainer &= matchQuery;
                    }

                    if (size.HasValue)
                    {
                        searchDescriptor.Size(size.Value);
                    }

                    if (from.HasValue)
                    {
                        searchDescriptor.From(from.Value);
                    }

                    searchDescriptor.Query(q => queryContainer);

                    var indexBoost = GlobalAttributesCache.Value("UniversalSearchIndexBoost");

                    if (indexBoost.IsNotNullOrWhiteSpace())
                    {
                        var boostItems = indexBoost.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var boostItem in boostItems)
                        {
                            var boostParms = boostItem.Split(new char[] { '^' });

                            if (boostParms.Length == 2)
                            {
                                int boost = 1;
                                Int32.TryParse(boostParms[1], out boost);
                                searchDescriptor.IndicesBoost(b => b.Add(boostParms[0], boost));
                            }
                        }
                    }

                    results = _client.Search <dynamic>(searchDescriptor);
                    break;
                }
                }

                totalResultsAvailable = results.Total;

                // normalize the results to rock search results
                if (results != null)
                {
                    foreach (var hit in results.Hits)
                    {
                        IndexModelBase document = new IndexModelBase();

                        try
                        {
                            if (hit.Source != null)
                            {
                                Type indexModelType = Type.GetType($"{ ((string)((JObject)hit.Source)["indexModelType"])}, { ((string)((JObject)hit.Source)["indexModelAssembly"])}");

                                if (indexModelType != null)
                                {
                                    document = (IndexModelBase)((JObject)hit.Source).ToObject(indexModelType);   // return the source document as the derived type
                                }
                                else
                                {
                                    document = ((JObject)hit.Source).ToObject <IndexModelBase>(); // return the source document as the base type
                                }
                            }

                            if (hit.Explanation != null)
                            {
                                document["Explain"] = hit.Explanation.ToJson();
                            }

                            document.Score = hit.Score;

                            documents.Add(document);
                        }
                        catch { } // ignore if the result if an exception resulted (most likely cause is getting a result from a non-rock index)
                    }
                }
            }

            return(documents);
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var contributionType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid());

            if (contributionType != null)
            {
                var rockContext = new RockContext();
                var transactionDetailService = new FinancialTransactionDetailService(rockContext);
                var qry = transactionDetailService.Queryable().AsNoTracking()
                          .Where(a =>
                                 a.Transaction.TransactionTypeValueId == contributionType.Id &&
                                 a.Transaction.TransactionDateTime.HasValue);

                var targetPerson = this.ContextEntity <Person>();
                if (targetPerson != null)
                {
                    qry = qry.Where(t => t.Transaction.AuthorizedPersonAlias.Person.GivingId == targetPerson.GivingId);
                }

                List <SummaryRecord> summaryList;

                using (new Rock.Data.QueryHintScope(rockContext, QueryHintType.RECOMPILE))
                {
                    summaryList = qry
                                  .GroupBy(a => new { a.Transaction.TransactionDateTime.Value.Year, a.AccountId })
                                  .Select(t => new SummaryRecord
                    {
                        Year        = t.Key.Year,
                        AccountId   = t.Key.AccountId,
                        TotalAmount = t.Sum(d => d.Amount)
                    }).OrderByDescending(a => a.Year)
                                  .ToList();
                }

                var mergeObjects      = GlobalAttributesCache.GetMergeFields(this.CurrentPerson);
                var financialAccounts = new FinancialAccountService(rockContext).Queryable().Select(a => new { a.Id, a.Name }).ToDictionary(k => k.Id, v => v.Name);

                var yearsMergeObjects = new List <Dictionary <string, object> >();
                foreach (var item in summaryList.GroupBy(a => a.Year))
                {
                    var year         = item.Key;
                    var accountsList = new List <object>();
                    foreach (var a in item)
                    {
                        var accountDictionary = new Dictionary <string, object>();
                        accountDictionary.Add("Account", financialAccounts.ContainsKey(a.AccountId) ? financialAccounts[a.AccountId] : string.Empty);
                        accountDictionary.Add("TotalAmount", a.TotalAmount);
                        accountsList.Add(accountDictionary);
                    }

                    var yearDictionary = new Dictionary <string, object>();
                    yearDictionary.Add("Year", year);
                    yearDictionary.Add("SummaryRows", accountsList);

                    yearsMergeObjects.Add(yearDictionary);
                }

                mergeObjects.Add("Rows", yearsMergeObjects);

                lLavaOutput.Text = string.Empty;
                if (GetAttributeValue("EnableDebug").AsBooleanOrNull().GetValueOrDefault(false))
                {
                    lLavaOutput.Text = mergeObjects.lavaDebugInfo(rockContext);
                }

                string template = GetAttributeValue("LavaTemplate");

                lLavaOutput.Text += template.ResolveMergeFields(mergeObjects).ResolveClientIds(upnlContent.ClientID);
            }
        }
Beispiel #30
0
        /// <summary>
        /// Sends the specified template.
        /// </summary>
        /// <param name="template">The template.</param>
        /// <param name="recipients">The recipients.</param>
        /// <param name="appRoot">The application root.</param>
        /// <param name="themeRoot">The theme root.</param>
        /// <param name="createCommunicationHistory">if set to <c>true</c> [create communication history].</param>
        public void Send(SystemEmail template, List <RecipientData> recipients, string appRoot, string themeRoot, bool createCommunicationHistory)
        {
            var globalAttributes = GlobalAttributesCache.Read();

            string from = template.From;

            if (string.IsNullOrWhiteSpace(from))
            {
                from = globalAttributes.GetValue("OrganizationEmail");
            }

            string fromName = template.FromName;

            if (string.IsNullOrWhiteSpace(fromName))
            {
                fromName = globalAttributes.GetValue("OrganizationName");
            }

            if (!string.IsNullOrWhiteSpace(from))
            {
                // Resolve any possible merge fields in the from address
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                from     = from.ResolveMergeFields(mergeFields);
                fromName = fromName.ResolveMergeFields(mergeFields);

                MailMessage message = new MailMessage();
                if (string.IsNullOrWhiteSpace(fromName))
                {
                    message.From = new MailAddress(from);
                }
                else
                {
                    message.From = new MailAddress(from, fromName);
                }

                CheckSafeSender(message, globalAttributes);

                if (!string.IsNullOrWhiteSpace(template.Cc))
                {
                    foreach (string ccRecipient in template.Cc.SplitDelimitedValues())
                    {
                        message.CC.Add(new MailAddress(ccRecipient));
                    }
                }

                if (!string.IsNullOrWhiteSpace(template.Bcc))
                {
                    foreach (string ccRecipient in template.Bcc.SplitDelimitedValues())
                    {
                        message.Bcc.Add(new MailAddress(ccRecipient));
                    }
                }

                message.IsBodyHtml = true;
                message.Priority   = MailPriority.Normal;

                using (var smtpClient = GetSmtpClient())
                {
                    foreach (var recipientData in recipients)
                    {
                        foreach (var g in mergeFields)
                        {
                            if (recipientData.MergeFields.ContainsKey(g.Key))
                            {
                                recipientData.MergeFields[g.Key] = g.Value;
                            }
                        }

                        // Add the recipients from the template
                        List <string> sendTo = SplitRecipient(template.To);

                        // Add the recipient from merge data ( if it's not null and not already added )
                        if (!string.IsNullOrWhiteSpace(recipientData.To) && !sendTo.Contains(recipientData.To, StringComparer.OrdinalIgnoreCase))
                        {
                            sendTo.Add(recipientData.To);
                        }

                        foreach (string to in sendTo)
                        {
                            message.To.Clear();
                            message.To.Add(to);

                            message.Headers.Clear();

                            string subject = template.Subject.ResolveMergeFields(recipientData.MergeFields);
                            string body    = Regex.Replace(template.Body.ResolveMergeFields(recipientData.MergeFields), @"\[\[\s*UnsubscribeOption\s*\]\]", string.Empty);

                            if (!string.IsNullOrWhiteSpace(themeRoot))
                            {
                                subject = subject.Replace("~~/", themeRoot);
                                body    = body.Replace("~~/", themeRoot);
                            }

                            if (!string.IsNullOrWhiteSpace(appRoot))
                            {
                                subject = subject.Replace("~/", appRoot);
                                body    = body.Replace("~/", appRoot);
                                body    = body.Replace(@" src=""/", @" src=""" + appRoot);
                                body    = body.Replace(@" src='/", @" src='" + appRoot);
                                body    = body.Replace(@" href=""/", @" href=""" + appRoot);
                                body    = body.Replace(@" href='/", @" href='" + appRoot);
                            }

                            message.Subject = subject;
                            message.Body    = body;

                            AddAdditionalHeaders(message, null);

                            smtpClient.Send(message);

                            if (createCommunicationHistory)
                            {
                                var transaction = new SaveCommunicationTransaction(
                                    to, fromName, from, subject, body);
                                RockQueue.TransactionQueue.Enqueue(transaction);
                            }
                        }
                    }
                }
            }
        }