Exemplo n.º 1
0
        static bool TryParse(byte[] text, ref int index, int endIndex, bool throwOnError, out AuthenticationResults authres)
        {
            int?   instance = null;
            string srvid    = null;
            string value;
            bool   quoted;

            authres = null;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            do
            {
                int start = index;

                if (index >= endIndex || !SkipValue(text, ref index, endIndex, out quoted))
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Incomplete authserv-id token at offset {0}", start), start, index);
                    }

                    return(false);
                }

                value = Encoding.UTF8.GetString(text, start, index - start);

                if (quoted)
                {
                    // this can only be the authserv-id token
                    srvid = MimeUtils.Unquote(value);
                }
                else
                {
                    // this could either be the authserv-id or it could be "i=#" (ARC instance)
                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index < endIndex && text[index] == (byte)'=')
                    {
                        // probably i=#
                        if (instance.HasValue)
                        {
                            if (throwOnError)
                            {
                                throw new ParseException(string.Format("Invalid token at offset {0}", start), start, index);
                            }

                            return(false);
                        }

                        if (value != "i")
                        {
                            if (throwOnError)
                            {
                                throw new ParseException(string.Format("Invalid instance token at offset {0}", start), start, index);
                            }

                            return(false);
                        }

                        // skip over '='
                        index++;

                        if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                        {
                            return(false);
                        }

                        start = index;

                        if (!ParseUtils.TryParseInt32(text, ref index, endIndex, out int i))
                        {
                            if (throwOnError)
                            {
                                throw new ParseException(string.Format("Invalid instance value at offset {0}", start), start, index);
                            }

                            return(false);
                        }

                        instance = i;

                        if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                        {
                            return(false);
                        }

                        if (index >= endIndex)
                        {
                            if (throwOnError)
                            {
                                throw new ParseException(string.Format("Missing semi-colon after instance value at offset {0}", start), start, index);
                            }

                            return(false);
                        }

                        if (text[index] != ';')
                        {
                            if (throwOnError)
                            {
                                throw new ParseException(string.Format("Unexpected token after instance value at offset {0}", index), index, index);
                            }

                            return(false);
                        }

                        // skip over ';'
                        index++;

                        if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        srvid = value;
                    }
                }
            } while (srvid == null);

            authres = new AuthenticationResults(srvid)
            {
                Instance = instance
            };

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                return(true);
            }

            if (text[index] != (byte)';')
            {
                // might be the authres-version token
                int start = index;

                if (!ParseUtils.TryParseInt32(text, ref index, endIndex, out int version))
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Invalid authres-version at offset {0}", start), start, index);
                    }

                    return(false);
                }

                authres.Version = version;

                if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                {
                    return(false);
                }

                if (index >= endIndex)
                {
                    return(true);
                }

                if (text[index] != (byte)';')
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Unknown token at offset {0}", index), index, index);
                    }

                    return(false);
                }
            }

            // skip the ';'
            index++;

            while (index < endIndex)
            {
                if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                {
                    return(false);
                }

                if (index >= endIndex)
                {
                    break;
                }

                int methodIndex = index;

                // skip the method name
                if (!SkipKeyword(text, ref index, endIndex))
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Invalid method token at offset {0}", methodIndex), methodIndex, index);
                    }

                    return(false);
                }

                var method = Encoding.ASCII.GetString(text, methodIndex, index - methodIndex);

                if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                {
                    return(false);
                }

                if (index >= endIndex)
                {
                    if (method != "none")
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Incomplete methodspec token at offset {0}", methodIndex), methodIndex, index);
                        }

                        return(false);
                    }

                    if (authres.Results.Count > 0)
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Invalid no-result token at offset {0}", methodIndex), methodIndex, index);
                        }

                        return(false);
                    }

                    break;
                }

                var resinfo = new AuthenticationMethodResult(method);
                authres.Results.Add(resinfo);

                int tokenIndex;

                if (text[index] == (byte)'/')
                {
                    // optional method-version token
                    index++;

                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    tokenIndex = index;

                    if (!ParseUtils.TryParseInt32(text, ref index, endIndex, out int version))
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Invalid method-version token at offset {0}", tokenIndex), tokenIndex, index);
                        }

                        return(false);
                    }

                    resinfo.Version = version;

                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index >= endIndex)
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Incomplete methodspec token at offset {0}", methodIndex), methodIndex, index);
                        }

                        return(false);
                    }
                }

                if (text[index] != (byte)'=')
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Invalid methodspec token at offset {0}", methodIndex), methodIndex, index);
                    }

                    return(false);
                }

                // skip over '='
                index++;

                if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                {
                    return(false);
                }

                if (index >= endIndex)
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Incomplete methodspec token at offset {0}", methodIndex), methodIndex, index);
                    }

                    return(false);
                }

                tokenIndex = index;

                if (!SkipKeyword(text, ref index, endIndex))
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Invalid result token at offset {0}", tokenIndex), tokenIndex, index);
                    }

                    return(false);
                }

                resinfo.Result = Encoding.ASCII.GetString(text, tokenIndex, index - tokenIndex);

                ParseUtils.SkipWhiteSpace(text, ref index, endIndex);

                if (index < endIndex && text[index] == '(')
                {
                    int commentIndex = index;

                    if (!ParseUtils.SkipComment(text, ref index, endIndex))
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Incomplete comment token at offset {0}", commentIndex), commentIndex, index);
                        }

                        return(false);
                    }

                    commentIndex++;

                    resinfo.ResultComment = Header.Unfold(Encoding.UTF8.GetString(text, commentIndex, (index - 1) - commentIndex));

                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }
                }

                if (index >= endIndex)
                {
                    break;
                }

                if (text[index] == (byte)';')
                {
                    index++;
                    continue;
                }

                // optional reasonspec or propspec
                tokenIndex = index;

                if (!SkipKeyword(text, ref index, endIndex))
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Invalid reasonspec or propspec token at offset {0}", tokenIndex), tokenIndex, index);
                    }

                    return(false);
                }

                value = Encoding.ASCII.GetString(text, tokenIndex, index - tokenIndex);

                if (value == "reason")
                {
                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index >= endIndex)
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Incomplete reasonspec token at offset {0}", tokenIndex), tokenIndex, index);
                        }

                        return(false);
                    }

                    if (text[index] != (byte)'=')
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Invalid reasonspec token at offset {0}", tokenIndex), tokenIndex, index);
                        }

                        return(false);
                    }

                    index++;

                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    int reasonIndex = index;

                    if (index >= endIndex || !SkipValue(text, ref index, endIndex, out quoted))
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Invalid reasonspec value token at offset {0}", reasonIndex), reasonIndex, index);
                        }

                        return(false);
                    }

                    resinfo.Reason = Encoding.UTF8.GetString(text, reasonIndex, index - reasonIndex);

                    if (quoted)
                    {
                        resinfo.Reason = MimeUtils.Unquote(resinfo.Reason);
                    }

                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index >= endIndex)
                    {
                        break;
                    }

                    if (text[index] == (byte)';')
                    {
                        index++;
                        continue;
                    }

                    // optional propspec
                    tokenIndex = index;

                    if (!SkipKeyword(text, ref index, endIndex))
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Invalid propspec token at offset {0}", tokenIndex), tokenIndex, index);
                        }

                        return(false);
                    }

                    value = Encoding.ASCII.GetString(text, tokenIndex, index - tokenIndex);
                }

                do
                {
                    // value is a propspec ptype token
                    var ptype = value;

                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index >= endIndex)
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Incomplete propspec token at offset {0}", tokenIndex), tokenIndex, index);
                        }

                        return(false);
                    }

                    if (text[index] != (byte)'.')
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Invalid propspec token at offset {0}", tokenIndex), tokenIndex, index);
                        }

                        return(false);
                    }

                    index++;

                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index >= endIndex)
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Incomplete propspec token at offset {0}", tokenIndex), tokenIndex, index);
                        }

                        return(false);
                    }

                    int propertyIndex = index;

                    if (!SkipKeyword(text, ref index, endIndex))
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Invalid property token at offset {0}", propertyIndex), propertyIndex, index);
                        }

                        return(false);
                    }

                    var property = Encoding.ASCII.GetString(text, propertyIndex, index - propertyIndex);

                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index >= endIndex)
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Incomplete propspec token at offset {0}", tokenIndex), tokenIndex, index);
                        }

                        return(false);
                    }

                    if (text[index] != (byte)'=')
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Invalid propspec token at offset {0}", tokenIndex), tokenIndex, index);
                        }

                        return(false);
                    }

                    index++;

                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index >= endIndex)
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Incomplete propspec token at offset {0}", tokenIndex), tokenIndex, index);
                        }

                        return(false);
                    }

                    int valueIndex = index;

                    while (index < endIndex && text[index] != ';' && !text[index].IsWhitespace())
                    {
                        index++;
                    }

                    if (index == valueIndex)
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Incomplete propspec token at offset {0}", tokenIndex), tokenIndex, index);
                        }

                        return(false);
                    }

                    value = Encoding.UTF8.GetString(text, valueIndex, index - valueIndex);

                    var propspec = new AuthenticationMethodProperty(ptype, property, value);
                    resinfo.Properties.Add(propspec);

                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index >= endIndex || text[index] == (byte)';')
                    {
                        break;
                    }

                    tokenIndex = index;

                    if (!SkipKeyword(text, ref index, endIndex))
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Invalid propspec token at offset {0}", tokenIndex), tokenIndex, index);
                        }

                        return(false);
                    }

                    value = Encoding.ASCII.GetString(text, tokenIndex, index - tokenIndex);
                } while (true);

                // skip over ';'
                index++;
            }

            return(true);
        }
 public void TestParse()
 {
     Assert.AreEqual(5, ParseUtils.ParseInt("5"));
     Assert.AreEqual(10, ParseUtils.ParseInt("sdvavd", 10));
 }
Exemplo n.º 3
0
        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 = ParseUtils.GetStlLabels(contentBuilder.ToString());

                if (ParseUtils.IsStlElementExists(StlPageContents.ElementName, stlLabelList))
                {
                    var stlElement             = ParseUtils.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 (ParseUtils.IsStlElementExists(StlPageSqlContents.ElementName, stlLabelList))
                {
                    var stlElement = ParseUtils.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));
            }
        }
