public async Task <ActionResult <StringResult> > Submit([FromBody] StlSearchRequest request)
        {
            var template = string.Empty;

            try
            {
                var form = GetPostCollection(request);

                template = _settingsManager.Decrypt(request.Template);
                var pageIndex = request.Page - 1;
                if (pageIndex < 0)
                {
                    pageIndex = 0;
                }

                var templateInfo = new Template
                {
                    Id                  = 0,
                    SiteId              = request.SiteId,
                    TemplateName        = string.Empty,
                    TemplateType        = TemplateType.FileTemplate,
                    RelatedFileName     = string.Empty,
                    CreatedFileFullName = string.Empty,
                    CreatedFileExtName  = string.Empty,
                    DefaultTemplate     = false
                };
                var site = await _siteRepository.GetAsync(request.SiteId);

                await _parseManager.InitAsync(EditMode.Default, site, request.SiteId, 0, templateInfo);

                _parseManager.PageInfo.User = await _authManager.GetUserAsync();

                var contentBuilder = new StringBuilder(StlRequest.ParseRequestEntities(form, template));

                var stlLabelList = StlParserUtility.GetStlLabelList(contentBuilder.ToString());

                if (StlParserUtility.IsStlElementExists(StlPageContents.ElementName, stlLabelList))
                {
                    var stlElement             = StlParserUtility.GetStlElement(StlPageContents.ElementName, stlLabelList);
                    var stlPageContentsElement = stlElement;
                    var stlPageContentsElementReplaceString = stlElement;

                    var query = await _contentRepository.GetQueryByStlSearchAsync(_databaseManager, request.IsAllSites, request.SiteName, request.SiteDir, request.SiteIds, request.ChannelIndex, request.ChannelName, request.ChannelIds, request.Type, request.Word, request.DateAttribute, request.DateFrom, request.DateTo, request.Since, request.SiteId, StlSearch.GetSearchExcludeAttributeNames, form);

                    var stlPageContents = await StlPageContents.GetByStlSearchAsync(stlPageContentsElement, _parseManager, request.PageNum, query);

                    var(pageCount, totalNum) = stlPageContents.GetPageCount();
                    if (totalNum == 0)
                    {
                        return(NotFound());
                    }

                    for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                    {
                        if (currentPageIndex != pageIndex)
                        {
                            continue;
                        }

                        var pageHtml = await stlPageContents.ParseAsync(totalNum, currentPageIndex, pageCount, false);

                        var pagedBuilder = new StringBuilder(contentBuilder.ToString().Replace(stlPageContentsElementReplaceString, pageHtml));

                        await _parseManager.ReplacePageElementsInSearchPageAsync(pagedBuilder, stlLabelList, request.AjaxDivId, currentPageIndex, pageCount, totalNum);

                        if (request.IsHighlight && !string.IsNullOrEmpty(request.Word))
                        {
                            var pagedContents = pagedBuilder.ToString();
                            pagedBuilder = new StringBuilder();
                            pagedBuilder.Append(RegexUtils.Replace(
                                                    $"({request.Word.Replace(" ", "\\s")})(?!</a>)(?![^><]*>)", pagedContents,
                                                    $"<span style='color:#cc0000'>{request.Word}</span>"));
                        }

                        await _parseManager.ParseAsync(pagedBuilder, string.Empty, false);

                        return(new StringResult
                        {
                            Value = pagedBuilder.ToString()
                        });
                    }
                }
                else if (StlParserUtility.IsStlElementExists(StlPageSqlContents.ElementName, stlLabelList))
                {
                    var stlElement = StlParserUtility.GetStlElement(StlPageSqlContents.ElementName, stlLabelList);

                    var stlPageSqlContents = await StlPageSqlContents.GetAsync(stlElement, _parseManager);

                    var pageCount = stlPageSqlContents.GetPageCount(out var totalNum);
                    if (totalNum == 0)
                    {
                        return(NotFound());
                    }

                    for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                    {
                        if (currentPageIndex != pageIndex)
                        {
                            continue;
                        }

                        var pageHtml = await stlPageSqlContents.ParseAsync(totalNum, currentPageIndex, pageCount, false);

                        var pagedBuilder = new StringBuilder(contentBuilder.ToString().Replace(stlElement, pageHtml));

                        await _parseManager.ReplacePageElementsInSearchPageAsync(pagedBuilder, stlLabelList, request.AjaxDivId, currentPageIndex, pageCount, totalNum);

                        if (request.IsHighlight && !string.IsNullOrEmpty(request.Word))
                        {
                            var pagedContents = pagedBuilder.ToString();
                            pagedBuilder = new StringBuilder();
                            pagedBuilder.Append(RegexUtils.Replace(
                                                    $"({request.Word.Replace(" ", "\\s")})(?!</a>)(?![^><]*>)", pagedContents,
                                                    $"<span style='color:#cc0000'>{request.Word}</span>"));
                        }

                        await _parseManager.ParseAsync(pagedBuilder, string.Empty, false);

                        return(new StringResult
                        {
                            Value = pagedBuilder.ToString()
                        });
                    }
                }

                await _parseManager.ParseAsync(contentBuilder, string.Empty, false);

                return(new StringResult
                {
                    Value = contentBuilder.ToString()
                });
            }
            catch (Exception ex)
            {
                var message = await _parseManager.AddStlErrorLogAsync(StlSearch.ElementName, template, ex);

                return(this.Error(message));
            }
        }
Example #2
0
 public void IsValidRegexOk1()
 {
     Assert.IsTrue(RegexUtils.IsValidRegex(@"^(?![\s\S])"));
 }
Example #3
0
 public void IsValidRegexBad1()
 {
     Assert.IsFalse(RegexUtils.IsValidRegex(@"[\s\S(\()()(()\)"));
 }
