Пример #1
0
        public void TestArgumentExceptions()
        {
            var          writer = new StringWriter();
            const string text   = "text";

            // HtmlAttributeEncode
            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlAttributeEncode(null));
            Assert.Throws <ArgumentException> (() => HtmlUtils.HtmlAttributeEncode(text, 'x'));

            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlAttributeEncode(null, text));
            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlAttributeEncode(writer, null));
            Assert.Throws <ArgumentException> (() => HtmlUtils.HtmlAttributeEncode(writer, text, 'x'));

            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlAttributeEncode((string)null, 0, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlAttributeEncode(text, -1, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlAttributeEncode(text, 0, text.Length + 1));
            Assert.Throws <ArgumentException> (() => HtmlUtils.HtmlAttributeEncode(text, 0, text.Length, 'x'));

            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlAttributeEncode((char[])null, 0, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlAttributeEncode(text.ToCharArray(), -1, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlAttributeEncode(text.ToCharArray(), 0, text.Length + 1));
            Assert.Throws <ArgumentException> (() => HtmlUtils.HtmlAttributeEncode(text.ToCharArray(), 0, text.Length, 'x'));

            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlAttributeEncode(null, text, 0, text.Length));
            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlAttributeEncode(writer, (string)null, 0, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlAttributeEncode(writer, text, -1, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlAttributeEncode(writer, text, 0, text.Length + 1));
            Assert.Throws <ArgumentException> (() => HtmlUtils.HtmlAttributeEncode(writer, text, 0, text.Length, 'x'));

            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlAttributeEncode(null, text.ToCharArray(), 0, text.Length));
            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlAttributeEncode(writer, (char[])null, 0, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlAttributeEncode(writer, text.ToCharArray(), -1, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlAttributeEncode(writer, text.ToCharArray(), 0, text.Length + 1));
            Assert.Throws <ArgumentException> (() => HtmlUtils.HtmlAttributeEncode(writer, text.ToCharArray(), 0, text.Length, 'x'));

            // HtmlEncode
            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlEncode(null));

            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlEncode(null, text));
            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlEncode(writer, null));

            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlEncode((string)null, 0, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlEncode(text, -1, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlEncode(text, 0, text.Length + 1));

            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlEncode((char[])null, 0, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlEncode(text.ToCharArray(), -1, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlEncode(text.ToCharArray(), 0, text.Length + 1));

            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlEncode(null, text, 0, text.Length));
            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlEncode(writer, (string)null, 0, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlEncode(writer, text, -1, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlEncode(writer, text, 0, text.Length + 1));

            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlEncode(null, text.ToCharArray(), 0, text.Length));
            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlEncode(writer, (char[])null, 0, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlEncode(writer, text.ToCharArray(), -1, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlEncode(writer, text.ToCharArray(), 0, text.Length + 1));

            // HtmlDecode
            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlDecode(null));

            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlDecode(null, text));
            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlDecode(writer, null));

            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlDecode(null, 0, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlDecode(text, -1, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlDecode(text, 0, text.Length + 1));

            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlDecode(null, text, 0, text.Length));
            Assert.Throws <ArgumentNullException> (() => HtmlUtils.HtmlDecode(writer, null, 0, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlDecode(writer, text, -1, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => HtmlUtils.HtmlDecode(writer, text, 0, text.Length + 1));
        }
Пример #2
0
        /// <summary>
        /// Applies the product description to an expando object.
        /// Projection settings controls in detail how the product description is to be exported here.
        /// </summary>
        private static async Task ApplyProductDescription(dynamic dynObject, Product product, DataExporterContext ctx)
        {
            try
            {
                var    languageId  = ctx.LanguageId;
                string description = "";

                // Description merging.
                if (ctx.Projection.DescriptionMerging == ExportDescriptionMerging.None)
                {
                    // Export empty description.
                }
                else if (ctx.Projection.DescriptionMerging == ExportDescriptionMerging.ShortDescriptionOrNameIfEmpty)
                {
                    description = dynObject.FullDescription;

                    if (description.IsEmpty())
                    {
                        description = dynObject.ShortDescription;
                    }
                    if (description.IsEmpty())
                    {
                        description = dynObject.Name;
                    }
                }
                else if (ctx.Projection.DescriptionMerging == ExportDescriptionMerging.ShortDescription)
                {
                    description = dynObject.ShortDescription;
                }
                else if (ctx.Projection.DescriptionMerging == ExportDescriptionMerging.Description)
                {
                    description = dynObject.FullDescription;
                }
                else if (ctx.Projection.DescriptionMerging == ExportDescriptionMerging.NameAndShortDescription)
                {
                    description = ((string)dynObject.Name).Grow((string)dynObject.ShortDescription, " ");
                }
                else if (ctx.Projection.DescriptionMerging == ExportDescriptionMerging.NameAndDescription)
                {
                    description = ((string)dynObject.Name).Grow((string)dynObject.FullDescription, " ");
                }
                else if (ctx.Projection.DescriptionMerging == ExportDescriptionMerging.ManufacturerAndNameAndShortDescription ||
                         ctx.Projection.DescriptionMerging == ExportDescriptionMerging.ManufacturerAndNameAndDescription)
                {
                    var productManus = await ctx.ProductBatchContext.ProductManufacturers.GetOrLoadAsync(product.Id);

                    if (productManus != null && productManus.Any())
                    {
                        var manufacturer = productManus.First().Manufacturer;
                        description = ctx.GetTranslation(manufacturer, nameof(manufacturer.Name), manufacturer.Name);
                    }

                    description = description.Grow((string)dynObject.Name, " ");
                    description = ctx.Projection.DescriptionMerging == ExportDescriptionMerging.ManufacturerAndNameAndShortDescription
                        ? description.Grow((string)dynObject.ShortDescription, " ")
                        : description.Grow((string)dynObject.FullDescription, " ");
                }

                // Append text.
                if (ctx.Projection.AppendDescriptionText.HasValue() && ((string)dynObject.ShortDescription).IsEmpty() && ((string)dynObject.FullDescription).IsEmpty())
                {
                    var appendText = ctx.Projection.AppendDescriptionText.SplitSafe(",").ToArray();
                    if (appendText.Any())
                    {
                        var rnd = CommonHelper.GenerateRandomInteger(0, appendText.Length - 1);
                        description = description.Grow(appendText.ElementAtOrDefault(rnd), " ");
                    }
                }

                // Remove critical characters.
                if (description.HasValue() && ctx.Projection.RemoveCriticalCharacters)
                {
                    foreach (var str in ctx.Projection.CriticalCharacters.SplitSafe(","))
                    {
                        description = description.Replace(str, "");
                    }
                }

                // Convert to plain text.
                if (description.HasValue() && ctx.Projection.DescriptionToPlainText)
                {
                    //Regex reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
                    //description = HttpUtility.HtmlDecode(reg.Replace(description, ""));

                    description = HtmlUtils.ConvertHtmlToPlainText(description);
                    description = HtmlUtils.StripTags(HttpUtility.HtmlDecode(description));
                }

                dynObject.FullDescription = description.TrimSafe();
            }
            catch { }
        }
Пример #3
0
        public static string UploadLegacySkin(string RootPath, string SkinRoot, string SkinName, Stream objInputStream)
        {
            ZipInputStream objZipInputStream = new ZipInputStream(objInputStream);
            ZipEntry       objZipEntry;
            string         strExtension;
            string         strFileName;
            FileStream     objFileStream;
            int            intSize = 2048;

            byte[]         arrData                = new byte[2048];
            string         strMessage             = "";
            ArrayList      arrSkinFiles           = new ArrayList();
            PortalSettings ResourcePortalSettings = CommonLibrary.Common.Globals.GetPortalSettings();
            string         BEGIN_MESSAGE          = Localization.GetString("BeginZip", ResourcePortalSettings);
            string         CREATE_DIR             = Localization.GetString("CreateDir", ResourcePortalSettings);
            string         WRITE_FILE             = Localization.GetString("WriteFile", ResourcePortalSettings);
            string         FILE_ERROR             = Localization.GetString("FileError", ResourcePortalSettings);
            string         END_MESSAGE            = Localization.GetString("EndZip", ResourcePortalSettings);
            string         FILE_RESTICTED         = Localization.GetString("FileRestricted", ResourcePortalSettings);

            strMessage += FormatMessage(BEGIN_MESSAGE, SkinName, -1, false);
            objZipEntry = objZipInputStream.GetNextEntry();
            while (objZipEntry != null)
            {
                if (!objZipEntry.IsDirectory)
                {
                    strExtension = objZipEntry.Name.Substring(objZipEntry.Name.LastIndexOf(".") + 1);
                    if (("," + strExtension.ToUpper()).IndexOf(",ASCX,HTM,HTML,CSS,SWF,RESX,XAML,JS," + Host.FileExtensions.ToUpper()) != 0)
                    {
                        if (objZipEntry.Name.ToLower() == SkinController.RootSkin.ToLower() + ".zip")
                        {
                            MemoryStream objMemoryStream = new MemoryStream();
                            intSize = objZipInputStream.Read(arrData, 0, arrData.Length);
                            while (intSize > 0)
                            {
                                objMemoryStream.Write(arrData, 0, intSize);
                                intSize = objZipInputStream.Read(arrData, 0, arrData.Length);
                            }
                            objMemoryStream.Seek(0, SeekOrigin.Begin);
                            strMessage += UploadLegacySkin(RootPath, SkinController.RootSkin, SkinName, (Stream)objMemoryStream);
                        }
                        else if (objZipEntry.Name.ToLower() == SkinController.RootContainer.ToLower() + ".zip")
                        {
                            MemoryStream objMemoryStream = new MemoryStream();
                            intSize = objZipInputStream.Read(arrData, 0, arrData.Length);
                            while (intSize > 0)
                            {
                                objMemoryStream.Write(arrData, 0, intSize);
                                intSize = objZipInputStream.Read(arrData, 0, arrData.Length);
                            }
                            objMemoryStream.Seek(0, SeekOrigin.Begin);
                            strMessage += UploadLegacySkin(RootPath, SkinController.RootContainer, SkinName, (Stream)objMemoryStream);
                        }
                        else
                        {
                            strFileName = RootPath + SkinRoot + "\\" + SkinName + "\\" + objZipEntry.Name;
                            if (!Directory.Exists(Path.GetDirectoryName(strFileName)))
                            {
                                strMessage += FormatMessage(CREATE_DIR, Path.GetDirectoryName(strFileName), 2, false);
                                Directory.CreateDirectory(Path.GetDirectoryName(strFileName));
                            }
                            if (File.Exists(strFileName))
                            {
                                File.SetAttributes(strFileName, FileAttributes.Normal);
                                File.Delete(strFileName);
                            }
                            objFileStream = File.Create(strFileName);
                            strMessage   += FormatMessage(WRITE_FILE, Path.GetFileName(strFileName), 2, false);
                            intSize       = objZipInputStream.Read(arrData, 0, arrData.Length);
                            while (intSize > 0)
                            {
                                objFileStream.Write(arrData, 0, intSize);
                                intSize = objZipInputStream.Read(arrData, 0, arrData.Length);
                            }
                            objFileStream.Close();
                            switch (Path.GetExtension(strFileName))
                            {
                            case ".htm":
                            case ".html":
                            case ".ascx":
                            case ".css":
                                if (strFileName.ToLower().IndexOf(Globals.glbAboutPage.ToLower()) < 0)
                                {
                                    arrSkinFiles.Add(strFileName);
                                }
                                break;
                            }
                            break;
                        }
                    }
                    else
                    {
                        strMessage += string.Format(FILE_RESTICTED, objZipEntry.Name, Host.FileExtensions.ToString(), ",", ", *.").Replace("2", "true");
                    }
                }
                objZipEntry = objZipInputStream.GetNextEntry();
            }
            strMessage += FormatMessage(END_MESSAGE, SkinName + ".zip", 1, false);
            objZipInputStream.Close();
            UI.Skins.SkinFileProcessor NewSkin = new UI.Skins.SkinFileProcessor(RootPath, SkinRoot, SkinName);
            strMessage += NewSkin.ProcessList(arrSkinFiles, SkinParser.Portable);
            try
            {
                Services.Log.EventLog.LogInfo objEventLogInfo = new Services.Log.EventLog.LogInfo();
                objEventLogInfo.LogTypeKey = Services.Log.EventLog.EventLogController.EventLogType.HOST_ALERT.ToString();
                objEventLogInfo.LogProperties.Add(new CommonLibrary.Services.Log.EventLog.LogDetailInfo("Install Skin:", SkinName));
                Array arrMessage = strMessage.Split(new string[] { "<br>" }, StringSplitOptions.None);
                foreach (string strRow in arrMessage)
                {
                    objEventLogInfo.LogProperties.Add(new CommonLibrary.Services.Log.EventLog.LogDetailInfo("Info:", HtmlUtils.StripTags(strRow, true)));
                }
                Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
                objEventLog.AddLog(objEventLogInfo);
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return(strMessage);
        }
Пример #4
0
        /// <summary>
        /// Inserts a set of images into the current editor, optionally assigning each image an id.
        /// </summary>
        /// <param name="imagePaths">paths of the images to insert</param>
        internal static void InsertImagesCore(IBlogPostHtmlEditor currentEditor, ISupportingFileService fileService, IEditorAccount editorAccount, OpenLiveWriter.PostEditor.ContentEditor editor, string[] imagePaths)
        {
            using (OpenLiveWriter.PostEditor.ContentEditor.EditorUndoUnit undo = new OpenLiveWriter.PostEditor.ContentEditor.EditorUndoUnit(currentEditor))
            {
                StringBuilder htmlBuilder = new StringBuilder();

                //calculate the size for inserted images (based on the user's saved default for this blog)
                DefaultImageSettings defaultImageSettings = new DefaultImageSettings(editorAccount.Id, editor.DecoratorsManager);
                Size defaultImageSize = defaultImageSettings.GetDefaultInlineImageSize();

                //Generate the default img HTML for the image paths.  Initially, the images are linked to the source image
                //path so that the DOM version of the HTML can be loaded.  Once the images are loaded into the DOM, we can apply
                //the image decorators to generate scaled images, borders, etc.
                ImagePropertiesInfo[] imageInfos = new ImagePropertiesInfo[imagePaths.Length];

                // don't insert into the title
                currentEditor.FocusBody();

                for (int i = 0; i < imageInfos.Length; i++)
                {
                    string imagePath = imagePaths[i];

                    Uri imgUri;
                    if (UrlHelper.IsUrl(imagePath))
                    {
                        imgUri = new Uri(imagePath);
                    }
                    else
                    {
                        imgUri = new Uri(UrlHelper.CreateUrlFromPath(imagePath));
                    }

                    Size imageSize = new Size(1, 1);
                    if (imgUri.IsFile && File.Exists(imagePath))
                    {
                        if (!File.Exists(imgUri.LocalPath))
                        {
                            Trace.Fail("Error inserting image - the image URL was corrupted: " + imagePath);
                        }
                        else
                        {
                            try
                            {
                                //check the validity of the image file
                                imageSize = ImageUtils.GetImageSize(imagePath);
                            }
                            catch (Exception)
                            {
                                Trace.WriteLine("There is a problem with the image file: " + imagePath);

                                // Insert anyway, MSHTML will show a red X in place of the image.
                                htmlBuilder.AppendFormat(CultureInfo.InvariantCulture, "<img src=\"{0}\" />", HtmlUtils.EscapeEntities(UrlHelper.SafeToAbsoluteUri(imgUri)));

                                continue;
                            }
                        }
                    }

                    // If the image has an embedded thumbnail, we'll use it as a place holder for the <img src="...">
                    // until we generate an inline image and apply decorators.
                    Stream embeddedThumbnailStream = ImageHelper2.GetEmbeddedThumbnailStream(imagePath);

                    if (embeddedThumbnailStream != null)
                    {
                        // Save thumbnail to disk.
                        ISupportingFile imageFileEmbeddedThumbnail = fileService.CreateSupportingFile(Path.GetFileName(imagePath), Guid.NewGuid().ToString(), embeddedThumbnailStream);

                        imageSize = ImageUtils.GetScaledImageSize(defaultImageSize.Width, defaultImageSize.Height, imageSize);
                        //insert the default image html
                        String imageElementAttrs = String.Format(CultureInfo.InvariantCulture, " width=\"{0}\" height=\"{1}\"", imageSize.Width, imageSize.Height);

                        htmlBuilder.AppendFormat(CultureInfo.InvariantCulture, "<img src=\"{0}\" srcDelay=\"{1}\" {2} />", HtmlUtils.EscapeEntities(UrlHelper.SafeToAbsoluteUri(imageFileEmbeddedThumbnail.FileUri)), HtmlUtils.EscapeEntities(imgUri.ToString()), imageElementAttrs);
                    }
                    else if (currentEditor is BlogPostHtmlEditorControl && (imagePaths.Length > DELAYED_IMAGE_THRESHOLD || imageSize.Width * imageSize.Height > 16777216 /*4096 X 4096*/))
                    {
                        // If we are using a delayed loading tactic then we insert using the srcdelay
                        htmlBuilder.Append(MakeHtmlForImageSourceDelay(imgUri.ToString()));
                    }
                    else
                    {
                        imageSize = ImageUtils.GetScaledImageSize(defaultImageSize.Width, defaultImageSize.Height, imageSize);
                        //insert the default image html
                        String imageElementAttrs = imgUri.IsFile ? String.Format(CultureInfo.InvariantCulture, " width=\"{0}\" height=\"{1}\"", imageSize.Width, imageSize.Height) : String.Empty;

                        htmlBuilder.AppendFormat(CultureInfo.InvariantCulture, "<img src=\"{0}\" {1} />", HtmlUtils.EscapeEntities(UrlHelper.SafeToAbsoluteUri(imgUri)), imageElementAttrs);
                    }
                }

                //insert the HTML into the editor
                currentEditor.InsertHtml(htmlBuilder.ToString(), false);

                selectionChanged = false;
                BlogPostHtmlEditorControl blogPostEditor = currentEditor as BlogPostHtmlEditorControl;
                if (blogPostEditor != null)
                {
                    blogPostEditor.SelectionChanged += blogPostEditor_SelectionChanged;
                }

                //now that the image HTML is inserted into the editor, apply the default settings to the new images.
                undo.Commit();
            }
        }
 public static string RemoveHtml(this string source)
 {
     return(HtmlUtils.StripTags(source).Trim().HtmlDecode());
 }
Пример #6
0
        private Tuple <int, IList <SearchResult> > GetResults(SearchQuery searchQuery)
        {
            Requires.NotNull("Query", searchQuery);
            Requires.PropertyNotEqualTo("searchQuery", "SearchTypeIds", searchQuery.SearchTypeIds.Count(), 0);

            if ((searchQuery.ModuleId > 0) && (searchQuery.SearchTypeIds.Count() > 1 || !searchQuery.SearchTypeIds.Contains(this._moduleSearchTypeId)))
            {
                throw new ArgumentException(Localization.GetExceptionMessage("ModuleIdMustHaveSearchTypeIdForModule", "ModuleId based search must have SearchTypeId for a module only"));
            }

            if (searchQuery.SortField == SortFields.CustomStringField || searchQuery.SortField == SortFields.CustomNumericField ||
                searchQuery.SortField == SortFields.NumericKey || searchQuery.SortField == SortFields.Keyword)
            {
                Requires.NotNullOrEmpty("CustomSortField", searchQuery.CustomSortField);
            }

            var query = new BooleanQuery();

            if (!string.IsNullOrEmpty(searchQuery.KeyWords))
            {
                try
                {
                    var allowLeadingWildcard = HostController.Instance.GetString("Search_AllowLeadingWildcard", "N") == "Y" || searchQuery.AllowLeadingWildcard;
                    var keywords             = SearchHelper.Instance.RephraseSearchText(searchQuery.KeyWords, searchQuery.WildCardSearch, allowLeadingWildcard);

                    // don't use stemming analyzer for exact matches or non-analyzed fields (e.g. Tags)
                    var analyzer           = LuceneController.Instance.GetCustomAnalyzer() ?? new SearchQueryAnalyzer(true);
                    var nonStemmerAnalyzer = new SearchQueryAnalyzer(false);
                    var keywordQuery       = new BooleanQuery();
                    foreach (var fieldToSearch in Constants.KeyWordSearchFields)
                    {
                        var parserContent = new QueryParser(Constants.LuceneVersion, fieldToSearch,
                                                            fieldToSearch == Constants.Tag ? nonStemmerAnalyzer : analyzer);
                        parserContent.AllowLeadingWildcard = allowLeadingWildcard;
                        var parsedQueryContent = parserContent.Parse(keywords);
                        keywordQuery.Add(parsedQueryContent, Occur.SHOULD);
                    }

                    query.Add(keywordQuery, Occur.MUST);
                }
                catch (Exception)
                {
                    foreach (var word in searchQuery.KeyWords.Split(' '))
                    {
                        query.Add(new TermQuery(new Term(Constants.ContentTag, word.ToLowerInvariant())), Occur.SHOULD);
                    }
                }
            }

            var portalIdQuery = new BooleanQuery();

            foreach (var portalId in searchQuery.PortalIds)
            {
                portalIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.PortalIdTag, portalId, portalId, true, true), Occur.SHOULD);
            }

            if (searchQuery.PortalIds.Any())
            {
                query.Add(portalIdQuery, Occur.MUST);
            }

            this.ApplySearchTypeIdFilter(query, searchQuery);

            if (searchQuery.BeginModifiedTimeUtc > DateTime.MinValue && searchQuery.EndModifiedTimeUtc >= searchQuery.BeginModifiedTimeUtc)
            {
                query.Add(NumericRangeQuery.NewLongRange(Constants.ModifiedTimeTag, long.Parse(searchQuery.BeginModifiedTimeUtc.ToString(Constants.DateTimeFormat)), long.Parse(searchQuery.EndModifiedTimeUtc.ToString(Constants.DateTimeFormat)), true, true), Occur.MUST);
            }

            if (searchQuery.RoleId > 0)
            {
                query.Add(NumericRangeQuery.NewIntRange(Constants.RoleIdTag, searchQuery.RoleId, searchQuery.RoleId, true, true), Occur.MUST);
            }

            foreach (var tag in searchQuery.Tags)
            {
                var text = tag.ToLowerInvariant();
                if (HtmlUtils.ContainsEntity(text))
                {
                    text = System.Net.WebUtility.HtmlDecode(text);
                }

                query.Add(new TermQuery(new Term(Constants.Tag, text)), Occur.MUST);
            }

            foreach (var kvp in searchQuery.CustomKeywords)
            {
                query.Add(
                    new TermQuery(new Term(
                                      SearchHelper.Instance.StripTagsNoAttributes(Constants.KeywordsPrefixTag + kvp.Key, true), kvp.Value)), Occur.MUST);
            }

            foreach (var kvp in searchQuery.NumericKeys)
            {
                query.Add(NumericRangeQuery.NewIntRange(Constants.NumericKeyPrefixTag + kvp.Key, kvp.Value, kvp.Value, true, true), Occur.MUST);
            }

            if (!string.IsNullOrEmpty(searchQuery.CultureCode))
            {
                var localeQuery = new BooleanQuery();

                var languageId = Localization.GetCultureLanguageID(searchQuery.CultureCode);
                localeQuery.Add(NumericRangeQuery.NewIntRange(Constants.LocaleTag, languageId, languageId, true, true), Occur.SHOULD);
                localeQuery.Add(NumericRangeQuery.NewIntRange(Constants.LocaleTag, Null.NullInteger, Null.NullInteger, true, true), Occur.SHOULD);
                query.Add(localeQuery, Occur.MUST);
            }

            var luceneQuery = new LuceneQuery
            {
                Query              = query,
                Sort               = this.GetSort(searchQuery),
                PageIndex          = searchQuery.PageIndex,
                PageSize           = searchQuery.PageSize,
                TitleSnippetLength = searchQuery.TitleSnippetLength,
                BodySnippetLength  = searchQuery.BodySnippetLength,
            };

            return(this.GetSecurityTrimmedResults(searchQuery, luceneQuery));
        }