Exemplo n.º 4
0
        internal static bool TryParse(ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out ContentType contentType)
        {
            string type, subtype;
            int    start;

            contentType = null;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            start = index;
            if (!SkipType(text, ref index, endIndex))
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Invalid type token at position {0}", start), start, index);
                }

                return(false);
            }

            type = Encoding.ASCII.GetString(text, start, index - start);

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex || text[index] != (byte)'/')
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Expected '/' at position {0}", index), index, index);
                }

                return(false);
            }

            // skip over the '/'
            index++;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            start = index;
            if (!ParseUtils.SkipToken(text, ref index, endIndex))
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Invalid atom token at position {0}", start), start, index);
                }

                return(false);
            }

            subtype = Encoding.ASCII.GetString(text, start, index - start);

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            contentType = new ContentType(type, subtype);

            if (index >= endIndex)
            {
                return(true);
            }

            if (text[index] != (byte)';')
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Expected ';' at position {0}", index), index, index);
                }

                return(false);
            }

            index++;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                return(true);
            }

            ParameterList parameters;

            if (!ParameterList.TryParse(options, text, ref index, endIndex, throwOnError, out parameters))
            {
                return(false);
            }

            contentType.Parameters = parameters;

            return(true);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Asynchronously parses a message from the stream.
        /// </summary>
        /// <remarks>
        /// Parses a message from the stream.
        /// </remarks>
        /// <returns>The parsed message.</returns>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <exception cref="System.OperationCanceledException">
        /// The operation was canceled via the cancellation token.
        /// </exception>
        /// <exception cref="System.FormatException">
        /// There was an error parsing the message.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        public async Task <MimeMessage> ParseMessageAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            // Note: if a previously parsed MimePart's content has been read,
            // then the stream position will have moved and will need to be
            // reset.
            if (persistent && stream.Position != offset)
            {
                stream.Seek(offset, SeekOrigin.Begin);
            }

            // scan the from-line if we are parsing an mbox
            while (state != MimeParserState.MessageHeaders)
            {
                switch (await StepAsync(cancellationToken).ConfigureAwait(false))
                {
                case MimeParserState.Error:
                    throw new FormatException("Failed to find mbox From marker.");

                case MimeParserState.Eos:
                    throw new FormatException("End of stream.");
                }
            }

            toplevel = true;

            // parse the headers
            if (state < MimeParserState.Content && await StepAsync(cancellationToken).ConfigureAwait(false) == MimeParserState.Error)
            {
                throw new FormatException("Failed to parse message headers.");
            }

            var message = new MimeMessage(options, headers, RfcComplianceMode.Loose);

            if (format == MimeFormat.Mbox && options.RespectContentLength)
            {
                contentEnd = 0;

                for (int i = 0; i < headers.Count; i++)
                {
                    if (headers[i].Id != HeaderId.ContentLength)
                    {
                        continue;
                    }

                    var value = headers[i].RawValue;
                    int length, index = 0;

                    if (!ParseUtils.SkipWhiteSpace(value, ref index, value.Length))
                    {
                        continue;
                    }

                    if (!ParseUtils.TryParseInt32(value, ref index, value.Length, out length))
                    {
                        continue;
                    }

                    long endOffset = GetOffset(inputIndex) + length;

                    contentEnd = endOffset;
                    break;
                }
            }

            var type   = GetContentType(null);
            var entity = options.CreateEntity(type, headers, true, 0);

            message.Body = entity;

            if (entity is Multipart)
            {
                await ConstructMultipartAsync((Multipart)entity, 0, cancellationToken).ConfigureAwait(false);
            }
            else if (entity is MessagePart)
            {
                await ConstructMessagePartAsync((MessagePart)entity, 0, cancellationToken).ConfigureAwait(false);
            }
            else
            {
                await ConstructMimePartAsync((MimePart)entity, cancellationToken).ConfigureAwait(false);
            }

            if (boundary != BoundaryType.Eos)
            {
                if (format == MimeFormat.Mbox)
                {
                    state = MimeParserState.MboxMarker;
                }
                else
                {
                    state = MimeParserState.Complete;
                }
            }
            else
            {
                state = MimeParserState.Eos;
            }

            return(message);
        }
Exemplo n.º 6
0
        internal static bool TryParse(ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out ParameterList paramList)
        {
            var rfc2231 = new Dictionary <string, List <NameValuePair> > (MimeUtils.OrdinalIgnoreCase);
            var @params = new List <NameValuePair> ();
            List <NameValuePair> parts;

            paramList = null;

            do
            {
                if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                {
                    return(false);
                }

                if (index >= endIndex)
                {
                    break;
                }

                // handle empty parameter name/value pairs
                if (text[index] == (byte)';')
                {
                    index++;
                    continue;
                }

                NameValuePair pair;
                if (!TryParseNameValuePair(options, text, ref index, endIndex, throwOnError, out pair))
                {
                    return(false);
                }

                if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                {
                    return(false);
                }

                if (pair.Id.HasValue)
                {
                    if (rfc2231.TryGetValue(pair.Name, out parts))
                    {
                        parts.Add(pair);
                    }
                    else
                    {
                        parts = new List <NameValuePair> ();
                        rfc2231[pair.Name] = parts;
                        @params.Add(pair);
                        parts.Add(pair);
                    }
                }
                else
                {
                    @params.Add(pair);
                }

                if (index >= endIndex)
                {
                    break;
                }

                if (text[index] != (byte)';')
                {
                    if (options.ParameterComplianceMode == RfcComplianceMode.Strict)
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Invalid parameter list token at offset {0}", index), index, index);
                        }

                        return(false);
                    }
                }
                else
                {
                    // Skip over ';'
                    index++;
                }
            } while (true);

            paramList = new ParameterList();
            var hex = new HexDecoder();

            foreach (var param in @params)
            {
                var       method     = ParameterEncodingMethod.Default;
                int       startIndex = param.ValueStart;
                int       length     = param.ValueLength;
                var       buffer     = param.Value;
                Encoding  encoding   = null;
                Decoder   decoder    = null;
                Parameter parameter;
                string    value;

                if (param.Id.HasValue)
                {
                    method = ParameterEncodingMethod.Rfc2231;
                    parts  = rfc2231[param.Name];
                    parts.Sort();

                    value = string.Empty;

                    for (int i = 0; i < parts.Count; i++)
                    {
                        startIndex = parts[i].ValueStart;
                        length     = parts[i].ValueLength;
                        buffer     = parts[i].Value;

                        if (parts[i].Encoded)
                        {
                            bool     flush = i + 1 >= parts.Count || !parts[i + 1].Encoded;
                            Encoding charset;

                            // Note: Some mail clients mistakenly quote encoded parameter values when they shouldn't
                            if (length >= 2 && buffer[startIndex] == (byte)'"' && buffer[startIndex + length - 1] == (byte)'"')
                            {
                                startIndex++;
                                length -= 2;
                            }

                            value   += DecodeRfc2231(out charset, ref decoder, hex, buffer, startIndex, length, flush);
                            encoding = encoding ?? charset;
                        }
                        else if (length >= 2 && buffer[startIndex] == (byte)'"')
                        {
                            var quoted = CharsetUtils.ConvertToUnicode(options, buffer, startIndex, length);
                            value += MimeUtils.Unquote(quoted);
                            hex.Reset();
                        }
                        else if (length > 0)
                        {
                            value += CharsetUtils.ConvertToUnicode(options, buffer, startIndex, length);
                            hex.Reset();
                        }
                    }
                    hex.Reset();
                }
                else if (param.Encoded)
                {
                    // Note: param value is not supposed to be quoted, but issue #239 illustrates
                    // that this can happen in the wild. Hopefully we will not need to worry
                    // about quoted-pairs.
                    if (length >= 2 && buffer[startIndex] == (byte)'"')
                    {
                        if (buffer[startIndex + length - 1] == (byte)'"')
                        {
                            length--;
                        }

                        startIndex++;
                        length--;
                    }

                    value  = DecodeRfc2231(out encoding, ref decoder, hex, buffer, startIndex, length, true);
                    method = ParameterEncodingMethod.Rfc2231;
                    hex.Reset();
                }
                else if (!paramList.Contains(param.Name))
                {
                    // Note: If we've got an rfc2231-encoded version of the same parameter, then
                    // we'll want to choose that one as opposed to the ASCII variant (i.e. this one).
                    //
                    // While most mail clients that I know of do not send multiple parameters of the
                    // same name, rfc6266 suggests that HTTP servers are using this approach to work
                    // around HTTP clients that do not (yet) implement support for the rfc2231
                    // encoding of parameter values. Since none of the MIME specifications provide
                    // any suggestions for dealing with this, following rfc6266 seems to make the
                    // most sense, even though it is meant for HTTP clients and servers.
                    int codepage = -1;

                    if (length >= 2 && text[startIndex] == (byte)'"')
                    {
                        var quoted = Rfc2047.DecodeText(options, buffer, startIndex, length, out codepage);
                        value = MimeUtils.Unquote(quoted);
                    }
                    else if (length > 0)
                    {
                        value = Rfc2047.DecodeText(options, buffer, startIndex, length, out codepage);
                    }
                    else
                    {
                        value = string.Empty;
                    }

                    if (codepage != -1 && codepage != 65001)
                    {
                        encoding = CharsetUtils.GetEncoding(codepage);
                        method   = ParameterEncodingMethod.Rfc2047;
                    }
                }
                else
                {
                    continue;
                }

                if (paramList.table.TryGetValue(param.Name, out parameter))
                {
                    parameter.Encoding = encoding;
                    parameter.Value    = value;
                }
                else if (encoding != null)
                {
                    paramList.Add(encoding, param.Name, value);
                    parameter = paramList[paramList.Count - 1];
                }
                else
                {
                    paramList.Add(param.Name, value);
                    parameter = paramList[paramList.Count - 1];
                }

                parameter.EncodingMethod = method;
            }

            return(true);
        }
Exemplo n.º 7
0
        /**
         * Parse binary xml.
         */
        public async Task parse()
        {
            ChunkHeader chunkHeader = await readChunkHeader();

            if (chunkHeader == null)
            {
                return;
            }
            if (chunkHeader.getChunkType() != ChunkType.XML && chunkHeader.getChunkType() != ChunkType.NULL)
            {
                // notice that some apk mark xml header type as 0, really weird
                // see https://github.com/clearthesky/apk-parser/issues/49#issuecomment-256852727
                return;
            }

            // read string pool chunk
            chunkHeader = await readChunkHeader();

            if (chunkHeader == null)
            {
                return;
            }
            ParseUtils.checkChunkType(ChunkType.STRING_POOL, chunkHeader.getChunkType());
            stringPool = await ParseUtils.readStringPool(buffer, (StringPoolHeader)chunkHeader);

            // read on chunk, check if it was an optional XMLResourceMap chunk
            chunkHeader = await readChunkHeader();

            if (chunkHeader == null)
            {
                return;
            }
            if (chunkHeader.getChunkType() == ChunkType.XML_RESOURCE_MAP)
            {
                long[] resourceIds = readXmlResourceMap((XmlResourceMapHeader)chunkHeader);
                resourceMap = new string[resourceIds.Length];
                for (int i = 0; i < resourceIds.Length; i++)
                {
                    resourceMap[i] = await Attribute_.AttrIds.getString(resourceIds[i]);
                }
                chunkHeader = await readChunkHeader();
            }

            while (chunkHeader != null)
            {
                /*if (chunkHeader.chunkType == ChunkType.XML_END_NAMESPACE) {
                 *  break;
                 * }*/
                long beginPos = buffer.position();
                switch (chunkHeader.getChunkType())
                {
                case ChunkType.XML_END_NAMESPACE:
                    XmlNamespaceEndTag xmlNamespaceEndTag = readXmlNamespaceEndTag();
                    xmlStreamer.onNamespaceEnd(xmlNamespaceEndTag);
                    break;

                case ChunkType.XML_START_NAMESPACE:
                    XmlNamespaceStartTag namespaceStartTag = readXmlNamespaceStartTag();
                    xmlStreamer.onNamespaceStart(namespaceStartTag);
                    break;

                case ChunkType.XML_START_ELEMENT:
                    XmlNodeStartTag xmlNodeStartTag = await readXmlNodeStartTag();

                    break;

                case ChunkType.XML_END_ELEMENT:
                    XmlNodeEndTag xmlNodeEndTag = readXmlNodeEndTag();
                    break;

                case ChunkType.XML_CDATA:
                    XmlCData xmlCData = await readXmlCData();

                    break;

                default:
                    if (chunkHeader.getChunkType() >= ChunkType.XML_FIRST_CHUNK &&
                        chunkHeader.getChunkType() <= ChunkType.XML_LAST_CHUNK)
                    {
                        Buffers.skip(buffer, chunkHeader.getBodySize());
                    }
                    else
                    {
                        throw new ParserException("Unexpected chunk type:" + chunkHeader.getChunkType());
                    }
                    break;
                }
                buffer.position((int)(beginPos + chunkHeader.getBodySize()));
                chunkHeader = await readChunkHeader();
            }
        }