Example #4
0
        private async Task <string> ParseContentPathAsync(Site site, int channelId, Content content, string contentFilePathRule)
        {
            var filePath  = contentFilePathRule.Trim();
            var regex     = "(?<element>{@[^}]+})";
            var elements  = RegexUtils.GetContents("element", regex, filePath);
            var addDate   = content.AddDate;
            var contentId = content.Id;

            foreach (var element in elements)
            {
                var value = string.Empty;

                if (StringUtils.EqualsIgnoreCase(element, ChannelId))
                {
                    value = channelId.ToString();
                }
                else if (StringUtils.EqualsIgnoreCase(element, ContentId))
                {
                    value = contentId.ToString();
                }
                else if (StringUtils.EqualsIgnoreCase(element, Sequence))
                {
                    var tableName = await _databaseManager.ChannelRepository.GetTableNameAsync(site, channelId);

                    value = Convert.ToString(await _databaseManager.ContentRepository.GetSequenceAsync(tableName, site.Id, channelId, contentId));
                }
                else if (StringUtils.EqualsIgnoreCase(element, ParentRule))
                {
                    var nodeInfo = await _databaseManager.ChannelRepository.GetAsync(channelId);

                    var parentInfo = await _databaseManager.ChannelRepository.GetAsync(nodeInfo.ParentId);

                    if (parentInfo != null)
                    {
                        var parentRule = await _pathManager.GetContentFilePathRuleAsync(site, parentInfo.Id);

                        value = DirectoryUtils.GetDirectoryPath(await ParseContentPathAsync(site, parentInfo.Id, content, parentRule)).Replace("\\", "/");
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(element, ChannelName))
                {
                    var nodeInfo = await _databaseManager.ChannelRepository.GetAsync(channelId);

                    if (nodeInfo != null)
                    {
                        value = nodeInfo.ChannelName;
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(element, LowerChannelName))
                {
                    var nodeInfo = await _databaseManager.ChannelRepository.GetAsync(channelId);

                    if (nodeInfo != null)
                    {
                        value = StringUtils.ToLower(nodeInfo.ChannelName);
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(element, ChannelIndex))
                {
                    var nodeInfo = await _databaseManager.ChannelRepository.GetAsync(channelId);

                    if (nodeInfo != null)
                    {
                        value = nodeInfo.IndexName;
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(element, LowerChannelIndex))
                {
                    var nodeInfo = await _databaseManager.ChannelRepository.GetAsync(channelId);

                    if (nodeInfo != null)
                    {
                        value = StringUtils.ToLower(nodeInfo.IndexName);
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(element, Year) || StringUtils.EqualsIgnoreCase(element, Month) || StringUtils.EqualsIgnoreCase(element, Day) || StringUtils.EqualsIgnoreCase(element, Hour) || StringUtils.EqualsIgnoreCase(element, Minute) || StringUtils.EqualsIgnoreCase(element, Second))
                {
                    if (StringUtils.EqualsIgnoreCase(element, Year))
                    {
                        if (addDate.HasValue)
                        {
                            value = addDate.Value.Year.ToString();
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, Month))
                    {
                        if (addDate.HasValue)
                        {
                            value = addDate.Value.Month.ToString("D2");
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, Day))
                    {
                        if (addDate.HasValue)
                        {
                            value = addDate.Value.Day.ToString("D2");
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, Hour))
                    {
                        if (addDate.HasValue)
                        {
                            value = addDate.Value.Hour.ToString();
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, Minute))
                    {
                        if (addDate.HasValue)
                        {
                            value = addDate.Value.Minute.ToString();
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, Second))
                    {
                        if (addDate.HasValue)
                        {
                            value = addDate.Value.Second.ToString();
                        }
                    }
                }
                else
                {
                    var attributeName = element.Replace("{@", string.Empty).Replace("}", string.Empty);

                    var isLower = false;
                    if (StringUtils.StartsWithIgnoreCase(attributeName, "lower"))
                    {
                        isLower       = true;
                        attributeName = attributeName.Substring(5);
                    }

                    value = content.Get <string>(attributeName);
                    if (isLower)
                    {
                        value = StringUtils.ToLower(value);
                    }
                }

                value = StringUtils.HtmlDecode(value);

                filePath = filePath.Replace(element, value);
            }

            if (filePath.Contains("//"))
            {
                filePath = Regex.Replace(filePath, @"(/)\1{2,}", "/");
                filePath = filePath.Replace("//", "/");
            }

            if (filePath.Contains("("))
            {
                regex    = @"(?<element>\([^\)]+\))";
                elements = RegexUtils.GetContents("element", regex, filePath);
                foreach (var element in elements)
                {
                    if (!element.Contains("|"))
                    {
                        continue;
                    }

                    var value  = element.Replace("(", string.Empty).Replace(")", string.Empty);
                    var value1 = value.Split('|')[0];
                    var value2 = value.Split('|')[1];
                    value = value1 + value2;

                    if (!string.IsNullOrEmpty(value1) && !string.IsNullOrEmpty(value1))
                    {
                        value = value1;
                    }

                    filePath = filePath.Replace(element, value);
                }
            }
            return(filePath);
        }
Example #5
0
        //NOTE - While making modifications in this method, developer must refer to call tree in Register.ascx.cs.
        //Especially Validate and CreateUser methods. Register class inherits from UserModuleBase, which also contains bunch of logic.
        //This method can easily be modified to pass passowrd, display name, etc.
        //It is recommended to write unit tests.
        public UserBasicDto Register(RegisterationDetails registerationDetails)
        {
            var portalSettings = registerationDetails.PortalSettings;
            var username       = registerationDetails.UserName;
            var email          = registerationDetails.Email;

            Requires.NotNullOrEmpty("email", email);

            var disallowRegistration = !registerationDetails.IgnoreRegistrationMode &&
                                       ((portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration) ||
                                        (portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration));

            if (disallowRegistration)
            {
                throw new Exception(Localization.GetString("RegistrationNotAllowed", Library.Constants.SharedResources));
            }

            //initial creation of the new User object
            var newUser = new UserInfo
            {
                PortalID = portalSettings.PortalId,
                Email    = email
            };

            var cleanUsername = PortalSecurity.Instance.InputFilter(username,
                                                                    PortalSecurity.FilterFlag.NoScripting |
                                                                    PortalSecurity.FilterFlag.NoAngleBrackets |
                                                                    PortalSecurity.FilterFlag.NoMarkup);

            if (!cleanUsername.Equals(username))
            {
                throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid."));
            }

            var valid = UserController.Instance.IsValidUserName(username);

            if (!valid)
            {
                throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid."));
            }

            //ensure this user doesn't exist
            if (!string.IsNullOrEmpty(username) && UserController.GetUserByName(portalSettings.PortalId, username) != null)
            {
                throw new Exception(Localization.GetString("RegistrationUsernameAlreadyPresent",
                                                           Library.Constants.SharedResources));
            }

            //set username as email if not specified
            newUser.Username = string.IsNullOrEmpty(username) ? email : username;

            if (!string.IsNullOrEmpty(registerationDetails.Password) && !registerationDetails.RandomPassword)
            {
                newUser.Membership.Password = registerationDetails.Password;
            }
            else
            {
                //Generate a random password for the user
                newUser.Membership.Password = UserController.GeneratePassword();
            }

            newUser.Membership.PasswordConfirm = newUser.Membership.Password;

            //set other profile properties
            newUser.Profile.PreferredLocale = new Localization().CurrentUICulture;
            newUser.Profile.InitialiseProfile(portalSettings.PortalId);
            newUser.Profile.PreferredTimeZone = portalSettings.TimeZone;

            //derive display name from supplied firstname, lastname or from email
            if (!string.IsNullOrEmpty(registerationDetails.FirstName) &&
                !string.IsNullOrEmpty(registerationDetails.LastName))
            {
                newUser.DisplayName = registerationDetails.FirstName + " " + registerationDetails.LastName;
                newUser.FirstName   = registerationDetails.FirstName;
                newUser.LastName    = registerationDetails.LastName;
            }
            else
            {
                newUser.DisplayName = newUser.Email.Substring(0, newUser.Email.IndexOf("@", StringComparison.Ordinal));
            }

            //read all the user account settings
            var settings = UserController.GetUserSettings(portalSettings.PortalId);

            //Verify Profanity filter
            if (GetBoolSetting(settings, "Registration_UseProfanityFilter"))
            {
                var portalSecurity = PortalSecurity.Instance;
                if (!portalSecurity.ValidateInput(newUser.Username, PortalSecurity.FilterFlag.NoProfanity) || !portalSecurity.ValidateInput(newUser.DisplayName, PortalSecurity.FilterFlag.NoProfanity))
                {
                    throw new Exception(Localization.GetString("RegistrationProfanityNotAllowed",
                                                               Library.Constants.SharedResources));
                }
            }

            //Email Address Validation
            var emailValidator = GetStringSetting(settings, "Security_EmailValidation");

            if (!string.IsNullOrEmpty(emailValidator))
            {
                var regExp  = RegexUtils.GetCachedRegex(emailValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                var matches = regExp.Matches(newUser.Email);
                if (matches.Count == 0)
                {
                    throw new Exception(Localization.GetString("RegistrationInvalidEmailUsed",
                                                               Library.Constants.SharedResources));
                }
            }

            //Excluded Terms Verification
            var excludeRegex = GetExcludeTermsRegex(settings);

            if (!string.IsNullOrEmpty(excludeRegex))
            {
                var regExp  = RegexUtils.GetCachedRegex(excludeRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                var matches = regExp.Matches(newUser.Username);
                if (matches.Count > 0)
                {
                    throw new Exception(Localization.GetString("RegistrationExcludedTermsUsed",
                                                               Library.Constants.SharedResources));
                }
            }

            //User Name Validation
            var userNameValidator = GetStringSetting(settings, "Security_UserNameValidation");

            if (!string.IsNullOrEmpty(userNameValidator))
            {
                var regExp  = RegexUtils.GetCachedRegex(userNameValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                var matches = regExp.Matches(newUser.Username);
                if (matches.Count == 0)
                {
                    throw new Exception(Localization.GetString("RegistrationInvalidUserNameUsed",
                                                               Library.Constants.SharedResources));
                }
            }

            //ensure unique username
            var user = UserController.GetUserByName(portalSettings.PortalId, newUser.Username);

            if (user != null)
            {
                if (GetBoolSetting(settings, "Registration_UseEmailAsUserName"))
                {
                    throw new Exception(UserController.GetUserCreateStatus(UserCreateStatus.DuplicateEmail));
                }

                var    i        = 1;
                string userName = null;
                while (user != null)
                {
                    userName = newUser.Username + "0" + i.ToString(CultureInfo.InvariantCulture);
                    user     = UserController.GetUserByName(portalSettings.PortalId, userName);
                    i++;
                }
                newUser.Username = userName;
            }

            //ensure unique display name
            if (GetBoolSetting(settings, "Registration_RequireUniqueDisplayName"))
            {
                user = UserController.Instance.GetUserByDisplayname(portalSettings.PortalId, newUser.DisplayName);
                if (user != null)
                {
                    var    i           = 1;
                    string displayName = null;
                    while (user != null)
                    {
                        displayName = newUser.DisplayName + " 0" + i.ToString(CultureInfo.InvariantCulture);
                        user        = UserController.Instance.GetUserByDisplayname(portalSettings.PortalId, displayName);
                        i++;
                    }
                    newUser.DisplayName = displayName;
                }
            }

            //Update display name format
            var displaynameFormat = GetStringSetting(settings, "Security_DisplayNameFormat");

            if (!string.IsNullOrEmpty(displaynameFormat))
            {
                newUser.UpdateDisplayName(displaynameFormat);
            }

            //membership is approved only for public registration
            newUser.Membership.Approved =
                (registerationDetails.IgnoreRegistrationMode ||
                 portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PublicRegistration) && registerationDetails.Authorize;
            newUser.Membership.PasswordQuestion = registerationDetails.Question;
            newUser.Membership.PasswordAnswer   = registerationDetails.Answer;
            //final creation of user
            var createStatus = UserController.CreateUser(ref newUser, registerationDetails.Notify);

            //clear cache
            if (createStatus == UserCreateStatus.Success)
            {
                CachingProvider.Instance().Remove(string.Format(DataCache.PortalUserCountCacheKey, portalSettings.PortalId));
            }

            if (createStatus != UserCreateStatus.Success)
            {
                throw new Exception(UserController.GetUserCreateStatus(createStatus));
            }

//            if (registerationDetails.IgnoreRegistrationMode)
//            {
//                Mail.SendMail(newUser, MessageType.UserRegistrationPublic, portalSettings);
//                return UserBasicDto.FromUserInfo(newUser);
//            }

            //send notification to portal administrator of new user registration
            //check the receive notification setting first, but if register type is Private, we will always send the notification email.
            //because the user need administrators to do the approve action so that he can continue use the website.
            if (!registerationDetails.IgnoreRegistrationMode &&
                (portalSettings.EnableRegisterNotification || portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration))
            {
                Mail.SendMail(newUser, MessageType.UserRegistrationAdmin, portalSettings);
                SendAdminNotification(newUser, portalSettings);
            }

            return(UserBasicDto.FromUserInfo(newUser));
        }
Example #6
0
 public void GetMethodPropertyMemberFullNameRegexMatchAsExpected()
 {
     Assert.Equal(_autoPropertyMember.Name,
                  RegexUtils.MatchGetPropertyName(_expectedGetMethodFullName));
 }
Example #7
0
 public void SetMethodPropertyMemberRegexMatchAsExpected()
 {
     Assert.Equal(_autoPropertyMember.Name,
                  RegexUtils.MatchSetPropertyName(_expectedSetMethodName));
 }
Example #8
0
        public PartRule()
        {
            var prefixes = new[]  {
                "pt",
                "part"
            };

            RB = new ReBulk(name: "part").Options(RegexOptions.IgnoreCase)
                 .Regex(RegexUtils.BuildOrPattern(prefixes, "prefixes") + @"-?(?<part>" + RegexUtils.BuildOrPattern(new[] { Regexes.digital_numeral, Regexes.roman_numeral }, "partnumber") + @")")
                 .Then(x => IsNumeric(x));
        }
Example #9
0
 //判断属于某种类型(type)的<stl:channel>元素是否存在
 public static bool IsStlChannelElement(string labelString, string type)
 {
     return(RegexUtils.IsMatch($@"<stl:channel[^>]+type=""{type}""[^>]*>", labelString));
 }
Example #10
0
            //递归处理
            private static string ParseChannelPath(SiteInfo siteInfo, int channelId, string channelFilePathRule)
            {
                var          filePath = channelFilePathRule.Trim();
                const string regex    = "(?<element>{@[^}]+})";
                var          elements = RegexUtils.GetContents("element", regex, filePath);
                ChannelInfo  nodeInfo = null;

                foreach (var element in elements)
                {
                    var value = string.Empty;

                    if (StringUtils.EqualsIgnoreCase(element, ChannelId))
                    {
                        value = channelId.ToString();
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, Year))
                    {
                        if (nodeInfo == null)
                        {
                            nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        }
                        value = nodeInfo.AddDate.Year.ToString();
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, Month))
                    {
                        if (nodeInfo == null)
                        {
                            nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        }
                        value = nodeInfo.AddDate.Month.ToString();
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, Day))
                    {
                        if (nodeInfo == null)
                        {
                            nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        }
                        value = nodeInfo.AddDate.Day.ToString();
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, Hour))
                    {
                        if (nodeInfo == null)
                        {
                            nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        }
                        value = nodeInfo.AddDate.Hour.ToString();
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, Minute))
                    {
                        if (nodeInfo == null)
                        {
                            nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        }
                        value = nodeInfo.AddDate.Minute.ToString();
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, Second))
                    {
                        if (nodeInfo == null)
                        {
                            nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        }
                        value = nodeInfo.AddDate.Second.ToString();
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, Sequence))
                    {
                        value = StlChannelCache.GetSequence(siteInfo.Id, channelId).ToString();
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, ParentRule))
                    {
                        if (nodeInfo == null)
                        {
                            nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        }
                        var parentInfo = ChannelManager.GetChannelInfo(siteInfo.Id, nodeInfo.ParentId);
                        if (parentInfo != null)
                        {
                            var parentRule = GetChannelFilePathRule(siteInfo, parentInfo.Id);
                            value = DirectoryUtils.GetDirectoryPath(ParseChannelPath(siteInfo, parentInfo.Id, parentRule)).Replace("\\", "/");
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, ChannelName))
                    {
                        if (nodeInfo == null)
                        {
                            nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        }
                        value = nodeInfo.ChannelName;
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, LowerChannelName))
                    {
                        if (nodeInfo == null)
                        {
                            nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        }
                        value = nodeInfo.ChannelName.ToLower();
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, LowerChannelIndex))
                    {
                        if (nodeInfo == null)
                        {
                            nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        }
                        value = nodeInfo.IndexName.ToLower();
                    }
                    else
                    {
                        if (nodeInfo == null)
                        {
                            nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        }
                        var attributeName = element.Replace("{@", string.Empty).Replace("}", string.Empty);

                        var isLower = false;
                        if (StringUtils.StartsWithIgnoreCase(attributeName, "lower"))
                        {
                            isLower       = true;
                            attributeName = attributeName.Substring(5);
                        }

                        value = nodeInfo.Additional.GetString(attributeName);

                        if (isLower)
                        {
                            value = value.ToLower();
                        }
                    }

                    filePath = filePath.Replace(element, value);
                }

                if (!filePath.Contains("//"))
                {
                    return(filePath);
                }

                filePath = Regex.Replace(filePath, @"(/)\1{2,}", "/");
                filePath = Regex.Replace(filePath, @"//", "/");
                return(filePath);
            }