Пример #7
0
        private void BindView()
        {
            handler.Post(() =>
            {
                txtTitle.Text     = question.Title;
                txtDateAdded.Text = DateTimeUtils.CommonTime(question.DateAdded);
                if (question.Award > 0)
                {
                    this.txtGold.Text       = question.Award.ToString();
                    this.txtGold.Visibility = ViewStates.Visible;
                }
                else
                {
                    this.txtGold.Visibility = ViewStates.Gone;
                }
                if (question.DealFlag == 1)
                {
                    this.txtDealFlag.Text     = Resources.GetString(Resource.String.question_dealflag_1);
                    this.txtDealFlag.Selected = false;
                }
                else if (question.DealFlag == -1)
                {
                    this.txtDealFlag.Text     = Resources.GetString(Resource.String.question_dealflag_2);
                    this.txtDealFlag.Selected = true;
                }
                else
                {
                    this.txtDealFlag.Text     = Resources.GetString(Resource.String.question_dealflag_0);
                    this.txtDealFlag.Selected = true;
                }
                if (question.Tags != null && question.Tags.Length > 0)
                {
                    txtTag.Visibility = ViewStates.Visible;
                    txtTag.Text       = " " + question.Tags.Replace(',', ' ');
                }
                else
                {
                    txtTag.Visibility = ViewStates.Gone;
                }
                if (question.DiggCount > 0)
                {
                    txtDigg.Text = question.DiggCount.ToString();
                }
                if (question.ViewCount > 0)
                {
                    txtRead.Text = question.ViewCount.ToString();
                }
                if (question.AnswerCount > 0)
                {
                    txtComments.Text = question.AnswerCount.ToString();
                }

                if (question.Content == null || question.Content == "")
                {
                    OnRefresh();
                }
                else
                {
                    var content = HtmlUtils.ReadHtml(Assets);
                    var body    = HtmlUtils.ReplaceHtml(question.Content).Trim('"');
                    if (question.Addition != null)
                    {
                        body += " <h2>ÎÊÌâ²¹³ä£º</h2>" + question.Addition.Content;
                    }
                    txtBody.LoadDataWithBaseURL("file:///android_asset/", content.Replace("#title#", "").Replace("#body#", body), "text/html", "utf-8", null);
                }
                if (question.QuestionUserInfo != null && question.QuestionUserInfo.UserID > 0)
                {
                    txtUserName.Text = Html.FromHtml(question.QuestionUserInfo.UserName).ToString();
                    txtScore.Text    = HtmlUtils.GetScoreName(question.QuestionUserInfo.QScore) + " ¡¤ " + question.QuestionUserInfo.QScore + "Ô°¶¹ ¡¤ ";
                    try
                    {
                        Picasso.With(this)
                        .Load("https://pic.cnblogs.com/face/" + question.QuestionUserInfo.IconName)
                        .Placeholder(Resource.Drawable.placeholder)
                        .Error(Resource.Drawable.placeholder)
                        .Transform(new CircleTransform())
                        .Into(imgIconName);
                    }
                    catch (Exception)
                    {
                    }
                }
            });
        }
        public Series[] SearchForSeries(string name)
        {
            var series = new List <Series>();

            var     json    = HtmlUtils.GetHtmlPage(Utils.Combine(Info().SiteUrl, $"/ajax/url_s/search&keywords={name}"));
            dynamic jsonObj = JsonConvert.DeserializeObject(json);

            foreach (var item in jsonObj.items)
            {
                if (item.language == "Аниме онлайн")
                {
                    string title    = item.name;
                    string link     = item.html_url;
                    string imageUrl = item.image;

                    if (link.StartsWith("//"))
                    {
                        link = "http:" + link;
                    }

                    series.Add(new Series()
                    {
                        Name      = title,
                        SeriesUrl = link,
                        ImageUrl  = imageUrl
                    });
                }
            }

            #region Temporary broken full search

            /*
             * var doc = new HtmlDocument();
             * try
             * {
             *  doc.LoadHtml(HtmlUtils.GetHtmlPage(Utils.Combine(Info().SiteUrl, $"/ajax/search_result_search_page/P0?keywords={name}")));
             * }
             * catch (Exception ex)
             * {
             *  LogManager.GetCurrentClassLogger().Error(ex, $"Ошибка при получении страницы {name}");
             * }
             *
             * var nodes = doc.DocumentNode.SelectNodes("//div[@class='ads-list__item']");
             * if (nodes != null && nodes.Count > 0)
             * {
             *  foreach(var node in nodes)
             *  {
             *      try
             *      {
             *          var titleNode = node.SelectSingleNode("./a[contains(@class,'ads-list__item__title')]");
             *          var title = titleNode.InnerText;
             *          var link = titleNode.Attributes["href"].Value;
             *
             *          var imageNode = node.SelectSingleNode("./div/a/img");
             *          var imageUrl = imageNode.Attributes["data-src"].Value;
             *
             *          series.Add(new Series()
             *          {
             *              Name = title,
             *              SeriesUrl = link,
             *              ImageUrl = imageUrl
             *          });
             *
             *      }
             *      catch (Exception ex)
             *      {
             *          LogManager.GetCurrentClassLogger().Error(ex, "Ошибка парсинга сериала");
             *      }
             *  }
             * }
             */
            #endregion

            return(series.ToArray());
        }