Exemplo n.º 8
0
        public void TryParseNullableDateTypes_DayBeforeMonth_19991231(string s)
        {
            var expected = new DateTime(1999, 12, 31);
            var expectedWithUtcOffset   = new DateTimeOffset(expected, TimeSpan.Zero);
            var expectedWithLocalOffset = new DateTimeOffset(expected, TimeZoneInfo.Local.GetUtcOffset(expected));

            Assert.IsNull(ParseUtils.TryParseNullableDateInvariant(s));
            Assert.IsNull(RunForCulture(enUsCulture, () => ParseUtils.TryParseNullableDate(s)));
            Assert.AreEqual(expected, RunForCulture(enGbCulture, () => ParseUtils.TryParseNullableDate(s)));
            Assert.AreEqual(expected, RunForCulture(frFrCulture, () => ParseUtils.TryParseNullableDate(s)));

            Assert.IsNull(ParseUtils.TryParseNullableDateTimeUtcInvariant(s));
            Assert.IsNull(RunForCulture(enUsCulture, () => ParseUtils.TryParseNullableDateTime(s)));
            Assert.AreEqual(expected, RunForCulture(enGbCulture, () => ParseUtils.TryParseNullableDateTime(s)));
            Assert.AreEqual(expected, RunForCulture(frFrCulture, () => ParseUtils.TryParseNullableDateTime(s)));

            Assert.IsNull(RunForCulture(enUsCulture, () => ParseUtils.TryParseNullableDateTimeOffset(s)));
            Assert.AreEqual(expectedWithLocalOffset, RunForCulture(enGbCulture, () => ParseUtils.TryParseNullableDateTimeOffset(s)));
            Assert.AreEqual(expectedWithLocalOffset, RunForCulture(frFrCulture, () => ParseUtils.TryParseNullableDateTimeOffset(s)));

            Assert.IsNull(ParseUtils.TryParseNullableDateTimeOffsetAssumeUtcInvariant(s));
        }
Exemplo n.º 9
0
        public void TryParseNullableDateTimeTypes_19991231T130203(string s)
        {
            var expectedDate            = new DateTime(1999, 12, 31);
            var expected                = new DateTime(1999, 12, 31, 13, 2, 3);
            var expectedWithUtcOffset   = new DateTimeOffset(expected, TimeSpan.Zero);
            var expectedWithLocalOffset = new DateTimeOffset(expected, TimeZoneInfo.Local.GetUtcOffset(expected));

            Assert.AreEqual(expectedDate, ParseUtils.TryParseNullableDateInvariant(s));
            Assert.AreEqual(DateTimeKind.Unspecified, ParseUtils.TryParseNullableDateInvariant(s).Value.Kind);
            Assert.AreEqual(expectedDate, RunForCulture(enUsCulture, () => ParseUtils.TryParseNullableDate(s)));
            Assert.AreEqual(expectedDate, RunForCulture(enGbCulture, () => ParseUtils.TryParseNullableDate(s)));
            Assert.AreEqual(expectedDate, RunForCulture(frFrCulture, () => ParseUtils.TryParseNullableDate(s)));

            Assert.AreEqual(expected, ParseUtils.TryParseNullableDateTimeUtcInvariant(s));
            Assert.AreEqual(DateTimeKind.Utc, ParseUtils.TryParseNullableDateTimeUtcInvariant(s).Value.Kind);

            Assert.AreEqual(expected, RunForCulture(enUsCulture, () => ParseUtils.TryParseNullableDateTime(s)));
            Assert.AreEqual(expected, RunForCulture(enGbCulture, () => ParseUtils.TryParseNullableDateTime(s)));
            Assert.AreEqual(expected, RunForCulture(frFrCulture, () => ParseUtils.TryParseNullableDateTime(s)));

            Assert.AreEqual(expectedWithLocalOffset, RunForCulture(enUsCulture, () => ParseUtils.TryParseNullableDateTimeOffset(s)));
            Assert.AreEqual(expectedWithLocalOffset, RunForCulture(enGbCulture, () => ParseUtils.TryParseNullableDateTimeOffset(s)));
            Assert.AreEqual(expectedWithLocalOffset, RunForCulture(frFrCulture, () => ParseUtils.TryParseNullableDateTimeOffset(s)));

            Assert.AreEqual(expectedWithUtcOffset, ParseUtils.TryParseNullableDateTimeOffsetAssumeUtcInvariant(s));
        }
Exemplo n.º 10
0
        protected override RequestedAction PostCreateImageAttributes(ImageState s)
        {
            if (!s.settings.WasOneSpecified((string[])GetSupportedQuerystringKeys()))
            {
                return(RequestedAction.None);
            }

            List <float[][]> filters = new List <float[][]>();

            string filter = s.settings["filter"];

            if (!string.IsNullOrEmpty(filter))
            {
                int      valuesStart = filter.IndexOf('(');
                string   valStr      = null;
                double[] values      = null;
                if (valuesStart > -1)
                {
                    valStr = filter.Substring(valuesStart);
                    filter = filter.Substring(0, valuesStart);
                    values = ParseUtils.ParseList <double>(valStr, 0, 0, 1);
                }

                if ("grayscale".Equals(filter, StringComparison.OrdinalIgnoreCase))
                {
                    filters.Add(GrayscaleFlat());
                }
                if ("sepia".Equals(filter, StringComparison.OrdinalIgnoreCase))
                {
                    filters.Add(Sepia());
                }
                if (values != null && values.Length == 1)
                {
                    if ("alpha".Equals(filter, StringComparison.OrdinalIgnoreCase))
                    {
                        filters.Add(Alpha((float)values[0]));
                    }
                    if ("brightness".Equals(filter, StringComparison.OrdinalIgnoreCase))
                    {
                        filters.Add(Brightness((float)values[0]));
                    }
                }
            }
            if ("true".Equals(s.settings["s.grayscale"], StringComparison.OrdinalIgnoreCase))
            {
                filters.Add(GrayscaleNTSC());
            }
            if ("flat".Equals(s.settings["s.grayscale"], StringComparison.OrdinalIgnoreCase))
            {
                filters.Add(GrayscaleFlat());
            }
            if ("y".Equals(s.settings["s.grayscale"], StringComparison.OrdinalIgnoreCase))
            {
                filters.Add(GrayscaleY());
            }
            if ("ry".Equals(s.settings["s.grayscale"], StringComparison.OrdinalIgnoreCase))
            {
                filters.Add(GrayscaleRY());
            }
            if ("ntsc".Equals(s.settings["s.grayscale"], StringComparison.OrdinalIgnoreCase))
            {
                filters.Add(GrayscaleNTSC());
            }
            if ("bt709".Equals(s.settings["s.grayscale"], StringComparison.OrdinalIgnoreCase))
            {
                filters.Add(GrayscaleBT709());
            }

            if ("true".Equals(s.settings["s.sepia"], StringComparison.OrdinalIgnoreCase))
            {
                filters.Add(Sepia());
            }
            if ("true".Equals(s.settings["s.invert"], StringComparison.OrdinalIgnoreCase))
            {
                filters.Add(Invert());
            }

            Color?c = Util.ParseUtils.ParseColor(s.settings["s.shift"]);

            if (c != null)
            {
                filters.Add(Shift(c.Value));
            }

            string alpha      = s.settings["s.alpha"];
            string brightness = s.settings["s.brightness"];
            string contrast   = s.settings["s.contrast"];
            string saturation = s.settings["s.saturation"];

            double temp = 0;

            if (!string.IsNullOrEmpty(alpha) && double.TryParse(alpha, ParseUtils.FloatingPointStyle, NumberFormatInfo.InvariantInfo, out temp))
            {
                filters.Add(Alpha((float)temp));
            }
            if (!string.IsNullOrEmpty(brightness) && double.TryParse(brightness, ParseUtils.FloatingPointStyle, NumberFormatInfo.InvariantInfo, out temp))
            {
                filters.Add(Brightness((float)temp));
            }
            if (!string.IsNullOrEmpty(contrast) && double.TryParse(contrast, ParseUtils.FloatingPointStyle, NumberFormatInfo.InvariantInfo, out temp))
            {
                filters.Add(Contrast((float)temp));
            }
            if (!string.IsNullOrEmpty(saturation) && double.TryParse(saturation, ParseUtils.FloatingPointStyle, NumberFormatInfo.InvariantInfo, out temp))
            {
                filters.Add(Saturation((float)temp));
            }


            if (filters.Count == 0)
            {
                return(RequestedAction.None);
            }
            if (filters.Count == 1)
            {
                s.colorMatrix = filters[0];
            }
            else
            {
                //Multiple all the filters
                float[][] first = filters[0];

                for (int i = 1; i < filters.Count; i++)
                {
                    first = Multiply(first, filters[i]);
                }
                s.colorMatrix = first;
            }


            return(RequestedAction.None);
        }
Exemplo n.º 11
0
 public void Parse_Guid()
 {
     Assert.AreEqual(new Guid("2FD3E8A1-C209-4FB4-9243-DB63D6B1A0AD"), ParseUtils.ParseInvariant <Guid>("2FD3E8A1-C209-4FB4-9243-DB63D6B1A0AD"));
     Assert.AreEqual(new Guid("2FD3E8A1-C209-4FB4-9243-DB63D6B1A0AD"), ParseUtils.ParseInvariant <Guid?>("2FD3E8A1-C209-4FB4-9243-DB63D6B1A0AD"));
 }
Exemplo n.º 12
0
        public void LbTemplate_Click(object sender, EventArgs e)
        {
            CacheUtils.InsertMinutes("SiteServer.BackgroundPages.Cms.PageTemplatePreview", Main.Instance.DataApi.Encrypt(ParseUtils.GetFormStlElement(FormInfo)), 5);
            var url =
                Main.Instance.FilesApi.GetAdminDirectoryUrl(
                    $"cms/pageTemplatePreview.aspx?siteId={SiteId}&fromCache={true}&returnUrl={Main.Instance.DataApi.Encrypt(Main.Instance.PluginApi.GetPluginUrl(PageLogsUrl))}");

            Response.Redirect(Main.Instance.FilesApi.GetAdminDirectoryUrl($"loading.aspx?redirectUrl={Main.Instance.DataApi.Encrypt(url)}"));
        }