Example #11
0
            private static string ParseContentPath(SiteInfo siteInfo, int channelId, IContentInfo contentInfo, string contentFilePathRule)
            {
                var filePath  = contentFilePathRule.Trim();
                var regex     = "(?<element>{@[^}]+})";
                var elements  = RegexUtils.GetContents("element", regex, filePath);
                var addDate   = contentInfo.AddDate;
                var contentId = contentInfo.Id;

                foreach (var element in elements)
                {
                    var value = string.Empty;

                    if (StringUtils.EqualsIgnoreCase(element, ChannelId))
                    {
                        value = channelId.ToString();
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, ContentId))
                    {
                        value = contentId.ToString();
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, Sequence))
                    {
                        var tableName = ChannelManager.GetTableName(siteInfo, channelId);
                        value = StlContentCache.GetSequence(tableName, channelId, contentId).ToString();
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, ParentRule))//继承父级设置 20151113 sessionliang
                    {
                        var nodeInfo   = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        var parentInfo = ChannelManager.GetChannelInfo(siteInfo.Id, nodeInfo.ParentId);
                        if (parentInfo != null)
                        {
                            var parentRule = GetContentFilePathRule(siteInfo, parentInfo.Id);
                            value = DirectoryUtils.GetDirectoryPath(ParseContentPath(siteInfo, parentInfo.Id, contentInfo, parentRule)).Replace("\\", "/");
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, ChannelName))
                    {
                        var nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        if (nodeInfo != null)
                        {
                            value = nodeInfo.ChannelName;
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, LowerChannelName))
                    {
                        var nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        if (nodeInfo != null)
                        {
                            value = nodeInfo.ChannelName.ToLower();
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, ChannelIndex))
                    {
                        var nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        if (nodeInfo != null)
                        {
                            value = nodeInfo.IndexName;
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, LowerChannelIndex))
                    {
                        var nodeInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId);
                        if (nodeInfo != null)
                        {
                            value = nodeInfo.IndexName.ToLower();
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(element, Year) || StringUtils.EqualsIgnoreCase(element, Month) || StringUtils.EqualsIgnoreCase(element, Day) || StringUtils.EqualsIgnoreCase(element, Hour) || StringUtils.EqualsIgnoreCase(element, Minute) || StringUtils.EqualsIgnoreCase(element, Second))
                    {
                        if (StringUtils.EqualsIgnoreCase(element, Year))
                        {
                            value = addDate.Year.ToString();
                        }
                        else if (StringUtils.EqualsIgnoreCase(element, Month))
                        {
                            value = addDate.Month.ToString("D2");
                            //value = addDate.ToString("MM");
                        }
                        else if (StringUtils.EqualsIgnoreCase(element, Day))
                        {
                            value = addDate.Day.ToString("D2");
                            //value = addDate.ToString("dd");
                        }
                        else if (StringUtils.EqualsIgnoreCase(element, Hour))
                        {
                            value = addDate.Hour.ToString();
                        }
                        else if (StringUtils.EqualsIgnoreCase(element, Minute))
                        {
                            value = addDate.Minute.ToString();
                        }
                        else if (StringUtils.EqualsIgnoreCase(element, Second))
                        {
                            value = addDate.Second.ToString();
                        }
                    }
                    else
                    {
                        var attributeName = element.Replace("{@", string.Empty).Replace("}", string.Empty);

                        var isLower = false;
                        if (StringUtils.StartsWithIgnoreCase(attributeName, "lower"))
                        {
                            isLower       = true;
                            attributeName = attributeName.Substring(5);
                        }

                        value = contentInfo.GetString(attributeName);
                        if (isLower)
                        {
                            value = value.ToLower();
                        }
                    }

                    value = StringUtils.HtmlDecode(value);

                    filePath = filePath.Replace(element, value);
                }

                if (filePath.Contains("//"))
                {
                    filePath = Regex.Replace(filePath, @"(/)\1{2,}", "/");
                    filePath = filePath.Replace("//", "/");
                }

                if (filePath.Contains("("))
                {
                    regex    = @"(?<element>\([^\)]+\))";
                    elements = RegexUtils.GetContents("element", regex, filePath);
                    foreach (var element in elements)
                    {
                        if (!element.Contains("|"))
                        {
                            continue;
                        }

                        var value  = element.Replace("(", string.Empty).Replace(")", string.Empty);
                        var value1 = value.Split('|')[0];
                        var value2 = value.Split('|')[1];
                        value = value1 + value2;

                        if (!string.IsNullOrEmpty(value1) && !string.IsNullOrEmpty(value1))
                        {
                            value = value1;
                        }

                        filePath = filePath.Replace(element, value);
                    }
                }
                return(filePath);
            }