Пример #9
0
        public static string UploadLegacySkin(string rootPath, string skinRoot, string skinName, Stream inputStream)
        {
            var objZipInputStream = new ZipInputStream(inputStream);

            ZipEntry   objZipEntry;
            string     strExtension;
            string     strFileName;
            FileStream objFileStream;
            int        intSize      = 2048;
            var        arrData      = new byte[2048];
            string     strMessage   = "";
            var        arrSkinFiles = new ArrayList();

            //Localized Strings
            PortalSettings ResourcePortalSettings = Globals.GetPortalSettings();
            string         BEGIN_MESSAGE          = Localization.GetString("BeginZip", ResourcePortalSettings);
            string         CREATE_DIR             = Localization.GetString("CreateDir", ResourcePortalSettings);
            string         WRITE_FILE             = Localization.GetString("WriteFile", ResourcePortalSettings);
            string         FILE_ERROR             = Localization.GetString("FileError", ResourcePortalSettings);
            string         END_MESSAGE            = Localization.GetString("EndZip", ResourcePortalSettings);
            string         FILE_RESTICTED         = Localization.GetString("FileRestricted", ResourcePortalSettings);

            strMessage += FormatMessage(BEGIN_MESSAGE, skinName, -1, false);

            objZipEntry = objZipInputStream.GetNextEntry();
            while (objZipEntry != null)
            {
                if (!objZipEntry.IsDirectory)
                {
                    //validate file extension
                    strExtension = objZipEntry.Name.Substring(objZipEntry.Name.LastIndexOf(".") + 1);
                    var extraExtensions = new List <string> {
                        ".ASCX", ".HTM", ".HTML", ".CSS", ".SWF", ".RESX", ".XAML", ".JS"
                    };
                    if (Host.AllowedExtensionWhitelist.IsAllowedExtension(strExtension, extraExtensions))
                    {
                        //process embedded zip files
                        if (objZipEntry.Name.Equals(RootSkin.ToLowerInvariant() + ".zip", StringComparison.InvariantCultureIgnoreCase))
                        {
                            using (var objMemoryStream = new MemoryStream())
                            {
                                intSize = objZipInputStream.Read(arrData, 0, arrData.Length);
                                while (intSize > 0)
                                {
                                    objMemoryStream.Write(arrData, 0, intSize);
                                    intSize = objZipInputStream.Read(arrData, 0, arrData.Length);
                                }
                                objMemoryStream.Seek(0, SeekOrigin.Begin);
                                strMessage += UploadLegacySkin(rootPath, RootSkin, skinName, objMemoryStream);
                            }
                        }
                        else if (objZipEntry.Name.Equals(RootContainer.ToLowerInvariant() + ".zip", StringComparison.InvariantCultureIgnoreCase))
                        {
                            using (var objMemoryStream = new MemoryStream())
                            {
                                intSize = objZipInputStream.Read(arrData, 0, arrData.Length);
                                while (intSize > 0)
                                {
                                    objMemoryStream.Write(arrData, 0, intSize);
                                    intSize = objZipInputStream.Read(arrData, 0, arrData.Length);
                                }
                                objMemoryStream.Seek(0, SeekOrigin.Begin);
                                strMessage += UploadLegacySkin(rootPath, RootContainer, skinName, objMemoryStream);
                            }
                        }
                        else
                        {
                            strFileName = rootPath + skinRoot + "\\" + skinName + "\\" + objZipEntry.Name;

                            //create the directory if it does not exist
                            if (!Directory.Exists(Path.GetDirectoryName(strFileName)))
                            {
                                strMessage += FormatMessage(CREATE_DIR, Path.GetDirectoryName(strFileName), 2, false);
                                Directory.CreateDirectory(Path.GetDirectoryName(strFileName));
                            }

                            //remove the old file
                            if (File.Exists(strFileName))
                            {
                                File.SetAttributes(strFileName, FileAttributes.Normal);
                                File.Delete(strFileName);
                            }

                            //create the new file
                            objFileStream = File.Create(strFileName);

                            //unzip the file
                            strMessage += FormatMessage(WRITE_FILE, Path.GetFileName(strFileName), 2, false);
                            intSize     = objZipInputStream.Read(arrData, 0, arrData.Length);
                            while (intSize > 0)
                            {
                                objFileStream.Write(arrData, 0, intSize);
                                intSize = objZipInputStream.Read(arrData, 0, arrData.Length);
                            }
                            objFileStream.Close();

                            //save the skin file
                            switch (Path.GetExtension(strFileName))
                            {
                            case ".htm":
                            case ".html":
                            case ".ascx":
                            case ".css":
                                if (strFileName.ToLowerInvariant().IndexOf(Globals.glbAboutPage.ToLowerInvariant()) < 0)
                                {
                                    arrSkinFiles.Add(strFileName);
                                }
                                break;
                            }
                            break;
                        }
                    }
                    else
                    {
                        strMessage += string.Format(FILE_RESTICTED, objZipEntry.Name, Host.AllowedExtensionWhitelist.ToStorageString(), ",", ", *.").Replace("2", "true");
                    }
                }
                objZipEntry = objZipInputStream.GetNextEntry();
            }
            strMessage += FormatMessage(END_MESSAGE, skinName + ".zip", 1, false);
            objZipInputStream.Close();

            //process the list of skin files
            var NewSkin = new SkinFileProcessor(rootPath, skinRoot, skinName);

            strMessage += NewSkin.ProcessList(arrSkinFiles, SkinParser.Portable);

            //log installation event
            try
            {
                var log = new LogInfo {
                    LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString()
                };
                log.LogProperties.Add(new LogDetailInfo("Install Skin:", skinName));
                Array arrMessage = strMessage.Split(new[] { "<br />" }, StringSplitOptions.None);
                foreach (string strRow in arrMessage)
                {
                    log.LogProperties.Add(new LogDetailInfo("Info:", HtmlUtils.StripTags(strRow, true)));
                }
                LogController.Instance.AddLog(log);
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
            }
            return(strMessage);
        }