Exemplo n.º 13
0
 private string GetTemplateOwner(Template template)
 {
     if (ParseUtils.ParseGitHubRepoOwnerAndName(template.RemoteUrl, out global::System.String owner, out global::System.String name))
     {
         return(owner);
     }
Exemplo n.º 14
0
 public float DistanceToPlane(Vec3 v)
 {
     return((float)(ParseUtils.RoundToSignificantDigits(Vec3.Dot(this.Normal, v), 5) + ParseUtils.RoundToSignificantDigits(this.Distance, 5)));
 }
Exemplo n.º 15
0
        internal static bool TryParse(ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out ParameterList paramList)
        {
            var rfc2184 = new Dictionary <string, List <NameValuePair> > (icase);
            var @params = new List <NameValuePair> ();
            List <NameValuePair> parts;

            paramList = null;

            do
            {
                if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                {
                    return(false);
                }

                if (index >= endIndex)
                {
                    break;
                }

                // handle empty parameter name/value pairs
                if (text[index] == (byte)';')
                {
                    index++;
                    continue;
                }

                NameValuePair pair;
                if (!TryParseNameValuePair(options, text, ref index, endIndex, throwOnError, out pair))
                {
                    return(false);
                }

                if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                {
                    return(false);
                }

                if (pair.Id.HasValue)
                {
                    if (rfc2184.TryGetValue(pair.Name, out parts))
                    {
                        parts.Add(pair);
                    }
                    else
                    {
                        parts = new List <NameValuePair> ();
                        rfc2184[pair.Name] = parts;
                        @params.Add(pair);
                        parts.Add(pair);
                    }
                }
                else
                {
                    @params.Add(pair);
                }

                if (index >= endIndex)
                {
                    break;
                }

                if (text[index] != (byte)';')
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Invalid parameter list token at offset {0}", index), index, index);
                    }

                    return(false);
                }

                index++;
            } while (true);

            paramList = new ParameterList();
            var hex = new HexDecoder();

            foreach (var param in @params)
            {
                int     startIndex = param.ValueStart;
                int     length     = param.ValueLength;
                Decoder decoder    = null;
                string  value;

                if (param.Id.HasValue)
                {
                    parts = rfc2184[param.Name];
                    parts.Sort();

                    value = string.Empty;
                    for (int i = 0; i < parts.Count; i++)
                    {
                        startIndex = parts[i].ValueStart;
                        length     = parts[i].ValueLength;

                        if (parts[i].Encoded)
                        {
                            bool flush = i + 1 >= parts.Count || !parts[i + 1].Encoded;

                            // Note: Some mail clients mistakenly quote encoded parameter values when they shouldn't
                            if (length >= 2 && text[startIndex] == (byte)'"' && text[startIndex + length - 1] == (byte)'"')
                            {
                                startIndex++;
                                length -= 2;
                            }

                            value += DecodeRfc2184(ref decoder, hex, text, startIndex, length, flush);
                        }
                        else if (length >= 2 && text[startIndex] == (byte)'"')
                        {
                            var quoted = CharsetUtils.ConvertToUnicode(options, text, startIndex, length);
                            value += MimeUtils.Unquote(quoted);
                            hex.Reset();
                        }
                        else if (length > 0)
                        {
                            value += CharsetUtils.ConvertToUnicode(options, text, startIndex, length);
                            hex.Reset();
                        }
                    }
                    hex.Reset();
                }
                else if (param.Encoded)
                {
                    value = DecodeRfc2184(ref decoder, hex, text, startIndex, length, true);
                    hex.Reset();
                }
                else if (!paramList.Contains(param.Name))
                {
                    // Note: If we've got an rfc2184-encoded version of the same parameter, then
                    // we'll want to choose that one as opposed to the ASCII variant (i.e. this one).
                    //
                    // While most mail clients that I know of do not send multiple parameters of the
                    // same name, rfc6266 suggests that HTTP servers are using this approach to work
                    // around HTTP clients that do not (yet) implement support for the rfc2184/2231
                    // encoding of parameter values. Since none of the MIME specifications provide
                    // any suggestions for dealing with this, following rfc6266 seems to make the
                    // most sense, even though it is meant for HTTP clients and servers.
                    if (length >= 2 && text[startIndex] == (byte)'"')
                    {
                        var quoted = Rfc2047.DecodeText(options, text, startIndex, length);
                        value = MimeUtils.Unquote(quoted);
                    }
                    else if (length > 0)
                    {
                        value = Rfc2047.DecodeText(options, text, startIndex, length);
                    }
                    else
                    {
                        value = string.Empty;
                    }
                }
                else
                {
                    continue;
                }

                paramList[param.Name] = value;
            }

            return(true);
        }
Exemplo n.º 16
0
 public void Parse_NumbersFrance(string s, double expected)
 {
     Assert.AreEqual(expected, RunForCulture(frFrCulture, () => ParseUtils.Parse(s, typeof(double))));
     Assert.AreEqual((float)expected, RunForCulture(frFrCulture, () => ParseUtils.Parse(s, typeof(float))));
     Assert.AreEqual((decimal)expected, RunForCulture(frFrCulture, () => ParseUtils.Parse(s, typeof(decimal))));
 }
Exemplo n.º 17
0
        internal static bool TryParse(ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out ContentDisposition disposition)
        {
            string type;
            int    atom;

            disposition = null;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            atom = index;
            if (!ParseUtils.SkipAtom(text, ref index, endIndex))
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Invalid atom token at position {0}", atom), atom, index);
                }

                return(false);
            }

            type = Encoding.ASCII.GetString(text, atom, index - atom);

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            disposition             = new ContentDisposition();
            disposition.disposition = type;

            if (index >= endIndex)
            {
                return(true);
            }

            if (text[index] != (byte)';')
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Expected ';' at position {0}", index), index, index);
                }

                return(false);
            }

            index++;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                return(true);
            }

            ParameterList parameters;

            if (!ParameterList.TryParse(options, text, ref index, endIndex, throwOnError, out parameters))
            {
                return(false);
            }

            disposition.Parameters = parameters;

            return(true);
        }
Exemplo n.º 18
0
 public void Parse_Failures_NumbersAmerica(string s)
 {
     Assert.Throws <FormatException>(() => RunForCulture(enUsCulture, () => ParseUtils.Parse(s, typeof(double))));
     Assert.Throws <FormatException>(() => RunForCulture(enUsCulture, () => ParseUtils.Parse(s, typeof(float))));
     Assert.Throws <FormatException>(() => RunForCulture(enUsCulture, () => ParseUtils.Parse(s, typeof(decimal))));
 }
Exemplo n.º 19
0
        static bool TryParseNameValuePair(ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out NameValuePair pair)
        {
            int  valueIndex, valueLength, startIndex;
            bool encoded = false;
            int? id      = null;

            byte[] value;
            string name;

            pair = null;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            startIndex = index;
            if (!SkipParamName(text, ref index, endIndex))
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Invalid parameter name token at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            name = Encoding.ASCII.GetString(text, startIndex, index - startIndex);

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Incomplete parameter at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            if (text[index] == (byte)'*')
            {
                // the parameter is either encoded or it has a part id
                index++;

                if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                {
                    return(false);
                }

                if (index >= endIndex)
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Incomplete parameter at offset {0}", startIndex), startIndex, index);
                    }

                    return(false);
                }

                int identifier;
                if (ParseUtils.TryParseInt32(text, ref index, endIndex, out identifier))
                {
                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index >= endIndex)
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Incomplete parameter at offset {0}", startIndex), startIndex, index);
                        }

                        return(false);
                    }

                    if (text[index] == (byte)'*')
                    {
                        encoded = true;
                        index++;

                        if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                        {
                            return(false);
                        }

                        if (index >= endIndex)
                        {
                            if (throwOnError)
                            {
                                throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Incomplete parameter at offset {0}", startIndex), startIndex, index);
                            }

                            return(false);
                        }
                    }

                    id = identifier;
                }
                else
                {
                    encoded = true;
                }
            }

            if (text[index] != (byte)'=')
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Incomplete parameter at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            index++;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Incomplete parameter at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            valueIndex = index;
            value      = text;

            if (text[index] == (byte)'"')
            {
                ParseUtils.SkipQuoted(text, ref index, endIndex, throwOnError);
                valueLength = index - valueIndex;
            }
            else if (options.ParameterComplianceMode == RfcComplianceMode.Strict)
            {
                ParseUtils.SkipToken(text, ref index, endIndex);
                valueLength = index - valueIndex;
            }
            else
            {
                // Note: Google Docs, for example, does not always quote name/filename parameters
                // with spaces in the name. See https://github.com/jstedfast/MimeKit/issues/106
                // for details.
                while (index < endIndex && text[index] != (byte)';' && text[index] != (byte)'\r' && text[index] != (byte)'\n')
                {
                    index++;
                }

                valueLength = index - valueIndex;

                if (index < endIndex && text[index] != (byte)';')
                {
                    // Note: https://github.com/jstedfast/MimeKit/issues/159 adds to this suckage
                    // by having a multi-line unquoted value with spaces... don't you just love
                    // mail software written by people who have never heard of standards?
                    using (var memory = new MemoryStream()) {
                        memory.Write(text, valueIndex, valueLength);

                        do
                        {
                            while (index < endIndex && (text[index] == (byte)'\r' || text[index] == (byte)'\n'))
                            {
                                index++;
                            }

                            valueIndex = index;

                            while (index < endIndex && text[index] != (byte)';' && text[index] != (byte)'\r' && text[index] != (byte)'\n')
                            {
                                index++;
                            }

                            memory.Write(text, valueIndex, index - valueIndex);
                        } while (index < endIndex && text[index] != ';');

                        value       = memory.ToArray();
                        valueLength = value.Length;
                        valueIndex  = 0;
                    }
                }

                // Trim trailing white space characters to work around issues such as the
                // one described in https://github.com/jstedfast/MimeKit/issues/278
                while (valueLength > valueIndex && value[valueLength - 1].IsWhitespace())
                {
                    valueLength--;
                }
            }

            pair = new NameValuePair {
                ValueLength = valueLength,
                ValueStart  = valueIndex,
                Encoded     = encoded,
                Value       = value,
                Name        = name,
                Id          = id
            };

            return(true);
        }