Example #12
0
        /// <summary>
        /// This method checks the list of rules for parameter replacement and modifies the parameter path accordingly
        /// </summary>
        /// <param name="parameterPath"></param>
        /// <param name="tab"></param>
        /// <param name="settings"></param>
        /// <param name="portalId"></param>
        /// <param name="replacedPath"></param>
        /// <param name="messages"></param>
        /// <param name="changeToSiteRoot"></param>
        /// <param name="parentTraceId"></param>
        /// <returns></returns>
        internal static bool CheckParameterRegexReplacement(string parameterPath,
                                                            TabInfo tab,
                                                            FriendlyUrlSettings settings,
                                                            int portalId,
                                                            out string replacedPath,
                                                            ref List <string> messages,
                                                            out bool changeToSiteRoot,
                                                            Guid parentTraceId)
        {
            bool replaced = false;

            replacedPath     = "";
            changeToSiteRoot = false;
            if (messages == null)
            {
                messages = new List <string>();
            }

            var replaceActions = CacheController.GetParameterReplacements(settings, portalId, ref messages);

            if (replaceActions != null && replaceActions.Count > 0)
            {
                List <ParameterReplaceAction> parmReplaces = null;
                int tabId = tab.TabID;

                if (replaceActions.ContainsKey(tabId))
                {
                    //find the right set of replaced actions for this tab
                    parmReplaces = replaceActions[tabId];
                }

                //check for 'all tabs' replaceions
                if (replaceActions.ContainsKey(-1)) //-1 means 'all tabs' - replacing across all tabs
                {
                    //initialise to empty collection if there are no specific tab replaces
                    if (parmReplaces == null)
                    {
                        parmReplaces = new List <ParameterReplaceAction>();
                    }
                    //add in the all replaces
                    List <ParameterReplaceAction> allReplaces = replaceActions[-1];
                    parmReplaces.AddRange(allReplaces); //add the 'all' range to the tab range
                }
                if (parmReplaces != null)
                {
                    //OK what we have now is a list of replaces for the currently requested tab (either because it was specified by tab id,
                    // or because there is a replaced for 'all tabs'
                    try
                    {
                        foreach (ParameterReplaceAction parmReplace in parmReplaces)
                        {
                            //do a regex on the 'lookFor' in the parameter path
                            var parmRegex = RegexUtils.GetCachedRegex(parmReplace.LookFor,
                                                                      RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
                            if (parmRegex.IsMatch(parameterPath))
                            {
                                replacedPath = parmRegex.Replace(parameterPath, parmReplace.ReplaceWith);
                                messages.Add(parmReplace.Name + " replace rule match, replaced : " + parameterPath + " with: " + replacedPath);
                                replaced = true;
                                //593: if this replacement is marked as a site root replacement, we will be
                                //removing the page path from the final url
                                changeToSiteRoot = parmReplace.ChangeToSiteRoot;
                                break;
                            }
                            messages.Add(parmReplace.Name + " replace rule not matched {" + parameterPath + "}");
                        }
                    }
                    catch (Exception ex)
                    {
                        //catch exceptions here because most likely to be related to regular expressions
                        //don't want to kill entire site because of this
                        Services.Exceptions.Exceptions.LogException(ex);
                        messages.Add("Exception : " + ex.Message + "\n" + ex.StackTrace);
                    }
                }
            }
            return(replaced);
        }
Example #13
0
        //递归处理
        private async Task <string> ParseChannelPathAsync(Site site, int channelId, string channelFilePathRule)
        {
            var          filePath = channelFilePathRule.Trim();
            const string regex    = "(?<element>{@[^}]+})";
            var          elements = RegexUtils.GetContents("element", regex, filePath);
            Channel      node     = null;

            foreach (var element in elements)
            {
                var value = string.Empty;

                if (StringUtils.EqualsIgnoreCase(element, ChannelId))
                {
                    value = channelId.ToString();
                }
                else if (StringUtils.EqualsIgnoreCase(element, Year))
                {
                    if (node == null)
                    {
                        node = await _databaseManager.ChannelRepository.GetAsync(channelId);
                    }
                    if (node.AddDate.HasValue)
                    {
                        value = node.AddDate.Value.Year.ToString();
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(element, Month))
                {
                    if (node == null)
                    {
                        node = await _databaseManager.ChannelRepository.GetAsync(channelId);
                    }
                    if (node.AddDate.HasValue)
                    {
                        value = node.AddDate.Value.Month.ToString();
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(element, Day))
                {
                    if (node == null)
                    {
                        node = await _databaseManager.ChannelRepository.GetAsync(channelId);
                    }
                    if (node.AddDate.HasValue)
                    {
                        value = node.AddDate.Value.Day.ToString();
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(element, Hour))
                {
                    if (node == null)
                    {
                        node = await _databaseManager.ChannelRepository.GetAsync(channelId);
                    }
                    if (node.AddDate.HasValue)
                    {
                        value = node.AddDate.Value.Hour.ToString();
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(element, Minute))
                {
                    if (node == null)
                    {
                        node = await _databaseManager.ChannelRepository.GetAsync(channelId);
                    }
                    if (node.AddDate.HasValue)
                    {
                        value = node.AddDate.Value.Minute.ToString();
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(element, Second))
                {
                    if (node == null)
                    {
                        node = await _databaseManager.ChannelRepository.GetAsync(channelId);
                    }
                    if (node.AddDate.HasValue)
                    {
                        value = node.AddDate.Value.Second.ToString();
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(element, Sequence))
                {
                    value = (await _databaseManager.ChannelRepository.GetSequenceAsync(site.Id, channelId)).ToString();
                }
                else if (StringUtils.EqualsIgnoreCase(element, ParentRule))
                {
                    if (node == null)
                    {
                        node = await _databaseManager.ChannelRepository.GetAsync(channelId);
                    }
                    var parentInfo = await _databaseManager.ChannelRepository.GetAsync(node.ParentId);

                    if (parentInfo != null)
                    {
                        var parentRule = await _pathManager.GetChannelFilePathRuleAsync(site, parentInfo.Id);

                        value = DirectoryUtils.GetDirectoryPath(await ParseChannelPathAsync(site, parentInfo.Id, parentRule)).Replace("\\", "/");
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(element, ChannelName))
                {
                    if (node == null)
                    {
                        node = await _databaseManager.ChannelRepository.GetAsync(channelId);
                    }
                    value = node.ChannelName;
                }
                else if (StringUtils.EqualsIgnoreCase(element, LowerChannelName))
                {
                    if (node == null)
                    {
                        node = await _databaseManager.ChannelRepository.GetAsync(channelId);
                    }
                    value = StringUtils.ToLower(node.ChannelName);
                }
                else if (StringUtils.EqualsIgnoreCase(element, LowerChannelIndex))
                {
                    if (node == null)
                    {
                        node = await _databaseManager.ChannelRepository.GetAsync(channelId);
                    }
                    value = StringUtils.ToLower(node.IndexName);
                }
                else
                {
                    if (node == null)
                    {
                        node = await _databaseManager.ChannelRepository.GetAsync(channelId);
                    }
                    var attributeName = element.Replace("{@", string.Empty).Replace("}", string.Empty);

                    var isLower = false;
                    if (StringUtils.StartsWithIgnoreCase(attributeName, "lower"))
                    {
                        isLower       = true;
                        attributeName = attributeName.Substring(5);
                    }

                    value = node.Get <string>(attributeName);

                    if (isLower)
                    {
                        value = StringUtils.ToLower(value);
                    }
                }

                filePath = filePath.Replace(element, value);
            }

            if (!filePath.Contains("//"))
            {
                return(filePath);
            }

            filePath = Regex.Replace(filePath, @"(/)\1{2,}", "/");
            filePath = Regex.Replace(filePath, @"//", "/");
            return(filePath);
        }
Example #14
0
 public static string GetAttribute(string stlElement, string attributeName)
 {
     return(RegexUtils.GetAttributeContent(attributeName, stlElement));
 }
Example #15
0
        public static string Parse(int siteId, string filePath, bool isClearFormat, bool isFirstLineIndent, bool isClearFontSize, bool isClearFontFamily, bool isClearImages)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                return(string.Empty);
            }

            var filename = PathUtils.GetFileNameWithoutExtension(filePath);

            //被转换的html文档保存的位置
            try
            {
                var saveFilePath = PathUtils.GetTemporaryFilesPath(filename + ".html");
                FileUtils.DeleteFileIfExists(saveFilePath);
                WordDntb.buildWord(filePath, saveFilePath);

                var parsedContent = FileUtils.ReadText(saveFilePath, System.Text.Encoding.Default);
                parsedContent = RegexUtils.GetInnerContent("body", parsedContent);

                //try
                //{
                //    parsedContent = HtmlClearUtils.ClearElementAttributes(parsedContent, "p");
                //}
                //catch { }

                if (isClearFormat)
                {
                    parsedContent = HtmlClearUtils.ClearFormat(parsedContent);
                }

                if (isFirstLineIndent)
                {
                    parsedContent = HtmlClearUtils.FirstLineIndent(parsedContent);
                }

                if (isClearFontSize)
                {
                    parsedContent = HtmlClearUtils.ClearFontSize(parsedContent);
                }

                if (isClearFontFamily)
                {
                    parsedContent = HtmlClearUtils.ClearFontFamily(parsedContent);
                }

                if (isClearImages)
                {
                    parsedContent = StringUtils.StripTags(parsedContent, "img");
                }
                else
                {
                    var siteInfo = SiteManager.GetSiteInfo(siteId);
                    var imageFileNameArrayList = RegexUtils.GetOriginalImageSrcs(parsedContent);
                    if (imageFileNameArrayList != null && imageFileNameArrayList.Count > 0)
                    {
                        foreach (var imageFileName in imageFileNameArrayList)
                        {
                            var imageFilePath       = PathUtils.GetTemporaryFilesPath(imageFileName);
                            var fileExtension       = PathUtils.GetExtension(imageFilePath);
                            var uploadDirectoryPath = PathUtility.GetUploadDirectoryPath(siteInfo, fileExtension);
                            var uploadDirectoryUrl  = PageUtility.GetSiteUrlByPhysicalPath(siteInfo, uploadDirectoryPath, true);
                            if (!FileUtils.IsFileExists(imageFilePath))
                            {
                                continue;
                            }

                            var uploadFileName = PathUtility.GetUploadFileName(siteInfo, imageFilePath);
                            var destFilePath   = PathUtils.Combine(uploadDirectoryPath, uploadFileName);
                            FileUtils.MoveFile(imageFilePath, destFilePath, false);
                            parsedContent = parsedContent.Replace(imageFileName, PageUtils.Combine(uploadDirectoryUrl, uploadFileName));

                            FileUtils.DeleteFileIfExists(imageFilePath);
                        }
                    }
                }

                FileUtils.DeleteFileIfExists(filePath);
                FileUtils.DeleteFileIfExists(saveFilePath);
                return(parsedContent.Trim());
            }
            catch (Exception ex)
            {
                LogUtils.AddErrorLog(ex);
                return(string.Empty);
            }
        }
Example #16
0
        protected string GetWeatherHtml(string provider)
        {
            var result = string.Empty;

            try
            {
                var group = "title";
                if (provider == yahoo)
                {
                    var    pinyinCity = TranslateUtils.ToPinYin(City);
                    string weatherUrl = $"http://weather.cn.yahoo.com/weather.html?city={pinyinCity}&s=1";
                    string regex      =
                        $@"<\!--today\s+-->\s+<div\s+class=""dt_c"">\s+<div\s+class=""tn"">{DateTime.Now.Year}-{TranslateUtils
					        .ToTwoCharString(DateTime.Now.Month)}-{TranslateUtils.ToTwoCharString(DateTime.Now.Day)}</div>\s*(?<title>[\s\S]+?)\s*</div>\s+<\!--//today\s+-->"                    ;

                    var content = WebClientUtils.GetRemoteFileSource(weatherUrl, ECharset.utf_8);

                    if (!string.IsNullOrEmpty(content))
                    {
                        content = RegexUtils.GetContent(group, regex, content);

                        var flashRegex         = @"<p>\s*(?<title>[\s\S]+?)\s*</p>";
                        var weatherStringRegex = @"<span\s+class=""ft1"">\s*(?<title>[\s\S]+?)\s*</span>";
                        var highDegreeRegex    = @"<span\s+class=""hitp"">\s*(?<title>[\s\S]+?)\s*</span>";
                        var lowDegreeRegex     = @"<span\s+class=""lotp"">\s*(?<title>[\s\S]+?)\s*</span>";

                        var flashHtml = RegexUtils.GetContent(group, flashRegex, content);
                        flashHtml = flashHtml.Replace("width=\"64\" height=\"64\"", "width=\"20\" height=\"20\"");
                        var weatherString = RegexUtils.GetContent(group, weatherStringRegex, content);
                        var highDegree    = RegexUtils.GetContent(group, highDegreeRegex, content);
                        var lowDegree     = RegexUtils.GetContent(group, lowDegreeRegex, content);

                        if (!string.IsNullOrEmpty(highDegree))
                        {
                            result = flashHtml + weatherString + $"&nbsp;{highDegree} ~ {lowDegree}";
                        }
                    }
                }
                else if (provider == sina)
                {
                    string weatherUrl = $"http://php.weather.sina.com.cn/search.php?city={PageUtils.UrlEncode(City)}";
                    var    regex      = "<td\\s+bgcolor=\\#FEFEFF\\s+height=25\\s+style=\"padding-left:20px;\"\\s+align=center>24小时</td>\\s*(?<title>[\\s\\S]+?)\\s*</tr>";

                    var content = WebClientUtils.GetRemoteFileSource(weatherUrl, ECharset.gb2312);

                    if (!string.IsNullOrEmpty(content))
                    {
                        content = RegexUtils.GetContent(group, regex, content);

                        var contentArrayList = RegexUtils.GetTagInnerContents("td", content);

                        var weatherString = (string)contentArrayList[0];
                        var highDegree    = (string)contentArrayList[1];
                        var lowDegree     = (string)contentArrayList[2];

                        if (!string.IsNullOrEmpty(highDegree))
                        {
                            result = weatherString + $"&nbsp;{highDegree} ~ {lowDegree}";
                        }
                    }
                }
            }
            catch {}

            return(result);
        }
Example #17
0
 public void BackingFieldRegexRecognizesNonMatch()
 {
     Assert.Null(RegexUtils.MatchFieldName(_nonMatchEmpty));
     Assert.Null(RegexUtils.MatchFieldName(_nonMatch));
 }
Example #18
0
        private bool IsInvalidName(string itemName)
        {
            var invalidFilenameChars = RegexUtils.GetCachedRegex("[" + Regex.Escape(GetInvalidChars()) + "]");

            return(invalidFilenameChars.IsMatch(itemName));
        }
Example #19
0
 public void SetMethodNameRegexRecognizesNonMatch()
 {
     Assert.Null(RegexUtils.MatchSetPropertyName(_nonMatchEmpty));
     Assert.Null(RegexUtils.MatchSetPropertyName(_nonMatch));
 }
Example #20
0
        public string GetFileInputTemplate()
        {
            var content = FileUtils.ReadText(SiteFilesAssets.GetPath("govinteractapply/inputTemplate.html"), ECharset.utf_8);

            var regex        = "<!--parameters:(?<params>[^\"]*)-->";
            var paramstring  = RegexUtils.GetContent("params", regex, content);
            var parameters   = TranslateUtils.ToNameValueCollection(paramstring);
            var tdNameClass  = parameters["tdNameClass"];
            var tdInputClass = parameters["tdInputClass"];

            if (parameters.Count > 0)
            {
                content = content.Replace($"<!--parameters:{paramstring}-->\r\n", string.Empty);
            }

            content = $@"<link href=""{SiteFilesAssets.GovInteractApply.GetStyleUrl(_publishmentSystemInfo.Additional.ApiUrl)}"" type=""text/css"" rel=""stylesheet"" />
" + content;

            var builder       = new StringBuilder();
            var styleInfoList = RelatedIdentities.GetTableStyleInfoList(_publishmentSystemInfo, ETableStyle.GovInteractContent, _nodeId);

            var pageScripts = new NameValueCollection();

            var isPreviousSingleLine = true;
            var isPreviousLeftColumn = false;

            foreach (var styleInfo in styleInfoList)
            {
                if (styleInfo.IsVisible)
                {
                    var value = InputTypeParser.Parse(_publishmentSystemInfo, _nodeId, styleInfo, ETableStyle.GovInteractContent, styleInfo.AttributeName, null, false, false, null, pageScripts, styleInfo.Additional.IsValidate);

                    if (builder.Length > 0)
                    {
                        if (isPreviousSingleLine)
                        {
                            builder.Append("</tr>");
                        }
                        else
                        {
                            if (!isPreviousLeftColumn)
                            {
                                builder.Append("</tr>");
                            }
                            else if (styleInfo.IsSingleLine)
                            {
                                builder.Append(
                                    $@"<td class=""{tdNameClass}""></td><td class=""{tdInputClass}""></td></tr>");
                            }
                        }
                    }

                    //this line

                    if (styleInfo.IsSingleLine || isPreviousSingleLine || !isPreviousLeftColumn)
                    {
                        builder.Append("<tr>");
                    }

                    builder.Append(
                        $@"<td class=""{tdNameClass}"">{styleInfo.DisplayName}</td><td {(styleInfo.IsSingleLine
                            ? @"colspan=""3"""
                            : string.Empty)} class=""{tdInputClass}"">{value}</td>");


                    if (styleInfo.IsSingleLine)
                    {
                        isPreviousSingleLine = true;
                        isPreviousLeftColumn = false;
                    }
                    else
                    {
                        isPreviousSingleLine = false;
                        isPreviousLeftColumn = !isPreviousLeftColumn;
                    }
                }
            }

            if (builder.Length > 0)
            {
                if (isPreviousSingleLine || !isPreviousLeftColumn)
                {
                    builder.Append("</tr>");
                }
                else
                {
                    builder.Append($@"<td class=""{tdNameClass}""></td><td class=""{tdInputClass}""></td></tr>");
                }
            }

            if (content.Contains("<!--提交表单循环-->"))
            {
                content = content.Replace("<!--提交表单循环-->", builder.ToString());
            }

            return(content.Replace("[nodeID]", _nodeId.ToString()));
        }
Example #21
0
 public void BackingFieldRegexMatchAsExpected()
 {
     Assert.Equal(_autoPropertyMember.Name,
                  RegexUtils.MatchFieldName(_expectedBackingFieldName));
 }
Example #22
0
 public void PascalCaseSplit_NullString_ReturnsNull()
 {
     Assert.Null(RegexUtils.PascalCaseSplit(null));
 }
Example #23
0
        public IHttpActionResult Main()
        {
            try
            {
                var request = new Request();
                var form    = HttpContext.Current.Request.Form;

                var isAllSites       = request.GetPostBool(StlSearch.AttributeIsAllSites.ToLower());
                var siteName         = PageUtils.FilterSqlAndXss(request.GetPostString(StlSearch.AttributeSiteName.ToLower()));
                var siteDir          = PageUtils.FilterSqlAndXss(request.GetPostString(StlSearch.AttributeSiteDir.ToLower()));
                var siteIds          = PageUtils.FilterSqlAndXss(request.GetPostString(StlSearch.AttributeSiteIds.ToLower()));
                var channelIndex     = PageUtils.FilterSqlAndXss(request.GetPostString(StlSearch.AttributeChannelIndex.ToLower()));
                var channelName      = PageUtils.FilterSqlAndXss(request.GetPostString(StlSearch.AttributeChannelName.ToLower()));
                var channelIds       = PageUtils.FilterSqlAndXss(request.GetPostString(StlSearch.AttributeChannelIds.ToLower()));
                var type             = PageUtils.FilterSqlAndXss(request.GetPostString(StlSearch.AttributeType.ToLower()));
                var word             = PageUtils.FilterSql(request.GetPostString(StlSearch.AttributeWord.ToLower()));
                var dateAttribute    = PageUtils.FilterSqlAndXss(request.GetPostString(StlSearch.AttributeDateAttribute.ToLower()));
                var dateFrom         = PageUtils.FilterSqlAndXss(request.GetPostString(StlSearch.AttributeDateFrom.ToLower()));
                var dateTo           = PageUtils.FilterSqlAndXss(request.GetPostString(StlSearch.AttributeDateTo.ToLower()));
                var since            = PageUtils.FilterSqlAndXss(request.GetPostString(StlSearch.AttributeSince.ToLower()));
                var pageNum          = request.GetPostInt(StlSearch.AttributePageNum.ToLower());
                var isHighlight      = request.GetPostBool(StlSearch.AttributeIsHighlight.ToLower());
                var isDefaultDisplay = request.GetPostBool(StlSearch.AttributeIsDefaultDisplay.ToLower());
                var siteId           = request.GetPostInt("siteid");
                var ajaxDivId        = PageUtils.FilterSqlAndXss(request.GetPostString("ajaxdivid"));
                var template         = TranslateUtils.DecryptStringBySecretKey(request.GetPostString("template"));
                var pageIndex        = request.GetPostInt("page", 1) - 1;

                var templateInfo = new TemplateInfo(0, siteId, string.Empty, TemplateType.FileTemplate, string.Empty, string.Empty, string.Empty, ECharset.utf_8, false);
                var siteInfo     = SiteManager.GetSiteInfo(siteId);
                var pageInfo     = new PageInfo(siteId, 0, siteInfo, templateInfo, new Dictionary <string, object>())
                {
                    UserInfo = request.UserInfo
                };
                var contextInfo    = new ContextInfo(pageInfo);
                var contentBuilder = new StringBuilder(StlRequestEntities.ParseRequestEntities(form, template));

                var stlLabelList = StlParserUtility.GetStlLabelList(contentBuilder.ToString());

                if (StlParserUtility.IsStlElementExists(StlPageContents.ElementName, stlLabelList))
                {
                    var stlElement             = StlParserUtility.GetStlElement(StlPageContents.ElementName, stlLabelList);
                    var stlPageContentsElement = stlElement;
                    var stlPageContentsElementReplaceString = stlElement;

                    bool isDefaultCondition;
                    var  whereString = DataProvider.ContentDao.GetWhereStringByStlSearch(isAllSites, siteName, siteDir, siteIds, channelIndex, channelName, channelIds, type, word, dateAttribute, dateFrom, dateTo, since, siteId, ApiRouteActionsSearch.ExlcudeAttributeNames, form, out isDefaultCondition);

                    //没搜索条件时不显示搜索结果
                    if (isDefaultCondition && !isDefaultDisplay)
                    {
                        return(NotFound());
                    }

                    var stlPageContents = new StlPageContents(stlPageContentsElement, pageInfo, contextInfo, pageNum, siteInfo.TableName, whereString);

                    int totalNum;
                    var pageCount = stlPageContents.GetPageCount(out totalNum);

                    if (totalNum == 0)
                    {
                        return(NotFound());
                    }

                    for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                    {
                        if (currentPageIndex != pageIndex)
                        {
                            continue;
                        }

                        var pageHtml     = stlPageContents.Parse(totalNum, currentPageIndex, pageCount, false);
                        var pagedBuilder = new StringBuilder(contentBuilder.ToString().Replace(stlPageContentsElementReplaceString, pageHtml));

                        StlParserManager.ReplacePageElementsInSearchPage(pagedBuilder, pageInfo, stlLabelList, ajaxDivId, pageInfo.PageChannelId, currentPageIndex, pageCount, totalNum);

                        if (isHighlight && !string.IsNullOrEmpty(word))
                        {
                            var pagedContents = pagedBuilder.ToString();
                            pagedBuilder = new StringBuilder();
                            pagedBuilder.Append(RegexUtils.Replace(
                                                    $"({word.Replace(" ", "\\s")})(?!</a>)(?![^><]*>)", pagedContents,
                                                    $"<span style='color:#cc0000'>{word}</span>"));
                        }

                        Parser.Parse(siteInfo, pageInfo, contextInfo, pagedBuilder, string.Empty, false);
                        return(Ok(pagedBuilder.ToString()));
                    }
                }

                Parser.Parse(siteInfo, pageInfo, contextInfo, contentBuilder, string.Empty, false);
                return(Ok(contentBuilder.ToString()));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
        internal static bool CheckForParameterRedirect(Uri requestUri,
                                                       ref UrlAction result,
                                                       NameValueCollection queryStringCol,
                                                       FriendlyUrlSettings settings)
        {
            //check for parameter replaced works by inspecting the parameters on a rewritten request, comparing
            //them agains the list of regex expressions on the friendlyurls.config file, and redirecting to the same page
            //but with new parameters, if there was a match
            bool redirect = false;
            //get the redirect actions for this portal
            var messages = new List <string>();
            Dictionary <int, List <ParameterRedirectAction> > redirectActions = CacheController.GetParameterRedirects(settings, result.PortalId, ref messages);

            if (redirectActions != null && redirectActions.Count > 0)
            {
                try
                {
                    #region trycatch block

                    string rewrittenUrl = result.RewritePath ?? result.RawUrl;

                    List <ParameterRedirectAction> parmRedirects = null;
                    //find the matching redirects for the tabid
                    int tabId = result.TabId;
                    if (tabId > -1)
                    {
                        if (redirectActions.ContainsKey(tabId))
                        {
                            //find the right set of replaced actions for this tab
                            parmRedirects = redirectActions[tabId];
                        }
                    }
                    //check for 'all tabs' redirections
                    if (redirectActions.ContainsKey(-1)) //-1 means 'all tabs' - rewriting across all tabs
                    {
                        //initialise to empty collection if there are no specific tab redirects
                        if (parmRedirects == null)
                        {
                            parmRedirects = new List <ParameterRedirectAction>();
                        }
                        //add in the all redirects
                        List <ParameterRedirectAction> allRedirects = redirectActions[-1];
                        parmRedirects.AddRange(allRedirects); //add the 'all' range to the tab range
                        tabId = result.TabId;
                    }
                    if (redirectActions.ContainsKey(-2) && result.OriginalPath.ToLower().Contains("default.aspx"))
                    {
                        //for the default.aspx page
                        if (parmRedirects == null)
                        {
                            parmRedirects = new List <ParameterRedirectAction>();
                        }
                        List <ParameterRedirectAction> defaultRedirects = redirectActions[-2];
                        parmRedirects.AddRange(defaultRedirects); //add the default.aspx redirects to the list
                        tabId = result.TabId;
                    }
                    //726 : allow for site-root redirects, ie redirects where no page match
                    if (redirectActions.ContainsKey(-3))
                    {
                        //request is for site root
                        if (parmRedirects == null)
                        {
                            parmRedirects = new List <ParameterRedirectAction>();
                        }
                        List <ParameterRedirectAction> siteRootRedirects = redirectActions[-3];
                        parmRedirects.AddRange(siteRootRedirects); //add the site root redirects to the collection
                    }
                    //OK what we have now is a list of redirects for the currently requested tab (either because it was specified by tab id,
                    // or because there is a replaced for 'all tabs'

                    if (parmRedirects != null && parmRedirects.Count > 0 && rewrittenUrl != null)
                    {
                        foreach (ParameterRedirectAction parmRedirect in parmRedirects)
                        {
                            //regex test each replaced to see if there is a match between the parameter string
                            //and the parmRedirect
                            string compareWith   = rewrittenUrl;
                            var    redirectRegex = RegexUtils.GetCachedRegex(parmRedirect.LookFor,
                                                                             RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
                            Match regexMatch    = redirectRegex.Match(compareWith);
                            bool  success       = regexMatch.Success;
                            bool  siteRootTried = false;
                            //if no match, but there is a site root redirect to try
                            if (!success && parmRedirect.TabId == -3)
                            {
                                siteRootTried = true;
                                compareWith   = result.OriginalPathNoAlias;
                                regexMatch    = redirectRegex.Match(compareWith);
                                success       = regexMatch.Success;
                            }
                            if (!success)
                            {
                                result.DebugMessages.Add(parmRedirect.Name + " redirect not matched (" + rewrittenUrl +
                                                         ")");
                                if (siteRootTried)
                                {
                                    result.DebugMessages.Add(parmRedirect.Name + " redirect not matched [site root] (" +
                                                             result.OriginalPathNoAlias + ")");
                                }
                            }
                            else
                            {
                                //success! there was a match in the parameters
                                string parms = redirectRegex.Replace(compareWith, parmRedirect.RedirectTo);
                                if (siteRootTried)
                                {
                                    result.DebugMessages.Add(parmRedirect.Name + " redirect matched [site root] with (" +
                                                             result.OriginalPathNoAlias + "), replaced with " + parms);
                                }
                                else
                                {
                                    result.DebugMessages.Add(parmRedirect.Name + " redirect matched with (" +
                                                             compareWith + "), replaced with " + parms);
                                }
                                string finalUrl = "";
                                //now we need to generate the friendly Url

                                //first check to see if the parameter replacement string has a destination tabid specified
                                if (parms.ToLower().Contains("tabid/"))
                                {
                                    //if so, using a feature whereby the dest tabid can be changed within the parameters, which will
                                    //redirect the page as well as redirecting the parameter values
                                    string[] parmParts = parms.Split('/');
                                    bool     tabIdNext = false;
                                    foreach (string parmPart in parmParts)
                                    {
                                        if (tabIdNext)
                                        {
                                            //changes the tabid of page, effects a page redirect along with a parameter redirect
                                            Int32.TryParse(parmPart, out tabId);
                                            parms = parms.Replace("tabid/" + tabId.ToString(), "");
                                            //remove the tabid/xx from the path
                                            break; //that's it, we're finished
                                        }
                                        if (parmPart.ToLower() == "tabid")
                                        {
                                            tabIdNext = true;
                                        }
                                    }
                                }
                                else if (tabId == -1)
                                {
                                    //find the home tabid for this portal
                                    //735 : switch to custom method for getting portal
                                    PortalInfo portal = CacheController.GetPortal(result.PortalId, true);
                                    tabId = portal.HomeTabId;
                                }
                                if (parmRedirect.ChangeToSiteRoot)
                                {
                                    //when change to siteroot requested, new path goes directly off the portal alias
                                    //so set the finalUrl as the poratl alias
                                    finalUrl = result.Scheme + result.HttpAlias + "/";
                                }
                                else
                                {
                                    //if the tabid has been supplied, do a friendly url provider lookup to get the correct format for the tab url
                                    if (tabId > -1)
                                    {
                                        TabInfo tab = TabController.Instance.GetTab(tabId, result.PortalId, false);
                                        if (tab != null)
                                        {
                                            string path = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(tab.TabID, "");
                                            string friendlyUrlNoParms = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl(tab,
                                                                                                                        path,
                                                                                                                        Globals.glbDefaultPage,
                                                                                                                        result.HttpAlias,
                                                                                                                        false,
                                                                                                                        settings,
                                                                                                                        Guid.Empty);
                                            if (friendlyUrlNoParms.EndsWith("/") == false)
                                            {
                                                friendlyUrlNoParms += "/";
                                            }
                                            finalUrl = friendlyUrlNoParms;
                                        }
                                        if (tab == null)
                                        {
                                            result.DebugMessages.Add(parmRedirect.Name +
                                                                     " tabId in redirect rule (tabId:" +
                                                                     tabId.ToString() + ", portalId:" +
                                                                     result.PortalId.ToString() +
                                                                     " ), tab was not found");
                                        }
                                        else
                                        {
                                            result.DebugMessages.Add(parmRedirect.Name +
                                                                     " tabId in redirect rule (tabId:" +
                                                                     tabId.ToString() + ", portalId:" +
                                                                     result.PortalId.ToString() + " ), tab found : " +
                                                                     tab.TabName);
                                        }
                                    }
                                }
                                if (parms.StartsWith("//"))
                                {
                                    parms = parms.Substring(2);
                                }
                                if (parms.StartsWith("/"))
                                {
                                    parms = parms.Substring(1);
                                }

                                if (settings.PageExtensionUsageType != PageExtensionUsageType.Never)
                                {
                                    if (parms.EndsWith("/"))
                                    {
                                        parms = parms.TrimEnd('/');
                                    }
                                    if (parms.Length > 0)
                                    {
                                        //we are adding more parms onto the end, so remove the page extension
                                        //from the parameter list
                                        //946 : exception when settings.PageExtension value is empty
                                        parms += settings.PageExtension;
                                        //816: if page extension is /, then don't do this
                                        if (settings.PageExtension != "/" &&
                                            string.IsNullOrEmpty(settings.PageExtension) == false)
                                        {
                                            finalUrl = finalUrl.Replace(settings.PageExtension, "");
                                        }
                                    }
                                    else
                                    {
                                        //we are removing all the parms altogether, so
                                        //the url needs to end in the page extension only
                                        //816: if page extension is /, then don't do this
                                        if (settings.PageExtension != "/" &&
                                            string.IsNullOrEmpty(settings.PageExtension) == false)
                                        {
                                            finalUrl = finalUrl.Replace(settings.PageExtension + "/",
                                                                        settings.PageExtension);
                                        }
                                    }
                                }
                                //put the replaced parms back on the end
                                finalUrl += parms;

                                //set the final url
                                result.FinalUrl = finalUrl;
                                result.Reason   = RedirectReason.Custom_Redirect;
                                switch (parmRedirect.Action)
                                {
                                case "301":
                                    result.Action = ActionType.Redirect301;
                                    break;

                                case "302":
                                    result.Action = ActionType.Redirect302;
                                    break;

                                case "404":
                                    result.Action = ActionType.Output404;
                                    break;
                                }
                                redirect = true;
                                break;
                            }
                        }
                    }

                    #endregion
                }
                catch (Exception ex)
                {
                    Services.Exceptions.Exceptions.LogException(ex);
                    messages.Add("Exception: " + ex.Message + "\n" + ex.StackTrace);
                }
                finally
                {
                    if (messages.Count > 0)
                    {
                        result.DebugMessages.AddRange(messages);
                    }
                }
            }
            return(redirect);
        }
        private static bool InvalidFilename(string fileName)
        {
            var invalidFilenameChars = RegexUtils.GetCachedRegex("[" + Regex.Escape(new string(Path.GetInvalidFileNameChars())) + "]");

            return(invalidFilenameChars.IsMatch(fileName));
        }
Example #26
0
        public static SeoMetaInfo GetSeoMetaInfo(string content)
        {
            var seoMetaInfo = new SeoMetaInfo();

            if (!string.IsNullOrEmpty(content))
            {
                var metaRegex   = @"<title>(?<meta>[^<]*?)</title>";
                var metaContent = RegexUtils.GetContent("meta", metaRegex, content);
                if (!string.IsNullOrEmpty(metaContent))
                {
                    seoMetaInfo.PageTitle = metaContent;
                }

                metaRegex   = @"<META\s+NAME=(?:""|')keywords(?:""|')\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')(?:[^>]*)>|<META\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')\s+NAME=(?:""|')keywords(?:""|')(?:[^>]*)>";
                metaContent = RegexUtils.GetContent("meta", metaRegex, content);
                if (!string.IsNullOrEmpty(metaContent))
                {
                    seoMetaInfo.Keywords = metaContent;
                }

                metaRegex   = @"<META\s+NAME=(?:""|')description(?:""|')\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')(?:[^>]*)>|<META\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')\s+NAME=(?:""|')description(?:""|')(?:[^>]*)>";
                metaContent = RegexUtils.GetContent("meta", metaRegex, content);
                if (!string.IsNullOrEmpty(metaContent))
                {
                    seoMetaInfo.Description = metaContent;
                }

                metaRegex   = @"<META\s+NAME=(?:""|')copyright(?:""|')\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')(?:[^>]*)>|<META\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')\s+NAME=(?:""|')copyright(?:""|')(?:[^>]*)>";
                metaContent = RegexUtils.GetContent("meta", metaRegex, content);
                if (!string.IsNullOrEmpty(metaContent))
                {
                    seoMetaInfo.Copyright = metaContent;
                }

                metaRegex   = @"<META\s+NAME=(?:""|')author(?:""|')\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')(?:[^>]*)>|<META\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')\s+NAME=(?:""|')author(?:""|')(?:[^>]*)>";
                metaContent = RegexUtils.GetContent("meta", metaRegex, content);
                if (!string.IsNullOrEmpty(metaContent))
                {
                    seoMetaInfo.Author = metaContent;
                }

                metaRegex   = @"<META\s+NAME=(?:""|')email(?:""|')\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')(?:[^>]*)>|<META\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')\s+NAME=(?:""|')email(?:""|')(?:[^>]*)>";
                metaContent = RegexUtils.GetContent("meta", metaRegex, content);
                if (!string.IsNullOrEmpty(metaContent))
                {
                    seoMetaInfo.Email = metaContent;
                }

                metaRegex   = @"<META\s+NAME=(?:""|')language(?:""|')\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')(?:[^>]*)>|<META\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')\s+NAME=(?:""|')language(?:""|')(?:[^>]*)>";
                metaContent = RegexUtils.GetContent("meta", metaRegex, content);
                if (!string.IsNullOrEmpty(metaContent))
                {
                    seoMetaInfo.Language = metaContent;
                }

                metaRegex   = @"<META\s+NAME=(?:""|')charset(?:""|')\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')(?:[^>]*)>|<META\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')\s+NAME=(?:""|')charset(?:""|')(?:[^>]*)>";
                metaContent = RegexUtils.GetContent("meta", metaRegex, content);
                if (!string.IsNullOrEmpty(metaContent))
                {
                    seoMetaInfo.Charset = metaContent;
                }

                metaRegex   = @"<META\s+NAME=(?:""|')distribution(?:""|')\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')(?:[^>]*)>|<META\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')\s+NAME=(?:""|')distribution(?:""|')(?:[^>]*)>";
                metaContent = RegexUtils.GetContent("meta", metaRegex, content);
                if (!string.IsNullOrEmpty(metaContent))
                {
                    seoMetaInfo.Distribution = metaContent;
                }

                metaRegex   = @"<META\s+NAME=(?:""|')rating(?:""|')\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')(?:[^>]*)>|<META\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')\s+NAME=(?:""|')rating(?:""|')(?:[^>]*)>";
                metaContent = RegexUtils.GetContent("meta", metaRegex, content);
                if (!string.IsNullOrEmpty(metaContent))
                {
                    seoMetaInfo.Rating = metaContent;
                }

                metaRegex   = @"<META\s+NAME=(?:""|')robots(?:""|')\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')(?:[^>]*)>|<META\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')\s+NAME=(?:""|')robots(?:""|')(?:[^>]*)>";
                metaContent = RegexUtils.GetContent("meta", metaRegex, content);
                if (!string.IsNullOrEmpty(metaContent))
                {
                    seoMetaInfo.Robots = metaContent;
                }

                metaRegex   = @"<META\s+NAME=(?:""|')revisit-after(?:""|')\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')(?:[^>]*)>|<META\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')\s+NAME=(?:""|')revisit-after(?:""|')(?:[^>]*)>";
                metaContent = RegexUtils.GetContent("meta", metaRegex, content);
                if (!string.IsNullOrEmpty(metaContent))
                {
                    seoMetaInfo.RevisitAfter = metaContent;
                }

                metaRegex   = @"<META\s+NAME=(?:""|')expires(?:""|')\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')(?:[^>]*)>|<META\s+CONTENT=(?:""|')(?<meta>[^<]*?)(?:""|')\s+NAME=(?:""|')expires(?:""|')(?:[^>]*)>";
                metaContent = RegexUtils.GetContent("meta", metaRegex, content);
                if (!string.IsNullOrEmpty(metaContent))
                {
                    seoMetaInfo.Expires = metaContent;
                }
            }

            return(seoMetaInfo);
        }
Example #27
0
 public void IsValidRegexOk2()
 {
     Assert.IsTrue(RegexUtils.IsValidRegex(@"\d+"));
 }
Example #28
0
 /// <summary>
 /// Checks, if given phrase is a admin mode command.
 /// </summary>
 /// <param name="phrase">given phrase</param>
 /// <returns>true means command, false otherwise</returns>
 private bool IsCommand(string phrase) => Regex.IsMatch(phrase, RegexUtils.RegularPattern($"{COMMAND_WORD}*;*"));
        public bool ShouldSkip(Type type)
        {
            var typeName = type.Namespace + "." + type.Name;

            return(!RegexUtils.ShouldInclude(_regexActions, typeName));
        }
Example #30
0
        void Login()
        {
            string email    = Request.Form["email"];
            string password = Request.Form["password"];

            if (string.IsNullOrEmpty(email))
            {
                DoResponse(JsonConvert.SerializeObject(new GlobalValues.ResponseData()
                {
                    Data      = null,
                    ErrorCode = 1,
                    Message   = "Please provide the email!",
                }));

                return;
            }

            if (string.IsNullOrEmpty(password))
            {
                DoResponse(JsonConvert.SerializeObject(new GlobalValues.ResponseData()
                {
                    Data      = null,
                    ErrorCode = 2,
                    Message   = "Please provide the password!",
                }));

                return;
            }

            if (password.Length < 5)
            {
                DoResponse(JsonConvert.SerializeObject(new GlobalValues.ResponseData()
                {
                    Data      = null,
                    ErrorCode = 3,
                    Message   = "Password must be at least 5 characters long!",
                }));

                return;
            }

            PrivateEncryptor encryptor = new PrivateEncryptor();

            //if (email.Trim().ToLower() == SiteValues.GodeSys_User_Username.ToLower())
            //{
            //    if (password == SiteValues.GodeSys_User_Password)
            //    {
            //        DoResponse(JsonConvert.SerializeObject(new GlobalValues.ResponseData()
            //        {
            //            Data = encryptor.Encrypt("0"),
            //            ErrorCode = 0,
            //            Message = "Login successfull!",
            //        }));
            //        return;
            //    }
            //}

            if (!RegexUtils.IsMatchRegex(RegexUtils.Regex_Email, email))
            {
                DoResponse(JsonConvert.SerializeObject(new GlobalValues.ResponseData()
                {
                    Data      = null,
                    ErrorCode = 4,
                    Message   = "Email is invalid!",
                }));

                return;
            }

            using (DALTools dalTools = new DALTools())
            {
                Sys_User eSys_User = dalTools.Sys_User_Get(email, password);
                if (eSys_User == null)
                {
                    DoResponse(JsonConvert.SerializeObject(new GlobalValues.ResponseData()
                    {
                        Data      = null,
                        ErrorCode = 5,
                        Message   = "Authentication fail!",
                    }));
                }
                else
                {
                    DoResponse(JsonConvert.SerializeObject(new GlobalValues.ResponseData()
                    {
                        Data      = encryptor.Encrypt(eSys_User.ID.ToString()),
                        ErrorCode = 0,
                        Message   = "Login successfull!",
                    }));
                }
            }
        }