Пример #10
0
        /// <summary>
        /// Converts tag names, attribute names, and style text to lowercase.
        /// </summary>
        private string CleanupHtml(string html, bool xml)
        {
            bool needsCleanup;

            do
            {
                needsCleanup = false;
                StringBuilder    output     = new StringBuilder(html.Length);
                SimpleHtmlParser htmlParser = new SimpleHtmlParser(html);
                for (Element el; null != (el = htmlParser.Next());)
                {
                    if (el is BeginTag)
                    {
                        BeginTag bt = (BeginTag)el;

                        if (RemoveMeaninglessTags(htmlParser, bt))
                        {
                            // Since we are removing a tag, we will want to clean up again, since that might mean
                            // there will be another tag to remove
                            needsCleanup = true;
                            continue;
                        }

                        output.Append("<");
                        output.Append(bt.Name.ToLower(CultureInfo.InvariantCulture));
                        foreach (Attr attr in bt.Attributes)
                        {
                            if (attr.NameEquals("contenteditable") || attr.NameEquals("atomicselection") ||
                                attr.NameEquals("unselectable"))
                            {
                                continue;
                            }

                            output.Append(" ");
                            output.Append(attr.Name.ToLower(CultureInfo.InvariantCulture));
                            if (attr.Value != null)
                            {
                                string attrVal = attr.Value;
                                if (attr.NameEquals("style"))
                                {
                                    attrVal = LowerCaseCss(attrVal);
                                }
                                else if (attr.Name == attr.Value)
                                {
                                    attrVal = attrVal.ToLower(CultureInfo.InvariantCulture);
                                }
                                output.AppendFormat("=\"{0}\"",
                                                    xml
                                                        ? HtmlUtils.EscapeEntitiesForXml(attrVal, true)
                                                        : HtmlUtils.EscapeEntities(attrVal));
                            }
                        }
                        if (bt.HasResidue)
                        {
                            if (bt.Attributes.Length == 0)
                            {
                                output.Append(" ");
                            }
                            output.Append(bt.Residue);
                        }
                        if (bt.Complete)
                        {
                            output.Append(" /");
                        }
                        output.Append(">");
                    }
                    else if (el is EndTag)
                    {
                        output.AppendFormat("</{0}>", ((EndTag)el).Name.ToLower(CultureInfo.InvariantCulture));
                    }
                    else if (el is Text)
                    {
                        string textHtml = HtmlUtils.TidyNbsps(el.RawText);
                        if (xml)
                        {
                            textHtml =
                                HtmlUtils.EscapeEntitiesForXml(
                                    HtmlUtils.UnEscapeEntities(textHtml, HtmlUtils.UnEscapeMode.NonMarkupText), false);
                        }
                        output.Append(textHtml);
                    }
                    else if (el is StyleText)
                    {
                        output.Append(el.RawText.ToLower(CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        output.Append(el.RawText);
                    }
                }
                html = output.ToString();
            } while (needsCleanup);
            return(html);
        }
        public Episode[] SearchForEpisode(string url)
        {
            var episodes = new List <Episode>();

            var doc = new HtmlDocument();

            try
            {
                doc.LoadHtml(HtmlUtils.GetHtmlPage(url));
            }
            catch (Exception ex)
            {
                LogManager.GetCurrentClassLogger().Error(ex, $"Ошибка при получении страницы {url}");
            }

            int seriesId = 0, playlistId = 0;

            // Episode Id - //ul[@role='tablist'] - @data-entry_id
            var seriesIdNode = doc.DocumentNode.SelectSingleNode("//ul[@role='tablist']");

            if (seriesIdNode == null)
            {
                return(episodes.ToArray());
            }
            else
            {
                seriesId = int.Parse(seriesIdNode.Attributes["data-entry_id"].Value);
            }

            // Playlists Ids - //a[contains(@href,'#tab')] - @href (only numbers)
            var playlistNodes = doc.DocumentNode.SelectNodes("//a[contains(@href,'#tab')]");

            if (playlistNodes != null && playlistNodes.Count > 0)
            {
                foreach (var playlistNode in playlistNodes)
                {
                    try
                    {
                        playlistId = int.Parse(playlistNode.Attributes["href"].Value.Replace("#tab", "")) + 1;

                        // Episode file (JSON) - https://online.animedia.tv/embeds/playlist-j.txt/{seriesId}/{playlistId}
                        var     json    = HtmlUtils.GetHtmlPage(Utils.Combine(Info().SiteUrl, $"embeds/playlist-j.txt/{seriesId}/{playlistId}"));
                        dynamic jsonObj = JsonConvert.DeserializeObject($"{{\"episodes\":{json}}}");
                        foreach (var episode in jsonObj.episodes)
                        {
                            // Episode description - title
                            string title = episode.title;

                            // Link to m3u8 file - file
                            string file = episode.file;

                            if (file.StartsWith("//"))
                            {
                                file = "http:" + file;
                            }

                            episodes.Add(new Episode()
                            {
                                Name         = title,
                                MovieUrl     = file,
                                IsDirectLink = true
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.GetCurrentClassLogger().Error(ex, $"Ошибка при обработке эпизодов {seriesId} {playlistId}");
                    }
                }
            }

            // Get all episodes - https://online.animedia.tv/ajax/episodes/{episodeId}/{playlistId}
            // Episode node - //div[@class='media__tabs__series__list__item']
            // Link to episode - ./a - @href (+provider url)
            // Preview image - ./a/img - @data-src
            // Episode description - ./a/img - @alt

            return(episodes.ToArray());
        }
Пример #12
0
        private static void WriteLog(LogQueueItem logQueueItem)
        {
            LogTypeConfigInfo logTypeConfigInfo = null;

            try
            {
                logTypeConfigInfo = logQueueItem.LogTypeConfigInfo;
                if (logTypeConfigInfo != null)
                {
                    LogInfo objLogInfo    = logQueueItem.LogInfo;
                    string  logProperties = objLogInfo.LogProperties.Serialize();
                    DataProvider.Instance().AddLog(objLogInfo.LogGUID,
                                                   objLogInfo.LogTypeKey,
                                                   objLogInfo.LogUserID,
                                                   objLogInfo.LogUserName,
                                                   objLogInfo.LogPortalID,
                                                   objLogInfo.LogPortalName,
                                                   objLogInfo.LogCreateDate,
                                                   objLogInfo.LogServerName,
                                                   logProperties,
                                                   Convert.ToInt32(objLogInfo.LogConfigID));
                    if (logTypeConfigInfo.EmailNotificationIsActive)
                    {
                        LockNotif.AcquireWriterLock(ReaderLockTimeout);
                        try
                        {
                            if (logTypeConfigInfo.NotificationThreshold == 0)
                            {
                                string str = logQueueItem.LogInfo.Serialize();

                                Mail.Mail.SendEmail(logTypeConfigInfo.MailFromAddress, logTypeConfigInfo.MailToAddress, "Event Notification", str);
                            }
                        }
                        finally
                        {
                            LockNotif.ReleaseWriterLock();
                        }
                    }
                }
            }
            catch (SqlException exc)
            {
                DnnLog.Error(exc);
                if ((HttpContext.Current != null))
                {
                    if (HttpContext.Current.IsCustomErrorEnabled)
                    {
                        HttpContext.Current.AddError(exc);
                    }
                    else
                    {
                        HttpResponse response = HttpContext.Current.Response;
                        response.StatusCode = 500;
                        HtmlUtils.WriteHeader(response, "SQL Exception");

                        string strMessage = SqlUtils.TranslateSQLException(exc);
                        if (logTypeConfigInfo != null)
                        {
                            HtmlUtils.WriteError(response, logTypeConfigInfo.LogFileNameWithPath, strMessage);
                        }

                        HtmlUtils.WriteFooter(response);
                        response.End();
                    }
                }
            }
            catch (Exception exc)
            {
                DnnLog.Error(exc);

                if (HttpContext.Current != null)
                {
                    HttpResponse response = HttpContext.Current.Response;
                    HtmlUtils.WriteHeader(response, "Unhandled Error");
                    string strMessage = exc.Message;
                    if (logTypeConfigInfo != null)
                    {
                        HtmlUtils.WriteError(response, logTypeConfigInfo.LogFileNameWithPath, strMessage);
                    }
                    HtmlUtils.WriteFooter(response);
                    response.End();
                }
            }
        }
Пример #13
0
        public ActionResult ConfirmOrder(FormCollection form)
        {
            //validation
            var storeId  = _storeContext.CurrentStore.Id;
            var customer = _workContext.CurrentCustomer;
            var cart     = customer.GetCartItems(ShoppingCartType.ShoppingCart, storeId);

            if (cart.Count == 0)
            {
                return(RedirectToRoute("ShoppingCart"));
            }

            if ((customer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
            {
                return(new HttpUnauthorizedResult());
            }

            var model = new CheckoutConfirmModel();
            PlaceOrderResult          placeOrderResult          = null;
            PostProcessPaymentRequest postProcessPaymentRequest = null;

            try
            {
                var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest;
                if (processPaymentRequest == null)
                {
                    //Check whether payment workflow is required
                    if (IsPaymentWorkflowRequired(cart))
                    {
                        return(RedirectToAction("PaymentMethod"));
                    }

                    processPaymentRequest = new ProcessPaymentRequest();
                }

                //prevent 2 orders being placed within an X seconds time frame
                if (!IsMinimumOrderPlacementIntervalValid(customer))
                {
                    throw new Exception(T("Checkout.MinOrderPlacementInterval"));
                }

                //place order
                processPaymentRequest.StoreId    = storeId;
                processPaymentRequest.CustomerId = customer.Id;
                processPaymentRequest.PaymentMethodSystemName = customer.GetAttribute <string>(SystemCustomerAttributeNames.SelectedPaymentMethod, _genericAttributeService, storeId);

                var placeOrderExtraData = new Dictionary <string, string>();
                placeOrderExtraData["CustomerComment"]               = form["customercommenthidden"];
                placeOrderExtraData["SubscribeToNewsLetter"]         = form["SubscribeToNewsLetterHidden"];
                placeOrderExtraData["AcceptThirdPartyEmailHandOver"] = form["AcceptThirdPartyEmailHandOverHidden"];

                placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest, placeOrderExtraData);

                if (!placeOrderResult.Success)
                {
                    model.Warnings.AddRange(placeOrderResult.Errors.Select(x => HtmlUtils.ConvertPlainTextToHtml(x)));
                }
            }
            catch (Exception exception)
            {
                Logger.Warn(exception, exception.Message);

                if (!model.Warnings.Any(x => x == exception.Message))
                {
                    model.Warnings.Add(exception.Message);
                }
            }

            if (placeOrderResult == null || !placeOrderResult.Success || model.Warnings.Any())
            {
                return(View(model));
            }

            try
            {
                postProcessPaymentRequest = new PostProcessPaymentRequest
                {
                    Order = placeOrderResult.PlacedOrder
                };

                _paymentService.PostProcessPayment(postProcessPaymentRequest);
            }
            catch (Exception exception)
            {
                NotifyError(exception);
            }
            finally
            {
                _httpContext.Session["OrderPaymentInfo"] = null;
                _httpContext.RemoveCheckoutState();
            }

            if (postProcessPaymentRequest != null && postProcessPaymentRequest.RedirectUrl.HasValue())
            {
                return(Redirect(postProcessPaymentRequest.RedirectUrl));
            }

            return(RedirectToAction("Completed"));
        }
Пример #14
0
        public void CreateDownloadedPostOnDisk(Post post, string weblogName)
        {
            string filename = FileUtils.SafeFilename(post.Title);

            var folder = Path.Combine(WeblogAddinConfiguration.Current.PostsFolder,
                                      "Downloaded", weblogName,
                                      filename);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            var outputFile = Path.Combine(folder, StringUtils.ToCamelCase(filename) + ".md");



            bool   isMarkdown    = false;
            string body          = post.Body;
            string featuredImage = null;

            if (post.CustomFields != null)
            {
                var cf = post.CustomFields.FirstOrDefault(custf => custf.Id == "mt_markdown");
                if (cf != null)
                {
                    body       = cf.Value;
                    isMarkdown = true;
                }

                cf = post.CustomFields.FirstOrDefault(custf => custf.Id == "wp_post_thumbnail");
                if (cf != null)
                {
                    featuredImage = cf.Value;
                }
            }
            if (!isMarkdown)
            {
                if (!string.IsNullOrEmpty(post.mt_text_more))
                {
                    // Wordpress ReadMore syntax - SERIOUSLY???
                    if (string.IsNullOrEmpty(post.mt_excerpt))
                    {
                        post.mt_excerpt = HtmlUtils.StripHtml(post.Body);
                    }

                    body = MarkdownUtilities.HtmlToMarkdown(body) +
                           $"{mmApp.NewLine}{mmApp.NewLine}<!--more-->{mmApp.NewLine}{mmApp.NewLine}" +
                           MarkdownUtilities.HtmlToMarkdown(post.mt_text_more);
                }
                else
                {
                    body = MarkdownUtilities.HtmlToMarkdown(body);
                }
            }

            string categories = null;

            if (post.Categories != null && post.Categories.Length > 0)
            {
                categories = string.Join(",", post.Categories);
            }


            // Create the new post by creating a file with title preset
            var meta = new WeblogPostMetadata()
            {
                Title            = post.Title,
                MarkdownBody     = body,
                Categories       = categories,
                Keywords         = post.mt_keywords,
                Abstract         = post.mt_excerpt,
                PostId           = post.PostId.ToString(),
                WeblogName       = weblogName,
                FeaturedImageUrl = featuredImage,
                PostDate         = post.DateCreated,
                PostStatus       = post.PostStatus,
                Permalink        = post.Permalink
            };

            string newPostMarkdown = NewWeblogPost(meta);

            try
            {
                File.WriteAllText(outputFile, newPostMarkdown);
            }
            catch (Exception ex)
            {
                MessageBox.Show($@"Couldn't write new file at:
{outputFile}

{ex.Message}
",
                                "Weblog Entry File not created",
                                MessageBoxButton.OK,
                                MessageBoxImage.Warning);
                return;
            }

            mmApp.Configuration.LastFolder = Path.GetDirectoryName(outputFile);

            if (isMarkdown)
            {
                string html = post.Body;
                string path = mmApp.Configuration.LastFolder;

                // do this synchronously so images show up :-<
                ShowStatus("Downloading post images...", mmApp.Configuration.StatusMessageTimeout);
                SaveMarkdownImages(html, path);
                ShowStatus("Post download complete.", mmApp.Configuration.StatusMessageTimeout);

                //new Action<string,string>(SaveImages).BeginInvoke(html,path,null, null);
            }

            Model.Window.OpenTab(outputFile);
            Model.Window.ShowFolderBrowser(folder: Path.GetDirectoryName(outputFile));
        }
Пример #15
0
        public virtual async Task <string> FormatAttributesAsync(
            ProductVariantAttributeSelection selection,
            Product product,
            Customer customer              = null,
            string separator               = "<br />",
            bool htmlEncode                = true,
            bool includePrices             = true,
            bool includeProductAttributes  = true,
            bool includeGiftCardAttributes = true,
            bool includeHyperlinks         = true)
        {
            Guard.NotNull(selection, nameof(selection));
            Guard.NotNull(product, nameof(product));

            using var pool = StringBuilderPool.Instance.Get(out var result);

            if (includeProductAttributes)
            {
                var languageId = _workContext.WorkingLanguage.Id;
                var attributes = await _productAttributeMaterializer.MaterializeProductVariantAttributesAsync(selection);

                var attributesDic = attributes.ToDictionary(x => x.Id);

                foreach (var kvp in selection.AttributesMap)
                {
                    if (!attributesDic.TryGetValue(kvp.Key, out var pva))
                    {
                        continue;
                    }

                    foreach (var value in kvp.Value)
                    {
                        var valueStr     = value.ToString().EmptyNull();
                        var pvaAttribute = string.Empty;

                        if (pva.IsListTypeAttribute())
                        {
                            var pvaValue = pva.ProductVariantAttributeValues.FirstOrDefault(x => x.Id == valueStr.ToInt());
                            if (pvaValue != null)
                            {
                                pvaAttribute = "{0}: {1}".FormatInvariant(
                                    pva.ProductAttribute.GetLocalized(x => x.Name, languageId),
                                    pvaValue.GetLocalized(x => x.Name, languageId));

                                if (includePrices)
                                {
                                    // TODO: (mg) (core) Complete ProductAttributeFormatter.FormatAttributesAsync (IPriceCalculationService required).
                                    //var attributeValuePriceAdjustment = _priceCalculationService.GetProductVariantAttributeValuePriceAdjustment(pvaValue, product, customer ?? _workContext.CurrentCustomer, null, 1);
                                    var attributeValuePriceAdjustment = decimal.Zero;
                                    var priceAdjustmentBase           = await _taxService.GetProductPriceAsync(product, attributeValuePriceAdjustment, customer : customer ?? _workContext.CurrentCustomer);

                                    var priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);

                                    if (_shoppingCartSettings.ShowLinkedAttributeValueQuantity &&
                                        pvaValue.ValueType == ProductVariantAttributeValueType.ProductLinkage &&
                                        pvaValue.Quantity > 1)
                                    {
                                        pvaAttribute = pvaAttribute + " × " + pvaValue.Quantity;
                                    }

                                    if (_catalogSettings.ShowVariantCombinationPriceAdjustment)
                                    {
                                        if (priceAdjustmentBase > 0)
                                        {
                                            pvaAttribute += " (+{0})".FormatInvariant(_priceFormatter.FormatPrice(priceAdjustment, true, displayTax: false));
                                        }
                                        else if (priceAdjustmentBase < decimal.Zero)
                                        {
                                            pvaAttribute += " (-{0})".FormatInvariant(_priceFormatter.FormatPrice(-priceAdjustment, true, displayTax: false));
                                        }
                                    }
                                }

                                if (htmlEncode)
                                {
                                    pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute);
                                }
                            }
                        }
                        else if (pva.AttributeControlType == AttributeControlType.MultilineTextbox)
                        {
                            string attributeName = pva.ProductAttribute.GetLocalized(x => x.Name, languageId);

                            pvaAttribute = "{0}: {1}".FormatInvariant(
                                htmlEncode ? HttpUtility.HtmlEncode(attributeName) : attributeName,
                                HtmlUtils.ConvertPlainTextToHtml(valueStr.HtmlEncode()));
                        }
                        else if (pva.AttributeControlType == AttributeControlType.FileUpload)
                        {
                            if (Guid.TryParse(valueStr, out var downloadGuid) && downloadGuid != Guid.Empty)
                            {
                                var download = await _db.Downloads
                                               .AsNoTracking()
                                               .Include(x => x.MediaFile)
                                               .Where(x => x.DownloadGuid == downloadGuid)
                                               .FirstOrDefaultAsync();

                                if (download?.MediaFile != null)
                                {
                                    var attributeText = string.Empty;
                                    var fileName      = htmlEncode
                                        ? HttpUtility.HtmlEncode(download.MediaFile.Name)
                                        : download.MediaFile.Name;

                                    if (includeHyperlinks)
                                    {
                                        // TODO: (core) add a method for getting URL (use routing because it handles all SEO friendly URLs).
                                        var downloadLink = _webHelper.GetStoreLocation(false) + "download/getfileupload/?downloadId=" + download.DownloadGuid;
                                        attributeText = $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{fileName}</a>";
                                    }
                                    else
                                    {
                                        attributeText = fileName;
                                    }

                                    string attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, languageId);

                                    pvaAttribute = "{0}: {1}".FormatInvariant(
                                        htmlEncode ? HttpUtility.HtmlEncode(attributeName) : attributeName,
                                        attributeText);
                                }
                            }
                        }
                        else
                        {
                            // TextBox, Datepicker
                            pvaAttribute = "{0}: {1}".FormatInvariant(pva.ProductAttribute.GetLocalized(x => x.Name, languageId), valueStr);

                            if (htmlEncode)
                            {
                                pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute);
                            }
                        }

                        result.Grow(pvaAttribute, separator);
                    }
                }
            }

            if (includeGiftCardAttributes && product.IsGiftCard)
            {
                var gca = selection.GetGiftCardAttributes();
                if (gca != null)
                {
                    // Sender.
                    var giftCardFrom = product.GiftCardType == GiftCardType.Virtual
                        ? (await _localizationService.GetResourceAsync("GiftCardAttribute.From.Virtual")).FormatInvariant(gca.SenderName, gca.SenderEmail)
                        : (await _localizationService.GetResourceAsync("GiftCardAttribute.From.Physical")).FormatInvariant(gca.SenderName);

                    // Recipient.
                    var giftCardFor = product.GiftCardType == GiftCardType.Virtual
                        ? (await _localizationService.GetResourceAsync("GiftCardAttribute.For.Virtual")).FormatInvariant(gca.RecipientName, gca.RecipientEmail)
                        : (await _localizationService.GetResourceAsync("GiftCardAttribute.For.Physical")).FormatInvariant(gca.RecipientName);

                    if (htmlEncode)
                    {
                        giftCardFrom = HttpUtility.HtmlEncode(giftCardFrom);
                        giftCardFor  = HttpUtility.HtmlEncode(giftCardFor);
                    }

                    result.Grow(giftCardFrom, separator);
                    result.Grow(giftCardFor, separator);
                }
            }

            return(result.ToString());
        }
Пример #16
0
        private void UpgradeApplication()
        {
            var databaseVersion = DataProvider.Instance().GetVersion();

            //Start Timer
            Upgrade.Upgrade.StartTimer();

            //Write out Header
            HtmlUtils.WriteHeader(Response, "upgrade");

            Response.Write("<h2>Current Assembly Version: " + Globals.FormatVersion(DotNetNukeContext.Current.Application.Version) + "</h2>");
            Response.Flush();

            //get path to script files
            string strProviderPath = DataProvider.Instance().GetProviderPath();

            if (!strProviderPath.StartsWith("ERROR:"))
            {
                //get current database version
                var strDatabaseVersion = Globals.FormatVersion(databaseVersion);

                Response.Write("<h2>Current Database Version: " + strDatabaseVersion + "</h2>");
                Response.Flush();

                string ignoreWarning = Null.NullString;
                string strWarning    = Null.NullString;
                if ((databaseVersion.Major == 3 && databaseVersion.Minor < 3) || (databaseVersion.Major == 4 && databaseVersion.Minor < 3))
                {
                    //Users and profile have not been transferred
                    //Get the name of the data provider
                    ProviderConfiguration objProviderConfiguration = ProviderConfiguration.GetProviderConfiguration("data");

                    //Execute Special Script
                    Upgrade.Upgrade.ExecuteScript(strProviderPath + "Upgrade." + objProviderConfiguration.DefaultProvider);

                    if ((Request.QueryString["ignoreWarning"] != null))
                    {
                        ignoreWarning = Request.QueryString["ignoreWarning"].ToLower();
                    }
                    strWarning = Upgrade.Upgrade.CheckUpgrade();
                }
                else
                {
                    ignoreWarning = "true";
                }

                //Check whether Upgrade is ok
                if (strWarning == Null.NullString || ignoreWarning == "true")
                {
                    Response.Write("<br><br>");
                    Response.Write("<h2>Upgrade Status Report</h2>");
                    Response.Flush();
                    //stop scheduler
                    SchedulingProvider.Instance().Halt("Stopped by Upgrade Process");

                    Upgrade.Upgrade.UpgradeDNN(strProviderPath, databaseVersion);

                    //Install optional resources if present
                    var packages = Upgrade.Upgrade.GetInstallPackages();
                    foreach (var package in packages)
                    {
                        Upgrade.Upgrade.InstallPackage(package.Key, package.Value.PackageType, true);
                    }

                    //calling GetInstallVersion after SQL scripts exection to ensure sp GetDatabaseInstallVersion exists
                    var    installVersion = DataProvider.Instance().GetInstallVersion();
                    string strError       = Config.UpdateInstallVersion(installVersion);
                    if (!string.IsNullOrEmpty(strError))
                    {
                        Logger.Error(strError);
                    }
                    Response.Write("<h2>Upgrade Complete</h2>");
                    Response.Write("<br><br><h2><a href='../Default.aspx'>Click Here To Access Your Site</a></h2><br><br>");
                }
                else
                {
                    Response.Write("<h2>Warning:</h2>" + strWarning.Replace(Environment.NewLine, "<br />"));

                    Response.Write("<br><br><a href='Install.aspx?mode=upgrade&ignoreWarning=true'>Click Here To Proceed With The Upgrade.</a>");
                }
                Response.Flush();
            }
            else
            {
                Response.Write("<h2>Upgrade Error: " + strProviderPath + "</h2>");
                Response.Flush();
            }

            //Write out Footer
            HtmlUtils.WriteFooter(Response);
        }
Пример #17
0
        protected void OnSaveClick(object sender, EventArgs e)
        {
            const bool redirect = true;

            try
            {
                // get content
                var htmlContent = GetLatestHTMLContent();

                var aliases = from PortalAliasInfo pa in PortalAliasController.Instance.GetPortalAliasesByPortalId(PortalSettings.PortalId)
                              select pa.HTTPAlias;
                string content;
                if (phEdit.Visible)
                {
                    content = txtContent.Text;
                }
                else
                {
                    content = hfEditor.Value;
                }


                if (Request.QueryString["nuru"] == null)
                {
                    content = HtmlUtils.AbsoluteToRelativeUrls(content, aliases);
                }
                htmlContent.Content = content;

                var draftStateID     = _workflowStateController.GetFirstWorkflowStateID(WorkflowID);
                var publishedStateID = _workflowStateController.GetLastWorkflowStateID(WorkflowID);

                switch (CurrentWorkflowType)
                {
                case WorkflowType.DirectPublish:
                    _htmlTextController.UpdateHtmlText(htmlContent, _htmlTextController.GetMaximumVersionHistory(PortalId));

                    break;

                case WorkflowType.ContentStaging:
                    if (chkPublish.Checked)
                    {
                        //if it's already published set it to draft
                        if (htmlContent.StateID == publishedStateID)
                        {
                            htmlContent.StateID = draftStateID;
                        }
                        else
                        {
                            htmlContent.StateID = publishedStateID;
                            //here it's in published mode
                        }
                    }
                    else
                    {
                        //if it's already published set it back to draft
                        if ((htmlContent.StateID != draftStateID))
                        {
                            htmlContent.StateID = draftStateID;
                        }
                    }

                    _htmlTextController.UpdateHtmlText(htmlContent, _htmlTextController.GetMaximumVersionHistory(PortalId));
                    break;
                }
            }
            catch (Exception exc)
            {
                Exceptions.LogException(exc);
                UI.Skins.Skin.AddModuleMessage(Page, "Error occurred: ", exc.Message, ModuleMessage.ModuleMessageType.RedError);
                return;
            }

            // redirect back to portal
            if (redirect)
            {
                Response.Redirect(Globals.NavigateURL(), true);
            }
        }
Пример #18
0
        private void NoUpgrade()
        {
            //get path to script files
            string strProviderPath = DataProvider.Instance().GetProviderPath();

            if (!strProviderPath.StartsWith("ERROR:"))
            {
                string strDatabaseVersion;
                //get current database version
                try
                {
                    IDataReader dr = DataProvider.Instance().GetDatabaseVersion();
                    if (dr.Read())
                    {
                        //Write out Header
                        HtmlUtils.WriteHeader(Response, "none");
                        string currentAssembly = DotNetNukeContext.Current.Application.Version.ToString(3);
                        string currentDatabase = dr["Major"] + "." + dr["Minor"] + "." + dr["Build"];
                        //do not show versions if the same to stop information leakage
                        if (currentAssembly == currentDatabase)
                        {
                            Response.Write("<h2>Current Assembly Version && current Database Version are identical.</h2>");
                        }
                        else
                        {
                            Response.Write("<h2>Current Assembly Version: " + currentAssembly + "</h2>");
                            //Call Upgrade with the current DB Version to upgrade an
                            //existing DNN installation
                            strDatabaseVersion = ((int)dr["Major"]).ToString("00") + "." + ((int)dr["Minor"]).ToString("00") + "." + ((int)dr["Build"]).ToString("00");
                            Response.Write("<h2>Current Database Version: " + strDatabaseVersion + "</h2>");
                        }

                        Response.Write("<br><br><a href='Install.aspx?mode=Install'>Click Here To Upgrade DotNetNuke</a>");
                        Response.Flush();
                    }
                    else
                    {
                        //Write out Header
                        HtmlUtils.WriteHeader(Response, "noDBVersion");
                        Response.Write("<h2>Current Assembly Version: " + DotNetNukeContext.Current.Application.Version.ToString(3) + "</h2>");

                        Response.Write("<h2>Current Database Version: N/A</h2>");
                        Response.Write("<br><br><h2><a href='Install.aspx?mode=Install'>Click Here To Install DotNetNuke</a></h2>");
                        Response.Flush();
                    }
                    dr.Close();
                }
                catch (Exception ex)
                {
                    //Write out Header
                    Logger.Error(ex);
                    HtmlUtils.WriteHeader(Response, "error");
                    Response.Write("<h2>Current Assembly Version: " + DotNetNukeContext.Current.Application.Version.ToString(3) + "</h2>");

                    Response.Write("<h2>" + ex.Message + "</h2>");
                    Response.Flush();
                }
            }
            else
            {
                //Write out Header
                HtmlUtils.WriteHeader(Response, "error");
                Response.Write("<h2>Current Assembly Version: " + DotNetNukeContext.Current.Application.Version.ToString(3) + "</h2>");

                Response.Write("<h2>" + strProviderPath + "</h2>");
                Response.Flush();
            }

            //Write out Footer
            HtmlUtils.WriteFooter(Response);
        }
Пример #19
0
        private static MimeMessage CreateMailMessage(MailInfo mailInfo, SmtpInfo smtpInfo)
        {
            var mailMessage = new MimeMessage();

            mailMessage.From.Add(ParseAddressWithDisplayName(displayName: mailInfo.FromName, address: mailInfo.From));
            if (!string.IsNullOrEmpty(mailInfo.Sender))
            {
                mailMessage.Sender = MailboxAddress.Parse(mailInfo.Sender);
            }

            // translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons
            if (!string.IsNullOrEmpty(mailInfo.To))
            {
                mailInfo.To = mailInfo.To.Replace(";", ",");
                mailMessage.To.AddRange(InternetAddressList.Parse(mailInfo.To));
            }

            if (!string.IsNullOrEmpty(mailInfo.CC))
            {
                mailInfo.CC = mailInfo.CC.Replace(";", ",");
                mailMessage.Cc.AddRange(InternetAddressList.Parse(mailInfo.CC));
            }

            if (!string.IsNullOrEmpty(mailInfo.BCC))
            {
                mailInfo.BCC = mailInfo.BCC.Replace(";", ",");
                mailMessage.Bcc.AddRange(InternetAddressList.Parse(mailInfo.BCC));
            }

            if (!string.IsNullOrEmpty(mailInfo.ReplyTo))
            {
                mailInfo.ReplyTo = mailInfo.ReplyTo.Replace(";", ",");
                mailMessage.ReplyTo.AddRange(InternetAddressList.Parse(mailInfo.ReplyTo));
            }

            mailMessage.Priority = (MessagePriority)mailInfo.Priority;

            // Only modify senderAddress if smtpAuthentication is enabled
            // Can be "0", empty or Null - anonymous, "1" - basic, "2" - NTLM.
            if (smtpInfo.Authentication == "1" || smtpInfo.Authentication == "2")
            {
                // if the senderAddress is the email address of the Host then switch it smtpUsername if different
                // if display name of senderAddress is empty, then use Host.HostTitle for it
                if (mailMessage.Sender != null)
                {
                    var senderAddress     = mailInfo.Sender;
                    var senderDisplayName = mailInfo.FromName;
                    var needUpdateSender  = false;
                    if (smtpInfo.Username.Contains("@") &&
                        senderAddress == Host.HostEmail &&
                        !senderAddress.Equals(smtpInfo.Username, StringComparison.InvariantCultureIgnoreCase))
                    {
                        senderAddress    = smtpInfo.Username;
                        needUpdateSender = true;
                    }

                    if (string.IsNullOrEmpty(senderDisplayName))
                    {
                        senderDisplayName = Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle;
                        needUpdateSender  = true;
                    }

                    if (needUpdateSender)
                    {
                        mailMessage.Sender = ParseAddressWithDisplayName(
                            displayName: senderDisplayName,
                            address: senderAddress);
                    }
                }
                else if (smtpInfo.Username.Contains("@"))
                {
                    mailMessage.Sender = ParseAddressWithDisplayName(
                        displayName: Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle,
                        address: smtpInfo.Username);
                }
            }

            var builder = new BodyBuilder {
                TextBody = Mail.ConvertToText(mailInfo.Body),
            };

            if (mailInfo.BodyFormat == MailFormat.Html)
            {
                builder.HtmlBody = mailInfo.Body;
            }

            // attachments
            if (mailInfo.Attachments != null)
            {
                foreach (var attachment in mailInfo.Attachments.Where(attachment => attachment.Content != null))
                {
                    builder.Attachments.Add(attachment.Filename, attachment.Content, ContentType.Parse(attachment.ContentType));
                }
            }

            // message
            mailMessage.Subject = HtmlUtils.StripWhiteSpace(mailInfo.Subject, true);
            mailMessage.Body    = builder.ToMessageBody();
            return(mailMessage);
        }
Пример #20
0
        private void InstallApplication()
        {
            //the application uses a two step installation process. The first step is used to update
            //the Web.config with any configuration settings - which forces an application restart.
            //The second step finishes the installation process and provisions the site.

            string installationDate = Config.GetSetting("InstallationDate");

            if (installationDate == null || String.IsNullOrEmpty(installationDate))
            {
                string strError = Config.UpdateMachineKey();
                if (String.IsNullOrEmpty(strError))
                {
                    //send a new request to the application to initiate step 2
                    Response.Redirect(HttpContext.Current.Request.RawUrl, true);
                }
                else
                {
                    //403-3 Error - Redirect to ErrorPage
                    //403.3 means directory permissions issue
                    string strURL = "~/ErrorPage.aspx?status=403_3&error=" + strError;
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Server.Transfer(strURL);
                }
            }
            else
            {
                var synchConnectionString = new SynchConnectionStringStep();
                synchConnectionString.Execute();
                if (synchConnectionString.Status == StepStatus.AppRestart)
                {
                    //send a new request to the application to initiate step 2
                    Response.Redirect(HttpContext.Current.Request.RawUrl, true);
                }

                //Start Timer
                Upgrade.Upgrade.StartTimer();

                //Write out Header
                HtmlUtils.WriteHeader(Response, "install");

                //get path to script files
                string strProviderPath = DataProvider.Instance().GetProviderPath();
                if (!strProviderPath.StartsWith("ERROR:"))
                {
                    Response.Write("<h2>Version: " + Globals.FormatVersion(DotNetNukeContext.Current.Application.Version) + "</h2>");
                    Response.Flush();

                    Response.Write("<br><br>");
                    Response.Write("<h2>Installation Status Report</h2>");
                    Response.Flush();

                    if (!CheckPermissions())
                    {
                        return;
                    }

                    var installConfig = InstallController.Instance.GetInstallConfig();

                    Upgrade.Upgrade.InstallDNN(strProviderPath);
                    //remove en-US from portal if installing in a different language
                    if (!installConfig.InstallCulture.Equals("en-us", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var locale = LocaleController.Instance.GetLocale("en-US");
                        Localization.Localization.RemoveLanguageFromPortal(0, locale.LanguageId);
                    }


                    var  licenseConfig     = (installConfig != null) ? installConfig.License : null;
                    bool IsProOrEnterprise = (File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Professional.dll")) || File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Enterprise.dll")));
                    if (IsProOrEnterprise && licenseConfig != null && !String.IsNullOrEmpty(licenseConfig.AccountEmail) && !String.IsNullOrEmpty(licenseConfig.InvoiceNumber))
                    {
                        Upgrade.Upgrade.ActivateLicense();
                    }

                    //Adding ClientDependency Resources config to web.config
                    if (!ClientResourceManager.IsInstalled())
                    {
                        ClientResourceManager.AddConfiguration();
                    }

                    var    installVersion = DataProvider.Instance().GetInstallVersion();
                    string strError       = Config.UpdateInstallVersion(installVersion);
                    if (!string.IsNullOrEmpty(strError))
                    {
                        Logger.Error(strError);
                    }

                    Response.Write("<h2>Installation Complete</h2>");
                    Response.Write("<br><br><h2><a href='../Default.aspx'>Click Here To Access Your Site</a></h2><br><br>");
                    Response.Flush();

                    //remove installwizard files
                    Upgrade.Upgrade.DeleteInstallerFiles();

                    //log APPLICATION_START event
                    Initialize.LogStart();

                    //Start Scheduler
                    Initialize.StartScheduler();
                }
                else
                {
                    //upgrade error
                    Response.Write("<h2>Upgrade Error: " + strProviderPath + "</h2>");
                    Response.Flush();
                }

                //Write out Footer
                HtmlUtils.WriteFooter(Response);
            }
        }
Пример #21
0
        public override IList <SearchDocument> GetModifiedSearchDocuments(ModuleInfo modInfo, DateTime beginDateUtc)
        {
            var workflowId      = GetWorkflow(modInfo.ModuleID, modInfo.TabID, modInfo.PortalID).Value;
            var searchDocuments = new List <SearchDocument>();
            var htmlTextInfo    = GetTopHtmlText(modInfo.ModuleID, true, workflowId);
            var repo            = new HtmlModuleSettingsRepository();
            var settings        = repo.GetSettings(modInfo);

            if (htmlTextInfo != null &&
                (htmlTextInfo.LastModifiedOnDate.ToUniversalTime() > beginDateUtc &&
                 htmlTextInfo.LastModifiedOnDate.ToUniversalTime() < DateTime.UtcNow))
            {
                var strContent = HtmlUtils.Clean(htmlTextInfo.Content, false);

                // Get the description string
                var description = strContent.Length <= settings.SearchDescLength ? strContent : HtmlUtils.Shorten(strContent, settings.SearchDescLength, "...");

                var searchDoc = new SearchDocument
                {
                    UniqueKey       = modInfo.ModuleID.ToString(),
                    PortalId        = modInfo.PortalID,
                    Title           = modInfo.ModuleTitle,
                    Description     = description,
                    Body            = strContent,
                    ModifiedTimeUtc = htmlTextInfo.LastModifiedOnDate.ToUniversalTime()
                };

                if (modInfo.Terms != null && modInfo.Terms.Count > 0)
                {
                    searchDoc.Tags = CollectHierarchicalTags(modInfo.Terms);
                }

                searchDocuments.Add(searchDoc);
            }

            return(searchDocuments);
        }
        /// <summary>
        /// Parses the actual markdown down to html
        /// </summary>
        /// <param name="markdown"></param>
        /// <returns></returns>
        public override string Parse(string markdown)
        {
            var options = mmApp.Configuration.MarkdownOptions;

            var builder = new MarkdownPipelineBuilder();

            var errors = Array.Empty <string>();
            var tokens = new Dictionary <string, string>();
            var files  = new Dictionary <string, string>();

            var actualErrors       = new List <string>();
            var actualDependencies = new HashSet <string>();

            var context = new MarkdownContext(
                getToken: key => tokens.TryGetValue(key, out var value) ? value : null,
                logInfo: (a, b, c, d) => { },
                logSuggestion: Log("suggestion"),
                logWarning: Log("warning"),
                logError: Log("error"),
                readFile: ReadFile);


            // Fake root path to what MM sees as the root path (.markdown, project file, project open etc.)
            string filePath = mmApp.Model.ActiveDocument?.Filename;

            if (string.IsNullOrEmpty(filePath) || filePath.Equals("untitled", StringComparison.OrdinalIgnoreCase))
            {
                filePath = mmApp.Model.ActiveDocument?.PreviewWebRootPath;
                if (string.IsNullOrEmpty(filePath))
                {
                    filePath = "preview.md";
                }
                else
                {
                    filePath += "\\preview";
                }
            }

            files.Add(filePath, markdown);


            builder = builder.UseEmphasisExtras(EmphasisExtraOptions.Strikethrough)
                      .UseAutoIdentifiers(AutoIdentifierOptions.GitHub)
                      .UseMediaLinks()
                      .UsePipeTables()
                      .UseAutoLinks()
                      .UseHeadingIdRewriter()
                      .UseIncludeFile(context)
                      .UseCodeSnippet(context)
                      .UseDFMCodeInfoPrefix()
                      .UseQuoteSectionNote(context)
                      .UseXref()
                      .UseEmojiAndSmiley(false)
                      .UseTabGroup(context)
                      .UseMonikerRange(context)
                      .UseInteractiveCode()
                      .UseRow(context)
                      .UseNestedColumn(context)
                      .UseTripleColon(context)
                      .UseNoloc();



            builder = RemoveUnusedExtensions(builder);
            builder = builder
                      .UseYamlFrontMatter()
                      .UseLineNumber();

            if (options.NoHtml)
            {
                builder = builder.DisableHtml();
            }

            if (UsePragmaLines)
            {
                builder = builder.UsePragmaLines();
            }

            var pipeline = builder.Build();

            string html;

            using (InclusionContext.PushFile(filePath))
            {
                html = Markdown.ToHtml(markdown, pipeline);
            }

            html = ParseFontAwesomeIcons(html);


            if (mmApp.Configuration.MarkdownOptions.RenderLinksAsExternal)
            {
                html = ParseExternalLinks(html);
            }

            if (!mmApp.Configuration.MarkdownOptions.AllowRenderScriptTags)
            {
                html = HtmlUtils.SanitizeHtml(html);
            }


            return(html);


            MarkdownContext.LogActionDelegate Log(string level)
            {
                return((code, message, origin, line) => actualErrors.Add(code));
            }

            // Handler to fix up file paths for nested/included documents
            (string content, object file) ReadFile(string path, MarkdownObject origin)
            {
                string key;

                var rootPath = mmApp.Model.ActiveDocument?.PreviewWebRootPath;

                if (rootPath == null)
                {
                    rootPath = Path.GetDirectoryName(files.FirstOrDefault().Key);
                }


                string parentDocPath = null; //relativeTo as string;   NOT PROVIDEd BY DOCFX ANYMORE???

                //if (!string.IsNullOrEmpty(parentDocPath))
                //    parentDocPath = Path.GetDirectoryName(parentDocPath);


                //fully qualified path
                if (path.Contains(":/") || path.Contains(":\\"))
                {
                    key = path;
                }
                else if (!string.IsNullOrEmpty(rootPath) && path.StartsWith("~/"))
                {
                    path = path.Substring(2);
                    key  = Path.Combine(rootPath, path).Replace('\\', '/');
                }
                // Site relative  path
                else if (!string.IsNullOrEmpty(rootPath) && path.StartsWith("/"))
                {
                    path = path.Substring(1);
                    key  = Path.Combine(rootPath, path).Replace('\\', '/');
                }
                // Site relative path
                else if (!string.IsNullOrEmpty(parentDocPath))
                {
                    key = Path.GetFullPath(Path.Combine(parentDocPath, path));
                }
                else
                {
                    key = path;
                }

                actualDependencies.Add(key);

                files.TryGetValue(key, out var value);
                if (value == null)
                {
                    try
                    {
                        value = File.ReadAllText(key)?.Trim();
                    }
                    catch
                    {
                    }
                }

                if (value == null)
                {
                    return(null, null);
                }

                return(value, key as object);
            }
        }
Пример #23
0
 public static string MakeHtmlForImageSourceDelay(string path)
 {
     return
         (String.Format(CultureInfo.InvariantCulture, "<img src=\"{1}\" srcDelay=\"{0}\" />", HtmlUtils.EscapeEntities(path), HtmlUtils.EscapeEntities(UrlHelper.SafeToAbsoluteUri(LoadingImagePath))));
 }
Пример #24
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The Install method installs the skin component
        /// </summary>
        /// <history>
        ///     [cnurse]	02/06/2008  created
        /// </history>
        public override void Install()
        {
            bool bAdd = Null.NullBoolean;

            try
            {
                //Attempt to get the Skin Package
                TempSkinPackage = SkinController.GetSkinPackage(SkinPackage.PortalID, SkinPackage.SkinName, SkinType);
                if (TempSkinPackage == null)
                {
                    bAdd = true;
                    SkinPackage.PackageID = Package.PackageID;
                }
                else
                {
                    SkinPackage.SkinPackageID = TempSkinPackage.SkinPackageID;
                    if (TempSkinPackage.PackageID != Package.PackageID)
                    {
                        Completed = false;
                        Log.AddFailure(Util.SKIN_Installed);
                        return;
                    }
                    else
                    {
                        SkinPackage.PackageID = TempSkinPackage.PackageID;
                    }
                }
                SkinPackage.SkinType = SkinType;
                if (bAdd)
                {
                    //Add new skin package
                    SkinPackage.SkinPackageID = SkinController.AddSkinPackage(SkinPackage);
                }
                else
                {
                    //Update skin package
                    SkinController.UpdateSkinPackage(SkinPackage);
                }
                Log.AddInfo(string.Format(Util.SKIN_Registered, SkinPackage.SkinName));

                //install (copy the files) by calling the base class
                base.Install();

                //process the list of skin files
                if (SkinFiles.Count > 0)
                {
                    Log.StartJob(Util.SKIN_BeginProcessing);
                    string strMessage = Null.NullString;
                    var    NewSkin    = new SkinFileProcessor(RootPath, SkinRoot, SkinPackage.SkinName);
                    foreach (string skinFile in SkinFiles)
                    {
                        strMessage += NewSkin.ProcessFile(skinFile, SkinParser.Portable);
                        skinFile.Replace(Globals.HostMapPath + "\\", "[G]");
                        switch (Path.GetExtension(skinFile))
                        {
                        case ".htm":
                            SkinController.AddSkin(SkinPackage.SkinPackageID, skinFile.Replace("htm", "ascx"));
                            break;

                        case ".html":
                            SkinController.AddSkin(SkinPackage.SkinPackageID, skinFile.Replace("html", "ascx"));
                            break;

                        case ".ascx":
                            SkinController.AddSkin(SkinPackage.SkinPackageID, skinFile);
                            break;
                        }
                    }
                    Array arrMessage = strMessage.Split(new[] { "<br />" }, StringSplitOptions.None);
                    foreach (string strRow in arrMessage)
                    {
                        Log.AddInfo(HtmlUtils.StripTags(strRow, true));
                    }
                    Log.EndJob(Util.SKIN_EndProcessing);
                }
                Completed = true;
            }
            catch (Exception ex)
            {
                Log.AddFailure(ex);
            }
        }
Пример #25
0
        /// <summary>
        /// Extract html tag attributes from the given sub-string.
        /// </summary>
        /// <param name="source">the html source to parse</param>
        /// <param name="idx">the start index of the tag attributes in the source</param>
        /// <param name="length">the length of the tag attributes from the start index in the source</param>
        /// <param name="attributes">return the dictionary of tag attributes</param>
        private static void ExtractAttributes(string source, int idx, int length, out Dictionary <string, string> attributes)
        {
            attributes = null;

            int startIdx = idx;

            while (startIdx < idx + length)
            {
                while (startIdx < idx + length && char.IsWhiteSpace(source, startIdx))
                {
                    startIdx++;
                }

                var endIdx = startIdx + 1;
                while (endIdx < idx + length && !char.IsWhiteSpace(source, endIdx) && source[endIdx] != '=')
                {
                    endIdx++;
                }

                if (startIdx < idx + length)
                {
                    var key   = source.Substring(startIdx, endIdx - startIdx);
                    var value = "";

                    startIdx = endIdx + 1;
                    while (startIdx < idx + length && (char.IsWhiteSpace(source, startIdx) || source[startIdx] == '='))
                    {
                        startIdx++;
                    }

                    bool hasPChar = false;
                    if (startIdx < idx + length)
                    {
                        char pChar = source[startIdx];
                        if (pChar == '"' || pChar == '\'')
                        {
                            hasPChar = true;
                            startIdx++;
                        }

                        endIdx = startIdx + (hasPChar ? 0 : 1);
                        while (endIdx < idx + length && (hasPChar ? source[endIdx] != pChar : !char.IsWhiteSpace(source, endIdx)))
                        {
                            endIdx++;
                        }

                        value = source.Substring(startIdx, endIdx - startIdx);
                        value = HtmlUtils.DecodeHtml(value);
                    }

                    if (key.Length != 0)
                    {
                        if (attributes == null)
                        {
                            attributes = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
                        }
                        attributes[key.ToLower()] = value;
                    }

                    startIdx = endIdx + (hasPChar ? 2 : 1);
                }
            }
        }
Пример #26
0
        private static async Task <FeedItemExt> DownloadFeedContent(FeedCfg feedCfg,
                                                                    FeedItem feedItem,
                                                                    SemaphoreSlim throttler,
                                                                    HttpClient client)
        {
            try
            {
                await throttler.WaitAsync();

                //
                // Check & update publishing dates

                if (feedCfg.UsePubDate)
                {
                    if (feedItem.PublishingDate == null)
                    {
                        LogTo.Warning(
                            $"Date missing, or unknown format for feed {feedCfg.Name}, item title '{feedItem.Title}', raw date '{feedItem.PublishingDateString}'");
                        return(null);
                    }

                    if (feedItem.PublishingDate <= feedCfg.LastPubDate)
                    {
                        return(null);
                    }
                }

                //
                // Check guid

                if (feedCfg.UseGuid)
                {
                    if (feedCfg.EntriesGuid.Contains(feedItem.Id))
                    {
                        return(null);
                    }
                }

                //
                // Check categories

                if (feedCfg.ShouldExcludeCategory(feedItem))
                {
                    return(null);
                }

                //
                // Download content or use inline content

                if (feedItem.Link != null)
                {
                    var httpReq = new HttpRequestMessage(HttpMethod.Get,
                                                         feedItem.MakeLink(feedCfg));
                    var httpResp = await client.SendAsync(httpReq);

                    if (httpResp != null && httpResp.IsSuccessStatusCode)
                    {
                        feedItem.Content = await httpResp.Content.ReadAsStringAsync();
                    }

                    else
                    {
                        feedItem.Content = null;
                        LogTo.Warning(
                            $"Failed to download content for feed {feedCfg.Name}, item title '{feedItem.Title}', link '{feedItem.MakeLink(feedCfg)}'. HTTP Status code : {httpResp?.StatusCode}");
                    }
                }

                else
                {
                    feedItem.Content = feedItem.Content ?? feedItem.Description;
                }

                if (string.IsNullOrWhiteSpace(feedItem.Content))
                {
                    return(null);
                }

                //
                // Process content if necessary & push back

                if (feedCfg.Filters.Any())
                {
                    feedItem.Content = string.Join(
                        "\r\n",
                        feedCfg.Filters
                        .Select(f => f.Filter(feedItem.Content))
                        .Where(s => string.IsNullOrWhiteSpace(s) == false)
                        );
                }

                if (feedItem.Link != null)
                {
                    feedItem.Content = HtmlUtils.EnsureAbsoluteLinks(feedItem.Content, new Uri(feedItem.MakeLink(feedCfg)));
                }

                // Add feed item
                return(new FeedItemExt(feedItem));
            }
            catch (Exception ex)
            {
                LogTo.Error(ex, $"Exception while downloading content for feed {feedCfg.Name}, item title '{feedItem.Title}', link '{feedItem.MakeLink(feedCfg)}'");
            }
            finally
            {
                throttler.Release();
            }

            return(null);
        }
Пример #27
0
        public void Render(XmlWriter writer, IEnumerable <NewsEntryInfo> newsEntries, ModuleInfo module,
                           PortalSettings portalSettings, string requestUrl, bool withImages)
        {
            var authorityDate = portalSettings.PortalAlias.CreatedOnDate.ToUniversalTime().ToString("yyyy-MM-dd");
            var updatedDate   = newsEntries.Any() ? newsEntries.First().PublishedOnDate() : module.LastModifiedOnDate;

            writer.WriteStartDocument();
            writer.WriteStartElement("feed", "http://www.w3.org/2005/Atom");

            writer.WriteElementString("title", module.ModuleTitle);
            writer.WriteStartElement("author");
            writer.WriteElementString("name", portalSettings.PortalName);
            writer.WriteEndElement();

            writer.WriteElementString("id", $"tag:{portalSettings.PortalAlias.HTTPAlias},{authorityDate}:feed#"
                                      + Base64ToCanonicalForm(UrlUtils.EncryptParameter($"{module.TabID}-{module.ModuleID}")));

            writer.WriteStartElement("link");
            writer.WriteAttributeString("rel", "self");
            writer.WriteAttributeString("href", requestUrl);
            writer.WriteEndElement();

            writer.WriteStartElement("link");
            writer.WriteAttributeString("rel", "alternate");
            writer.WriteAttributeString("href", Uri.EscapeUriString(Globals.NavigateURL(module.TabID)));
            writer.WriteEndElement();

            writer.WriteElementString("updated", IsoDateTime(updatedDate));

            foreach (var n in newsEntries)
            {
                var permalink = n.GetPermalinkFriendly(ModuleController.Instance, module.ModuleID, module.TabID);

                writer.WriteStartElement("entry");
                writer.WriteElementString("title", n.Title);

                writer.WriteStartElement("link");
                writer.WriteAttributeString("rel", "alternate");
                writer.WriteAttributeString("href", Uri.EscapeUriString(permalink));
                writer.WriteEndElement();

                writer.WriteElementString("id", $"tag:{portalSettings.PortalAlias.HTTPAlias},{authorityDate}:entry#{n.EntryId}");
                writer.WriteElementString("updated", IsoDateTime(n.PublishedOnDate()));
                writer.WriteElementString("summary", HttpUtility.HtmlDecode(HtmlUtils.StripTags(HttpUtility.HtmlDecode(n.Description), true)).Trim());

                writer.WriteStartElement("content");

                writer.WriteAttributeString("type", "html");

                var htmlContent = HttpUtility.HtmlDecode(n.Description);
                if (withImages && n.ContentItem.Images.Count > 0)
                {
                    var imageUrl = n.GetRawImageUrl();
                    if (!string.IsNullOrEmpty(imageUrl))
                    {
                        htmlContent = $"<img src=\"{imageUrl}\" alt=\"{n.Title}\" />" + htmlContent;
                    }
                }

                writer.WriteCData(htmlContent);

                writer.WriteEndElement();
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
            writer.WriteEndDocument();

            writer.Close();
        }
Пример #28
0
        //todo: Settings
        //Public Function SaveTabInfoObject(ByVal newTab As DotNetNuke.Entities.Tabs.TabInfo, ByVal relativeToTab As DotNetNuke.Entities.Tabs.TabInfo, ByVal location As TabRelativeLocation, ByVal templateMapPath As String, ByVal tabSettings As Hashtable) As Integer
        public static int SaveTabInfoObject(TabInfo tab, TabInfo relativeToTab, TabRelativeLocation location, string templateMapPath)
        {
            TabController tabCtrl = new TabController();

            //Validation:
            //Tab name is required
            //Tab name is invalid
            if ((tab.TabName == string.Empty))
            {
                throw new DotNetNukeException("Page name is required.", DotNetNukeErrorCode.PageNameRequired);
            }
            else if ((Regex.IsMatch(tab.TabName, "^LPT[1-9]$|^COM[1-9]$", RegexOptions.IgnoreCase)))
            {
                throw new DotNetNukeException("Page name is invalid.", DotNetNukeErrorCode.PageNameInvalid);
            }
            else if ((Regex.IsMatch(HtmlUtils.StripNonWord(tab.TabName, false), "^AUX$|^CON$|^NUL$|^SITEMAP$|^LINKCLICK$|^KEEPALIVE$|^DEFAULT$|^ERRORPAGE$", RegexOptions.IgnoreCase)))
            {
                throw new DotNetNukeException("Page name is invalid.", DotNetNukeErrorCode.PageNameInvalid);
            }
            else if ((Validate_IsCircularReference(tab.PortalID, tab.TabID)))
            {
                throw new DotNetNukeException("Cannot move page to that location.", DotNetNukeErrorCode.PageCircularReference);
            }

            bool usingDefaultLanguage = (tab.CultureCode == PortalSettings.Current.DefaultLanguage) || tab.CultureCode == null;

            if (PortalSettings.Current.ContentLocalizationEnabled)
            {
                if ((!usingDefaultLanguage))
                {
                    TabInfo defaultLanguageSelectedTab = tab.DefaultLanguageTab;

                    if ((defaultLanguageSelectedTab == null))
                    {
                        //get the siblings from the selectedtab and iterate through until you find a sibbling with a corresponding defaultlanguagetab
                        //if none are found get a list of all the tabs from the default language and then select the last one
                        var selectedTabSibblings = tabCtrl.GetTabsByPortal(tab.PortalID).WithCulture(tab.CultureCode, true).AsList();
                        foreach (TabInfo sibling in selectedTabSibblings)
                        {
                            TabInfo siblingDefaultTab = sibling.DefaultLanguageTab;
                            if (((siblingDefaultTab != null)))
                            {
                                defaultLanguageSelectedTab = siblingDefaultTab;
                                break;
                            }
                        }

                        //still haven't found it
                        if ((defaultLanguageSelectedTab == null))
                        {
                            var defaultLanguageTabs = tabCtrl.GetTabsByPortal(tab.PortalID).WithCulture(PortalSettings.Current.DefaultLanguage, true).AsList();
                            defaultLanguageSelectedTab = defaultLanguageTabs[defaultLanguageTabs.Count];
                            //get the last tab
                        }
                    }

                    relativeToTab = defaultLanguageSelectedTab;
                }
            }


            if ((location != TabRelativeLocation.NOTSET))
            {
                //Check Host tab - don't allow adding before or after
                if ((IsHostConsolePage(relativeToTab) && (location == TabRelativeLocation.AFTER || location == TabRelativeLocation.BEFORE)))
                {
                    throw new DotNetNukeException("You cannot add or move pages before or after the Host tab.", DotNetNukeErrorCode.HostBeforeAfterError);
                }

                TabInfo parentTab      = GetParentTab(relativeToTab, location);
                string  permissionList = "ADD,COPY,EDIT,MANAGE";
                //Check permissions for Page Editors when moving or inserting
                if ((!PortalSecurity.IsInRole("Administrators")))
                {
                    if (((parentTab == null) || !TabPermissionController.HasTabPermission(parentTab.TabPermissions, permissionList)))
                    {
                        throw new DotNetNukeException("You do not have permissions to add or move pages to this location. You can only add or move pages as children of pages you can edit.",
                                                      DotNetNukeErrorCode.PageEditorPermissionError);
                    }
                }

                if (((parentTab != null)))
                {
                    tab.ParentId = parentTab.TabID;
                    tab.Level    = parentTab.Level + 1;
                }
                else
                {
                    tab.ParentId = Null.NullInteger;
                    tab.Level    = 0;
                }
            }

            if ((tab.TabID > Null.NullInteger && tab.TabID == tab.ParentId))
            {
                throw new DotNetNukeException("Parent page is invalid.", DotNetNukeErrorCode.ParentTabInvalid);
            }

            tab.TabPath = Globals.GenerateTabPath(tab.ParentId, tab.TabName);
            //check whether have conflict between tab path and portal alias.
            if (TabController.IsDuplicateWithPortalAlias(PortalSettings.Current.PortalId, tab.TabPath))
            {
                throw new DotNetNukeException("The page path is duplicate with a site alias", DotNetNukeErrorCode.DuplicateWithAlias);
            }

            try
            {
                if ((tab.TabID < 0))
                {
                    if ((tab.TabPermissions.Count == 0 && tab.PortalID != Null.NullInteger))
                    {
                        //Give admin full permission
                        ArrayList permissions = PermissionController.GetPermissionsByTab();

                        foreach (PermissionInfo permission in permissions)
                        {
                            TabPermissionInfo newTabPermission = new TabPermissionInfo();
                            newTabPermission.PermissionID   = permission.PermissionID;
                            newTabPermission.PermissionKey  = permission.PermissionKey;
                            newTabPermission.PermissionName = permission.PermissionName;
                            newTabPermission.AllowAccess    = true;
                            newTabPermission.RoleID         = PortalSettings.Current.AdministratorRoleId;
                            tab.TabPermissions.Add(newTabPermission);
                        }
                    }

                    PortalSettings _PortalSettings = PortalController.GetCurrentPortalSettings();

                    if (_PortalSettings.ContentLocalizationEnabled)
                    {
                        Locale defaultLocale = LocaleController.Instance.GetDefaultLocale(tab.PortalID);
                        tab.CultureCode = defaultLocale.Code;
                    }
                    else
                    {
                        tab.CultureCode = Null.NullString;
                    }

                    if ((location == TabRelativeLocation.AFTER && (relativeToTab != null)))
                    {
                        tab.TabID = tabCtrl.AddTabAfter(tab, relativeToTab.TabID);
                    }
                    else if ((location == TabRelativeLocation.BEFORE && (relativeToTab != null)))
                    {
                        tab.TabID = tabCtrl.AddTabBefore(tab, relativeToTab.TabID);
                    }
                    else
                    {
                        tab.TabID = tabCtrl.AddTab(tab);
                    }

                    if (_PortalSettings.ContentLocalizationEnabled)
                    {
                        tabCtrl.CreateLocalizedCopies(tab);
                    }

                    tabCtrl.UpdateTabSetting(tab.TabID, "CacheProvider", "");
                    tabCtrl.UpdateTabSetting(tab.TabID, "CacheDuration", "");
                    tabCtrl.UpdateTabSetting(tab.TabID, "CacheIncludeExclude", "0");
                    tabCtrl.UpdateTabSetting(tab.TabID, "IncludeVaryBy", "");
                    tabCtrl.UpdateTabSetting(tab.TabID, "ExcludeVaryBy", "");
                    tabCtrl.UpdateTabSetting(tab.TabID, "MaxVaryByCount", "");
                }
                else
                {
                    tabCtrl.UpdateTab(tab);

                    if ((location == TabRelativeLocation.AFTER && (relativeToTab != null)))
                    {
                        tabCtrl.MoveTabAfter(tab, relativeToTab.TabID);
                    }
                    else if ((location == TabRelativeLocation.BEFORE && (relativeToTab != null)))
                    {
                        tabCtrl.MoveTabBefore(tab, relativeToTab.TabID);
                    }
                }
            }
            catch (Exception ex)
            {
                DnnLog.Error(ex);

                if (ex.Message.StartsWith("Page Exists"))
                {
                    throw new DotNetNukeException(ex.Message, DotNetNukeErrorCode.PageExists);
                }
            }

            // create the page from a template
            if ((!string.IsNullOrEmpty(templateMapPath)))
            {
                XmlDocument xmlDoc = new XmlDocument();
                try
                {
                    xmlDoc.Load(templateMapPath);
                    TabController.DeserializePanes(xmlDoc.SelectSingleNode("//portal/tabs/tab/panes"), tab.PortalID, tab.TabID, PortalTemplateModuleAction.Ignore, new Hashtable());

                    //save tab permissions
                    DeserializeTabPermissions(xmlDoc.SelectNodes("//portal/tabs/tab/tabpermissions/permission"), tab);
                }
                catch (Exception ex)
                {
                    Exceptions.LogException(ex);
                    throw new DotNetNukeException("Unable to process page template.", ex, DotNetNukeErrorCode.DeserializePanesFailed);
                }
            }

            //todo: reload tab from db or send back tabid instead?
            return(tab.TabID);
        }
        /// <summary>
        /// Formats attributes
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="attributes">Attributes</param>
        /// <param name="customer">Customer</param>
        /// <param name="serapator">Serapator</param>
        /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
        /// <param name="renderPrices">A value indicating whether to render prices</param>
        /// <param name="renderProductAttributes">A value indicating whether to render product attributes</param>
        /// <param name="renderGiftCardAttributes">A value indicating whether to render gift card attributes</param>
        /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>
        /// <returns>Attributes</returns>
        public string FormatAttributes(Product product, string attributes,
                                       Customer customer, string serapator = "<br />", bool htmlEncode           = true, bool renderPrices = true,
                                       bool renderProductAttributes        = true, bool renderGiftCardAttributes = true,
                                       bool allowHyperlinks = true)
        {
            var result = new StringBuilder();

            //attributes
            if (renderProductAttributes)
            {
                var pvaCollection = _productAttributeParser.ParseProductVariantAttributes(attributes);
                for (int i = 0; i < pvaCollection.Count; i++)
                {
                    var pva       = pvaCollection[i];
                    var valuesStr = _productAttributeParser.ParseValues(attributes, pva.Id);
                    for (int j = 0; j < valuesStr.Count; j++)
                    {
                        string valueStr     = valuesStr[j];
                        string pvaAttribute = string.Empty;
                        if (!pva.ShouldHaveValues())
                        {
                            //no values
                            if (pva.AttributeControlType == AttributeControlType.MultilineTextbox)
                            {
                                //multiline textbox
                                var attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = HttpUtility.HtmlEncode(attributeName);
                                }
                                pvaAttribute = string.Format("{0}: {1}", attributeName, HtmlUtils.FormatText(valueStr, false, true, false, false, false, false));
                                //we never encode multiline textbox input
                            }
                            else if (pva.AttributeControlType == AttributeControlType.FileUpload)
                            {
                                //file upload
                                Guid downloadGuid;
                                Guid.TryParse(valueStr, out downloadGuid);
                                var download = _downloadService.GetDownloadByGuid(downloadGuid);
                                if (download != null)
                                {
                                    //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
                                    string attributeText = "";
                                    var    fileName      = string.Format("{0}{1}",
                                                                         download.Filename ?? download.DownloadGuid.ToString(),
                                                                         download.Extension);
                                    //encode (if required)
                                    if (htmlEncode)
                                    {
                                        fileName = HttpUtility.HtmlEncode(fileName);
                                    }
                                    if (allowHyperlinks)
                                    {
                                        //hyperlinks are allowed
                                        var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid);
                                        attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName);
                                    }
                                    else
                                    {
                                        //hyperlinks aren't allowed
                                        attributeText = fileName;
                                    }
                                    var attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
                                    //encode (if required)
                                    if (htmlEncode)
                                    {
                                        attributeName = HttpUtility.HtmlEncode(attributeName);
                                    }
                                    pvaAttribute = string.Format("{0}: {1}", attributeName, attributeText);
                                }
                            }
                            else
                            {
                                //other attributes (textbox, datepicker)
                                pvaAttribute = string.Format("{0}: {1}", pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), valueStr);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute);
                                }
                            }
                        }
                        else
                        {
                            //attributes with values
                            int pvaId = 0;
                            if (int.TryParse(valueStr, out pvaId))
                            {
                                var pvaValue = _productAttributeService.GetProductVariantAttributeValueById(pvaId);
                                if (pvaValue != null)
                                {
                                    pvaAttribute = string.Format("{0}: {1}", pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id),
                                                                 pvaValue.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id));

                                    if (renderPrices)
                                    {
                                        decimal taxRate = decimal.Zero;
                                        decimal attributeValuePriceAdjustment = _priceCalculationService.GetProductVariantAttributeValuePriceAdjustment(pvaValue);
                                        decimal priceAdjustmentBase           = _taxService.GetProductPrice(product, attributeValuePriceAdjustment, customer, out taxRate);
                                        decimal priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);

                                        if (_shoppingCartSettings.ShowLinkedAttributeValueQuantity && pvaValue.ValueType == ProductVariantAttributeValueType.ProductLinkage &&
                                            pvaValue.Quantity > 1)
                                        {
                                            pvaAttribute += string.Format(" � {0}", pvaValue.Quantity);
                                        }

                                        if (priceAdjustmentBase > 0)
                                        {
                                            string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment, true, false);
                                            pvaAttribute += string.Format(" [+{0}]", priceAdjustmentStr);
                                        }
                                        else if (priceAdjustmentBase < decimal.Zero)
                                        {
                                            string priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustment, true, false);
                                            pvaAttribute += string.Format(" [-{0}]", priceAdjustmentStr);
                                        }
                                    }
                                }
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute);
                                }
                            }
                        }

                        if (!String.IsNullOrEmpty(pvaAttribute))
                        {
                            if (i != 0 || j != 0)
                            {
                                result.Append(serapator);
                            }
                            result.Append(pvaAttribute);
                        }
                    }
                }
            }

            //gift cards
            if (renderGiftCardAttributes)
            {
                if (product.IsGiftCard)
                {
                    string giftCardRecipientName  = "";
                    string giftCardRecipientEmail = "";
                    string giftCardSenderName     = "";
                    string giftCardSenderEmail    = "";
                    string giftCardMessage        = "";
                    _productAttributeParser.GetGiftCardAttribute(attributes, out giftCardRecipientName, out giftCardRecipientEmail,
                                                                 out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage);

                    //sender
                    var giftCardFrom = product.GiftCardType == GiftCardType.Virtual ?
                                       string.Format(_localizationService.GetResource("GiftCardAttribute.From.Virtual"), giftCardSenderName, giftCardSenderEmail) :
                                       string.Format(_localizationService.GetResource("GiftCardAttribute.From.Physical"), giftCardSenderName);
                    //recipient
                    var giftCardFor = product.GiftCardType == GiftCardType.Virtual ?
                                      string.Format(_localizationService.GetResource("GiftCardAttribute.For.Virtual"), giftCardRecipientName, giftCardRecipientEmail) :
                                      string.Format(_localizationService.GetResource("GiftCardAttribute.For.Physical"), giftCardRecipientName);

                    //encode (if required)
                    if (htmlEncode)
                    {
                        giftCardFrom = HttpUtility.HtmlEncode(giftCardFrom);
                        giftCardFor  = HttpUtility.HtmlEncode(giftCardFor);
                    }

                    if (!String.IsNullOrEmpty(result.ToString()))
                    {
                        result.Append(serapator);
                    }
                    result.Append(giftCardFrom);
                    result.Append(serapator);
                    result.Append(giftCardFor);
                }
            }
            return(result.ToString());
        }
Пример #30
0
 public void TestEscapeHtmlCharacters()
 {
     Assert.AreEqual("&lt;p&gt;&quot;test", HtmlUtils.EscapeHtmlCharacters("<p>\"test"));
 }