Exemplo n.º 20
0
        public static async Task <ListInfo> GetListInfoAsync(IParseManager parseManager, ParseType contextType, Query query = null)
        {
            var contextInfo = parseManager.ContextInfo;

            var listInfo = new ListInfo
            {
                _contextType     = contextType,
                DatabaseType     = parseManager.SettingsManager.DatabaseType,
                ConnectionString = parseManager.SettingsManager.DatabaseConnectionString,
                Query            = query
            };

            var innerHtml    = contextInfo.InnerHtml;
            var itemTemplate = string.Empty;

            if (!string.IsNullOrEmpty(innerHtml))
            {
                var stlElementList = ParseUtils.GetStlElements(innerHtml);
                if (stlElementList.Count > 0)
                {
                    foreach (var theStlElement in stlElementList)
                    {
                        if (ParseUtils.IsSpecifiedStlElement(theStlElement, StlItemTemplate.ElementName))
                        {
                            var(templateString, attributes) = ParseUtils.GetInnerHtmlAndAttributes(theStlElement);
                            if (!string.IsNullOrEmpty(templateString))
                            {
                                foreach (var key in attributes.AllKeys)
                                {
                                    if (!StringUtils.EqualsIgnoreCase(key, StlItemTemplate.Type))
                                    {
                                        continue;
                                    }

                                    var type = attributes[key];
                                    if (StringUtils.EqualsIgnoreCase(type, StlItemTemplate.TypeItem))
                                    {
                                        itemTemplate = templateString;
                                    }
                                    else if (StringUtils.EqualsIgnoreCase(type, StlItemTemplate.TypeHeader))
                                    {
                                        listInfo.HeaderTemplate = templateString;
                                    }
                                    else if (StringUtils.EqualsIgnoreCase(type, StlItemTemplate.TypeFooter))
                                    {
                                        listInfo.FooterTemplate = templateString;
                                    }
                                    else if (StringUtils.EqualsIgnoreCase(type, StlItemTemplate.TypeAlternatingItem))
                                    {
                                        listInfo.AlternatingItemTemplate = templateString;
                                    }
                                    else if (StringUtils.EqualsIgnoreCase(type, StlItemTemplate.TypeSelectedItem))
                                    {
                                        if (!string.IsNullOrEmpty(attributes[StlItemTemplate.Selected]))
                                        {
                                            var selected = attributes[StlItemTemplate.Selected];
                                            var list     = new List <string>();
                                            if (selected.IndexOf(',') != -1)
                                            {
                                                list.AddRange(selected.Split(','));
                                            }
                                            else
                                            {
                                                if (selected.IndexOf('-') != -1)
                                                {
                                                    var first  = TranslateUtils.ToInt(selected.Split('-')[0]);
                                                    var second = TranslateUtils.ToInt(selected.Split('-')[1]);
                                                    for (var i = first; i <= second; i++)
                                                    {
                                                        list.Add(i.ToString());
                                                    }
                                                }
                                                else
                                                {
                                                    list.Add(selected);
                                                }
                                            }
                                            foreach (string val in list)
                                            {
                                                listInfo.SelectedItems.Set(val, templateString);
                                            }
                                            if (!string.IsNullOrEmpty(attributes[StlItemTemplate.SelectedValue]))
                                            {
                                                var selectedValue = attributes[StlItemTemplate.SelectedValue];
                                                listInfo.SelectedValues.Set(selectedValue, templateString);
                                            }
                                        }
                                    }
                                    else if (StringUtils.EqualsIgnoreCase(type, StlItemTemplate.TypeSeparator))
                                    {
                                        var selectedValue = TranslateUtils.ToInt(attributes[StlItemTemplate.SelectedValue], 1);
                                        if (selectedValue <= 1)
                                        {
                                            listInfo.SeparatorTemplate = templateString;
                                        }
                                        else
                                        {
                                            listInfo.SeparatorRepeatTemplate = templateString;
                                            listInfo.SeparatorRepeat         = selectedValue;
                                        }
                                    }
                                }
                            }
                            innerHtml = innerHtml.Replace(theStlElement, string.Empty);
                        }
                        else if (ParseUtils.IsSpecifiedStlElement(theStlElement, StlLoading.ElementName))
                        {
                            var innerBuilder = new StringBuilder(ParseUtils.GetInnerHtml(theStlElement));
                            await parseManager.ParseInnerContentAsync(innerBuilder);

                            listInfo.LoadingTemplate = innerBuilder.ToString();
                            innerHtml = innerHtml.Replace(theStlElement, string.Empty);
                        }
                        else if (ParseUtils.IsSpecifiedStlElement(theStlElement, StlQuery.ElementName))
                        {
                            if (listInfo.Query == null)
                            {
                                listInfo.Query = Q.NewQuery();
                            }
                            listInfo.Query.AddQuery(theStlElement);
                            innerHtml = innerHtml.Replace(theStlElement, string.Empty);
                        }
                        else if (contextType == ParseType.SqlContent && ParseUtils.IsSpecifiedStlElement(theStlElement, StlQueryString.ElementName))
                        {
                            var innerBuilder = new StringBuilder(ParseUtils.GetInnerHtml(theStlElement));
                            await parseManager.ParseInnerContentAsync(innerBuilder);

                            listInfo.QueryString = innerBuilder.ToString();
                            innerHtml            = innerHtml.Replace(theStlElement, string.Empty);
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(itemTemplate))
            {
                listInfo.ItemTemplate = !string.IsNullOrEmpty(innerHtml) ? innerHtml : "<stl:a target=\"_blank\"></stl:a>";
            }
            else
            {
                listInfo.ItemTemplate = itemTemplate;
            }

            var isSetDirection = false;//是否设置了direction属性

            foreach (var name in contextInfo.Attributes.AllKeys)
            {
                var value = contextInfo.Attributes[name];

                if (StringUtils.EqualsIgnoreCase(name, StlListBase.ChannelIndex) || StringUtils.EqualsIgnoreCase(name, StlListBase.Index))
                {
                    listInfo.ChannelIndex = await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.ChannelName))
                {
                    listInfo.ChannelName = await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.Parent))
                {
                    listInfo.UpLevel = 1;
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.UpLevel))
                {
                    listInfo.UpLevel = TranslateUtils.ToInt(value);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.TopLevel))
                {
                    listInfo.TopLevel = TranslateUtils.ToInt(value);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.Scope))
                {
                    listInfo.Scope = TranslateUtils.ToEnum(value, ScopeType.Self);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.IsTop))
                {
                    listInfo.IsTop = TranslateUtils.ToBool(value);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.IsRecommend))
                {
                    listInfo.IsRecommend = TranslateUtils.ToBool(value);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.IsHot))
                {
                    listInfo.IsHot = TranslateUtils.ToBool(value);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.IsColor))
                {
                    listInfo.IsColor = TranslateUtils.ToBool(value);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.TotalNum))
                {
                    listInfo.TotalNum = TranslateUtils.ToInt(await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value));
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlPageContents.PageNum))
                {
                    listInfo.PageNum = TranslateUtils.ToInt(await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value), Constants.PageSize);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlPageContents.MaxPage))
                {
                    listInfo.MaxPage = TranslateUtils.ToInt(await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value));
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.StartNum))
                {
                    listInfo.StartNum = TranslateUtils.ToInt(await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value));
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.Order))
                {
                    listInfo.Order = value;
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.Where))
                {
                    listInfo.Where = value;
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.Group))
                {
                    if (contextType == ParseType.Channel)
                    {
                        listInfo.GroupChannel = await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value);

                        if (string.IsNullOrEmpty(listInfo.GroupChannel))
                        {
                            listInfo.GroupChannel = "__Empty__";
                        }
                    }
                    else if (contextType == ParseType.Content)
                    {
                        listInfo.GroupContent = await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value);

                        if (string.IsNullOrEmpty(listInfo.GroupContent))
                        {
                            listInfo.GroupContent = "__Empty__";
                        }
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.GroupNot))
                {
                    if (contextType == ParseType.Channel)
                    {
                        listInfo.GroupChannelNot = await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value);

                        if (string.IsNullOrEmpty(listInfo.GroupChannelNot))
                        {
                            listInfo.GroupChannelNot = "__Empty__";
                        }
                    }
                    else if (contextType == ParseType.Content)
                    {
                        listInfo.GroupContentNot = await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value);

                        if (string.IsNullOrEmpty(listInfo.GroupContentNot))
                        {
                            listInfo.GroupContentNot = "__Empty__";
                        }
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.GroupChannel))
                {
                    listInfo.GroupChannel = await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value);

                    if (string.IsNullOrEmpty(listInfo.GroupChannel))
                    {
                        listInfo.GroupChannel = "__Empty__";
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.GroupChannelNot))
                {
                    listInfo.GroupChannelNot = await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value);

                    if (string.IsNullOrEmpty(listInfo.GroupChannelNot))
                    {
                        listInfo.GroupChannelNot = "__Empty__";
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.GroupContent))
                {
                    listInfo.GroupContent = await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value);

                    if (string.IsNullOrEmpty(listInfo.GroupContent))
                    {
                        listInfo.GroupContent = "__Empty__";
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.GroupContentNot))
                {
                    listInfo.GroupContentNot = await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value);

                    if (string.IsNullOrEmpty(listInfo.GroupContentNot))
                    {
                        listInfo.GroupContentNot = "__Empty__";
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.Tags))
                {
                    listInfo.Tags = await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.Columns))
                {
                    listInfo.Columns = TranslateUtils.ToInt(value);
                    listInfo.Layout  = ListLayout.Table;
                    if (listInfo.Columns > 1 && isSetDirection == false)
                    {
                        listInfo.Direction = "horizontal";
                    }
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.Direction))
                {
                    listInfo.Layout    = ListLayout.Table;
                    listInfo.Direction = value;
                    isSetDirection     = true;
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.Align))
                {
                    listInfo.Align = value;
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.ItemAlign))
                {
                    listInfo.ItemAlign = value;
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.ItemVerticalAlign))
                {
                    listInfo.ItemVerticalAlign = value;
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.ItemClass))
                {
                    listInfo.ItemClass = value;
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.IsImage))
                {
                    listInfo.IsImage = TranslateUtils.ToBool(value);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.IsVideo))
                {
                    listInfo.IsVideo = TranslateUtils.ToBool(value);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.IsFile))
                {
                    listInfo.IsFile = TranslateUtils.ToBool(value);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlContents.IsRelatedContents))
                {
                    listInfo.IsRelatedContents = TranslateUtils.ToBool(value);
                }
                else if (StringUtils.EqualsIgnoreCase(name, StlListBase.Layout))
                {
                    listInfo.Layout = TranslateUtils.ToEnum(value, ListLayout.None);
                }
                else if (contextType == ParseType.SqlContent && StringUtils.EqualsIgnoreCase(name, StlSqlContents.DatabaseTypeName))
                {
                    var databaseType = parseManager.SettingsManager.Configuration[name];
                    if (!string.IsNullOrEmpty(databaseType))
                    {
                        listInfo.DatabaseType = TranslateUtils.ToEnum(databaseType, DatabaseType.MySql);
                    }
                }
                else if (contextType == ParseType.SqlContent && StringUtils.EqualsIgnoreCase(name, StlSqlContents.DatabaseType))
                {
                    listInfo.DatabaseType = TranslateUtils.ToEnum(value, DatabaseType.MySql);
                }
                else if (contextType == ParseType.SqlContent && StringUtils.EqualsIgnoreCase(name, StlSqlContents.ConnectionStringName))
                {
                    var connectionString = parseManager.SettingsManager.Configuration[name];
                    if (!string.IsNullOrEmpty(connectionString))
                    {
                        listInfo.ConnectionString = connectionString;
                    }
                }
                else if (contextType == ParseType.SqlContent && StringUtils.EqualsIgnoreCase(name, StlSqlContents.ConnectionString))
                {
                    listInfo.ConnectionString = value;
                }
                else if (contextType == ParseType.SqlContent && StringUtils.EqualsIgnoreCase(name, StlSqlContents.QueryString))
                {
                    listInfo.QueryString = await parseManager.ReplaceStlEntitiesForAttributeValueAsync(value);
                }
                else
                {
                    listInfo.Others.Set(name, value);
                }
            }

            return(listInfo);
        }
Exemplo n.º 21
0
        internal static bool TryParse(ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out ContentDisposition disposition)
        {
            string type;
            int    atom;

            disposition = null;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Expected atom token at position {0}", index), index, index);
                }

                return(false);
            }

            atom = index;
            if (text[index] == '"')
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Unxpected qstring token at position {0}", atom), atom, index);
                }

                // Note: This is a work-around for broken mailers that quote the disposition value...
                //
                // See https://github.com/jstedfast/MailKit/issues/486 for details.
                if (!ParseUtils.SkipQuoted(text, ref index, endIndex, throwOnError))
                {
                    return(false);
                }

                type = CharsetUtils.ConvertToUnicode(options, text, atom, index - atom);
                type = MimeUtils.Unquote(type);

                if (string.IsNullOrEmpty(type))
                {
                    type = Attachment;
                }
            }
            else
            {
                if (!ParseUtils.SkipAtom(text, ref index, endIndex))
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Invalid atom token at position {0}", atom), atom, index);
                    }

                    // Note: this is a work-around for broken mailers that do not specify a disposition value...
                    //
                    // See https://github.com/jstedfast/MailKit/issues/486 for details.
                    if (index > atom || text[index] != (byte)';')
                    {
                        return(false);
                    }

                    type = Attachment;
                }
                else
                {
                    type = Encoding.ASCII.GetString(text, atom, index - atom);
                }
            }

            disposition             = new ContentDisposition();
            disposition.disposition = type;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                return(true);
            }

            if (text[index] != (byte)';')
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Expected ';' at position {0}", index), index, index);
                }

                return(false);
            }

            index++;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                return(true);
            }

            ParameterList parameters;

            if (!ParameterList.TryParse(options, text, ref index, endIndex, throwOnError, out parameters))
            {
                return(false);
            }

            disposition.Parameters = parameters;

            return(true);
        }
Exemplo n.º 22
0
        private async Task ExecuteChannelAsync(int siteId, int channelId)
        {
            var site = await _siteRepository.GetAsync(siteId);

            var channelInfo = await _channelRepository.GetAsync(channelId);

            var count = await _contentRepository.GetCountAsync(site, channelInfo);

            if (!_channelRepository.IsCreatable(site, channelInfo, count))
            {
                return;
            }

            var template = channelId == siteId
                ? await _templateRepository.GetIndexPageTemplateAsync(siteId)
                : await _templateRepository.GetChannelTemplateAsync(siteId, channelInfo);

            var filePath = await _pathManager.GetChannelPageFilePathAsync(site, channelId, 0);

            await _parseManager.InitAsync(EditMode.Default, site, channelId, 0, template);

            _parseManager.ContextInfo.ContextType = ParseType.Channel;

            var contentBuilder = new StringBuilder(await _pathManager.GetTemplateContentAsync(site, template));

            var stlLabelList = ParseUtils.GetStlLabels(contentBuilder.ToString());

            //如果标签中存在<stl:channel type="PageContent"></stl:channel>
            if (StlParserUtility.IsStlChannelElementWithTypePageContent(stlLabelList)) //内容存在
            {
                var stlElement           = StlParserUtility.GetStlChannelElementWithTypePageContent(stlLabelList);
                var stlElementTranslated = _parseManager.StlEncrypt(stlElement);
                contentBuilder.Replace(stlElement, stlElementTranslated);

                var innerBuilder = new StringBuilder(stlElement);
                await _parseManager.ParseInnerContentAsync(innerBuilder);

                var pageContentHtml = innerBuilder.ToString();
                var pageCount       = StringUtils.GetCount(Constants.PagePlaceHolder, pageContentHtml) + 1; //一共需要的页数

                await _parseManager.ParseAsync(contentBuilder, filePath, false);

                for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                {
                    var page = _parseManager.PageInfo;
                    _parseManager.PageInfo = _parseManager.PageInfo.Clone();

                    var index  = pageContentHtml.IndexOf(Constants.PagePlaceHolder, StringComparison.Ordinal);
                    var length = index == -1 ? pageContentHtml.Length : index;

                    var pageHtml     = pageContentHtml.Substring(0, length);
                    var pagedBuilder =
                        new StringBuilder(contentBuilder.ToString().Replace(stlElementTranslated, pageHtml));
                    await _parseManager.ReplacePageElementsInChannelPageAsync(pagedBuilder, stlLabelList, currentPageIndex, pageCount, 0);

                    filePath = await _pathManager.GetChannelPageFilePathAsync(site, page.PageChannelId, currentPageIndex);
                    await GenerateFileAsync(filePath, pagedBuilder);

                    if (index != -1)
                    {
                        pageContentHtml = pageContentHtml.Substring(length + Constants.PagePlaceHolder.Length);
                    }

                    _parseManager.PageInfo = page;
                }
            }
            //如果标签中存在<stl:pageContents>
            else if (ParseUtils.IsStlElementExists(StlPageContents.ElementName, stlLabelList))
            {
                var stlElement           = ParseUtils.GetStlElement(StlPageContents.ElementName, stlLabelList);
                var stlElementTranslated = _parseManager.StlEncrypt(stlElement);

                var pageContentsElementParser = await StlPageContents.GetAsync(stlElement, _parseManager);

                var(pageCount, totalNum) = pageContentsElementParser.GetPageCount();

                await _parseManager.PageInfo.AddPageHeadCodeIfNotExistsAsync(ParsePage.Const.Jquery);

                await _parseManager.ParseAsync(contentBuilder, filePath, false);

                for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                {
                    var page = _parseManager.PageInfo;
                    _parseManager.PageInfo = _parseManager.PageInfo.Clone();

                    var pageHtml = await pageContentsElementParser.ParseAsync(totalNum, currentPageIndex, pageCount, true);

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

                    await _parseManager.ReplacePageElementsInChannelPageAsync(pagedBuilder, stlLabelList, currentPageIndex, pageCount, totalNum);

                    filePath = await _pathManager.GetChannelPageFilePathAsync(site, page.PageChannelId, currentPageIndex);

                    await GenerateFileAsync(filePath, pagedBuilder);

                    _parseManager.PageInfo = page;
                }
            }
            //如果标签中存在<stl:pageChannels>
            else if (ParseUtils.IsStlElementExists(StlPageChannels.ElementName, stlLabelList))
            {
                var stlElement           = ParseUtils.GetStlElement(StlPageChannels.ElementName, stlLabelList);
                var stlElementTranslated = _parseManager.StlEncrypt(stlElement);

                var pageChannelsElementParser = await StlPageChannels.GetAsync(stlElement, _parseManager);

                var pageCount = pageChannelsElementParser.GetPageCount(out var totalNum);

                await _parseManager.PageInfo.AddPageHeadCodeIfNotExistsAsync(ParsePage.Const.Jquery);

                await _parseManager.ParseAsync(contentBuilder, filePath, false);

                for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                {
                    var page = _parseManager.PageInfo;
                    _parseManager.PageInfo = _parseManager.PageInfo.Clone();

                    var pageHtml = await pageChannelsElementParser.ParseAsync(currentPageIndex, pageCount);

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

                    await _parseManager.ReplacePageElementsInChannelPageAsync(pagedBuilder, stlLabelList, currentPageIndex, pageCount, totalNum);

                    filePath = await _pathManager.GetChannelPageFilePathAsync(site, page.PageChannelId, currentPageIndex);
                    await GenerateFileAsync(filePath, pagedBuilder);

                    _parseManager.PageInfo = page;
                }
            }
            //如果标签中存在<stl:pageSqlContents>
            else if (ParseUtils.IsStlElementExists(StlPageSqlContents.ElementName, stlLabelList))
            {
                var stlElement           = ParseUtils.GetStlElement(StlPageSqlContents.ElementName, stlLabelList);
                var stlElementTranslated = _parseManager.StlEncrypt(stlElement);

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

                var pageCount = pageSqlContentsElementParser.GetPageCount(out var totalNum);

                await _parseManager.PageInfo.AddPageHeadCodeIfNotExistsAsync(ParsePage.Const.Jquery);

                await _parseManager.ParseAsync(contentBuilder, filePath, false);

                for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                {
                    var page = _parseManager.PageInfo;
                    _parseManager.PageInfo = _parseManager.PageInfo.Clone();

                    var pageHtml = await pageSqlContentsElementParser.ParseAsync(totalNum, currentPageIndex, pageCount, true);

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

                    await _parseManager.ReplacePageElementsInChannelPageAsync(pagedBuilder, stlLabelList, currentPageIndex, pageCount, totalNum);

                    filePath = await _pathManager.GetChannelPageFilePathAsync(site, page.PageChannelId, currentPageIndex);
                    await GenerateFileAsync(filePath, pagedBuilder);

                    _parseManager.PageInfo = page;
                }
            }
            else
            {
                await _parseManager.ParseAsync(contentBuilder, filePath, false);
                await GenerateFileAsync(filePath, contentBuilder);
            }
        }
Exemplo n.º 23
0
        public override async UniTask ExecuteAsync(CancellationToken cancellationToken = default)
        {
            // Don't just return here if skip is enabled; state snapshot is marked as allowed for player rollback when setting waiting for input.

            if (!Assigned(WaitMode))
            {
                LogWarningWithPosition($"`{nameof(WaitMode)}` parameter is not specified, the wait command will do nothing.");
                return;
            }

            // Waiting for player input.
            if (WaitMode.Value.EqualsFastIgnoreCase(InputLiteral))
            {
                scriptPlayer.SetWaitingForInputEnabled(true);
                return;
            }

            // Waiting for timer or input.
            if (WaitMode.Value.StartsWithFast(InputLiteral) && ParseUtils.TryInvariantFloat(WaitMode.Value.GetAfterFirst(InputLiteral), out var skippableWaitTime))
            {
                scriptPlayer.SetWaitingForInputEnabled(true);
                if (scriptPlayer.SkipActive)
                {
                    return;
                }

                var startTime = Time.time;
                while (Application.isPlaying)
                {
                    await AsyncUtils.WaitEndOfFrame;
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }
                    var waitedEnough   = (Time.time - startTime) >= skippableWaitTime;
                    var inputActivated = (inputManager.GetContinue()?.StartedDuringFrame ?? false) || (inputManager.GetSkip()?.StartedDuringFrame ?? false);
                    if (waitedEnough || inputActivated)
                    {
                        break;
                    }
                }
                scriptPlayer.SetWaitingForInputEnabled(false);
                return;
            }

            // Waiting for timer.
            if (ParseUtils.TryInvariantFloat(WaitMode, out var waitTime))
            {
                if (scriptPlayer.SkipActive)
                {
                    return;
                }

                var startTime = Time.time;
                while (Application.isPlaying)
                {
                    await AsyncUtils.WaitEndOfFrame;
                    var waitedEnough = (Time.time - startTime) >= waitTime;
                    if (cancellationToken.IsCancellationRequested || waitedEnough)
                    {
                        break;
                    }
                }
                return;
            }

            LogWarningWithPosition($"Failed to resolve value of the `{nameof(WaitMode)}` parameter for the wait command. Check the API reference for list of supported values.");
        }
        /// <summary>
        /// Decodes general data.
        /// </summary>
        private void DecodeGeneral(string line)
        {
            var data     = GetKeyValue(line);
            var detail   = map.Detail;
            var metadata = detail.Metadata;

            switch (data.Key)
            {
            case "AudioFilename":
                metadata.AudioFile = PathUtils.StandardPath(data.Value);
                break;

            case "AudioLeadIn":
                detail.AudioLeadIn = ParseUtils.ParseInt(data.Value);
                break;

            case "PreviewTime":
                metadata.PreviewTime = ParseUtils.ParseInt(data.Value) + offset;
                break;

            case "Countdown":
                detail.Countdown = ParseUtils.ParseInt(data.Value) == 1;
                break;

            case "SampleSet":
                defaultSampleType = (SampleType)Enum.Parse(typeof(SampleType), data.Value);
                break;

            case "SampleVolume":
                defaultSampleVolume = ParseUtils.ParseFloat(data.Value, 100) / 100f;
                break;

            case "StackLeniency":
                detail.StackLeniency = ParseUtils.ParseFloat(data.Value);
                break;

            case "Mode":
                detail.GameMode = (GameModeType)(ParseUtils.ParseInt(data.Value) + GameProviderType.Osu);

                switch (detail.GameMode)
                {
                // Osu Standard mode
                case GameModeType.OsuStandard:
                    objectParser = new Standard.HitObjectParser(offset, formatVersion);
                    break;
                    // TODO: Osu Taiko mode
                    // case GameModes.OsuTaiko:
                    //  break;
                    // TODO: Osu Catch mode
                    // case GameModes.OsuCatch:
                    //  break;
                    // TODO: Osu Mania mode
                    // case GameModes.OsuMania:
                    //  break;
                }
                break;

            case "LetterboxInBreaks":
                detail.LetterboxInBreaks = ParseUtils.ParseInt(data.Value) == 1;
                break;

            // TODO: Osu file contains a SpecialStyle property but it seems it's not being used anywhere.
            // May have to come back in future once I confirm this.
            case "SpecialStyle":
                break;

            case "WidescreenStoryboard":
                detail.WidescreenStoryboard = ParseUtils.ParseInt(data.Value) == 1;
                break;
            }
        }
Exemplo n.º 25
0
        internal static bool TryParse(ParserOptions options, byte[] text, ref int index, int endIndex, bool isGroup, bool throwOnError, out List <InternetAddress> addresses)
        {
            var             flags = throwOnError ? InternetAddress.AddressParserFlags.Parse : InternetAddress.AddressParserFlags.TryParse;
            var             list  = new List <InternetAddress> ();
            InternetAddress address;

            addresses = null;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index == endIndex)
            {
                if (throwOnError)
                {
                    throw new ParseException("No addresses found.", index, index);
                }

                return(false);
            }

            while (index < endIndex)
            {
                if (isGroup && text[index] == (byte)';')
                {
                    break;
                }

                if (!InternetAddress.TryParse(options, text, ref index, endIndex, flags, out address))
                {
                    // skip this address...
                    while (index < endIndex && text[index] != (byte)',' && (!isGroup || text[index] != (byte)';'))
                    {
                        index++;
                    }
                }
                else
                {
                    list.Add(address);
                }

                // Note: we loop here in case there are any null addresses between commas
                do
                {
                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index >= endIndex || text[index] != (byte)',')
                    {
                        break;
                    }

                    index++;
                } while (true);
            }

            addresses = list;

            return(true);
        }
        /// <summary>
        /// Decodes timing points.
        /// </summary>
        private void DecodeTimingPoints(string line)
        {
            try
            {
                string[] splits = line.Split(',');

                float time            = ParseUtils.ParseFloat(splits[0].Trim()) + offset;
                float beatLength      = ParseUtils.ParseFloat(splits[1].Trim());
                float speedMultiplier = beatLength < 0 ? 100 / -beatLength : 1;

                TimeSignatureType timeSignature = TimeSignatureType.Quadruple;
                if (splits.Length >= 3)
                {
                    timeSignature = splits[2][0] == '0' ? TimeSignatureType.Quadruple : (TimeSignatureType)ParseUtils.ParseInt(splits[2]);
                }

                SampleType sampleType = defaultSampleType;
                if (splits.Length >= 4)
                {
                    sampleType = (SampleType)ParseUtils.ParseInt(splits[3]);
                }

                string sampleTypeString = sampleType.ToString().ToLowerInvariant();
                if (sampleTypeString.Equals("none", StringComparison.Ordinal))
                {
                    sampleTypeString = "normal";
                }

                int sampleVariation = 0;
                if (splits.Length >= 5)
                {
                    sampleVariation = ParseUtils.ParseInt(splits[4]);
                }

                float sampleVolume = defaultSampleVolume;
                if (splits.Length >= 6)
                {
                    sampleVolume = ParseUtils.ParseFloat(splits[5]) / 100f;
                }

                bool isTimingChange = true;
                if (splits.Length >= 7)
                {
                    isTimingChange = splits[6][0] == '1';
                }

                bool isHighlight = false;
                if (splits.Length >= 8)
                {
                    int flags = ParseUtils.ParseInt(splits[7]);
                    isHighlight = (flags & (int)EffectFlagType.IsHighlight) != 0;
                }

                if (isTimingChange)
                {
                    var timingPoint = CreateTimingPoint();
                    timingPoint.Time          = time;
                    timingPoint.BeatLength    = beatLength;
                    timingPoint.TimeSignature = timeSignature;

                    AddTimingPoint(timingPoint);
                }

                AddDifficultyPoint(new DifficultyControlPoint()
                {
                    Time            = time,
                    SpeedMultiplier = speedMultiplier
                });

                AddEffectPoint(new EffectControlPoint()
                {
                    Time        = time,
                    IsHighlight = isHighlight
                });

                AddSamplePoint(new SampleControlPoint()
                {
                    Time    = time,
                    Sample  = sampleTypeString,
                    Variant = sampleVariation,
                    Volume  = sampleVolume,
                });
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 27
0
        static void ExtractAttachments(TnefReader reader, BodyBuilder builder)
        {
            var             attachMethod = TnefAttachMethod.ByValue;
            var             filter = new BestEncodingFilter();
            var             prop = reader.TnefPropertyReader;
            MimePart        attachment = null;
            int             outIndex, outLength;
            TnefAttachFlags flags;

            string[] mimeType;
            byte[]   attachData;
            string   text;

            do
            {
                if (reader.AttributeLevel != TnefAttributeLevel.Attachment)
                {
                    break;
                }

                switch (reader.AttributeTag)
                {
                case TnefAttributeTag.AttachRenderData:
                    attachMethod = TnefAttachMethod.ByValue;
                    attachment   = new MimePart();
                    break;

                case TnefAttributeTag.Attachment:
                    if (attachment == null)
                    {
                        break;
                    }

                    while (prop.ReadNextProperty())
                    {
                        switch (prop.PropertyTag.Id)
                        {
                        case TnefPropertyId.AttachLongFilename:
                            attachment.FileName = prop.ReadValueAsString();
                            break;

                        case TnefPropertyId.AttachFilename:
                            if (attachment.FileName == null)
                            {
                                attachment.FileName = prop.ReadValueAsString();
                            }
                            break;

                        case TnefPropertyId.AttachContentLocation:
                            attachment.ContentLocation = prop.ReadValueAsUri();
                            break;

                        case TnefPropertyId.AttachContentBase:
                            attachment.ContentBase = prop.ReadValueAsUri();
                            break;

                        case TnefPropertyId.AttachContentId:
                            text = prop.ReadValueAsString();

                            var buffer = CharsetUtils.UTF8.GetBytes(text);
                            int index  = 0;

                            if (ParseUtils.TryParseMsgId(buffer, ref index, buffer.Length, false, false, out string msgid))
                            {
                                attachment.ContentId = msgid;
                            }
                            break;

                        case TnefPropertyId.AttachDisposition:
                            text = prop.ReadValueAsString();
                            if (ContentDisposition.TryParse(text, out ContentDisposition disposition))
                            {
                                attachment.ContentDisposition = disposition;
                            }
                            break;

                        case TnefPropertyId.AttachData:
                            if (attachMethod == TnefAttachMethod.EmbeddedMessage)
                            {
                                var tnef = new TnefPart();

                                foreach (var param in attachment.ContentType.Parameters)
                                {
                                    tnef.ContentType.Parameters[param.Name] = param.Value;
                                }

                                if (attachment.ContentDisposition != null)
                                {
                                    tnef.ContentDisposition = attachment.ContentDisposition;
                                }

                                attachment = tnef;
                            }

                            attachData = prop.ReadValueAsBytes();
                            filter.Flush(attachData, 0, attachData.Length, out outIndex, out outLength);
                            attachment.ContentTransferEncoding = filter.GetBestEncoding(EncodingConstraint.SevenBit);
                            attachment.Content = new MimeContent(new MemoryStream(attachData, false));
                            filter.Reset();

                            builder.Attachments.Add(attachment);
                            break;

                        case TnefPropertyId.AttachMethod:
                            attachMethod = (TnefAttachMethod)prop.ReadValueAsInt32();
                            break;

                        case TnefPropertyId.AttachMimeTag:
                            mimeType = prop.ReadValueAsString().Split('/');
                            if (mimeType.Length == 2)
                            {
                                attachment.ContentType.MediaType    = mimeType[0].Trim();
                                attachment.ContentType.MediaSubtype = mimeType[1].Trim();
                            }
                            break;

                        case TnefPropertyId.AttachFlags:
                            flags = (TnefAttachFlags)prop.ReadValueAsInt32();
                            if ((flags & TnefAttachFlags.RenderedInBody) != 0)
                            {
                                if (attachment.ContentDisposition == null)
                                {
                                    attachment.ContentDisposition = new ContentDisposition(ContentDisposition.Inline);
                                }
                                else
                                {
                                    attachment.ContentDisposition.Disposition = ContentDisposition.Inline;
                                }
                            }
                            break;

                        case TnefPropertyId.AttachSize:
                            if (attachment.ContentDisposition == null)
                            {
                                attachment.ContentDisposition = new ContentDisposition();
                            }

                            attachment.ContentDisposition.Size = prop.ReadValueAsInt64();
                            break;

                        case TnefPropertyId.DisplayName:
                            attachment.ContentType.Name = prop.ReadValueAsString();
                            break;
                        }
                    }
                    break;

                case TnefAttributeTag.AttachCreateDate:
                    if (attachment != null)
                    {
                        if (attachment.ContentDisposition == null)
                        {
                            attachment.ContentDisposition = new ContentDisposition();
                        }

                        attachment.ContentDisposition.CreationDate = prop.ReadValueAsDateTime();
                    }
                    break;

                case TnefAttributeTag.AttachModifyDate:
                    if (attachment != null)
                    {
                        if (attachment.ContentDisposition == null)
                        {
                            attachment.ContentDisposition = new ContentDisposition();
                        }

                        attachment.ContentDisposition.ModificationDate = prop.ReadValueAsDateTime();
                    }
                    break;

                case TnefAttributeTag.AttachTitle:
                    if (attachment != null && string.IsNullOrEmpty(attachment.FileName))
                    {
                        attachment.FileName = prop.ReadValueAsString();
                    }
                    break;

                case TnefAttributeTag.AttachMetaFile:
                    if (attachment == null)
                    {
                        break;
                    }

                    // TODO: what to do with the meta data?
                    break;

                case TnefAttributeTag.AttachData:
                    if (attachment == null || attachMethod != TnefAttachMethod.ByValue)
                    {
                        break;
                    }

                    attachData = prop.ReadValueAsBytes();
                    filter.Flush(attachData, 0, attachData.Length, out outIndex, out outLength);
                    attachment.ContentTransferEncoding = filter.GetBestEncoding(EncodingConstraint.SevenBit);
                    attachment.Content = new MimeContent(new MemoryStream(attachData, false));
                    filter.Reset();

                    builder.Attachments.Add(attachment);
                    break;
                }
            } while (reader.ReadNextAttribute());
        }
Exemplo n.º 28
0
        static bool TryParseNameValuePair(ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out NameValuePair pair)
        {
            int    valueIndex, startIndex;
            bool   encoded = false;
            int?   id      = null;
            string name;

            pair = null;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            startIndex = index;
            if (!SkipParamName(text, ref index, endIndex))
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Invalid parameter name token at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            name = Encoding.ASCII.GetString(text, startIndex, index - startIndex);

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            if (text[index] == (byte)'*')
            {
                // the parameter is either encoded or it has a part id
                index++;

                if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                {
                    return(false);
                }

                if (index >= endIndex)
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                    }

                    return(false);
                }

                int value;
                if (ParseUtils.TryParseInt32(text, ref index, endIndex, out value))
                {
                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index >= endIndex)
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                        }

                        return(false);
                    }

                    if (text[index] == (byte)'*')
                    {
                        encoded = true;
                        index++;

                        if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                        {
                            return(false);
                        }

                        if (index >= endIndex)
                        {
                            if (throwOnError)
                            {
                                throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                            }

                            return(false);
                        }
                    }

                    id = value;
                }
                else
                {
                    encoded = true;
                }
            }

            if (text[index] != (byte)'=')
            {
                if (index >= endIndex)
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                    }

                    return(false);
                }
            }

            index++;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                if (index >= endIndex)
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                    }

                    return(false);
                }
            }

            valueIndex = index;

            if (text[index] == (byte)'"')
            {
                ParseUtils.SkipQuoted(text, ref index, endIndex, throwOnError);
            }
            else if (options.ParameterComplianceMode == RfcComplianceMode.Strict)
            {
                ParseUtils.SkipToken(text, ref index, endIndex);
            }
            else
            {
                // Note: Google Docs, for example, does not always quote name/filename parameters
                // with spaces in the name. See https://github.com/jstedfast/MimeKit/issues/106
                // for details.
                while (index < endIndex && text[index] != (byte)';' && text[index] != (byte)'\r' && text[index] != (byte)'\n')
                {
                    index++;
                }
            }

            pair = new NameValuePair {
                ValueLength = index - valueIndex,
                ValueStart  = valueIndex,
                Encoded     = encoded,
                Name        = name,
                Id          = id
            };

            return(true);
        }
Exemplo n.º 29
0
        public void Page_Load(object sender, EventArgs e)
        {
            _siteId    = Utils.ToInt(Request.QueryString["siteId"]);
            _formId    = Utils.ToInt(Request.QueryString["formId"]);
            _returnUrl = GetRedirectUrl(_siteId);

            if (!Main.Instance.AdminApi.IsSiteAuthorized(_siteId))
            {
                Response.Write("<h1>未授权访问</h1>");
                Response.End();
                return;
            }

            if (_formId > 0)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["up"]) || !string.IsNullOrEmpty(Request.QueryString["down"]))
                {
                    if (!string.IsNullOrEmpty(Request.QueryString["down"]))
                    {
                        Main.Instance.FormDao.UpdateTaxisToDown(_siteId, _formId);
                    }
                    else
                    {
                        Main.Instance.FormDao.UpdateTaxisToUp(_siteId, _formId);
                    }
                }
                if (!string.IsNullOrEmpty(Request.QueryString["delete"]))
                {
                    Main.Instance.FormDao.Delete(_formId);

                    LtlMessage.Text = Utils.GetMessageHtml("表单删除成功!", true);
                }
                if (!string.IsNullOrEmpty(Request.QueryString["template"]))
                {
                    var formInfo = Main.Instance.FormDao.GetFormInfo(_formId);
                    CacheUtils.InsertMinutes("SiteServer.BackgroundPages.Cms.PageTemplatePreview",
                                             Main.Instance.DataApi.Encrypt(ParseUtils.GetFormStlElement(formInfo)),
                                             5);
                    Response.Redirect(Main.Instance.FilesApi.GetAdminDirectoryUrl($"cms/pageTemplatePreview.aspx?siteId={_siteId}&fromCache={true}&returnUrl={Main.Instance.DataApi.Encrypt(Main.Instance.PluginApi.GetPluginUrl(_returnUrl))}"));
                    return;
                }
            }

            if (IsPostBack)
            {
                return;
            }

            DgContents.DataSource     = Main.Instance.FormDao.GetFormInfoListNotInChannel(_siteId);
            DgContents.ItemDataBound += DgContents_ItemDataBound;
            DgContents.DataBind();

            BtnAdd.Attributes.Add("onclick", ModalFormAdd.GetOpenScript(_siteId));
            BtnImport.Attributes.Add("onclick", ModalFormImport.GetOpenScript(_siteId));

            //if (!string.IsNullOrEmpty(Request.QueryString["export"]))
            //{
            //    string fileName;
            //    if (Utils.ExportInput(_formId, out fileName))
            //    {
            //        LtlScript.Text = Utils.SwalSuccess("导出成功", "点击按钮下载导出文件", "下 载", $"location.href = '{Main.Instance.Context.FilesApi.GetRootUrl($"sitefiles/temporaryfiles/{fileName}")}'");
            //    }
            //}
        }
Exemplo n.º 30
0
        private async Task <FileResult> GetChannelTemplateAsync(VisualInfo visualInfo, StringBuilder contentBuilder)
        {
            var nodeInfo = await _channelRepository.GetAsync(visualInfo.ChannelId);

            if (nodeInfo == null)
            {
                return(null);
            }

            if (nodeInfo.ParentId > 0)
            {
                if (!string.IsNullOrEmpty(nodeInfo.LinkUrl))
                {
                    HttpContext.Response.Redirect(nodeInfo.LinkUrl);
                    return(null);
                }
            }

            var stlLabelList = ParseUtils.GetStlLabels(contentBuilder.ToString());

            //如果标签中存在Content
            var stlContentElement = string.Empty;

            foreach (var label in stlLabelList)
            {
                if (StlParserUtility.IsStlChannelElement(label, StlParserUtility.PageContent))
                {
                    stlContentElement = label;
                    break;
                }
            }

            if (!string.IsNullOrEmpty(stlContentElement)) //内容存在
            {
                var innerBuilder = new StringBuilder(stlContentElement);
                await _parseManager.ParseInnerContentAsync(innerBuilder);

                var contentAttributeHtml = innerBuilder.ToString();
                var pageCount            = StringUtils.GetCount(Constants.PagePlaceHolder, contentAttributeHtml) + 1; //一共需要的页数
                if (pageCount > 1)
                {
                    await _parseManager.ParseAsync(contentBuilder, visualInfo.FilePath, true);

                    for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                    {
                        var index  = contentAttributeHtml.IndexOf(Constants.PagePlaceHolder, StringComparison.Ordinal);
                        var length = index == -1 ? contentAttributeHtml.Length : index;

                        if (currentPageIndex == visualInfo.PageIndex)
                        {
                            var pagedContentAttributeHtml = contentAttributeHtml.Substring(0, length);
                            var pagedBuilder = new StringBuilder(contentBuilder.ToString()
                                                                 .Replace(stlContentElement, pagedContentAttributeHtml));
                            await _parseManager.ReplacePageElementsInChannelPageAsync(pagedBuilder, stlLabelList, currentPageIndex, pageCount, 0);

                            return(GetResponse(pagedBuilder.ToString()));
                        }

                        if (index != -1)
                        {
                            contentAttributeHtml =
                                contentAttributeHtml.Substring(length + Constants.PagePlaceHolder.Length);
                        }
                    }

                    return(null);
                }

                contentBuilder.Replace(stlContentElement, contentAttributeHtml);
            }

            if (ParseUtils.IsStlElementExists(StlPageContents.ElementName, stlLabelList)) //如果标签中存在<stl:pageContents>
            {
                var stlElement           = ParseUtils.GetStlElement(StlPageContents.ElementName, stlLabelList);
                var stlElementTranslated = _parseManager.StlEncrypt(stlElement);

                var pageContentsElementParser = await StlPageContents.GetAsync(stlElement, _parseManager);

                var(pageCount, totalNum) = pageContentsElementParser.GetPageCount();

                await _parseManager.ParseAsync(contentBuilder, visualInfo.FilePath, true);

                for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                {
                    if (currentPageIndex == visualInfo.PageIndex)
                    {
                        var pageHtml = await pageContentsElementParser.ParseAsync(totalNum, currentPageIndex, pageCount, false);

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

                        await _parseManager.ReplacePageElementsInChannelPageAsync(pagedBuilder, stlLabelList, currentPageIndex, pageCount, totalNum);

                        return(GetResponse(pagedBuilder.ToString()));
                    }
                }
            }
            else if (ParseUtils.IsStlElementExists(StlPageChannels.ElementName, stlLabelList)) //如果标签中存在<stl:pageChannels>
            {
                var stlElement           = ParseUtils.GetStlElement(StlPageChannels.ElementName, stlLabelList);
                var stlElementTranslated = _parseManager.StlEncrypt(stlElement);

                var pageChannelsElementParser = await StlPageChannels.GetAsync(stlElement, _parseManager);

                var pageCount = pageChannelsElementParser.GetPageCount(out var totalNum);

                await _parseManager.ParseAsync(contentBuilder, visualInfo.FilePath, true);

                for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                {
                    if (currentPageIndex == visualInfo.PageIndex)
                    {
                        var pageHtml = await pageChannelsElementParser.ParseAsync(currentPageIndex, pageCount);

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

                        await _parseManager.ReplacePageElementsInChannelPageAsync(pagedBuilder, stlLabelList, currentPageIndex, pageCount, totalNum);

                        return(GetResponse(pagedBuilder.ToString()));
                    }
                }
            }
            //如果标签中存在<stl:pageSqlContents>
            else if (ParseUtils.IsStlElementExists(StlPageSqlContents.ElementName, stlLabelList))
            {
                var stlElement           = ParseUtils.GetStlElement(StlPageSqlContents.ElementName, stlLabelList);
                var stlElementTranslated = _parseManager.StlEncrypt(stlElement);

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

                var pageCount = pageSqlContentsElementParser.GetPageCount(out var totalNum);

                await _parseManager.ParseAsync(contentBuilder, visualInfo.FilePath, true);

                for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                {
                    if (currentPageIndex == visualInfo.PageIndex)
                    {
                        var pageHtml = await pageSqlContentsElementParser.ParseAsync(totalNum, currentPageIndex, pageCount);

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

                        await _parseManager.ReplacePageElementsInChannelPageAsync(pagedBuilder, stlLabelList, currentPageIndex, pageCount, totalNum);

                        return(GetResponse(pagedBuilder.ToString()));
                    }
                }
            }

            await _parseManager.ParseAsync(contentBuilder, visualInfo.FilePath, true);

            return(GetResponse(contentBuilder.ToString()));
        }